blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7f7d902a0ed302572c4dcb3acde64d7e2f003b62 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | The ClusterControllerService provides methods to manage clusters of Compute Engine instances. | ClusterControllerServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterControllerServicer:
"""The ClusterControllerService provides methods to manage clusters of Compute Engine instances."""
def CreateCluster(self, request, context):
"""Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will b... | stack_v2_sparse_classes_75kplus_train_071000 | 8,092 | permissive | [
{
"docstring": "Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will be [ClusterOperationMetadata](/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata).",
"name": "CreateCluster",
"signature": "def CreateCluster(sel... | 6 | stack_v2_sparse_classes_30k_train_039789 | Implement the Python class `ClusterControllerServicer` described below.
Class description:
The ClusterControllerService provides methods to manage clusters of Compute Engine instances.
Method signatures and docstrings:
- def CreateCluster(self, request, context): Creates a cluster in a project. The returned [Operatio... | Implement the Python class `ClusterControllerServicer` described below.
Class description:
The ClusterControllerService provides methods to manage clusters of Compute Engine instances.
Method signatures and docstrings:
- def CreateCluster(self, request, context): Creates a cluster in a project. The returned [Operatio... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class ClusterControllerServicer:
"""The ClusterControllerService provides methods to manage clusters of Compute Engine instances."""
def CreateCluster(self, request, context):
"""Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterControllerServicer:
"""The ClusterControllerService provides methods to manage clusters of Compute Engine instances."""
def CreateCluster(self, request, context):
"""Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will be [ClusterOpe... | the_stack_v2_python_sparse | dataproc/google/cloud/dataproc_v1beta2/proto/clusters_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
b2d5fd5eb9ecd7d3b874554c397432ca8ec9a23f | [
"def evaluator(v):\n hvp = self.hessian_vector_product(task, v, x=x, y=y)\n Av = (1.0 + regu_coef) * v + hvp / (lam + lam_damping)\n return Av\nreturn evaluator",
"grad_ft = torch.autograd.grad(tloss, model.parameters(), create_graph=True)\nflat_grad = torch.cat([g.contiguous().view(-1) for g in grad_ft]... | <|body_start_0|>
def evaluator(v):
hvp = self.hessian_vector_product(task, v, x=x, y=y)
Av = (1.0 + regu_coef) * v + hvp / (lam + lam_damping)
return Av
return evaluator
<|end_body_0|>
<|body_start_1|>
grad_ft = torch.autograd.grad(tloss, model.parameters(), ... | HessianVal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HessianVal:
def matrix_evaluator(self, task, lam, regu_coef=1.0, lam_damping=10.0, x=None, y=None):
"""Constructor function that can be given to CG optimizer Works for both type(lam) == float and type(lam) == np.ndarray"""
<|body_0|>
def hessian_vector_product(self, vector, ... | stack_v2_sparse_classes_75kplus_train_071001 | 13,735 | no_license | [
{
"docstring": "Constructor function that can be given to CG optimizer Works for both type(lam) == float and type(lam) == np.ndarray",
"name": "matrix_evaluator",
"signature": "def matrix_evaluator(self, task, lam, regu_coef=1.0, lam_damping=10.0, x=None, y=None)"
},
{
"docstring": "Performs hes... | 2 | stack_v2_sparse_classes_30k_train_020410 | Implement the Python class `HessianVal` described below.
Class description:
Implement the HessianVal class.
Method signatures and docstrings:
- def matrix_evaluator(self, task, lam, regu_coef=1.0, lam_damping=10.0, x=None, y=None): Constructor function that can be given to CG optimizer Works for both type(lam) == flo... | Implement the Python class `HessianVal` described below.
Class description:
Implement the HessianVal class.
Method signatures and docstrings:
- def matrix_evaluator(self, task, lam, regu_coef=1.0, lam_damping=10.0, x=None, y=None): Constructor function that can be given to CG optimizer Works for both type(lam) == flo... | 30fc92c25c00898f6b0e4ff3185e77d18dbde5a1 | <|skeleton|>
class HessianVal:
def matrix_evaluator(self, task, lam, regu_coef=1.0, lam_damping=10.0, x=None, y=None):
"""Constructor function that can be given to CG optimizer Works for both type(lam) == float and type(lam) == np.ndarray"""
<|body_0|>
def hessian_vector_product(self, vector, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HessianVal:
def matrix_evaluator(self, task, lam, regu_coef=1.0, lam_damping=10.0, x=None, y=None):
"""Constructor function that can be given to CG optimizer Works for both type(lam) == float and type(lam) == np.ndarray"""
def evaluator(v):
hvp = self.hessian_vector_product(task, v... | the_stack_v2_python_sparse | aggets/imaml/task.py | rwiatr/aggets | train | 1 | |
b776d785af58ad2396163f60decc67de683b300b | [
"if self._python_type == datetime.timedelta and isinstance(value, (datetime.timedelta,)):\n return str('{td.days}:{td.seconds}:{td.microseconds}'.format(td=value))\nelse:\n raise exceptions.pyOrmEngineAdapterError(\"InternalError : Unexpected value {} rec'd in Duration adapter\".format(value.__class__.__name_... | <|body_start_0|>
if self._python_type == datetime.timedelta and isinstance(value, (datetime.timedelta,)):
return str('{td.days}:{td.seconds}:{td.microseconds}'.format(td=value))
else:
raise exceptions.pyOrmEngineAdapterError("InternalError : Unexpected value {} rec'd in Duration ... | Adapter for the duration db_type Durations are stored as a string '<days>:<seconds>:<microseconds>' in the database | DurationAdapter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DurationAdapter:
"""Adapter for the duration db_type Durations are stored as a string '<days>:<seconds>:<microseconds>' in the database"""
def adapt(self, value):
"""Convert the value to the representation to be stored into the database"""
<|body_0|>
def convert(self, da... | stack_v2_sparse_classes_75kplus_train_071002 | 11,033 | permissive | [
{
"docstring": "Convert the value to the representation to be stored into the database",
"name": "adapt",
"signature": "def adapt(self, value)"
},
{
"docstring": "Convert the bytes value from the database to the relevant python type",
"name": "convert",
"signature": "def convert(self, da... | 2 | stack_v2_sparse_classes_30k_train_034053 | Implement the Python class `DurationAdapter` described below.
Class description:
Adapter for the duration db_type Durations are stored as a string '<days>:<seconds>:<microseconds>' in the database
Method signatures and docstrings:
- def adapt(self, value): Convert the value to the representation to be stored into the... | Implement the Python class `DurationAdapter` described below.
Class description:
Adapter for the duration db_type Durations are stored as a string '<days>:<seconds>:<microseconds>' in the database
Method signatures and docstrings:
- def adapt(self, value): Convert the value to the representation to be stored into the... | 6d811fa32d3ba4c4a013fbb8f627277fa9d20b64 | <|skeleton|>
class DurationAdapter:
"""Adapter for the duration db_type Durations are stored as a string '<days>:<seconds>:<microseconds>' in the database"""
def adapt(self, value):
"""Convert the value to the representation to be stored into the database"""
<|body_0|>
def convert(self, da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DurationAdapter:
"""Adapter for the duration db_type Durations are stored as a string '<days>:<seconds>:<microseconds>' in the database"""
def adapt(self, value):
"""Convert the value to the representation to be stored into the database"""
if self._python_type == datetime.timedelta and is... | the_stack_v2_python_sparse | pyorm/db/engine/sqlite.py | TonyFlury/pyorm | train | 0 |
84a38212379348fe98beb1223f21410f2b874bc4 | [
"divisors = []\nsqrt_n = int(n ** 0.5)\nfor x in range(1, sqrt_n + 1):\n if n % x == 0:\n k -= 1\n divisors.append(x)\n if k == 0:\n return x\nif sqrt_n * sqrt_n == n:\n k += 1\nreturn n // divisors[len(divisors) - k] if k <= len(divisors) else -1",
"def heappush_k(num):\n ... | <|body_start_0|>
divisors = []
sqrt_n = int(n ** 0.5)
for x in range(1, sqrt_n + 1):
if n % x == 0:
k -= 1
divisors.append(x)
if k == 0:
return x
if sqrt_n * sqrt_n == n:
k += 1
return n /... | KthFactor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthFactor:
def _of_n(self, n: int, k: int) -> int:
"""Approach: Math, O(sqrt(N)) time Time Complexity: O(sqrt(N)) Space Complexity: O(min(k, sqrt(N)) :param n: :param k: :return:"""
<|body_0|>
def of_n_(self, n: int, k: int) -> int:
"""Approach: Heap Time Complexity:... | stack_v2_sparse_classes_75kplus_train_071003 | 1,846 | no_license | [
{
"docstring": "Approach: Math, O(sqrt(N)) time Time Complexity: O(sqrt(N)) Space Complexity: O(min(k, sqrt(N)) :param n: :param k: :return:",
"name": "_of_n",
"signature": "def _of_n(self, n: int, k: int) -> int"
},
{
"docstring": "Approach: Heap Time Complexity: O(sqrt(N) * log k) Space Comple... | 3 | stack_v2_sparse_classes_30k_train_054028 | Implement the Python class `KthFactor` described below.
Class description:
Implement the KthFactor class.
Method signatures and docstrings:
- def _of_n(self, n: int, k: int) -> int: Approach: Math, O(sqrt(N)) time Time Complexity: O(sqrt(N)) Space Complexity: O(min(k, sqrt(N)) :param n: :param k: :return:
- def of_n_... | Implement the Python class `KthFactor` described below.
Class description:
Implement the KthFactor class.
Method signatures and docstrings:
- def _of_n(self, n: int, k: int) -> int: Approach: Math, O(sqrt(N)) time Time Complexity: O(sqrt(N)) Space Complexity: O(min(k, sqrt(N)) :param n: :param k: :return:
- def of_n_... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class KthFactor:
def _of_n(self, n: int, k: int) -> int:
"""Approach: Math, O(sqrt(N)) time Time Complexity: O(sqrt(N)) Space Complexity: O(min(k, sqrt(N)) :param n: :param k: :return:"""
<|body_0|>
def of_n_(self, n: int, k: int) -> int:
"""Approach: Heap Time Complexity:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthFactor:
def _of_n(self, n: int, k: int) -> int:
"""Approach: Math, O(sqrt(N)) time Time Complexity: O(sqrt(N)) Space Complexity: O(min(k, sqrt(N)) :param n: :param k: :return:"""
divisors = []
sqrt_n = int(n ** 0.5)
for x in range(1, sqrt_n + 1):
if n % x == 0:
... | the_stack_v2_python_sparse | expedia/kth_factor_of_n.py | Shiv2157k/leet_code | train | 1 | |
6684466b810f768b60e9bb66b81b9924532f2c19 | [
"self.map_ = in_map\nself.rank = self.comm.Get_rank()\nself.npix = len(self.map_.index_map['pixel'])\nself.nside = self.map_.nside\nself.z_arr = _freq_to_z(self.map_.index_map['freq'])\nself.z = self.z_arr[self.freq_idx]['centre']",
"local_pix_indices = mpiutil.partition_list_mpi(np.arange(self.npix))\nnpix_rank ... | <|body_start_0|>
self.map_ = in_map
self.rank = self.comm.Get_rank()
self.npix = len(self.map_.index_map['pixel'])
self.nside = self.map_.nside
self.z_arr = _freq_to_z(self.map_.index_map['freq'])
self.z = self.z_arr[self.freq_idx]['centre']
<|end_body_0|>
<|body_start_1... | Generate a 'catalog' of Healpix pixel centers. This is useful if you want to stack on each Healpix pixel for a given Healpix resolution (determined by an input map). This task outputs a SpectroscopicCatalog that can then be fed to the usual beamforming task. All "sources" are assigned to the same frequency channel, for... | MapPixelLocationGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapPixelLocationGenerator:
"""Generate a 'catalog' of Healpix pixel centers. This is useful if you want to stack on each Healpix pixel for a given Healpix resolution (determined by an input map). This task outputs a SpectroscopicCatalog that can then be fed to the usual beamforming task. All "sou... | stack_v2_sparse_classes_75kplus_train_071004 | 46,986 | permissive | [
{
"docstring": "Pre-load information from input map.",
"name": "setup",
"signature": "def setup(self, in_map)"
},
{
"docstring": "Make a catalog of pixel positions. Returns ------- mock_catalog : :class:`containers.SpectroscopicCatalog` Output catalog.",
"name": "process",
"signature": "... | 2 | null | Implement the Python class `MapPixelLocationGenerator` described below.
Class description:
Generate a 'catalog' of Healpix pixel centers. This is useful if you want to stack on each Healpix pixel for a given Healpix resolution (determined by an input map). This task outputs a SpectroscopicCatalog that can then be fed ... | Implement the Python class `MapPixelLocationGenerator` described below.
Class description:
Generate a 'catalog' of Healpix pixel centers. This is useful if you want to stack on each Healpix pixel for a given Healpix resolution (determined by an input map). This task outputs a SpectroscopicCatalog that can then be fed ... | 544e485c03c125d260eb22ef467ae4d2e4dfed09 | <|skeleton|>
class MapPixelLocationGenerator:
"""Generate a 'catalog' of Healpix pixel centers. This is useful if you want to stack on each Healpix pixel for a given Healpix resolution (determined by an input map). This task outputs a SpectroscopicCatalog that can then be fed to the usual beamforming task. All "sou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MapPixelLocationGenerator:
"""Generate a 'catalog' of Healpix pixel centers. This is useful if you want to stack on each Healpix pixel for a given Healpix resolution (determined by an input map). This task outputs a SpectroscopicCatalog that can then be fed to the usual beamforming task. All "sources" are ass... | the_stack_v2_python_sparse | draco/synthesis/mockcatalog.py | radiocosmology/draco | train | 8 |
7f43f15cf9e55c8a9c3151392086d821effb23ff | [
"self.task.set_status(hd_fields.TaskStatus.Running)\nself.task.save()\ndriver = self._get_driver('node')\nif driver is None:\n self.task.set_status(hd_fields.TaskStatus.Complete)\n self.task.add_status_msg(msg='No node driver enabled, ending task.', error=True, ctx=str(self.task.get_id()), ctx_type='task')\n ... | <|body_start_0|>
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
driver = self._get_driver('node')
if driver is None:
self.task.set_status(hd_fields.TaskStatus.Complete)
self.task.add_status_msg(msg='No node driver enabled, ending task.', error... | Action to configure site wide/inter-node settings. | PrepareSite | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrepareSite:
"""Action to configure site wide/inter-node settings."""
def start(self):
"""Start executing this action in the context of the local task."""
<|body_0|>
def step_configureprovisioner(self, driver):
"""Run the ConfigureNodeProvisioner step of this act... | stack_v2_sparse_classes_75kplus_train_071005 | 47,038 | permissive | [
{
"docstring": "Start executing this action in the context of the local task.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Run the ConfigureNodeProvisioner step of this action. :param driver: The driver instance to use for execution.",
"name": "step_configureprovision... | 4 | stack_v2_sparse_classes_30k_train_040352 | Implement the Python class `PrepareSite` described below.
Class description:
Action to configure site wide/inter-node settings.
Method signatures and docstrings:
- def start(self): Start executing this action in the context of the local task.
- def step_configureprovisioner(self, driver): Run the ConfigureNodeProvisi... | Implement the Python class `PrepareSite` described below.
Class description:
Action to configure site wide/inter-node settings.
Method signatures and docstrings:
- def start(self): Start executing this action in the context of the local task.
- def step_configureprovisioner(self, driver): Run the ConfigureNodeProvisi... | f99abfa4337f8cbb591513aac404b11208d4187c | <|skeleton|>
class PrepareSite:
"""Action to configure site wide/inter-node settings."""
def start(self):
"""Start executing this action in the context of the local task."""
<|body_0|>
def step_configureprovisioner(self, driver):
"""Run the ConfigureNodeProvisioner step of this act... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrepareSite:
"""Action to configure site wide/inter-node settings."""
def start(self):
"""Start executing this action in the context of the local task."""
self.task.set_status(hd_fields.TaskStatus.Running)
self.task.save()
driver = self._get_driver('node')
if drive... | the_stack_v2_python_sparse | python/drydock_provisioner/orchestrator/actions/orchestrator.py | airshipit/drydock | train | 13 |
15454fd2e598a2d782cd4f01bdb9403bbdfe1a69 | [
"model = Dog\nname = 'Dogs'\nsuper().__init__(model=model, collection_name=name)\nself.__dog_owner_repository = dog_owner_repository",
"dogs = list()\nowners = self.__dog_owner_repository.search(f'owner_id=={owner_id}')\nfor dog_owner in owners.to_list():\n try:\n dog = self.read(dog_owner.dog_id)\n ... | <|body_start_0|>
model = Dog
name = 'Dogs'
super().__init__(model=model, collection_name=name)
self.__dog_owner_repository = dog_owner_repository
<|end_body_0|>
<|body_start_1|>
dogs = list()
owners = self.__dog_owner_repository.search(f'owner_id=={owner_id}')
fo... | Dog repository class. | DogRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DogRepository:
"""Dog repository class."""
def __init__(self, dog_owner_repository):
"""Initialize dog repository."""
<|body_0|>
def read_dogs_of_owner(self, owner_id):
"""Get dogs associated with this user_id."""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_071006 | 950 | no_license | [
{
"docstring": "Initialize dog repository.",
"name": "__init__",
"signature": "def __init__(self, dog_owner_repository)"
},
{
"docstring": "Get dogs associated with this user_id.",
"name": "read_dogs_of_owner",
"signature": "def read_dogs_of_owner(self, owner_id)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000109 | Implement the Python class `DogRepository` described below.
Class description:
Dog repository class.
Method signatures and docstrings:
- def __init__(self, dog_owner_repository): Initialize dog repository.
- def read_dogs_of_owner(self, owner_id): Get dogs associated with this user_id. | Implement the Python class `DogRepository` described below.
Class description:
Dog repository class.
Method signatures and docstrings:
- def __init__(self, dog_owner_repository): Initialize dog repository.
- def read_dogs_of_owner(self, owner_id): Get dogs associated with this user_id.
<|skeleton|>
class DogReposito... | 129dc7f8213fb3112c35b1551d9ed3d8a14b7fb5 | <|skeleton|>
class DogRepository:
"""Dog repository class."""
def __init__(self, dog_owner_repository):
"""Initialize dog repository."""
<|body_0|>
def read_dogs_of_owner(self, owner_id):
"""Get dogs associated with this user_id."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DogRepository:
"""Dog repository class."""
def __init__(self, dog_owner_repository):
"""Initialize dog repository."""
model = Dog
name = 'Dogs'
super().__init__(model=model, collection_name=name)
self.__dog_owner_repository = dog_owner_repository
def read_dogs... | the_stack_v2_python_sparse | hugbunadarfr_backend/src/app/repository/repositories/dog_repository.py | birna17/veff_hugb | train | 0 |
c74217be9f7714ab14d92844a4b4d4cedc75bfe4 | [
"y_pred = y_pred.T\ny_true_ = np.zeros(y_pred.shape)\nfor i, y in enumerate(y_true.flatten()):\n y_true_[i, y] = 1\nC = -np.sum(y_true_ * np.log(y_pred))\nif penalty > 0:\n for w in W:\n C += 0.5 * penalty * np.sum(w ** 2)\nreturn C",
"a = np.exp(x - np.max(x))\nsm = a / np.sum(a, axis=0, keepdims=Tr... | <|body_start_0|>
y_pred = y_pred.T
y_true_ = np.zeros(y_pred.shape)
for i, y in enumerate(y_true.flatten()):
y_true_[i, y] = 1
C = -np.sum(y_true_ * np.log(y_pred))
if penalty > 0:
for w in W:
C += 0.5 * penalty * np.sum(w ** 2)
ret... | Class containing the cost and output activation function for classification. | C_classification | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class C_classification:
"""Class containing the cost and output activation function for classification."""
def C(y_true, y_pred, penalty=0, W=0):
"""Cost function for classification (cross entropy + penalty). Arguments: y_true (array): observed response y_pred (array): predicted response p... | stack_v2_sparse_classes_75kplus_train_071007 | 12,501 | no_license | [
{
"docstring": "Cost function for classification (cross entropy + penalty). Arguments: y_true (array): observed response y_pred (array): predicted response penalty (float, optional): penalty parameter, defaults to 0 W (float, optional): weight, defaults to 0",
"name": "C",
"signature": "def C(y_true, y_... | 2 | stack_v2_sparse_classes_30k_train_011738 | Implement the Python class `C_classification` described below.
Class description:
Class containing the cost and output activation function for classification.
Method signatures and docstrings:
- def C(y_true, y_pred, penalty=0, W=0): Cost function for classification (cross entropy + penalty). Arguments: y_true (array... | Implement the Python class `C_classification` described below.
Class description:
Class containing the cost and output activation function for classification.
Method signatures and docstrings:
- def C(y_true, y_pred, penalty=0, W=0): Cost function for classification (cross entropy + penalty). Arguments: y_true (array... | 5bbd2dc3fa274f6e48b2d4ef387b3939483cafe8 | <|skeleton|>
class C_classification:
"""Class containing the cost and output activation function for classification."""
def C(y_true, y_pred, penalty=0, W=0):
"""Cost function for classification (cross entropy + penalty). Arguments: y_true (array): observed response y_pred (array): predicted response p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class C_classification:
"""Class containing the cost and output activation function for classification."""
def C(y_true, y_pred, penalty=0, W=0):
"""Cost function for classification (cross entropy + penalty). Arguments: y_true (array): observed response y_pred (array): predicted response penalty (float... | the_stack_v2_python_sparse | Project2/neural_network.py | fridalarsen/FYS-STK4155 | train | 0 |
8335c37dc6a7255e9bba220253d98a50ff57b4a4 | [
"self.intrinsic = intrinsic\nself.PL = PL\nself.PR = PR\nself.params = params",
"if state_num == 0:\n self._process_first_frame(left_frame, right_frame, state_num)\n return (self.prevState.location, self.prevState.orientation)\nif state_num == 1:\n self._process_second_frame(left_frame, right_frame, stat... | <|body_start_0|>
self.intrinsic = intrinsic
self.PL = PL
self.PR = PR
self.params = params
<|end_body_0|>
<|body_start_1|>
if state_num == 0:
self._process_first_frame(left_frame, right_frame, state_num)
return (self.prevState.location, self.prevState.ori... | StereoVo : is the main driver code which calls upon drivers codes for DetectionEngine, TrackingEngine, PnP solver, Optimization to calculate the relative location and orientation of a stereo state at particular time instant | StereoVO | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StereoVO:
"""StereoVo : is the main driver code which calls upon drivers codes for DetectionEngine, TrackingEngine, PnP solver, Optimization to calculate the relative location and orientation of a stereo state at particular time instant"""
def __init__(self, intrinsic, PL, PR, params):
... | stack_v2_sparse_classes_75kplus_train_071008 | 5,911 | permissive | [
{
"docstring": ":param intrinsic (np.array): size (3x3) camera calibration parameters :param PL (np.array): size (3x4) left projection matrix such that x_L = PL * X_w :param PR (np.array): size (3x4) right projection matrix such that x_R = PR * X_w (where world coordinates are in the frame of the left camera) :... | 5 | stack_v2_sparse_classes_30k_train_029770 | Implement the Python class `StereoVO` described below.
Class description:
StereoVo : is the main driver code which calls upon drivers codes for DetectionEngine, TrackingEngine, PnP solver, Optimization to calculate the relative location and orientation of a stereo state at particular time instant
Method signatures an... | Implement the Python class `StereoVO` described below.
Class description:
StereoVo : is the main driver code which calls upon drivers codes for DetectionEngine, TrackingEngine, PnP solver, Optimization to calculate the relative location and orientation of a stereo state at particular time instant
Method signatures an... | 35df259a1524b04d1db578018c60814b26b2d437 | <|skeleton|>
class StereoVO:
"""StereoVo : is the main driver code which calls upon drivers codes for DetectionEngine, TrackingEngine, PnP solver, Optimization to calculate the relative location and orientation of a stereo state at particular time instant"""
def __init__(self, intrinsic, PL, PR, params):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StereoVO:
"""StereoVo : is the main driver code which calls upon drivers codes for DetectionEngine, TrackingEngine, PnP solver, Optimization to calculate the relative location and orientation of a stereo state at particular time instant"""
def __init__(self, intrinsic, PL, PR, params):
""":param ... | the_stack_v2_python_sparse | stereoVO/model/stereoVO.py | sakshamjindal/Stereo-Visual-SLAM-Odometry | train | 22 |
34804439eb9bede168bfdd67ab89a9948305a0f2 | [
"self.debug_mode = debug_mode\nself.em = Embedding()\nself.em.load()\nself.preprocessor()",
"logger.info('load data')\nself.train = pd.read_csv(config.root_path + '/data/train_clean.csv', sep='\\t').dropna()\nself.dev = pd.read_csv(config.root_path + '/data/dev_clean.csv', sep='\\t').dropna()\nif self.debug_mode:... | <|body_start_0|>
self.debug_mode = debug_mode
self.em = Embedding()
self.em.load()
self.preprocessor()
<|end_body_0|>
<|body_start_1|>
logger.info('load data')
self.train = pd.read_csv(config.root_path + '/data/train_clean.csv', sep='\t').dropna()
self.dev = pd.r... | MLData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLData:
def __init__(self, debug_mode=False):
"""init ML dataset, @param: debug_mode: if debug_mode, only deal 10000 data"""
<|body_0|>
def preprocessor(self):
"""process data, segment, transform label to id"""
<|body_1|>
def process_data(self, method='w... | stack_v2_sparse_classes_75kplus_train_071009 | 3,682 | no_license | [
{
"docstring": "init ML dataset, @param: debug_mode: if debug_mode, only deal 10000 data",
"name": "__init__",
"signature": "def __init__(self, debug_mode=False)"
},
{
"docstring": "process data, segment, transform label to id",
"name": "preprocessor",
"signature": "def preprocessor(self... | 4 | null | Implement the Python class `MLData` described below.
Class description:
Implement the MLData class.
Method signatures and docstrings:
- def __init__(self, debug_mode=False): init ML dataset, @param: debug_mode: if debug_mode, only deal 10000 data
- def preprocessor(self): process data, segment, transform label to id
... | Implement the Python class `MLData` described below.
Class description:
Implement the MLData class.
Method signatures and docstrings:
- def __init__(self, debug_mode=False): init ML dataset, @param: debug_mode: if debug_mode, only deal 10000 data
- def preprocessor(self): process data, segment, transform label to id
... | 71daf6bbe20300b943d409b4000f4bba6073a84b | <|skeleton|>
class MLData:
def __init__(self, debug_mode=False):
"""init ML dataset, @param: debug_mode: if debug_mode, only deal 10000 data"""
<|body_0|>
def preprocessor(self):
"""process data, segment, transform label to id"""
<|body_1|>
def process_data(self, method='w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLData:
def __init__(self, debug_mode=False):
"""init ML dataset, @param: debug_mode: if debug_mode, only deal 10000 data"""
self.debug_mode = debug_mode
self.em = Embedding()
self.em.load()
self.preprocessor()
def preprocessor(self):
"""process data, segme... | the_stack_v2_python_sparse | textClassification/src/data/mlData.py | jessie0624/NLPProjects | train | 0 | |
37023d51ebe250635475f75c61623f0f952c0ecd | [
"count = Counter(A.split())\ncount += Counter(B.split())\nreturn [w for w in count if count[w] == 1]",
"a_words = A.split()\nb_words = B.split()\ncount = {w: a_words.count(w) for w in a_words}\nfor w in b_words:\n if w in count:\n count[w] += b_words.count(w)\n else:\n count[w] = b_words.count... | <|body_start_0|>
count = Counter(A.split())
count += Counter(B.split())
return [w for w in count if count[w] == 1]
<|end_body_0|>
<|body_start_1|>
a_words = A.split()
b_words = B.split()
count = {w: a_words.count(w) for w in a_words}
for w in b_words:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uncommonFromSentences(self, A: str, B: str) -> list:
"""Runtime: 36 ms, faster than 91.68% of Python3. Memory Usage: 13.2 MB, less than 57.93% of Python3."""
<|body_0|>
def uncommonFromSentences2(self, A: str, B: str) -> list:
"""Runtime: 36 ms, faster ... | stack_v2_sparse_classes_75kplus_train_071010 | 2,212 | permissive | [
{
"docstring": "Runtime: 36 ms, faster than 91.68% of Python3. Memory Usage: 13.2 MB, less than 57.93% of Python3.",
"name": "uncommonFromSentences",
"signature": "def uncommonFromSentences(self, A: str, B: str) -> list"
},
{
"docstring": "Runtime: 36 ms, faster than 91.68% of Python3. Memory Us... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uncommonFromSentences(self, A: str, B: str) -> list: Runtime: 36 ms, faster than 91.68% of Python3. Memory Usage: 13.2 MB, less than 57.93% of Python3.
- def uncommonFromSent... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uncommonFromSentences(self, A: str, B: str) -> list: Runtime: 36 ms, faster than 91.68% of Python3. Memory Usage: 13.2 MB, less than 57.93% of Python3.
- def uncommonFromSent... | 9f66d352c805fcdd9930aaa18c93d7546768287c | <|skeleton|>
class Solution:
def uncommonFromSentences(self, A: str, B: str) -> list:
"""Runtime: 36 ms, faster than 91.68% of Python3. Memory Usage: 13.2 MB, less than 57.93% of Python3."""
<|body_0|>
def uncommonFromSentences2(self, A: str, B: str) -> list:
"""Runtime: 36 ms, faster ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> list:
"""Runtime: 36 ms, faster than 91.68% of Python3. Memory Usage: 13.2 MB, less than 57.93% of Python3."""
count = Counter(A.split())
count += Counter(B.split())
return [w for w in count if count[w] == 1]
def... | the_stack_v2_python_sparse | easy/884_uncommon_words_from_two_sentences.py | niki4/leetcode_py3 | train | 0 | |
003ce04460010f60deeaa0047f4fc75c44ca4a5d | [
"if len(arr) == 0:\n return -1\nif right >= left:\n mid = left + (right - left) // 2\n if value == arr[mid]:\n return 'Value {} found @ index {}'.format(value, mid)\n elif value < arr[mid]:\n return self.Recursive(arr, left, mid - 1, value)\n elif value > arr[mid]:\n return self.... | <|body_start_0|>
if len(arr) == 0:
return -1
if right >= left:
mid = left + (right - left) // 2
if value == arr[mid]:
return 'Value {} found @ index {}'.format(value, mid)
elif value < arr[mid]:
return self.Recursive(arr, le... | Read Google Blog about Binary Search BUG: https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms. -> mid value: it fails if the sum of low and high is greater than the maximum positive int value (2^31 - 1... | BinarySearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySearch:
"""Read Google Blog about Binary Search BUG: https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms. -> mid value: it fails if the sum of low and high is greater than ... | stack_v2_sparse_classes_75kplus_train_071011 | 2,129 | permissive | [
{
"docstring": "implemntation of Recursive Binary Search Algorithm",
"name": "Recursive",
"signature": "def Recursive(self, arr, left, right, value)"
},
{
"docstring": "implemntation of Iterative Binary Search Algorithm",
"name": "Iterative",
"signature": "def Iterative(self, arr, value)... | 2 | stack_v2_sparse_classes_30k_train_045504 | Implement the Python class `BinarySearch` described below.
Class description:
Read Google Blog about Binary Search BUG: https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms. -> mid value: it fails if t... | Implement the Python class `BinarySearch` described below.
Class description:
Read Google Blog about Binary Search BUG: https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms. -> mid value: it fails if t... | df6e2b5b0f74174d5c0950520f0c47b04212dfaa | <|skeleton|>
class BinarySearch:
"""Read Google Blog about Binary Search BUG: https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms. -> mid value: it fails if the sum of low and high is greater than ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinarySearch:
"""Read Google Blog about Binary Search BUG: https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms. -> mid value: it fails if the sum of low and high is greater than the maximum p... | the_stack_v2_python_sparse | leetcode/BinarySearch.py | AmrMKayid/KayAlgo | train | 2 |
0b0b05d98513cba036357a1f8a10a764d96b92b5 | [
"frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_alex_v0.1_27.pb', 'vgg_lin': 'net-lin_vgg_v0.1_27.pb', 'vgg': 'net_vgg_v0.1_27.pb'}\nfrozen_graph_path = osp.join(frozen_graphs_parent_dir, frozen_graph_name[net])\ninputs = ['0:0', '1:0']\noutputs = {'alex_lin': 'Reshape_10:0', 'alex': 'Add_... | <|body_start_0|>
frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_alex_v0.1_27.pb', 'vgg_lin': 'net-lin_vgg_v0.1_27.pb', 'vgg': 'net_vgg_v0.1_27.pb'}
frozen_graph_path = osp.join(frozen_graphs_parent_dir, frozen_graph_name[net])
inputs = ['0:0', '1:0']
outputs = {... | LPIPS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
<|body_0|>
def __call__(self, x, y, axis=None):
"... | stack_v2_sparse_classes_75kplus_train_071012 | 7,391 | permissive | [
{
"docstring": "Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips",
"name": "__init__",
"signature": "def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips')"
},
{
"docstring": "Computes LPIPS loss ... | 2 | stack_v2_sparse_classes_30k_train_040587 | Implement the Python class `LPIPS` described below.
Class description:
Implement the LPIPS class.
Method signatures and docstrings:
- def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'): Frozen graphs can be downloaded from the following link: http://rail.eecs.berke... | Implement the Python class `LPIPS` described below.
Class description:
Implement the LPIPS class.
Method signatures and docstrings:
- def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'): Frozen graphs can be downloaded from the following link: http://rail.eecs.berke... | a9a6643968a7b6b29cab3b53b73ab80d14fb32b7 | <|skeleton|>
class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
<|body_0|>
def __call__(self, x, y, axis=None):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LPIPS:
def __init__(self, net='alex_lin', frozen_graphs_parent_dir='/vulcanscratch/mmeshry/third_party/lpips'):
"""Frozen graphs can be downloaded from the following link: http://rail.eecs.berkeley.edu/models/lpips"""
frozen_graph_name = {'alex_lin': 'net-lin_alex_v0.1_27.pb', 'alex': 'net_ale... | the_stack_v2_python_sparse | losses/losses.py | czero69/lsr | train | 0 | |
00b694a13f5e540bcc922409d7975d78bdcccc98 | [
"assert self.signal in self.data\nassert len(self.axes) == 1\nassert self.axes[0] in self.data\ny = self.data[self.signal]\nx = self.data[self.axes[0]]\nts = self.timestamp()\ncharts.xy_plot(x, y, plotFile, title=self.plot_title(), subtitle=self.plot_subtitle(), xtitle=self.x_title(), ytitle=self.y_title(), xlog=se... | <|body_start_0|>
assert self.signal in self.data
assert len(self.axes) == 1
assert self.axes[0] in self.data
y = self.data[self.signal]
x = self.data[self.axes[0]]
ts = self.timestamp()
charts.xy_plot(x, y, plotFile, title=self.plot_title(), subtitle=self.plot_sub... | create a line plot | LinePlotter | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinePlotter:
"""create a line plot"""
def make_image(self, plotFile):
"""make MatPlotLib chart image from the SPEC scan :param str plotFile: name of image file to write"""
<|body_0|>
def plottable(self):
"""can this data be plotted as expected?"""
<|body_... | stack_v2_sparse_classes_75kplus_train_071013 | 24,832 | permissive | [
{
"docstring": "make MatPlotLib chart image from the SPEC scan :param str plotFile: name of image file to write",
"name": "make_image",
"signature": "def make_image(self, plotFile)"
},
{
"docstring": "can this data be plotted as expected?",
"name": "plottable",
"signature": "def plottabl... | 4 | null | Implement the Python class `LinePlotter` described below.
Class description:
create a line plot
Method signatures and docstrings:
- def make_image(self, plotFile): make MatPlotLib chart image from the SPEC scan :param str plotFile: name of image file to write
- def plottable(self): can this data be plotted as expecte... | Implement the Python class `LinePlotter` described below.
Class description:
create a line plot
Method signatures and docstrings:
- def make_image(self, plotFile): make MatPlotLib chart image from the SPEC scan :param str plotFile: name of image file to write
- def plottable(self): can this data be plotted as expecte... | 5ba73953f831eb823dda228f83dc0892474cce9d | <|skeleton|>
class LinePlotter:
"""create a line plot"""
def make_image(self, plotFile):
"""make MatPlotLib chart image from the SPEC scan :param str plotFile: name of image file to write"""
<|body_0|>
def plottable(self):
"""can this data be plotted as expected?"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinePlotter:
"""create a line plot"""
def make_image(self, plotFile):
"""make MatPlotLib chart image from the SPEC scan :param str plotFile: name of image file to write"""
assert self.signal in self.data
assert len(self.axes) == 1
assert self.axes[0] in self.data
y... | the_stack_v2_python_sparse | spec2nexus/specplot.py | prjemian/spec2nexus | train | 4 |
1310968a6e9c569296b7e3c1a1c48e8b38dc2fcb | [
"if any((not x.is_symbol() or not x.is_term() for x in formal_params)):\n raise PysmtValueError('Formal parameters of a function interpretation must be non-function symbols')\nif not allow_free_vars and (not function_body.get_free_variables().issubset(set(formal_params))):\n raise PysmtValueError('the body of... | <|body_start_0|>
if any((not x.is_symbol() or not x.is_term() for x in formal_params)):
raise PysmtValueError('Formal parameters of a function interpretation must be non-function symbols')
if not allow_free_vars and (not function_body.get_free_variables().issubset(set(formal_params))):
... | This class represents the interpretation of an uninterpreted function symbol and is intended to be used in substitutions. For example, let `phi` be the formula `phi = Equals(Function(f, [Int(2), Int(3)]), a)` where `a` is a Symbol of type INT and `f` is an uninterpreted function with two INT parameters that returns INT... | FunctionInterpretation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionInterpretation:
"""This class represents the interpretation of an uninterpreted function symbol and is intended to be used in substitutions. For example, let `phi` be the formula `phi = Equals(Function(f, [Int(2), Int(3)]), a)` where `a` is a Symbol of type INT and `f` is an uninterpreted... | stack_v2_sparse_classes_75kplus_train_071014 | 13,811 | permissive | [
{
"docstring": "Constructor, taking in input the list of formal parameters and the function body. The parameter `allow_free_vars` is used to skip the check that the function body has no free variables other than formal parameter and is used in the SmtLib model-validation utility because functions with uninterpr... | 2 | null | Implement the Python class `FunctionInterpretation` described below.
Class description:
This class represents the interpretation of an uninterpreted function symbol and is intended to be used in substitutions. For example, let `phi` be the formula `phi = Equals(Function(f, [Int(2), Int(3)]), a)` where `a` is a Symbol ... | Implement the Python class `FunctionInterpretation` described below.
Class description:
This class represents the interpretation of an uninterpreted function symbol and is intended to be used in substitutions. For example, let `phi` be the formula `phi = Equals(Function(f, [Int(2), Int(3)]), a)` where `a` is a Symbol ... | 8c79de2635936f980595f4a43ee20a7da7554844 | <|skeleton|>
class FunctionInterpretation:
"""This class represents the interpretation of an uninterpreted function symbol and is intended to be used in substitutions. For example, let `phi` be the formula `phi = Equals(Function(f, [Int(2), Int(3)]), a)` where `a` is a Symbol of type INT and `f` is an uninterpreted... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionInterpretation:
"""This class represents the interpretation of an uninterpreted function symbol and is intended to be used in substitutions. For example, let `phi` be the formula `phi = Equals(Function(f, [Int(2), Int(3)]), a)` where `a` is a Symbol of type INT and `f` is an uninterpreted function wit... | the_stack_v2_python_sparse | pysmt/substituter.py | pysmt/pysmt | train | 536 |
bc4609361c3cf4afec0a8f65fa06c956c45e5ba2 | [
"self.x = array_check(x)\nself.y = array_check(y)\nself._coef = None\nself._intercept = None\nself._pvalues = None\nself._f_statistics = None\nself._r_squared = None\nself.__m = OLS(self.y, sm.add_constant(self.x))",
"result = self.__m.fit()\nself._intercept, *self._coef = result.params\nself._pvalues = result.f_... | <|body_start_0|>
self.x = array_check(x)
self.y = array_check(y)
self._coef = None
self._intercept = None
self._pvalues = None
self._f_statistics = None
self._r_squared = None
self.__m = OLS(self.y, sm.add_constant(self.x))
<|end_body_0|>
<|body_start_1|>... | Linear regression for single variable or multi-variable. | LinearRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegression:
"""Linear regression for single variable or multi-variable."""
def __init__(self, x: array_like, y: array_like) -> None:
""":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like"""
<|body_0|>
def fit(self) -> LinearRegressionPar... | stack_v2_sparse_classes_75kplus_train_071015 | 4,947 | no_license | [
{
"docstring": ":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like",
"name": "__init__",
"signature": "def __init__(self, x: array_like, y: array_like) -> None"
},
{
"docstring": "Fit the self.x and self.y, then get fitting params. :return: class LinearRegressionParam... | 4 | stack_v2_sparse_classes_30k_val_002249 | Implement the Python class `LinearRegression` described below.
Class description:
Linear regression for single variable or multi-variable.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like) -> None: :param x: array_like N-D array with (n-sample, n-feature) :param y: array_like
- def ... | Implement the Python class `LinearRegression` described below.
Class description:
Linear regression for single variable or multi-variable.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like) -> None: :param x: array_like N-D array with (n-sample, n-feature) :param y: array_like
- def ... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class LinearRegression:
"""Linear regression for single variable or multi-variable."""
def __init__(self, x: array_like, y: array_like) -> None:
""":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like"""
<|body_0|>
def fit(self) -> LinearRegressionPar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearRegression:
"""Linear regression for single variable or multi-variable."""
def __init__(self, x: array_like, y: array_like) -> None:
""":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like"""
self.x = array_check(x)
self.y = array_check(y)
s... | the_stack_v2_python_sparse | statistics/regression.py | qliu0/PythonInAirSeaScience | train | 0 |
960f686dc343dd2093486594dfe09eab8fb96866 | [
"join_token = Token(word='JOIN', kind=Token.KEYWORD)\njoin_tokens = [Token(word='INNER', kind=Token.KEYWORD), Token(word='LEFT', kind=Token.KEYWORD), Token(word='RIGHT', kind=Token.KEYWORD), Token(word='FULL', kind=Token.KEYWORD), Token(word='CROSS', kind=Token.KEYWORD), Token(word='OUTER', kind=Token.KEYWORD), Tok... | <|body_start_0|>
join_token = Token(word='JOIN', kind=Token.KEYWORD)
join_tokens = [Token(word='INNER', kind=Token.KEYWORD), Token(word='LEFT', kind=Token.KEYWORD), Token(word='RIGHT', kind=Token.KEYWORD), Token(word='FULL', kind=Token.KEYWORD), Token(word='CROSS', kind=Token.KEYWORD), Token(word='OUTER... | KeywordJoinSplitter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordJoinSplitter:
def split_join(cls, tokens: List[Token]) -> Tuple[List[Token], List[List[Token]], List[Token]]:
"""Splits WHEN sequence Args: tokens: Returns:"""
<|body_0|>
def _split_condiction(cls, tokens: List[Token]) -> List[List[Token]]:
"""Splits ON or USI... | stack_v2_sparse_classes_75kplus_train_071016 | 27,650 | permissive | [
{
"docstring": "Splits WHEN sequence Args: tokens: Returns:",
"name": "split_join",
"signature": "def split_join(cls, tokens: List[Token]) -> Tuple[List[Token], List[List[Token]], List[Token]]"
},
{
"docstring": "Splits ON or USING sequence Args: tokens: Returns:",
"name": "_split_condiction... | 2 | stack_v2_sparse_classes_30k_test_002034 | Implement the Python class `KeywordJoinSplitter` described below.
Class description:
Implement the KeywordJoinSplitter class.
Method signatures and docstrings:
- def split_join(cls, tokens: List[Token]) -> Tuple[List[Token], List[List[Token]], List[Token]]: Splits WHEN sequence Args: tokens: Returns:
- def _split_con... | Implement the Python class `KeywordJoinSplitter` described below.
Class description:
Implement the KeywordJoinSplitter class.
Method signatures and docstrings:
- def split_join(cls, tokens: List[Token]) -> Tuple[List[Token], List[List[Token]], List[Token]]: Splits WHEN sequence Args: tokens: Returns:
- def _split_con... | ca6ec49149adf8597c39bf948af136146fcfe79b | <|skeleton|>
class KeywordJoinSplitter:
def split_join(cls, tokens: List[Token]) -> Tuple[List[Token], List[List[Token]], List[Token]]:
"""Splits WHEN sequence Args: tokens: Returns:"""
<|body_0|>
def _split_condiction(cls, tokens: List[Token]) -> List[List[Token]]:
"""Splits ON or USI... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeywordJoinSplitter:
def split_join(cls, tokens: List[Token]) -> Tuple[List[Token], List[List[Token]], List[Token]]:
"""Splits WHEN sequence Args: tokens: Returns:"""
join_token = Token(word='JOIN', kind=Token.KEYWORD)
join_tokens = [Token(word='INNER', kind=Token.KEYWORD), Token(word=... | the_stack_v2_python_sparse | src/sqlint/formatter/splitter.py | Matts966/sqlint | train | 0 | |
1977e5bc5f765b35a9cfaf773ad9cf978bd40b22 | [
"self.datum = data\nself.left = None\nself.right = None",
"if self:\n if value < self.datum:\n if self.left is None:\n self.left = Node(value)\n else:\n self.left + value\n elif value > self.datum:\n if self.right is None:\n self.right = Node(value)\n ... | <|body_start_0|>
self.datum = data
self.left = None
self.right = None
<|end_body_0|>
<|body_start_1|>
if self:
if value < self.datum:
if self.left is None:
self.left = Node(value)
else:
self.left + value... | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, data):
"""This constructor initializes the instance variable datum to the data and the instance variable left anf right to None."""
<|body_0|>
def __add__(self, value):
"""This magic method inserts a new item with self as a root, if the item ... | stack_v2_sparse_classes_75kplus_train_071017 | 4,969 | no_license | [
{
"docstring": "This constructor initializes the instance variable datum to the data and the instance variable left anf right to None.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "This magic method inserts a new item with self as a root, if the item is not alr... | 5 | stack_v2_sparse_classes_30k_train_023204 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, data): This constructor initializes the instance variable datum to the data and the instance variable left anf right to None.
- def __add__(self, value): This magic me... | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, data): This constructor initializes the instance variable datum to the data and the instance variable left anf right to None.
- def __add__(self, value): This magic me... | e773e87668af057c8adb1e012aa5d81f42c70f2a | <|skeleton|>
class Node:
def __init__(self, data):
"""This constructor initializes the instance variable datum to the data and the instance variable left anf right to None."""
<|body_0|>
def __add__(self, value):
"""This magic method inserts a new item with self as a root, if the item ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
def __init__(self, data):
"""This constructor initializes the instance variable datum to the data and the instance variable left anf right to None."""
self.datum = data
self.left = None
self.right = None
def __add__(self, value):
"""This magic method inserts ... | the_stack_v2_python_sparse | HW/HW5/hw5.py | SiddhantBhardwaj2018/ISTA-350 | train | 0 | |
babf5d48213be81d21e78465f294a3000127e498 | [
"super().__init__(model, batch_size, loss, goal, distance_metric, session, iteration_callback)\nself.rand_init_eps_ph = tf.placeholder(self.model.x_dtype, (self.batch_size,))\nself.rand_init_eps_var = tf.Variable(tf.zeros((self.batch_size,), dtype=self.model.x_dtype))\nd = np.prod(self.model.x_shape)\nif distance_m... | <|body_start_0|>
super().__init__(model, batch_size, loss, goal, distance_metric, session, iteration_callback)
self.rand_init_eps_ph = tf.placeholder(self.model.x_dtype, (self.batch_size,))
self.rand_init_eps_var = tf.Variable(tf.zeros((self.batch_size,), dtype=self.model.x_dtype))
d = n... | Projected Gradient Descent (PGD). A white-box iterative constraint-based method. Require a differentiable loss function and a ``ares.model.Classifier`` model. - Supported distance metric: ``l_2``, ``l_inf``. - Supported goal: ``t``, ``tm``, ``ut``. - References: https://arxiv.org/abs/1706.06083. | PGD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PGD:
"""Projected Gradient Descent (PGD). A white-box iterative constraint-based method. Require a differentiable loss function and a ``ares.model.Classifier`` model. - Supported distance metric: ``l_2``, ``l_inf``. - Supported goal: ``t``, ``tm``, ``ut``. - References: https://arxiv.org/abs/1706... | stack_v2_sparse_classes_75kplus_train_071018 | 3,690 | permissive | [
{
"docstring": "Initialize PGD. :param model: The model to attack. A ``ares.model.Classifier`` instance. :param batch_size: Batch size for the ``batch_attack()`` method. :param loss: The loss function to optimize. A ``ares.loss.Loss`` instance. :param goal: Adversarial goals. All supported values are ``'t'``, `... | 2 | null | Implement the Python class `PGD` described below.
Class description:
Projected Gradient Descent (PGD). A white-box iterative constraint-based method. Require a differentiable loss function and a ``ares.model.Classifier`` model. - Supported distance metric: ``l_2``, ``l_inf``. - Supported goal: ``t``, ``tm``, ``ut``. -... | Implement the Python class `PGD` described below.
Class description:
Projected Gradient Descent (PGD). A white-box iterative constraint-based method. Require a differentiable loss function and a ``ares.model.Classifier`` model. - Supported distance metric: ``l_2``, ``l_inf``. - Supported goal: ``t``, ``tm``, ``ut``. -... | 4bbd27458a5807382756492763d0bd2e935e7486 | <|skeleton|>
class PGD:
"""Projected Gradient Descent (PGD). A white-box iterative constraint-based method. Require a differentiable loss function and a ``ares.model.Classifier`` model. - Supported distance metric: ``l_2``, ``l_inf``. - Supported goal: ``t``, ``tm``, ``ut``. - References: https://arxiv.org/abs/1706... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PGD:
"""Projected Gradient Descent (PGD). A white-box iterative constraint-based method. Require a differentiable loss function and a ``ares.model.Classifier`` model. - Supported distance metric: ``l_2``, ``l_inf``. - Supported goal: ``t``, ``tm``, ``ut``. - References: https://arxiv.org/abs/1706.06083."""
... | the_stack_v2_python_sparse | ares/attack/pgd.py | LANCEREN/ares | train | 0 |
1cfb05798e3f9c366f41b06cb6d2def7b53fd43e | [
"try:\n return ujson.loads(data)\nexcept ValueError:\n return constants.ResponseConst.DEFAULT_ERROR_MESSAGE",
"formatted_data = self._unpack_response(data)\nif isinstance(formatted_data, dict):\n return formatted_data.get(constants.ResponseDataConst.DATA, formatted_data)\nelse:\n return formatted_data... | <|body_start_0|>
try:
return ujson.loads(data)
except ValueError:
return constants.ResponseConst.DEFAULT_ERROR_MESSAGE
<|end_body_0|>
<|body_start_1|>
formatted_data = self._unpack_response(data)
if isinstance(formatted_data, dict):
return formatted_d... | JSON data formatter class. | Json | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Json:
"""JSON data formatter class."""
def _unpack_response(self, data):
"""JSON decode"""
<|body_0|>
def _format_data(self, data):
"""Transform raw data from server into python native type."""
<|body_1|>
def _format_meta(self, data):
"""Tran... | stack_v2_sparse_classes_75kplus_train_071019 | 3,451 | permissive | [
{
"docstring": "JSON decode",
"name": "_unpack_response",
"signature": "def _unpack_response(self, data)"
},
{
"docstring": "Transform raw data from server into python native type.",
"name": "_format_data",
"signature": "def _format_data(self, data)"
},
{
"docstring": "Transform ... | 4 | stack_v2_sparse_classes_30k_train_017709 | Implement the Python class `Json` described below.
Class description:
JSON data formatter class.
Method signatures and docstrings:
- def _unpack_response(self, data): JSON decode
- def _format_data(self, data): Transform raw data from server into python native type.
- def _format_meta(self, data): Transform raw data ... | Implement the Python class `Json` described below.
Class description:
JSON data formatter class.
Method signatures and docstrings:
- def _unpack_response(self, data): JSON decode
- def _format_data(self, data): Transform raw data from server into python native type.
- def _format_meta(self, data): Transform raw data ... | eeaa8fa9c704b6f10d6e18ffa1766b619935c5db | <|skeleton|>
class Json:
"""JSON data formatter class."""
def _unpack_response(self, data):
"""JSON decode"""
<|body_0|>
def _format_data(self, data):
"""Transform raw data from server into python native type."""
<|body_1|>
def _format_meta(self, data):
"""Tran... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Json:
"""JSON data formatter class."""
def _unpack_response(self, data):
"""JSON decode"""
try:
return ujson.loads(data)
except ValueError:
return constants.ResponseConst.DEFAULT_ERROR_MESSAGE
def _format_data(self, data):
"""Transform raw data... | the_stack_v2_python_sparse | sendbee_api/formatter.py | kanchansharma06/sendbee-python-api-client | train | 0 |
32c71473b23a1945b6b487bab9f9315bfb2dc9e8 | [
"if not root:\n return ''\nqueue = collections.deque([root])\nretval = ''\nwhile queue:\n current = queue.popleft()\n if current != 'null':\n retval += str(current.val) + ','\n else:\n retval += 'null' + ','\n continue\n if current.left:\n queue.append(current.left)\n e... | <|body_start_0|>
if not root:
return ''
queue = collections.deque([root])
retval = ''
while queue:
current = queue.popleft()
if current != 'null':
retval += str(current.val) + ','
else:
retval += 'null' + ','... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_071020 | 1,942 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_test_000500 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | bbfee57ae89d23cd4f4132fbb62d8931ea654a0e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
queue = collections.deque([root])
retval = ''
while queue:
current = queue.popleft()
if current != 'nul... | the_stack_v2_python_sparse | Algorithms/Leetcode/449 - Serialize and Deserialize BST.py | timpark0807/self-taught-swe | train | 1 | |
54355bce51fe8b3075b380820570c5a6d6ce38fe | [
"self.seq_indexer = defaultdict(set)\nself.seq_store = list()\nself.seq2words = defaultdict(set)",
"self.seq_store.append(sequence)\nseq_index = len(self.seq_store) - 1\nfor i in range(len(sequence) - 2):\n word = sequence[i:i + 3]\n self.seq_indexer[word].add(seq_index)\n self.seq2words[sequence].add(wo... | <|body_start_0|>
self.seq_indexer = defaultdict(set)
self.seq_store = list()
self.seq2words = defaultdict(set)
<|end_body_0|>
<|body_start_1|>
self.seq_store.append(sequence)
seq_index = len(self.seq_store) - 1
for i in range(len(sequence) - 2):
word = sequen... | BlastDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlastDB:
def __init__(self):
"""Initialize the BlastDB class."""
<|body_0|>
def add_sequence(self, sequence):
"""Add a sequence to the database. :param sequence: a protein sequence (string)."""
<|body_1|>
def get_sequences(self, word):
"""Return ... | stack_v2_sparse_classes_75kplus_train_071021 | 21,782 | no_license | [
{
"docstring": "Initialize the BlastDB class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add a sequence to the database. :param sequence: a protein sequence (string).",
"name": "add_sequence",
"signature": "def add_sequence(self, sequence)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_035705 | Implement the Python class `BlastDB` described below.
Class description:
Implement the BlastDB class.
Method signatures and docstrings:
- def __init__(self): Initialize the BlastDB class.
- def add_sequence(self, sequence): Add a sequence to the database. :param sequence: a protein sequence (string).
- def get_sequen... | Implement the Python class `BlastDB` described below.
Class description:
Implement the BlastDB class.
Method signatures and docstrings:
- def __init__(self): Initialize the BlastDB class.
- def add_sequence(self, sequence): Add a sequence to the database. :param sequence: a protein sequence (string).
- def get_sequen... | be1e90c25c641d353fa8f3d16475fdb05d00f1d4 | <|skeleton|>
class BlastDB:
def __init__(self):
"""Initialize the BlastDB class."""
<|body_0|>
def add_sequence(self, sequence):
"""Add a sequence to the database. :param sequence: a protein sequence (string)."""
<|body_1|>
def get_sequences(self, word):
"""Return ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlastDB:
def __init__(self):
"""Initialize the BlastDB class."""
self.seq_indexer = defaultdict(set)
self.seq_store = list()
self.seq2words = defaultdict(set)
def add_sequence(self, sequence):
"""Add a sequence to the database. :param sequence: a protein sequence (... | the_stack_v2_python_sparse | pp1cs2020exercise5-ga24yek/blast.py | anhmt90/tum--ss20--protein-prediction-1-for-cs | train | 0 | |
81e1e70ebbf3ab460729c9c23c2f56229b85bf58 | [
"length = len(seq)\nfor cur_len in range(length - 1, 0, -1):\n exchange = False\n for i in range(cur_len):\n if seq[i + 1] < seq[i]:\n seq[i], seq[i + 1] = (seq[i + 1], seq[i])\n exchange = True\n if not exchange:\n break\nreturn seq",
"length = len(seq)\nfor cur_len i... | <|body_start_0|>
length = len(seq)
for cur_len in range(length - 1, 0, -1):
exchange = False
for i in range(cur_len):
if seq[i + 1] < seq[i]:
seq[i], seq[i + 1] = (seq[i + 1], seq[i])
exchange = True
if not excha... | SortIntegrate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SortIntegrate:
def bubble(seq):
"""反向遍历,两两比较,比较的同时伴随则数据交换 :param seq: :return:"""
<|body_0|>
def select(seq):
"""两两对比,每次记录最大值位置,每趟遍历的最后一次比较时触发数据交换 :param seq: :return:"""
<|body_1|>
def insert(seq):
"""类比扑克,【有序列表 | 无序列表】 正向遍历无序列表元素a(index:[1,...,... | stack_v2_sparse_classes_75kplus_train_071022 | 3,354 | no_license | [
{
"docstring": "反向遍历,两两比较,比较的同时伴随则数据交换 :param seq: :return:",
"name": "bubble",
"signature": "def bubble(seq)"
},
{
"docstring": "两两对比,每次记录最大值位置,每趟遍历的最后一次比较时触发数据交换 :param seq: :return:",
"name": "select",
"signature": "def select(seq)"
},
{
"docstring": "类比扑克,【有序列表 | 无序列表】 正向遍历无序... | 4 | null | Implement the Python class `SortIntegrate` described below.
Class description:
Implement the SortIntegrate class.
Method signatures and docstrings:
- def bubble(seq): 反向遍历,两两比较,比较的同时伴随则数据交换 :param seq: :return:
- def select(seq): 两两对比,每次记录最大值位置,每趟遍历的最后一次比较时触发数据交换 :param seq: :return:
- def insert(seq): 类比扑克,【有序列表 | 无... | Implement the Python class `SortIntegrate` described below.
Class description:
Implement the SortIntegrate class.
Method signatures and docstrings:
- def bubble(seq): 反向遍历,两两比较,比较的同时伴随则数据交换 :param seq: :return:
- def select(seq): 两两对比,每次记录最大值位置,每趟遍历的最后一次比较时触发数据交换 :param seq: :return:
- def insert(seq): 类比扑克,【有序列表 | 无... | a2d9a71765624cfc126bfff93198c2cc7d610f86 | <|skeleton|>
class SortIntegrate:
def bubble(seq):
"""反向遍历,两两比较,比较的同时伴随则数据交换 :param seq: :return:"""
<|body_0|>
def select(seq):
"""两两对比,每次记录最大值位置,每趟遍历的最后一次比较时触发数据交换 :param seq: :return:"""
<|body_1|>
def insert(seq):
"""类比扑克,【有序列表 | 无序列表】 正向遍历无序列表元素a(index:[1,...,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SortIntegrate:
def bubble(seq):
"""反向遍历,两两比较,比较的同时伴随则数据交换 :param seq: :return:"""
length = len(seq)
for cur_len in range(length - 1, 0, -1):
exchange = False
for i in range(cur_len):
if seq[i + 1] < seq[i]:
seq[i], seq[i + 1] ... | the_stack_v2_python_sparse | abstract/sorts/sort_integrate.py | freshklauser/datastructure_algorithm | train | 0 | |
7efc8c327d1fbab1df88f7a28a4f699ea3595ddd | [
"for album_id in album_ids:\n response = music_service.delete_album(album_id=album_id.encode('utf-8'))\n logging.info('Deleted album %s: %s', album_id, response.album_deleted)",
"action = self.request.params['action']\nartist_id = self.request.params['artist_id']\nalbum_ids = [a for a in self.request.get_al... | <|body_start_0|>
for album_id in album_ids:
response = music_service.delete_album(album_id=album_id.encode('utf-8'))
logging.info('Deleted album %s: %s', album_id, response.album_deleted)
<|end_body_0|>
<|body_start_1|>
action = self.request.params['action']
artist_id = ... | Album action handler. | AlbumActionHandler | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbumActionHandler:
"""Album action handler."""
def __delete_albums(self, album_ids):
"""Delete album action. Args: album_ids: Iterable of album ids to delete."""
<|body_0|>
def post(self):
"""General purpose action handler. Operates on a all album ids provided b... | stack_v2_sparse_classes_75kplus_train_071023 | 11,524 | permissive | [
{
"docstring": "Delete album action. Args: album_ids: Iterable of album ids to delete.",
"name": "__delete_albums",
"signature": "def __delete_albums(self, album_ids)"
},
{
"docstring": "General purpose action handler. Operates on a all album ids provided by the album_id parameters. Parameters: ... | 2 | null | Implement the Python class `AlbumActionHandler` described below.
Class description:
Album action handler.
Method signatures and docstrings:
- def __delete_albums(self, album_ids): Delete album action. Args: album_ids: Iterable of album ids to delete.
- def post(self): General purpose action handler. Operates on a all... | Implement the Python class `AlbumActionHandler` described below.
Class description:
Album action handler.
Method signatures and docstrings:
- def __delete_albums(self, album_ids): Delete album action. Args: album_ids: Iterable of album ids to delete.
- def post(self): General purpose action handler. Operates on a all... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class AlbumActionHandler:
"""Album action handler."""
def __delete_albums(self, album_ids):
"""Delete album action. Args: album_ids: Iterable of album ids to delete."""
<|body_0|>
def post(self):
"""General purpose action handler. Operates on a all album ids provided b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlbumActionHandler:
"""Album action handler."""
def __delete_albums(self, album_ids):
"""Delete album action. Args: album_ids: Iterable of album ids to delete."""
for album_id in album_ids:
response = music_service.delete_album(album_id=album_id.encode('utf-8'))
lo... | the_stack_v2_python_sparse | third_party/catapult/third_party/gsutil/third_party/protorpc/demos/tunes_db/client/main.py | metux/chromium-suckless | train | 5 |
9cf76c47305a23838024b467811929ce87c04012 | [
"argument_group.add_argument('--extract_winreg_binary', '--extract-winreg-binary', dest='extract_winreg_binary', action='store_true', default=False, help='Extract binary Windows Registry values. WARNING: This can make processing significantly slower.')\nargument_group.add_argument('--preferred_year', '--preferred-y... | <|body_start_0|>
argument_group.add_argument('--extract_winreg_binary', '--extract-winreg-binary', dest='extract_winreg_binary', action='store_true', default=False, help='Extract binary Windows Registry values. WARNING: This can make processing significantly slower.')
argument_group.add_argument('--pref... | Extraction CLI arguments helper. | ExtractionArgumentsHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractionArgumentsHelper:
"""Extraction CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper s... | stack_v2_sparse_classes_75kplus_train_071024 | 2,843 | permissive | [
{
"docstring": "Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.",
"name": "AddArgum... | 2 | null | Implement the Python class `ExtractionArgumentsHelper` described below.
Class description:
Extraction CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object an... | Implement the Python class `ExtractionArgumentsHelper` described below.
Class description:
Extraction CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments to an argument group. This function takes an argument parser or an argument group object an... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ExtractionArgumentsHelper:
"""Extraction CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtractionArgumentsHelper:
"""Extraction CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args... | the_stack_v2_python_sparse | plaso/cli/helpers/extraction.py | log2timeline/plaso | train | 1,506 |
a3b8b74717cdd078cf65a9dd17ac0b11f75cf37a | [
"col_sum = col_filter if col_sum is None else col_sum\ndf_filted = df.loc[(df[col_filter] >= float(min_v)) & (df[col_filter] <= float(max_v))]\nserie = df_filted[col_sum].sum()\nreturn serie",
"if collumn is None or _filter is None:\n return group.apply(lambda x: x.shape[0])\nserie = group.apply(lambda x: x[x[... | <|body_start_0|>
col_sum = col_filter if col_sum is None else col_sum
df_filted = df.loc[(df[col_filter] >= float(min_v)) & (df[col_filter] <= float(max_v))]
serie = df_filted[col_sum].sum()
return serie
<|end_body_0|>
<|body_start_1|>
if collumn is None or _filter is None:
... | Analysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Analysis:
def sum_interval(self, df, col_filter, min_v, max_v, col_sum=None):
"""Soma os valores contindo no intervalo fechado min_v e max_v."""
<|body_0|>
def count(self, group, collumn=None, _filter=None):
"""Conta a quantidade de linhas de cada dataframe de um gro... | stack_v2_sparse_classes_75kplus_train_071025 | 3,159 | no_license | [
{
"docstring": "Soma os valores contindo no intervalo fechado min_v e max_v.",
"name": "sum_interval",
"signature": "def sum_interval(self, df, col_filter, min_v, max_v, col_sum=None)"
},
{
"docstring": "Conta a quantidade de linhas de cada dataframe de um groupby. Conta a quantidade linhas de c... | 3 | stack_v2_sparse_classes_30k_train_042624 | Implement the Python class `Analysis` described below.
Class description:
Implement the Analysis class.
Method signatures and docstrings:
- def sum_interval(self, df, col_filter, min_v, max_v, col_sum=None): Soma os valores contindo no intervalo fechado min_v e max_v.
- def count(self, group, collumn=None, _filter=No... | Implement the Python class `Analysis` described below.
Class description:
Implement the Analysis class.
Method signatures and docstrings:
- def sum_interval(self, df, col_filter, min_v, max_v, col_sum=None): Soma os valores contindo no intervalo fechado min_v e max_v.
- def count(self, group, collumn=None, _filter=No... | 5d19d09f6729ae4518fd57861ce5766f06d795a1 | <|skeleton|>
class Analysis:
def sum_interval(self, df, col_filter, min_v, max_v, col_sum=None):
"""Soma os valores contindo no intervalo fechado min_v e max_v."""
<|body_0|>
def count(self, group, collumn=None, _filter=None):
"""Conta a quantidade de linhas de cada dataframe de um gro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Analysis:
def sum_interval(self, df, col_filter, min_v, max_v, col_sum=None):
"""Soma os valores contindo no intervalo fechado min_v e max_v."""
col_sum = col_filter if col_sum is None else col_sum
df_filted = df.loc[(df[col_filter] >= float(min_v)) & (df[col_filter] <= float(max_v))]
... | the_stack_v2_python_sparse | src/submission/analysis/analysis/analysis.py | PETComputacaoUFPR/adega | train | 2 | |
aeda58e49a488dbebde457d4dc86fa231f11d5e2 | [
"self.warmup_epochs = warmup_epochs\nself.total_epochs = total_epochs\nself.warmup_start_lr = warmup_start_lr\nself.start_lr = start_lr\nself.end_lr = end_lr\nself.cycles = cycles\nsuper(WarmupCosineScheduler, self).__init__(learning_rate, last_epoch, verbose)",
"if self.last_epoch < self.warmup_epochs:\n val ... | <|body_start_0|>
self.warmup_epochs = warmup_epochs
self.total_epochs = total_epochs
self.warmup_start_lr = warmup_start_lr
self.start_lr = start_lr
self.end_lr = end_lr
self.cycles = cycles
super(WarmupCosineScheduler, self).__init__(learning_rate, last_epoch, ve... | Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_lr" over remaining "total_epochs - warmup_epochs" Attributes: learning_rate: the starting... | WarmupCosineScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarmupCosineScheduler:
"""Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_lr" over remaining "total_epochs - warmu... | stack_v2_sparse_classes_75kplus_train_071026 | 8,472 | permissive | [
{
"docstring": "init WarmupCosineScheduler",
"name": "__init__",
"signature": "def __init__(self, learning_rate, warmup_start_lr, start_lr, end_lr, warmup_epochs, total_epochs, cycles=0.5, last_epoch=-1, verbose=False)"
},
{
"docstring": "return lr value",
"name": "get_lr",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_046771 | Implement the Python class `WarmupCosineScheduler` described below.
Class description:
Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_l... | Implement the Python class `WarmupCosineScheduler` described below.
Class description:
Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_l... | c90a6c8dc3787e69cef3a37b9a260bd59eeff1f7 | <|skeleton|>
class WarmupCosineScheduler:
"""Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_lr" over remaining "total_epochs - warmu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WarmupCosineScheduler:
"""Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_lr" over remaining "total_epochs - warmup_epochs" Att... | the_stack_v2_python_sparse | object_detection/DETR/utils.py | Dongsheng-Bi/PaddleViT | train | 1 |
ba1e52215174e2827076884f20e6d9ac1625287c | [
"if not matrix:\n return False\nrow = 0\nmaxrow = len(matrix) - 1\ncol = len(matrix[0]) - 1\nwhile col >= 0 and row <= maxrow:\n if matrix[row][col] == target:\n return True\n elif target > matrix[row][col]:\n row += 1\n else:\n target < matrix[row][col]\n col -= 1\nreturn Fa... | <|body_start_0|>
if not matrix:
return False
row = 0
maxrow = len(matrix) - 1
col = len(matrix[0]) - 1
while col >= 0 and row <= maxrow:
if matrix[row][col] == target:
return True
elif target > matrix[row][col]:
... | 首先从行号最小列号最大(右上角)的数开始比较,若目标较小,说明当前遍历的数较大,则使列号减一,减小当前遍历的数; 若目标较大,说明当前遍历的数较小,则使行号加一,增大当前遍历的数。 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""首先从行号最小列号最大(右上角)的数开始比较,若目标较小,说明当前遍历的数较大,则使列号减一,减小当前遍历的数; 若目标较大,说明当前遍历的数较小,则使行号加一,增大当前遍历的数。"""
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
... | stack_v2_sparse_classes_75kplus_train_071027 | 2,633 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix1",
"signature": "def searchMatrix1(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def sear... | 2 | stack_v2_sparse_classes_30k_train_004607 | Implement the Python class `Solution` described below.
Class description:
首先从行号最小列号最大(右上角)的数开始比较,若目标较小,说明当前遍历的数较大,则使列号减一,减小当前遍历的数; 若目标较大,说明当前遍历的数较小,则使行号加一,增大当前遍历的数。
Method signatures and docstrings:
- def searchMatrix1(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMat... | Implement the Python class `Solution` described below.
Class description:
首先从行号最小列号最大(右上角)的数开始比较,若目标较小,说明当前遍历的数较大,则使列号减一,减小当前遍历的数; 若目标较大,说明当前遍历的数较小,则使行号加一,增大当前遍历的数。
Method signatures and docstrings:
- def searchMatrix1(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMat... | b8f705a77cfcdb7d498d3422f9c4ee88fd61a3b3 | <|skeleton|>
class Solution:
"""首先从行号最小列号最大(右上角)的数开始比较,若目标较小,说明当前遍历的数较大,则使列号减一,减小当前遍历的数; 若目标较大,说明当前遍历的数较小,则使行号加一,增大当前遍历的数。"""
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""首先从行号最小列号最大(右上角)的数开始比较,若目标较小,说明当前遍历的数较大,则使列号减一,减小当前遍历的数; 若目标较大,说明当前遍历的数较小,则使行号加一,增大当前遍历的数。"""
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
row = 0
maxrow = l... | the_stack_v2_python_sparse | LeetcodePython/Base/算法面试题2018/1-3-搜索二维矩阵 II.py | selonsy/leetcode | train | 0 |
f1e6740f2196bbc526164dd74e577c9007211703 | [
"if len(matrix) == 0:\n return False\nm, n = (len(matrix), len(matrix[0]))\nrow, col = (0, n - 1)\nwhile m > row and col >= 0:\n pointer = matrix[row][col]\n if target == pointer:\n return True\n elif target < pointer:\n col -= 1\n else:\n row += 1\nreturn False",
"for row in m... | <|body_start_0|>
if len(matrix) == 0:
return False
m, n = (len(matrix), len(matrix[0]))
row, col = (0, n - 1)
while m > row and col >= 0:
pointer = matrix[row][col]
if target == pointer:
return True
elif target < pointer:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrixCheat(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_071028 | 1,025 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrixCheat",
"signature": "def se... | 2 | stack_v2_sparse_classes_30k_train_003744 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrixCheat(self, matrix, target): :type matrix: List[List[int]] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrixCheat(self, matrix, target): :type matrix: List[List[int]] ... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrixCheat(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if len(matrix) == 0:
return False
m, n = (len(matrix), len(matrix[0]))
row, col = (0, n - 1)
while m > row and col >= 0:
pointer ... | the_stack_v2_python_sparse | cs_notes/arrays/search_a_2d_matrix_ii.py | hwc1824/LeetCodeSolution | train | 0 | |
bdeeae3d262cf069d26a89adb49b3094b82d7944 | [
"http_auth = request.META['HTTP_AUTHORIZATION']\nparts = http_auth.split(' ')\nif parts[0] != 'token':\n return None\nif len(parts) != 2:\n logger.warning('WebAPITokenAuthBackend: Missing token in HTTP_AUTHORIZATION header %s', http_auth, extra={'request': request})\n return None\nreturn {'token': parts[1]... | <|body_start_0|>
http_auth = request.META['HTTP_AUTHORIZATION']
parts = http_auth.split(' ')
if parts[0] != 'token':
return None
if len(parts) != 2:
logger.warning('WebAPITokenAuthBackend: Missing token in HTTP_AUTHORIZATION header %s', http_auth, extra={'request'... | Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user. | WebAPITokenAuthBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebAPITokenAuthBackend:
"""Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user."""
def get_credentials(self, request: H... | stack_v2_sparse_classes_75kplus_train_071029 | 12,956 | no_license | [
{
"docstring": "Return credentials for the token. If the request is attempting to authenticate with a token, this will return a dictionary containing the token in a ``token`` key. Args: request (HttpRequest): The HTTP request from the client. Returns: dict: A dictionary containing the token in a ``token`` key, ... | 3 | stack_v2_sparse_classes_30k_train_022361 | Implement the Python class `WebAPITokenAuthBackend` described below.
Class description:
Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user.
Meth... | Implement the Python class `WebAPITokenAuthBackend` described below.
Class description:
Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user.
Meth... | 99ea69d80a3a393b0da4da3152ef26e808dd8487 | <|skeleton|>
class WebAPITokenAuthBackend:
"""Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user."""
def get_credentials(self, request: H... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WebAPITokenAuthBackend:
"""Authenticates users using their generated API token. This will check the ``HTTP_AUTHORIZATION`` header for a ``token <token>`` value. If found, it will attempt to find the user that owns the token, and authenticate that user."""
def get_credentials(self, request: HttpRequest) -... | the_stack_v2_python_sparse | djblets/webapi/auth/backends/api_tokens.py | chipx86/djblets | train | 2 |
5ea887a98a8511e81424f3e651397f271d6b589c | [
"npts = len(x)\nmat = np.zeros((3, npts))\nmat[1, 1:-1] = (x[2:] - x[0:-2]) / 3.0\nmat[2, 0:-2] = (x[1:-1] - x[0:-2]) / 6.0\nmat[0, 2:] = (x[2:] - x[1:-1]) / 6.0\nbb = np.zeros(npts)\nbb[1:-1] = (y[2:] - y[1:-1]) / (x[2:] - x[1:-1]) - (y[1:-1] - y[0:-2]) / (x[1:-1] - x[0:-2])\nif yp is None:\n mat[1, 0] = 1.0\n ... | <|body_start_0|>
npts = len(x)
mat = np.zeros((3, npts))
mat[1, 1:-1] = (x[2:] - x[0:-2]) / 3.0
mat[2, 0:-2] = (x[1:-1] - x[0:-2]) / 6.0
mat[0, 2:] = (x[2:] - x[1:-1]) / 6.0
bb = np.zeros(npts)
bb[1:-1] = (y[2:] - y[1:-1]) / (x[2:] - x[1:-1]) - (y[1:-1] - y[0:-2])... | CubicSpline interpolation class. | CubicSpline | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CubicSpline:
"""CubicSpline interpolation class."""
def __init__(self, x, y, yp=None, fixextrap=False):
"""Instantiate a CubicSpline object. Parameters ---------- x: `np.array` Float array of node positions y: `np.array` Float array of node values yp: `str` Type of spline. Default is... | stack_v2_sparse_classes_75kplus_train_071030 | 36,307 | permissive | [
{
"docstring": "Instantiate a CubicSpline object. Parameters ---------- x: `np.array` Float array of node positions y: `np.array` Float array of node values yp: `str` Type of spline. Default is None, which is \"natural\" fixextrap: `bool`, optional Fix the extrapolation at the end of the node positions. Default... | 3 | null | Implement the Python class `CubicSpline` described below.
Class description:
CubicSpline interpolation class.
Method signatures and docstrings:
- def __init__(self, x, y, yp=None, fixextrap=False): Instantiate a CubicSpline object. Parameters ---------- x: `np.array` Float array of node positions y: `np.array` Float ... | Implement the Python class `CubicSpline` described below.
Class description:
CubicSpline interpolation class.
Method signatures and docstrings:
- def __init__(self, x, y, yp=None, fixextrap=False): Instantiate a CubicSpline object. Parameters ---------- x: `np.array` Float array of node positions y: `np.array` Float ... | d3a8b432c2f3a20aa518a7781c0f2aa315624855 | <|skeleton|>
class CubicSpline:
"""CubicSpline interpolation class."""
def __init__(self, x, y, yp=None, fixextrap=False):
"""Instantiate a CubicSpline object. Parameters ---------- x: `np.array` Float array of node positions y: `np.array` Float array of node values yp: `str` Type of spline. Default is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CubicSpline:
"""CubicSpline interpolation class."""
def __init__(self, x, y, yp=None, fixextrap=False):
"""Instantiate a CubicSpline object. Parameters ---------- x: `np.array` Float array of node positions y: `np.array` Float array of node values yp: `str` Type of spline. Default is None, which ... | the_stack_v2_python_sparse | redmapper/utilities.py | erykoff/redmapper | train | 20 |
1552058a422fc9bce65570bbf0469dc7c96cdb92 | [
"post = get_post(uuid)\nif not post:\n logging.error('Could not find post. UUID: %s' % uuid)\n self.error(404)\n return\nresponse = post.to_obj()\nself.respondJSON(response.get('value'), response_key=response.get('key'))",
"params = cgi.parse_qsl(self.request.body)\nself.request.PUT = webob.MultiDict(par... | <|body_start_0|>
post = get_post(uuid)
if not post:
logging.error('Could not find post. UUID: %s' % uuid)
self.error(404)
return
response = post.to_obj()
self.respondJSON(response.get('value'), response_key=response.get('key'))
<|end_body_0|>
<|body_s... | A resource for accessing posts using JSON | ReEngagePostJSONHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReEngagePostJSONHandler:
"""A resource for accessing posts using JSON"""
def get(self, uuid):
"""Get all details for a given post"""
<|body_0|>
def put(self, uuid):
"""Update the details of a post. check ReEngageQueueHandler.put for post creation."""
<|bo... | stack_v2_sparse_classes_75kplus_train_071031 | 12,697 | no_license | [
{
"docstring": "Get all details for a given post",
"name": "get",
"signature": "def get(self, uuid)"
},
{
"docstring": "Update the details of a post. check ReEngageQueueHandler.put for post creation.",
"name": "put",
"signature": "def put(self, uuid)"
},
{
"docstring": "Delete an... | 3 | stack_v2_sparse_classes_30k_train_017206 | Implement the Python class `ReEngagePostJSONHandler` described below.
Class description:
A resource for accessing posts using JSON
Method signatures and docstrings:
- def get(self, uuid): Get all details for a given post
- def put(self, uuid): Update the details of a post. check ReEngageQueueHandler.put for post crea... | Implement the Python class `ReEngagePostJSONHandler` described below.
Class description:
A resource for accessing posts using JSON
Method signatures and docstrings:
- def get(self, uuid): Get all details for a given post
- def put(self, uuid): Update the details of a post. check ReEngageQueueHandler.put for post crea... | d1e046d5b7bf1ba0febb337a31ec04f5888fb341 | <|skeleton|>
class ReEngagePostJSONHandler:
"""A resource for accessing posts using JSON"""
def get(self, uuid):
"""Get all details for a given post"""
<|body_0|>
def put(self, uuid):
"""Update the details of a post. check ReEngageQueueHandler.put for post creation."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReEngagePostJSONHandler:
"""A resource for accessing posts using JSON"""
def get(self, uuid):
"""Get all details for a given post"""
post = get_post(uuid)
if not post:
logging.error('Could not find post. UUID: %s' % uuid)
self.error(404)
return
... | the_stack_v2_python_sparse | apps/reengage/resources.py | bbarclay/Willet-Referrals | train | 0 |
830b71a39965f54131cfa3f2d3f16fa82f413651 | [
"start = sourceid * (self.nshape + self.nfilters)\ninds = range(start, start + self.nshape)\ninds.insert(0, start + self.nshape + filterid)\nreturn inds",
"t = np.array(theta).copy()\nif len(t) == 3:\n t = np.append(t, np.array([1.0, 0.0, 0.0, 0.0]))\nelif len(t) == 5:\n t = np.append(np.array(t), np.array(... | <|body_start_0|>
start = sourceid * (self.nshape + self.nfilters)
inds = range(start, start + self.nshape)
inds.insert(0, start + self.nshape + filterid)
return inds
<|end_body_0|>
<|body_start_1|>
t = np.array(theta).copy()
if len(t) == 3:
t = np.append(t, n... | The Scene holds the sources and provides the mapping between a giant 1-d array of parameters and the parameters of each source in each band/image | Scene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scene:
"""The Scene holds the sources and provides the mapping between a giant 1-d array of parameters and the parameters of each source in each band/image"""
def param_indices(self, sourceid, filterid):
"""Get the indices of the relevant parameters in the giant Theta vector. :return... | stack_v2_sparse_classes_75kplus_train_071032 | 8,752 | no_license | [
{
"docstring": "Get the indices of the relevant parameters in the giant Theta vector. :returns theta: An array with elements [flux, (shape_params)]",
"name": "param_indices",
"signature": "def param_indices(self, sourceid, filterid)"
},
{
"docstring": "Set the parameters of a source",
"name"... | 3 | stack_v2_sparse_classes_30k_train_016569 | Implement the Python class `Scene` described below.
Class description:
The Scene holds the sources and provides the mapping between a giant 1-d array of parameters and the parameters of each source in each band/image
Method signatures and docstrings:
- def param_indices(self, sourceid, filterid): Get the indices of t... | Implement the Python class `Scene` described below.
Class description:
The Scene holds the sources and provides the mapping between a giant 1-d array of parameters and the parameters of each source in each band/image
Method signatures and docstrings:
- def param_indices(self, sourceid, filterid): Get the indices of t... | a14b553006bd7057742deb9b3d63ad667a6b0e35 | <|skeleton|>
class Scene:
"""The Scene holds the sources and provides the mapping between a giant 1-d array of parameters and the parameters of each source in each band/image"""
def param_indices(self, sourceid, filterid):
"""Get the indices of the relevant parameters in the giant Theta vector. :return... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scene:
"""The Scene holds the sources and provides the mapping between a giant 1-d array of parameters and the parameters of each source in each band/image"""
def param_indices(self, sourceid, filterid):
"""Get the indices of the relevant parameters in the giant Theta vector. :returns theta: An a... | the_stack_v2_python_sparse | demo/boneyard/demo_sim_ps_twostamps.py | lgarrison/forcepho | train | 0 |
48966475e1d1fa8435d560a77c1235ed4d73ef1c | [
"super().__init__(experiment_name, train_func, **kwargs)\nself.end_train_func = end_train_func\nself.delay = True",
"if isinstance(models, Recorder):\n models = [models]\nif end_train_func is None:\n end_train_func = self.end_train_func\nif experiment_name is None:\n experiment_name = self.experiment_nam... | <|body_start_0|>
super().__init__(experiment_name, train_func, **kwargs)
self.end_train_func = end_train_func
self.delay = True
<|end_body_0|>
<|body_start_1|>
if isinstance(models, Recorder):
models = [models]
if end_train_func is None:
end_train_func = ... | A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting. | DelayTrainerR | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayTrainerR:
"""A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting."""
def __init__(self, experiment_name: str=None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_071033 | 22,767 | permissive | [
{
"docstring": "Init TrainerRM. Args: experiment_name (str): the default name of experiment. train_func (Callable, optional): default train method. Defaults to `begin_task_train`. end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`.",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_test_000279 | Implement the Python class `DelayTrainerR` described below.
Class description:
A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting.
Method signatures and docstrings:
- def __init__(self, experiment_name: str=None, tra... | Implement the Python class `DelayTrainerR` described below.
Class description:
A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting.
Method signatures and docstrings:
- def __init__(self, experiment_name: str=None, tra... | 4c30e5827b74bcc45f14cf3ae0c1715459ed09ae | <|skeleton|>
class DelayTrainerR:
"""A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting."""
def __init__(self, experiment_name: str=None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DelayTrainerR:
"""A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting."""
def __init__(self, experiment_name: str=None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs):
"""In... | the_stack_v2_python_sparse | qlib/model/trainer.py | microsoft/qlib | train | 12,822 |
9ad1f5f42c6118578b47c7c484af87f4c645de9d | [
"super(colorFrame, self).__init__(parent)\nself.kind = number\nself.hexadecimal = QLabel('', self)\nself.color = QColor(red, green, blue)\nself.update_color(self.color)\nvertical_layout = QVBoxLayout()\nvertical_layout.addWidget(self.hexadecimal)\nvertical_layout.setAlignment(QtCore.Qt.AlignCenter)\nself.setFrameSt... | <|body_start_0|>
super(colorFrame, self).__init__(parent)
self.kind = number
self.hexadecimal = QLabel('', self)
self.color = QColor(red, green, blue)
self.update_color(self.color)
vertical_layout = QVBoxLayout()
vertical_layout.addWidget(self.hexadecimal)
... | colorFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class colorFrame:
def __init__(self, parent, number, red, green, blue):
"""Create a customizable QFrame that reacts to a click by opening a QColorDialog :param parent: Widget parent of this frame :param number: 1 if it's Color Light, 2 if it's Shadow Color :param red: Red value to set on a new... | stack_v2_sparse_classes_75kplus_train_071034 | 21,305 | no_license | [
{
"docstring": "Create a customizable QFrame that reacts to a click by opening a QColorDialog :param parent: Widget parent of this frame :param number: 1 if it's Color Light, 2 if it's Shadow Color :param red: Red value to set on a new QColor :param green: Green value to set on a new QColor :param blue: Blue va... | 2 | stack_v2_sparse_classes_30k_train_037247 | Implement the Python class `colorFrame` described below.
Class description:
Implement the colorFrame class.
Method signatures and docstrings:
- def __init__(self, parent, number, red, green, blue): Create a customizable QFrame that reacts to a click by opening a QColorDialog :param parent: Widget parent of this frame... | Implement the Python class `colorFrame` described below.
Class description:
Implement the colorFrame class.
Method signatures and docstrings:
- def __init__(self, parent, number, red, green, blue): Create a customizable QFrame that reacts to a click by opening a QColorDialog :param parent: Widget parent of this frame... | 45301c31814e87a6e5a28d857e9b2ef6421b5c16 | <|skeleton|>
class colorFrame:
def __init__(self, parent, number, red, green, blue):
"""Create a customizable QFrame that reacts to a click by opening a QColorDialog :param parent: Widget parent of this frame :param number: 1 if it's Color Light, 2 if it's Shadow Color :param red: Red value to set on a new... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class colorFrame:
def __init__(self, parent, number, red, green, blue):
"""Create a customizable QFrame that reacts to a click by opening a QColorDialog :param parent: Widget parent of this frame :param number: 1 if it's Color Light, 2 if it's Shadow Color :param red: Red value to set on a new QColor :param... | the_stack_v2_python_sparse | recipies/python/LightInterface_recreation.py | igor-si/shared | train | 1 | |
1c7371fa786f45b30039391075b7c6b4a990bdf8 | [
"self.prefix = list(w)\nfor i in range(1, len(w)):\n self.prefix[i] = self.prefix[i - 1] + w[i]",
"target = random.randint(0, self.prefix[-1] - 1)\nleft, right = (0, len(self.prefix) - 1)\nwhile left < right:\n mid = left + (right - left) // 2\n if self.prefix[mid] <= target:\n left = mid + 1\n ... | <|body_start_0|>
self.prefix = list(w)
for i in range(1, len(w)):
self.prefix[i] = self.prefix[i - 1] + w[i]
<|end_body_0|>
<|body_start_1|>
target = random.randint(0, self.prefix[-1] - 1)
left, right = (0, len(self.prefix) - 1)
while left < right:
mid = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefix = list(w)
for i in range(1, len(w)):
self.prefix[i] = self.prefi... | stack_v2_sparse_classes_75kplus_train_071035 | 841 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032426 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 5b14b6f42baf59b04cbcc8e115df4272029b64c8 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.prefix = list(w)
for i in range(1, len(w)):
self.prefix[i] = self.prefix[i - 1] + w[i]
def pickIndex(self):
""":rtype: int"""
target = random.randint(0, self.prefix[-1] - 1)
left, ri... | the_stack_v2_python_sparse | LeetCode/0528.Random-Pick-With-Weight/Random-Pick-With-Weight.py | htingwang/HandsOnAlgoDS | train | 12 | |
8e378c13bcb0be823822999d7bcce0d1b021bc8e | [
"N = 1\nfor d in factor_shape:\n N = N * d\nself.shape = (N, N)\nself.dtype = np.float64\nself.factor_shape = factor_shape\nself.N = N\nself.ops = ops",
"y = x.copy().reshape(self.factor_shape)\nfor op in self.ops:\n if op[0] == 'swap':\n y = np.swapaxes(y, op[1], op[2])\n elif op[0] == 'flip':\n ... | <|body_start_0|>
N = 1
for d in factor_shape:
N = N * d
self.shape = (N, N)
self.dtype = np.float64
self.factor_shape = factor_shape
self.N = N
self.ops = ops
<|end_body_0|>
<|body_start_1|>
y = x.copy().reshape(self.factor_shape)
for ... | A general-case symmetry operator for direct-product-basis vectors. ============= ========================== `op` tuple Description ============= ========================== ('swap',i,j) Swap axes `i` and `j`. ('flip',i) Flip axis `i`. ('diag',i,v) Multiply a diagonal operator with diagonal elements `v` along axis `i`. =... | GenericSymmetryOperator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericSymmetryOperator:
"""A general-case symmetry operator for direct-product-basis vectors. ============= ========================== `op` tuple Description ============= ========================== ('swap',i,j) Swap axes `i` and `j`. ('flip',i) Flip axis `i`. ('diag',i,v) Multiply a diagonal op... | stack_v2_sparse_classes_75kplus_train_071036 | 3,550 | permissive | [
{
"docstring": "Parameters ---------- factor_shape : tuple The direct product basis shape, (`n1`, `n2`, ...). ops : list of tuple The operations to perform. See description in class notes.",
"name": "__init__",
"signature": "def __init__(self, factor_shape, ops)"
},
{
"docstring": "The matrix-ve... | 2 | stack_v2_sparse_classes_30k_train_030062 | Implement the Python class `GenericSymmetryOperator` described below.
Class description:
A general-case symmetry operator for direct-product-basis vectors. ============= ========================== `op` tuple Description ============= ========================== ('swap',i,j) Swap axes `i` and `j`. ('flip',i) Flip axis `... | Implement the Python class `GenericSymmetryOperator` described below.
Class description:
A general-case symmetry operator for direct-product-basis vectors. ============= ========================== `op` tuple Description ============= ========================== ('swap',i,j) Swap axes `i` and `j`. ('flip',i) Flip axis `... | c6341a58331deef3728cc43c627c556139deb673 | <|skeleton|>
class GenericSymmetryOperator:
"""A general-case symmetry operator for direct-product-basis vectors. ============= ========================== `op` tuple Description ============= ========================== ('swap',i,j) Swap axes `i` and `j`. ('flip',i) Flip axis `i`. ('diag',i,v) Multiply a diagonal op... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericSymmetryOperator:
"""A general-case symmetry operator for direct-product-basis vectors. ============= ========================== `op` tuple Description ============= ========================== ('swap',i,j) Swap axes `i` and `j`. ('flip',i) Flip axis `i`. ('diag',i,v) Multiply a diagonal operator with d... | the_stack_v2_python_sparse | nitrogen/symmetry.py | bchangala/nitrogen | train | 11 |
b10d3963c8fb2eac58867ca1e1be402822072b2e | [
"if offset is None:\n return default_value\noffset = to_int(offset, 'offset')\nif offset < 0:\n raise ParamValueError(\"'offset' should be greater than or equal to 0.\")\nreturn offset",
"if limit is None:\n return default_value\nlimit = to_int(limit, 'limit')\nif limit < min_value or limit > max_value:\... | <|body_start_0|>
if offset is None:
return default_value
offset = to_int(offset, 'offset')
if offset < 0:
raise ParamValueError("'offset' should be greater than or equal to 0.")
return offset
<|end_body_0|>
<|body_start_1|>
if limit is None:
r... | Validation class, define all check methods. | Validation | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validation:
"""Validation class, define all check methods."""
def check_offset(cls, offset, default_value=0):
"""Check offset parameter, it must be greater or equal 0. Args: offset (Union[str, int]): Value can be string number or int. default_value (int): Default value for checked of... | stack_v2_sparse_classes_75kplus_train_071037 | 3,530 | permissive | [
{
"docstring": "Check offset parameter, it must be greater or equal 0. Args: offset (Union[str, int]): Value can be string number or int. default_value (int): Default value for checked offset. Default: 0. Returns: int, offset.",
"name": "check_offset",
"signature": "def check_offset(cls, offset, default... | 4 | stack_v2_sparse_classes_30k_train_040549 | Implement the Python class `Validation` described below.
Class description:
Validation class, define all check methods.
Method signatures and docstrings:
- def check_offset(cls, offset, default_value=0): Check offset parameter, it must be greater or equal 0. Args: offset (Union[str, int]): Value can be string number ... | Implement the Python class `Validation` described below.
Class description:
Validation class, define all check methods.
Method signatures and docstrings:
- def check_offset(cls, offset, default_value=0): Check offset parameter, it must be greater or equal 0. Args: offset (Union[str, int]): Value can be string number ... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class Validation:
"""Validation class, define all check methods."""
def check_offset(cls, offset, default_value=0):
"""Check offset parameter, it must be greater or equal 0. Args: offset (Union[str, int]): Value can be string number or int. default_value (int): Default value for checked of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Validation:
"""Validation class, define all check methods."""
def check_offset(cls, offset, default_value=0):
"""Check offset parameter, it must be greater or equal 0. Args: offset (Union[str, int]): Value can be string number or int. default_value (int): Default value for checked offset. Default... | the_stack_v2_python_sparse | mindinsight/datavisual/common/validation.py | mindspore-ai/mindinsight | train | 224 |
bfa8ff75a81fe185ad97c1e2198655eb6d31e7d4 | [
"if not root:\n return\nso = [root]\nss = []\nwhile any(so):\n for i in xrange(len(so)):\n if so[i] is not None:\n ss.append(so[i].left)\n ss.append(so[i].right)\n if i < len(so) - 1:\n so[i].next = so[i + 1]\n else:\n so[i].next... | <|body_start_0|>
if not root:
return
so = [root]
ss = []
while any(so):
for i in xrange(len(so)):
if so[i] is not None:
ss.append(so[i].left)
ss.append(so[i].right)
if i < len(so) - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_0|>
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return
... | stack_v2_sparse_classes_75kplus_train_071038 | 2,232 | no_license | [
{
"docstring": ":type root: TreeLinkNode :rtype: nothing",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": ":type root: TreeLinkNode :rtype: nothing",
"name": "connect",
"signature": "def connect(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051097 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): :type root: TreeLinkNode :rtype: nothing
- def connect(self, root): :type root: TreeLinkNode :rtype: nothing | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): :type root: TreeLinkNode :rtype: nothing
- def connect(self, root): :type root: TreeLinkNode :rtype: nothing
<|skeleton|>
class Solution:
def conne... | c658b78c920aa94c25b3d932cd7e46c0df82b19a | <|skeleton|>
class Solution:
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_0|>
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def connect(self, root):
""":type root: TreeLinkNode :rtype: nothing"""
if not root:
return
so = [root]
ss = []
while any(so):
for i in xrange(len(so)):
if so[i] is not None:
ss.append(so[i].left)
... | the_stack_v2_python_sparse | LeetCode/populateNextRightPterInEachNode.py | armsky/OnlineJudge | train | 0 | |
63206345b46bee6668424f7896d261e2dbcff51c | [
"avglumi = 0.0\nif c1 and nBXs > 0:\n avglumi = c1 * luminonorm / nBXs\nAfterglow = 1.0\nif len(afterglow) != 0:\n afterglowmap = ast.literal_eval(afterglow)\n for bxthreshold, correction in afterglowmap:\n if nBXs >= bxthreshold:\n Afterglow = correction\ndriftterm = 1.0\nif drift and in... | <|body_start_0|>
avglumi = 0.0
if c1 and nBXs > 0:
avglumi = c1 * luminonorm / nBXs
Afterglow = 1.0
if len(afterglow) != 0:
afterglowmap = ast.literal_eval(afterglow)
for bxthreshold, correction in afterglowmap:
if nBXs >= bxthreshold:
... | luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params | normFunctionFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class normFunctionFactory:
"""luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params"""
def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drif... | stack_v2_sparse_classes_75kplus_train_071039 | 3,290 | permissive | [
{
"docstring": "input: luminonorm unit Hz/ub output: correction factor to be applied on lumi in Hz/ub",
"name": "fPoly",
"signature": "def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drift=0.0, c1=0.0, afterglow='')"
},
{
"docstring": "input: luminonorm unit H... | 2 | stack_v2_sparse_classes_30k_train_011050 | Implement the Python class `normFunctionFactory` described below.
Class description:
luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params
Method signatures and docstrings:
- def fPoly(self, lumi... | Implement the Python class `normFunctionFactory` described below.
Class description:
luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params
Method signatures and docstrings:
- def fPoly(self, lumi... | 80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7 | <|skeleton|>
class normFunctionFactory:
"""luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params"""
def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class normFunctionFactory:
"""luminorm and correction functions. The result of the functions are correction factors, not final luminosity all functions take 5 run time parameters, and arbituary named params"""
def fPoly(self, luminonorm, intglumi, nBXs, whatev, whatav, a0=1.0, a1=0.0, a2=0.0, drift=0.0, c1=0.0... | the_stack_v2_python_sparse | RecoLuminosity/LumiDB/python/normFunctors.py | CMS-TMTT/cmssw | train | 3 |
2822e27786c884745b508bc3c417ac538486b4a9 | [
"super(PairCropTF, self).__init__()\nassert 0 <= top and 0 <= left\nassert height is None or 0 < height\nassert width is None or 0 < width\nself.top = top\nself.left = left\nself.height = height\nself.width = width\npass",
"assert image.size[:2] == label.size[:2]\nw, h = image.size[:2]\nassert self.height is None... | <|body_start_0|>
super(PairCropTF, self).__init__()
assert 0 <= top and 0 <= left
assert height is None or 0 < height
assert width is None or 0 < width
self.top = top
self.left = left
self.height = height
self.width = width
pass
<|end_body_0|>
<|b... | PairCropTF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PairCropTF:
def __init__(self, top=0, left=0, height=None, width=None):
"""剪裁图像,这个不好用 :param top: :param left: :param height: :param width:"""
<|body_0|>
def __call__(self, image, label):
"""剪裁图像 :param image: [H,W,C] PIL Image RGB :param label: [H,W] PIL Image train... | stack_v2_sparse_classes_75kplus_train_071040 | 13,528 | no_license | [
{
"docstring": "剪裁图像,这个不好用 :param top: :param left: :param height: :param width:",
"name": "__init__",
"signature": "def __init__(self, top=0, left=0, height=None, width=None)"
},
{
"docstring": "剪裁图像 :param image: [H,W,C] PIL Image RGB :param label: [H,W] PIL Image trainId :return: [H,W,C] PIL ... | 2 | stack_v2_sparse_classes_30k_train_020352 | Implement the Python class `PairCropTF` described below.
Class description:
Implement the PairCropTF class.
Method signatures and docstrings:
- def __init__(self, top=0, left=0, height=None, width=None): 剪裁图像,这个不好用 :param top: :param left: :param height: :param width:
- def __call__(self, image, label): 剪裁图像 :param i... | Implement the Python class `PairCropTF` described below.
Class description:
Implement the PairCropTF class.
Method signatures and docstrings:
- def __init__(self, top=0, left=0, height=None, width=None): 剪裁图像,这个不好用 :param top: :param left: :param height: :param width:
- def __call__(self, image, label): 剪裁图像 :param i... | 63417a403f98b00f01f07aee91b70d83ee9c1e42 | <|skeleton|>
class PairCropTF:
def __init__(self, top=0, left=0, height=None, width=None):
"""剪裁图像,这个不好用 :param top: :param left: :param height: :param width:"""
<|body_0|>
def __call__(self, image, label):
"""剪裁图像 :param image: [H,W,C] PIL Image RGB :param label: [H,W] PIL Image train... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PairCropTF:
def __init__(self, top=0, left=0, height=None, width=None):
"""剪裁图像,这个不好用 :param top: :param left: :param height: :param width:"""
super(PairCropTF, self).__init__()
assert 0 <= top and 0 <= left
assert height is None or 0 < height
assert width is None or 0 ... | the_stack_v2_python_sparse | utils/augment.py | Ascetics/LaneSegmentation | train | 1 | |
409ebd29d0e3d73116f697f974f357ece0f5b91c | [
"search_term = request.args.get('q') or None\nlimit = request.args.get('limit') or Config.MAX_PAGE_SIZE\npage_limit = 100 if int(limit) > 100 else int(limit)\npage = request.args.get('page') or 1\nif page_limit < 1 or page < 1:\n return abort(400, 'Page or Limit cannot be negative values')\naddress_data = Addres... | <|body_start_0|>
search_term = request.args.get('q') or None
limit = request.args.get('limit') or Config.MAX_PAGE_SIZE
page_limit = 100 if int(limit) > 100 else int(limit)
page = request.args.get('page') or 1
if page_limit < 1 or page < 1:
return abort(400, 'Page or L... | AddressesEndPoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressesEndPoint:
def get(self):
"""Retrieve addresses"""
<|body_0|>
def post(self):
"""Create an address"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
search_term = request.args.get('q') or None
limit = request.args.get('limit') or Confi... | stack_v2_sparse_classes_75kplus_train_071041 | 6,668 | permissive | [
{
"docstring": "Retrieve addresses",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create an address",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034400 | Implement the Python class `AddressesEndPoint` described below.
Class description:
Implement the AddressesEndPoint class.
Method signatures and docstrings:
- def get(self): Retrieve addresses
- def post(self): Create an address | Implement the Python class `AddressesEndPoint` described below.
Class description:
Implement the AddressesEndPoint class.
Method signatures and docstrings:
- def get(self): Retrieve addresses
- def post(self): Create an address
<|skeleton|>
class AddressesEndPoint:
def get(self):
"""Retrieve addresses""... | 652c156b622e679fa2e68d2fb4b0f87180b3ca11 | <|skeleton|>
class AddressesEndPoint:
def get(self):
"""Retrieve addresses"""
<|body_0|>
def post(self):
"""Create an address"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressesEndPoint:
def get(self):
"""Retrieve addresses"""
search_term = request.args.get('q') or None
limit = request.args.get('limit') or Config.MAX_PAGE_SIZE
page_limit = 100 if int(limit) > 100 else int(limit)
page = request.args.get('page') or 1
if page_lim... | the_stack_v2_python_sparse | app/api/v1/address.py | Enkya/ims_beta | train | 0 | |
87db28f295ad2d4b4f2d696f22ddce5ec1ffee86 | [
"for command in AdminCommands.commands:\n if command_name == command.get_command_name():\n return command\nreturn None",
"if not isinstance(command_processor, CommandProcessor):\n raise TypeError('command_processor must be an instance of CommandProcessor, but got {}'.format(type(command_processor)))\... | <|body_start_0|>
for command in AdminCommands.commands:
if command_name == command.get_command_name():
return command
return None
<|end_body_0|>
<|body_start_1|>
if not isinstance(command_processor, CommandProcessor):
raise TypeError('command_processor mu... | AdminCommands contains all the commands for processing the commands from the parent process. | AdminCommands | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminCommands:
"""AdminCommands contains all the commands for processing the commands from the parent process."""
def get_command(command_name):
"""Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_071042 | 7,851 | permissive | [
{
"docstring": "Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object",
"name": "get_command",
"signature": "def get_command(command_name)"
},
{
"docstring": "Call to register the AdminCommand processor. Args: command_processor: AdminCommand p... | 2 | stack_v2_sparse_classes_30k_train_013622 | Implement the Python class `AdminCommands` described below.
Class description:
AdminCommands contains all the commands for processing the commands from the parent process.
Method signatures and docstrings:
- def get_command(command_name): Call to return the AdminCommand object. Args: command_name: AdminCommand name R... | Implement the Python class `AdminCommands` described below.
Class description:
AdminCommands contains all the commands for processing the commands from the parent process.
Method signatures and docstrings:
- def get_command(command_name): Call to return the AdminCommand object. Args: command_name: AdminCommand name R... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class AdminCommands:
"""AdminCommands contains all the commands for processing the commands from the parent process."""
def get_command(command_name):
"""Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object"""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdminCommands:
"""AdminCommands contains all the commands for processing the commands from the parent process."""
def get_command(command_name):
"""Call to return the AdminCommand object. Args: command_name: AdminCommand name Returns: AdminCommand object"""
for command in AdminCommands.co... | the_stack_v2_python_sparse | nvflare/private/fed/client/admin_commands.py | NVIDIA/NVFlare | train | 442 |
eeb63cd79be481d770dd81c851b08af8896b5f78 | [
"names = []\nif self.children[1].type == 'annassign':\n names = _defined_names(self.children[0], include_setitem)\nreturn [name for i in range(0, len(self.children) - 2, 2) if '=' in self.children[i + 1].value for name in _defined_names(self.children[i], include_setitem)] + names",
"node = self.children[-1]\ni... | <|body_start_0|>
names = []
if self.children[1].type == 'annassign':
names = _defined_names(self.children[0], include_setitem)
return [name for i in range(0, len(self.children) - 2, 2) if '=' in self.children[i + 1].value for name in _defined_names(self.children[i], include_setitem)]... | ExprStmt | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExprStmt:
def get_defined_names(self, include_setitem=False):
"""Returns a list of `Name` defined before the `=` sign."""
<|body_0|>
def get_rhs(self):
"""Returns the right-hand-side of the equals."""
<|body_1|>
def yield_operators(self):
"""Retu... | stack_v2_sparse_classes_75kplus_train_071043 | 38,111 | permissive | [
{
"docstring": "Returns a list of `Name` defined before the `=` sign.",
"name": "get_defined_names",
"signature": "def get_defined_names(self, include_setitem=False)"
},
{
"docstring": "Returns the right-hand-side of the equals.",
"name": "get_rhs",
"signature": "def get_rhs(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_010911 | Implement the Python class `ExprStmt` described below.
Class description:
Implement the ExprStmt class.
Method signatures and docstrings:
- def get_defined_names(self, include_setitem=False): Returns a list of `Name` defined before the `=` sign.
- def get_rhs(self): Returns the right-hand-side of the equals.
- def yi... | Implement the Python class `ExprStmt` described below.
Class description:
Implement the ExprStmt class.
Method signatures and docstrings:
- def get_defined_names(self, include_setitem=False): Returns a list of `Name` defined before the `=` sign.
- def get_rhs(self): Returns the right-hand-side of the equals.
- def yi... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class ExprStmt:
def get_defined_names(self, include_setitem=False):
"""Returns a list of `Name` defined before the `=` sign."""
<|body_0|>
def get_rhs(self):
"""Returns the right-hand-side of the equals."""
<|body_1|>
def yield_operators(self):
"""Retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExprStmt:
def get_defined_names(self, include_setitem=False):
"""Returns a list of `Name` defined before the `=` sign."""
names = []
if self.children[1].type == 'annassign':
names = _defined_names(self.children[0], include_setitem)
return [name for i in range(0, len... | the_stack_v2_python_sparse | contrib/python/parso/py2/parso/python/tree.py | catboost/catboost | train | 8,012 | |
728ea7d732e693adef7ed1699fd8389d68aaa297 | [
"self.num_samples = params.integer(num_samples, from_=0)\nself.failmode = self.failmode(failmode)\nif is_sequence(self.failmode) and self.failmode[0] == 'mask':\n self.failmode = 'mask'\n if len(failmode[1]) != self.num_samples:\n raise InvalidParameterError('failure mode mask length of {self.num_sampl... | <|body_start_0|>
self.num_samples = params.integer(num_samples, from_=0)
self.failmode = self.failmode(failmode)
if is_sequence(self.failmode) and self.failmode[0] == 'mask':
self.failmode = 'mask'
if len(failmode[1]) != self.num_samples:
raise InvalidPara... | Provide failure mode handling for 1:1 data transformations. Provides utility functionality for one-to-one data transformations (mapping one input sample to one output sample) to handle failed transformations of individual samples. | DataTransformationFailureMode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataTransformationFailureMode:
"""Provide failure mode handling for 1:1 data transformations. Provides utility functionality for one-to-one data transformations (mapping one input sample to one output sample) to handle failed transformations of individual samples."""
def __init__(self, failm... | stack_v2_sparse_classes_75kplus_train_071044 | 8,094 | permissive | [
{
"docstring": "Initialize failure handler. Parameters: failmode: how to handle failed descriptor calculations, either due to rejected SMILES encodings or failing descriptor code. Possible values: \"raise\" [default]: raise a Benchmarexception \"drop\": drop the sample. Returned Data will have fewer samples (\"... | 4 | null | Implement the Python class `DataTransformationFailureMode` described below.
Class description:
Provide failure mode handling for 1:1 data transformations. Provides utility functionality for one-to-one data transformations (mapping one input sample to one output sample) to handle failed transformations of individual sa... | Implement the Python class `DataTransformationFailureMode` described below.
Class description:
Provide failure mode handling for 1:1 data transformations. Provides utility functionality for one-to-one data transformations (mapping one input sample to one output sample) to handle failed transformations of individual sa... | e222cf9c126f81edfdb3b2b9a99abac6678129e8 | <|skeleton|>
class DataTransformationFailureMode:
"""Provide failure mode handling for 1:1 data transformations. Provides utility functionality for one-to-one data transformations (mapping one input sample to one output sample) to handle failed transformations of individual samples."""
def __init__(self, failm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataTransformationFailureMode:
"""Provide failure mode handling for 1:1 data transformations. Provides utility functionality for one-to-one data transformations (mapping one input sample to one output sample) to handle failed transformations of individual samples."""
def __init__(self, failmode, num_samp... | the_stack_v2_python_sparse | smlb/core/transformations.py | syam-s/smlb | train | 0 |
1a87ae6e617cb66cb05c4f62ac70995a8b0b91eb | [
"super().__init__()\nself.input_conv = Conv1d(in_channels, hidden_channels, 1)\nself.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_size, layers=layers, stacks=stacks, base_dilation=base_dilation, residual_channels=hidden_channels, aux_channels=-1, gate_channels=hidden_channels * 2, skip_chan... | <|body_start_0|>
super().__init__()
self.input_conv = Conv1d(in_channels, hidden_channels, 1)
self.encoder = WaveNet(in_channels=-1, out_channels=-1, kernel_size=kernel_size, layers=layers, stacks=stacks, base_dilation=base_dilation, residual_channels=hidden_channels, aux_channels=-1, gate_chann... | Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://arxiv.org/abs/2006.04558 | PosteriorEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speec... | stack_v2_sparse_classes_75kplus_train_071045 | 4,037 | permissive | [
{
"docstring": "Initilialize PosteriorEncoder module. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. hidden_channels (int): Number of hidden channels. kernel_size (int): Kernel size in WaveNet. layers (int): Number of layers of WaveNet. stacks (int): Number of ... | 2 | stack_v2_sparse_classes_30k_train_052037 | Implement the Python class `PosteriorEncoder` described below.
Class description:
Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversaria... | Implement the Python class `PosteriorEncoder` described below.
Class description:
Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversaria... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PosteriorEncoder:
"""Posterior encoder module in VITS. This is a module of posterior encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. .. _`Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`: https://a... | the_stack_v2_python_sparse | espnet2/gan_tts/vits/posterior_encoder.py | espnet/espnet | train | 7,242 |
ff93a18c697e6e0d64de601bcc9decf1326eeb9d | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service that handles processing/re-encoding of uploaded videos | UploadsServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadsServiceServicer:
"""Service that handles processing/re-encoding of uploaded videos"""
def GetUploadDestination(self, request, context):
"""Gets an upload destination for a user to upload a video"""
<|body_0|>
def MarkUploadComplete(self, request, context):
... | stack_v2_sparse_classes_75kplus_train_071046 | 3,536 | permissive | [
{
"docstring": "Gets an upload destination for a user to upload a video",
"name": "GetUploadDestination",
"signature": "def GetUploadDestination(self, request, context)"
},
{
"docstring": "Marks an upload as complete",
"name": "MarkUploadComplete",
"signature": "def MarkUploadComplete(se... | 3 | stack_v2_sparse_classes_30k_train_003455 | Implement the Python class `UploadsServiceServicer` described below.
Class description:
Service that handles processing/re-encoding of uploaded videos
Method signatures and docstrings:
- def GetUploadDestination(self, request, context): Gets an upload destination for a user to upload a video
- def MarkUploadComplete(... | Implement the Python class `UploadsServiceServicer` described below.
Class description:
Service that handles processing/re-encoding of uploaded videos
Method signatures and docstrings:
- def GetUploadDestination(self, request, context): Gets an upload destination for a user to upload a video
- def MarkUploadComplete(... | 55a610c97fd53c405edb2459c2722fc03857cb83 | <|skeleton|>
class UploadsServiceServicer:
"""Service that handles processing/re-encoding of uploaded videos"""
def GetUploadDestination(self, request, context):
"""Gets an upload destination for a user to upload a video"""
<|body_0|>
def MarkUploadComplete(self, request, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UploadsServiceServicer:
"""Service that handles processing/re-encoding of uploaded videos"""
def GetUploadDestination(self, request, context):
"""Gets an upload destination for a user to upload a video"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method ... | the_stack_v2_python_sparse | killrvideo/uploads/uploads_service_pb2_grpc.py | krzysztof-adamski/killrvideo-python | train | 0 |
4de8f1b4cc95a4fd1e355babe47c3b5e8afb1915 | [
"super().add_arguments(parser)\nparser.add_argument('--simulate', action='store_true', default=False, help='If True it only simulates the command without saving the changes.')\nparser.add_argument('--skip-sync-es', action='store_true', default=False, help='Skips running sync_es after the Companies House load finish... | <|body_start_0|>
super().add_arguments(parser)
parser.add_argument('--simulate', action='store_true', default=False, help='If True it only simulates the command without saving the changes.')
parser.add_argument('--skip-sync-es', action='store_true', default=False, help='Skips running sync_es aft... | Companies House sync command. | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Companies House sync command."""
def add_arguments(self, parser):
"""Define extra arguments."""
<|body_0|>
def handle(self, *args, **options):
"""Handle."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().add_arguments(parser)
... | stack_v2_sparse_classes_75kplus_train_071047 | 9,566 | no_license | [
{
"docstring": "Define extra arguments.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Handle.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007055 | Implement the Python class `Command` described below.
Class description:
Companies House sync command.
Method signatures and docstrings:
- def add_arguments(self, parser): Define extra arguments.
- def handle(self, *args, **options): Handle. | Implement the Python class `Command` described below.
Class description:
Companies House sync command.
Method signatures and docstrings:
- def add_arguments(self, parser): Define extra arguments.
- def handle(self, *args, **options): Handle.
<|skeleton|>
class Command:
"""Companies House sync command."""
de... | 7f033fcbcfb2f7c1c0e10bec51620742d3d929df | <|skeleton|>
class Command:
"""Companies House sync command."""
def add_arguments(self, parser):
"""Define extra arguments."""
<|body_0|>
def handle(self, *args, **options):
"""Handle."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""Companies House sync command."""
def add_arguments(self, parser):
"""Define extra arguments."""
super().add_arguments(parser)
parser.add_argument('--simulate', action='store_true', default=False, help='If True it only simulates the command without saving the changes.')... | the_stack_v2_python_sparse | datahub/company/management/commands/sync_ch.py | jakub-kozlowski/data-hub-leeloo | train | 0 |
df91a5a0e55577bdece500d3821eb0bec948f5c4 | [
"self.args = {}\nself.kwargs = {}\nif pos_arg:\n self.args[pos_arg] = f_arg\nprint(self.args)\nif name_kwarg:\n self.kwargs[name_kwarg] = f_kwarg\nprint(self.kwargs)",
"self.f = f\n\ndef inner_func(*args, **kwargs):\n print(f'function passed: {self.f}')\n print(f'args passed: {args}')\n print(f'kwa... | <|body_start_0|>
self.args = {}
self.kwargs = {}
if pos_arg:
self.args[pos_arg] = f_arg
print(self.args)
if name_kwarg:
self.kwargs[name_kwarg] = f_kwarg
print(self.kwargs)
<|end_body_0|>
<|body_start_1|>
self.f = f
def inner_func... | dector_arg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dector_arg:
def __init__(self, pos_arg=None, f_arg=None, name_kwarg=None, f_kwarg=None):
""":param pos_arg: the positional argument :param f_arg: the function to apply to the positional argument :param name_kwarg: the keyword argument :param f_kwarg: the function to apply to the keyword ... | stack_v2_sparse_classes_75kplus_train_071048 | 36,630 | permissive | [
{
"docstring": ":param pos_arg: the positional argument :param f_arg: the function to apply to the positional argument :param name_kwarg: the keyword argument :param f_kwarg: the function to apply to the keyword argument",
"name": "__init__",
"signature": "def __init__(self, pos_arg=None, f_arg=None, na... | 2 | null | Implement the Python class `dector_arg` described below.
Class description:
Implement the dector_arg class.
Method signatures and docstrings:
- def __init__(self, pos_arg=None, f_arg=None, name_kwarg=None, f_kwarg=None): :param pos_arg: the positional argument :param f_arg: the function to apply to the positional arg... | Implement the Python class `dector_arg` described below.
Class description:
Implement the dector_arg class.
Method signatures and docstrings:
- def __init__(self, pos_arg=None, f_arg=None, name_kwarg=None, f_kwarg=None): :param pos_arg: the positional argument :param f_arg: the function to apply to the positional arg... | b1866df148d28cf4c2d499b9cd2a94af31fbbd93 | <|skeleton|>
class dector_arg:
def __init__(self, pos_arg=None, f_arg=None, name_kwarg=None, f_kwarg=None):
""":param pos_arg: the positional argument :param f_arg: the function to apply to the positional argument :param name_kwarg: the keyword argument :param f_kwarg: the function to apply to the keyword ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class dector_arg:
def __init__(self, pos_arg=None, f_arg=None, name_kwarg=None, f_kwarg=None):
""":param pos_arg: the positional argument :param f_arg: the function to apply to the positional argument :param name_kwarg: the keyword argument :param f_kwarg: the function to apply to the keyword argument"""
... | the_stack_v2_python_sparse | CacheIntervals/MemoizationIntervals.py | cyrilgodart/CacheIntervals | train | 1 | |
0341adbcc9667e041ccd24776d3d8b1a0d8eb714 | [
"super().__init__(**kwargs)\nself.alpha = alpha\nself.gamma = gamma\nself.label_smoothing = label_smoothing",
"normalizer, y_true = y\nalpha = tf.convert_to_tensor(self.alpha, dtype=y_pred.dtype)\ngamma = tf.convert_to_tensor(self.gamma, dtype=y_pred.dtype)\npred_prob = tf.sigmoid(y_pred)\np_t = y_true * pred_pro... | <|body_start_0|>
super().__init__(**kwargs)
self.alpha = alpha
self.gamma = gamma
self.label_smoothing = label_smoothing
<|end_body_0|>
<|body_start_1|>
normalizer, y_true = y
alpha = tf.convert_to_tensor(self.alpha, dtype=y_pred.dtype)
gamma = tf.convert_to_tens... | Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. | FocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class."""
def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs):
"""Initialize focal loss. ... | stack_v2_sparse_classes_75kplus_train_071049 | 17,443 | permissive | [
{
"docstring": "Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kw... | 2 | stack_v2_sparse_classes_30k_train_008361 | Implement the Python class `FocalLoss` described below.
Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class.
Method signatures and docstrings:
- def __init__(self, alpha, gamma... | Implement the Python class `FocalLoss` described below.
Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class.
Method signatures and docstrings:
- def __init__(self, alpha, gamma... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class FocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class."""
def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs):
"""Initialize focal loss. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class."""
def __init__(self, alpha, gamma, label_smoothing=0.0, **kwargs):
"""Initialize focal loss. Args: alpha: ... | the_stack_v2_python_sparse | TensorFlow2/Detection/Efficientdet/utils/train_lib.py | NVIDIA/DeepLearningExamples | train | 11,838 |
af889b3e40267e6614ecec8cfb29ea0277b6486b | [
"user = self.request.user\npath = self.kwargs.get('path')\ntry:\n if user.is_authenticated:\n qs = get_path_file_queryset(path, user)\n else:\n qs = get_unauthenticated_user_path_file_queryset(path)\nexcept ValueError:\n raise Http404('Not found.')\nn_slashes = path.count('/') + 1\nreturn fil... | <|body_start_0|>
user = self.request.user
path = self.kwargs.get('path')
try:
if user.is_authenticated:
qs = get_path_file_queryset(path, user)
else:
qs = get_unauthenticated_user_path_file_queryset(path)
except ValueError:
... | A view for the collection of a file browser path's files. | FileBrowserPathFileList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileBrowserPathFileList:
"""A view for the collection of a file browser path's files."""
def get_queryset(self):
"""Overriden to return a custom queryset."""
<|body_0|>
def get_serializer_class(self):
"""Overriden to return the serializer class that should be use... | stack_v2_sparse_classes_75kplus_train_071050 | 6,485 | permissive | [
{
"docstring": "Overriden to return a custom queryset.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Overriden to return the serializer class that should be used for serializing output.",
"name": "get_serializer_class",
"signature": "def get_serialize... | 2 | stack_v2_sparse_classes_30k_train_012524 | Implement the Python class `FileBrowserPathFileList` described below.
Class description:
A view for the collection of a file browser path's files.
Method signatures and docstrings:
- def get_queryset(self): Overriden to return a custom queryset.
- def get_serializer_class(self): Overriden to return the serializer cla... | Implement the Python class `FileBrowserPathFileList` described below.
Class description:
A view for the collection of a file browser path's files.
Method signatures and docstrings:
- def get_queryset(self): Overriden to return a custom queryset.
- def get_serializer_class(self): Overriden to return the serializer cla... | 20d3eedf20610af9182f6cca8db8f0b3546b5336 | <|skeleton|>
class FileBrowserPathFileList:
"""A view for the collection of a file browser path's files."""
def get_queryset(self):
"""Overriden to return a custom queryset."""
<|body_0|>
def get_serializer_class(self):
"""Overriden to return the serializer class that should be use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileBrowserPathFileList:
"""A view for the collection of a file browser path's files."""
def get_queryset(self):
"""Overriden to return a custom queryset."""
user = self.request.user
path = self.kwargs.get('path')
try:
if user.is_authenticated:
... | the_stack_v2_python_sparse | chris_backend/filebrowser/views.py | FNNDSC/ChRIS_ultron_backEnd | train | 36 |
fcbddb3511bf200f06e703bc14f8642c592e3ca2 | [
"timestamps = sorted({state.timestamp for state in chain(measured_states, truth_states)})\nospa_distances = []\nfor timestamp in timestamps:\n meas_points = [state for state in measured_states if state.timestamp == timestamp]\n truth_points = [state for state in truth_states if state.timestamp == timestamp]\n... | <|body_start_0|>
timestamps = sorted({state.timestamp for state in chain(measured_states, truth_states)})
ospa_distances = []
for timestamp in timestamps:
meas_points = [state for state in measured_states if state.timestamp == timestamp]
truth_points = [state for state in... | Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consistent Metric for Performance Evaluation o... | OSPAMetric | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-secret-labs-2011"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSPAMetric:
"""Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consiste... | stack_v2_sparse_classes_75kplus_train_071051 | 19,882 | permissive | [
{
"docstring": "Compute the OSPA metric at every timestep from a list of measured states and truth states Parameters ---------- measured_states: list of :class:`~.State` Created by a filter truth_states: list of :class:`~.State` Truth states to compare against Returns ------- TimeRangeMetric Covering the durati... | 2 | stack_v2_sparse_classes_30k_train_013501 | Implement the Python class `OSPAMetric` described below.
Class description:
Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` obje... | Implement the Python class `OSPAMetric` described below.
Class description:
Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` obje... | f24090cc919b3b590b84f965a3884ed1293d181d | <|skeleton|>
class OSPAMetric:
"""Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consiste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OSPAMetric:
"""Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consistent Metric for... | the_stack_v2_python_sparse | stonesoup/metricgenerator/ospametric.py | dstl/Stone-Soup | train | 315 |
565970a3c45e839a28cf0c8db663722dd98bca10 | [
"this_matrix, these_means, these_standard_deviations = novelty_detection._normalize_features(feature_matrix=FEATURE_MATRIX_DENORM + 0.0)\nself.assertTrue(numpy.allclose(this_matrix, FEATURE_MATRIX_NORM, atol=TOLERANCE))\nself.assertTrue(numpy.allclose(these_means, FEATURE_MEANS, atol=TOLERANCE))\nself.assertTrue(nu... | <|body_start_0|>
this_matrix, these_means, these_standard_deviations = novelty_detection._normalize_features(feature_matrix=FEATURE_MATRIX_DENORM + 0.0)
self.assertTrue(numpy.allclose(this_matrix, FEATURE_MATRIX_NORM, atol=TOLERANCE))
self.assertTrue(numpy.allclose(these_means, FEATURE_MEANS, at... | Each method is a unit test for novelty_detection.py. | NoveltyDetectionTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoveltyDetectionTests:
"""Each method is a unit test for novelty_detection.py."""
def test_normalize_features(self):
"""Ensures correct output from _normalize_features."""
<|body_0|>
def test_fit_and_apply_svd(self):
"""Ensures correct output from _fit_svd and _a... | stack_v2_sparse_classes_75kplus_train_071052 | 2,930 | permissive | [
{
"docstring": "Ensures correct output from _normalize_features.",
"name": "test_normalize_features",
"signature": "def test_normalize_features(self)"
},
{
"docstring": "Ensures correct output from _fit_svd and _apply_svd.",
"name": "test_fit_and_apply_svd",
"signature": "def test_fit_an... | 2 | stack_v2_sparse_classes_30k_train_052041 | Implement the Python class `NoveltyDetectionTests` described below.
Class description:
Each method is a unit test for novelty_detection.py.
Method signatures and docstrings:
- def test_normalize_features(self): Ensures correct output from _normalize_features.
- def test_fit_and_apply_svd(self): Ensures correct output... | Implement the Python class `NoveltyDetectionTests` described below.
Class description:
Each method is a unit test for novelty_detection.py.
Method signatures and docstrings:
- def test_normalize_features(self): Ensures correct output from _normalize_features.
- def test_fit_and_apply_svd(self): Ensures correct output... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class NoveltyDetectionTests:
"""Each method is a unit test for novelty_detection.py."""
def test_normalize_features(self):
"""Ensures correct output from _normalize_features."""
<|body_0|>
def test_fit_and_apply_svd(self):
"""Ensures correct output from _fit_svd and _a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoveltyDetectionTests:
"""Each method is a unit test for novelty_detection.py."""
def test_normalize_features(self):
"""Ensures correct output from _normalize_features."""
this_matrix, these_means, these_standard_deviations = novelty_detection._normalize_features(feature_matrix=FEATURE_MA... | the_stack_v2_python_sparse | gewittergefahr/deep_learning/novelty_detection_test.py | thunderhoser/GewitterGefahr | train | 29 |
4a8bf5a3e5510e9685ce3886dd08cb4d3296ba1f | [
"if type(dm) is not int:\n raise TypeError('dm must be int representing dimensionality of model')\nif type(h) is not int:\n raise TypeError('h must be int representing number of heads')\nif type(hidden) is not int:\n raise TypeError('hidden must be int representing number of hidden units')\nif type(drop_ra... | <|body_start_0|>
if type(dm) is not int:
raise TypeError('dm must be int representing dimensionality of model')
if type(h) is not int:
raise TypeError('h must be int representing number of heads')
if type(hidden) is not int:
raise TypeError('hidden must be int... | Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense layer with dm units layernorm1: the first... | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense l... | stack_v2_sparse_classes_75kplus_train_071053 | 3,990 | no_license | [
{
"docstring": "Class constructor parameters: dm [int]: represents the dimensionality of the model h [int]: represents the number of heads hidden [int]: represents the number of hidden units in fully connected layer drop_rate [float]: the dropout rate sets the public instance attributes: mha: MultiHeadAttention... | 2 | stack_v2_sparse_classes_30k_train_021877 | Implement the Python class `EncoderBlock` described below.
Class description:
Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu acti... | Implement the Python class `EncoderBlock` described below.
Class description:
Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu acti... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class EncoderBlock:
"""Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderBlock:
"""Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense layer with dm ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
8d83d635ed64e6ce27e7e41e882506fa79177a1b | [
"self.phone = phone\nself.time = time\nself.content = content\nself.msg_id = msg_id",
"text = 'Message ['\ntext += 'phone: ' + str(self.phone) + ', '\ntext += 'time: ' + str(self.time) + ', '\ntext += 'content: ' + self.content + ']'\nreturn text"
] | <|body_start_0|>
self.phone = phone
self.time = time
self.content = content
self.msg_id = msg_id
<|end_body_0|>
<|body_start_1|>
text = 'Message ['
text += 'phone: ' + str(self.phone) + ', '
text += 'time: ' + str(self.time) + ', '
text += 'content: ' + s... | This class represents an abstract SMS message interface. | BaseSMS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseSMS:
"""This class represents an abstract SMS message interface."""
def __init__(self, phone, time, content, msg_id=None):
"""General-purpose constructor for SMS message If msg_id is None, message is not persisted yet"""
<|body_0|>
def __str__(self):
"""retur... | stack_v2_sparse_classes_75kplus_train_071054 | 1,488 | no_license | [
{
"docstring": "General-purpose constructor for SMS message If msg_id is None, message is not persisted yet",
"name": "__init__",
"signature": "def __init__(self, phone, time, content, msg_id=None)"
},
{
"docstring": "returns a textual representation of the message",
"name": "__str__",
"... | 2 | stack_v2_sparse_classes_30k_train_027600 | Implement the Python class `BaseSMS` described below.
Class description:
This class represents an abstract SMS message interface.
Method signatures and docstrings:
- def __init__(self, phone, time, content, msg_id=None): General-purpose constructor for SMS message If msg_id is None, message is not persisted yet
- def... | Implement the Python class `BaseSMS` described below.
Class description:
This class represents an abstract SMS message interface.
Method signatures and docstrings:
- def __init__(self, phone, time, content, msg_id=None): General-purpose constructor for SMS message If msg_id is None, message is not persisted yet
- def... | 0bbe17fb57650e8fa63a2b39e99da4b3643c8aa8 | <|skeleton|>
class BaseSMS:
"""This class represents an abstract SMS message interface."""
def __init__(self, phone, time, content, msg_id=None):
"""General-purpose constructor for SMS message If msg_id is None, message is not persisted yet"""
<|body_0|>
def __str__(self):
"""retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseSMS:
"""This class represents an abstract SMS message interface."""
def __init__(self, phone, time, content, msg_id=None):
"""General-purpose constructor for SMS message If msg_id is None, message is not persisted yet"""
self.phone = phone
self.time = time
self.content... | the_stack_v2_python_sparse | src/model/entity/message.py | janakaud/shopguru | train | 0 |
81bb71b3acf5461194705e6be46ba99c6b6d8d9b | [
"if not sample_n:\n print('Need to specify a size greater than 0!')\n raise ValueError\nif not balance_col:\n print('Need to specify the name of a column to perform balance sampling within this column!')\n raise ValueError\nif balance_col not in df.columns:\n print('Need to specify a valid column to ... | <|body_start_0|>
if not sample_n:
print('Need to specify a size greater than 0!')
raise ValueError
if not balance_col:
print('Need to specify the name of a column to perform balance sampling within this column!')
raise ValueError
if balance_col not... | BalancePopulationSampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BalancePopulationSampler:
def __init__(self, df, sample_n, balance_col, random_state=0):
""":param sample_n: integer, the size of the sampled subset of data :param balance_col: str, the name of a categorical column that the population of groups within this column are balanced in the samp... | stack_v2_sparse_classes_75kplus_train_071055 | 4,191 | no_license | [
{
"docstring": ":param sample_n: integer, the size of the sampled subset of data :param balance_col: str, the name of a categorical column that the population of groups within this column are balanced in the sampled subset. :param random_state: integer, the seed for random process, same as random_state in panda... | 2 | null | Implement the Python class `BalancePopulationSampler` described below.
Class description:
Implement the BalancePopulationSampler class.
Method signatures and docstrings:
- def __init__(self, df, sample_n, balance_col, random_state=0): :param sample_n: integer, the size of the sampled subset of data :param balance_col... | Implement the Python class `BalancePopulationSampler` described below.
Class description:
Implement the BalancePopulationSampler class.
Method signatures and docstrings:
- def __init__(self, df, sample_n, balance_col, random_state=0): :param sample_n: integer, the size of the sampled subset of data :param balance_col... | 064c07972dcdd7ae7d4f268bcbde63389be2a9c9 | <|skeleton|>
class BalancePopulationSampler:
def __init__(self, df, sample_n, balance_col, random_state=0):
""":param sample_n: integer, the size of the sampled subset of data :param balance_col: str, the name of a categorical column that the population of groups within this column are balanced in the samp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BalancePopulationSampler:
def __init__(self, df, sample_n, balance_col, random_state=0):
""":param sample_n: integer, the size of the sampled subset of data :param balance_col: str, the name of a categorical column that the population of groups within this column are balanced in the sampled subset. :p... | the_stack_v2_python_sparse | pipeline/preprocess/samplers.py | tinluu/Fairness_Labels_for_ML_Pipelines | train | 0 | |
a50606d4829c6c0e7e8ae375b078b6975e49f490 | [
"loop = self._get_loop(loop)\nif not loop:\n super(AsyncioContextProvider, self).activate(context)\n return context\ntask = asyncio.Task.current_task(loop=loop)\nif task:\n setattr(task, self._CONTEXT_ATTR, context)\nreturn context",
"try:\n return loop or asyncio.get_event_loop()\nexcept RuntimeError... | <|body_start_0|>
loop = self._get_loop(loop)
if not loop:
super(AsyncioContextProvider, self).activate(context)
return context
task = asyncio.Task.current_task(loop=loop)
if task:
setattr(task, self._CONTEXT_ATTR, context)
return context
<|end_... | Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContextProvider`` because it uses a thread-local storage ... | AsyncioContextProvider | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncioContextProvider:
"""Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContext... | stack_v2_sparse_classes_75kplus_train_071056 | 2,855 | permissive | [
{
"docstring": "Sets the scoped ``Context`` for the current running ``Task``.",
"name": "activate",
"signature": "def activate(self, context, loop=None)"
},
{
"docstring": "Helper to try and resolve the current loop",
"name": "_get_loop",
"signature": "def _get_loop(self, loop=None)"
}... | 4 | stack_v2_sparse_classes_30k_train_032983 | Implement the Python class `AsyncioContextProvider` described below.
Class description:
Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context ... | Implement the Python class `AsyncioContextProvider` described below.
Class description:
Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context ... | 1e3bd6d4edef5cda5a0831a6a7ec8e4046659d17 | <|skeleton|>
class AsyncioContextProvider:
"""Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContext... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AsyncioContextProvider:
"""Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContextProvider`` be... | the_stack_v2_python_sparse | ddtrace/contrib/asyncio/provider.py | DataDog/dd-trace-py | train | 461 |
f7e1cc49b3efbd99f8a2d7b49a887d4e614e73f5 | [
"storage_content = StorageContent(2, 4)\nsuper(MetalLocker, self).__init__(id_=id_, description=description, storage_content=storage_content, interface_class=MetalLockerInterface, open_sound=SND_OPEN, close_sound=SND_CLOSE)\nif state == 'normal':\n self.state = NORMAL\n self._actions_list = [ACTION_BAD, ACTIO... | <|body_start_0|>
storage_content = StorageContent(2, 4)
super(MetalLocker, self).__init__(id_=id_, description=description, storage_content=storage_content, interface_class=MetalLockerInterface, open_sound=SND_OPEN, close_sound=SND_CLOSE)
if state == 'normal':
self.state = NORMAL
... | Storage object - metal locker. | MetalLocker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetalLocker:
"""Storage object - metal locker."""
def __init__(self, id_, description, state='normal', **kwargs):
"""Init. id_: class ID in configuration files. description: index of description string in locale text files. state: 'normal', 'locked' or 'broken' strings"""
<|b... | stack_v2_sparse_classes_75kplus_train_071057 | 4,630 | no_license | [
{
"docstring": "Init. id_: class ID in configuration files. description: index of description string in locale text files. state: 'normal', 'locked' or 'broken' strings",
"name": "__init__",
"signature": "def __init__(self, id_, description, state='normal', **kwargs)"
},
{
"docstring": "\"Help\"... | 6 | stack_v2_sparse_classes_30k_train_030753 | Implement the Python class `MetalLocker` described below.
Class description:
Storage object - metal locker.
Method signatures and docstrings:
- def __init__(self, id_, description, state='normal', **kwargs): Init. id_: class ID in configuration files. description: index of description string in locale text files. sta... | Implement the Python class `MetalLocker` described below.
Class description:
Storage object - metal locker.
Method signatures and docstrings:
- def __init__(self, id_, description, state='normal', **kwargs): Init. id_: class ID in configuration files. description: index of description string in locale text files. sta... | ee9d5e8d233baad29bff60b949a346878f3ed071 | <|skeleton|>
class MetalLocker:
"""Storage object - metal locker."""
def __init__(self, id_, description, state='normal', **kwargs):
"""Init. id_: class ID in configuration files. description: index of description string in locale text files. state: 'normal', 'locked' or 'broken' strings"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetalLocker:
"""Storage object - metal locker."""
def __init__(self, id_, description, state='normal', **kwargs):
"""Init. id_: class ID in configuration files. description: index of description string in locale text files. state: 'normal', 'locked' or 'broken' strings"""
storage_content ... | the_stack_v2_python_sparse | source/environment/objects/storages/metal_locker.py | sychov/space-station | train | 0 |
6bbd82c6e9272ba625a86dd5e311916da31b2c72 | [
"self.long = longitude\nself.lat = latitude\nself.range = range\nself.fluence = fluence\nself.Cm = Cm",
"laser = ephem.Observer()\nlaser.lon = str(self.long)\nlaser.lat = str(self.lat)\nlaser.elevation = -4338\nyear, month, day, hour, minutes, sec = satellite.orbital_time\nlaser.date = datetime(year, month, day, ... | <|body_start_0|>
self.long = longitude
self.lat = latitude
self.range = range
self.fluence = fluence
self.Cm = Cm
<|end_body_0|>
<|body_start_1|>
laser = ephem.Observer()
laser.lon = str(self.long)
laser.lat = str(self.lat)
laser.elevation = -4338... | Laser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Laser:
def __init__(self, latitude, longitude, range, Cm, fluence):
"""This functions initializes a laser object with it's position and the parameters for the beam power. :param latitude: position :param longitude: position :param range: range/spot of the laser in lat/long :param Cm: is ... | stack_v2_sparse_classes_75kplus_train_071058 | 3,024 | no_license | [
{
"docstring": "This functions initializes a laser object with it's position and the parameters for the beam power. :param latitude: position :param longitude: position :param range: range/spot of the laser in lat/long :param Cm: is defined as the ratio of impulse density in N/W :param fluence: optical energy i... | 4 | stack_v2_sparse_classes_30k_train_016389 | Implement the Python class `Laser` described below.
Class description:
Implement the Laser class.
Method signatures and docstrings:
- def __init__(self, latitude, longitude, range, Cm, fluence): This functions initializes a laser object with it's position and the parameters for the beam power. :param latitude: positi... | Implement the Python class `Laser` described below.
Class description:
Implement the Laser class.
Method signatures and docstrings:
- def __init__(self, latitude, longitude, range, Cm, fluence): This functions initializes a laser object with it's position and the parameters for the beam power. :param latitude: positi... | 1560564bd3a79cc86757fa388e78d35836562fb1 | <|skeleton|>
class Laser:
def __init__(self, latitude, longitude, range, Cm, fluence):
"""This functions initializes a laser object with it's position and the parameters for the beam power. :param latitude: position :param longitude: position :param range: range/spot of the laser in lat/long :param Cm: is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Laser:
def __init__(self, latitude, longitude, range, Cm, fluence):
"""This functions initializes a laser object with it's position and the parameters for the beam power. :param latitude: position :param longitude: position :param range: range/spot of the laser in lat/long :param Cm: is defined as the... | the_stack_v2_python_sparse | laser.py | KalleJanssen/group10_PCS | train | 0 | |
cf326196c90ebb500cf30a9fcec9302babace189 | [
"if threshold is None or rows < 1 or cols < 1:\n return 0\nvisits = [0] * (rows * cols)\ncounts = self.moving_count_core(threshold, rows, cols, 0, 0, visits)\nreturn counts",
"moving_count = 0\nif self.check(threshold, rows, cols, row, col, visits):\n visits[row * cols + col] = 1\n moving_count = 1 + sel... | <|body_start_0|>
if threshold is None or rows < 1 or cols < 1:
return 0
visits = [0] * (rows * cols)
counts = self.moving_count_core(threshold, rows, cols, 0, 0, visits)
return counts
<|end_body_0|>
<|body_start_1|>
moving_count = 0
if self.check(threshold, r... | 计算机器人行走范围 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""计算机器人行走范围"""
def moving_count(self, threshold, rows, cols):
"""主函数,调用递归计算函数 :param threshold: 坐标数位之和的阈值 :param rows: 坐标行数 :param cols: 坐标列数 :return: 机器人行走范围之和"""
<|body_0|>
def moving_count_core(self, threshold, rows, cols, row, col, visits):
"""递归计算... | stack_v2_sparse_classes_75kplus_train_071059 | 4,600 | no_license | [
{
"docstring": "主函数,调用递归计算函数 :param threshold: 坐标数位之和的阈值 :param rows: 坐标行数 :param cols: 坐标列数 :return: 机器人行走范围之和",
"name": "moving_count",
"signature": "def moving_count(self, threshold, rows, cols)"
},
{
"docstring": "递归计算机器人行走范围 :param threshold: 坐标数位之和的阈值 :param rows: 行数 :param cols: 列数 :param... | 4 | stack_v2_sparse_classes_30k_train_003027 | Implement the Python class `Solution` described below.
Class description:
计算机器人行走范围
Method signatures and docstrings:
- def moving_count(self, threshold, rows, cols): 主函数,调用递归计算函数 :param threshold: 坐标数位之和的阈值 :param rows: 坐标行数 :param cols: 坐标列数 :return: 机器人行走范围之和
- def moving_count_core(self, threshold, rows, cols, ro... | Implement the Python class `Solution` described below.
Class description:
计算机器人行走范围
Method signatures and docstrings:
- def moving_count(self, threshold, rows, cols): 主函数,调用递归计算函数 :param threshold: 坐标数位之和的阈值 :param rows: 坐标行数 :param cols: 坐标列数 :return: 机器人行走范围之和
- def moving_count_core(self, threshold, rows, cols, ro... | 9fdc4b1a2b59b7aed22ddfe92aade487b4c19b71 | <|skeleton|>
class Solution:
"""计算机器人行走范围"""
def moving_count(self, threshold, rows, cols):
"""主函数,调用递归计算函数 :param threshold: 坐标数位之和的阈值 :param rows: 坐标行数 :param cols: 坐标列数 :return: 机器人行走范围之和"""
<|body_0|>
def moving_count_core(self, threshold, rows, cols, row, col, visits):
"""递归计算... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""计算机器人行走范围"""
def moving_count(self, threshold, rows, cols):
"""主函数,调用递归计算函数 :param threshold: 坐标数位之和的阈值 :param rows: 坐标行数 :param cols: 坐标列数 :return: 机器人行走范围之和"""
if threshold is None or rows < 1 or cols < 1:
return 0
visits = [0] * (rows * cols)
co... | the_stack_v2_python_sparse | my_target_offer/13_robot_run_range.py | MemoryForSky/Data-Structures-and-Algorithms | train | 0 |
600188b6f9933f65e2b301ba72118836c8061e9e | [
"self.messages = []\nself.x = x\nself.width = width\nself.height = height",
"new_msg_lines = textwrap.wrap(message.text, self.width)\nfor line in new_msg_lines:\n if len(self.messages) == self.height:\n del self.messages[0]\n self.messages.append(Message(line, message.color))"
] | <|body_start_0|>
self.messages = []
self.x = x
self.width = width
self.height = height
<|end_body_0|>
<|body_start_1|>
new_msg_lines = textwrap.wrap(message.text, self.width)
for line in new_msg_lines:
if len(self.messages) == self.height:
del... | Gère la boîte de dialogue dans laquelle s'affichent les message | MessageLog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageLog:
"""Gère la boîte de dialogue dans laquelle s'affichent les message"""
def __init__(self, x, width, height):
"""Crée un boîte de dialogue Parametres: ---------- x : int Ancrage de la boîte de dialogue width : int Largeur height : int Hauteur Renvoi: ------- Aucun"""
... | stack_v2_sparse_classes_75kplus_train_071060 | 1,567 | no_license | [
{
"docstring": "Crée un boîte de dialogue Parametres: ---------- x : int Ancrage de la boîte de dialogue width : int Largeur height : int Hauteur Renvoi: ------- Aucun",
"name": "__init__",
"signature": "def __init__(self, x, width, height)"
},
{
"docstring": "Ajoute un message à la boîte de dia... | 2 | stack_v2_sparse_classes_30k_train_024102 | Implement the Python class `MessageLog` described below.
Class description:
Gère la boîte de dialogue dans laquelle s'affichent les message
Method signatures and docstrings:
- def __init__(self, x, width, height): Crée un boîte de dialogue Parametres: ---------- x : int Ancrage de la boîte de dialogue width : int Lar... | Implement the Python class `MessageLog` described below.
Class description:
Gère la boîte de dialogue dans laquelle s'affichent les message
Method signatures and docstrings:
- def __init__(self, x, width, height): Crée un boîte de dialogue Parametres: ---------- x : int Ancrage de la boîte de dialogue width : int Lar... | 12350f1c56747e3c0cd3786321bcb136f6de0419 | <|skeleton|>
class MessageLog:
"""Gère la boîte de dialogue dans laquelle s'affichent les message"""
def __init__(self, x, width, height):
"""Crée un boîte de dialogue Parametres: ---------- x : int Ancrage de la boîte de dialogue width : int Largeur height : int Hauteur Renvoi: ------- Aucun"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageLog:
"""Gère la boîte de dialogue dans laquelle s'affichent les message"""
def __init__(self, x, width, height):
"""Crée un boîte de dialogue Parametres: ---------- x : int Ancrage de la boîte de dialogue width : int Largeur height : int Hauteur Renvoi: ------- Aucun"""
self.messag... | the_stack_v2_python_sparse | game_messages.py | Taezyn/RogueLike | train | 0 |
fbcb6aa77e01a84cb73db19899eaa70f295f7788 | [
"super(AnalogClient, self).__init__(handlers)\nAnalogClient.check_config(aconfig)\nself._input_list = aconfig['measurements']\nself.frequency = aconfig['frequency']\nself.averages = aconfig['averages']\nif self.averages == 0:\n raise ValueError('Cannot average 0 values')\nself.mfrequency = self.frequency / self.... | <|body_start_0|>
super(AnalogClient, self).__init__(handlers)
AnalogClient.check_config(aconfig)
self._input_list = aconfig['measurements']
self.frequency = aconfig['frequency']
self.averages = aconfig['averages']
if self.averages == 0:
raise ValueError('Canno... | AnalogClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalogClient:
def __init__(self, aconfig, handlers, data_store):
"""Set up a thread to read in analog values aconfig: the configuration values to read in {'measurements': [['current', 'A', "P9_39", 1.0, 0.0], ...], 'frequency': 0.1, # seconds 'averages': 8, # Number of values to average ... | stack_v2_sparse_classes_75kplus_train_071061 | 5,380 | no_license | [
{
"docstring": "Set up a thread to read in analog values aconfig: the configuration values to read in {'measurements': [['current', 'A', \"P9_39\", 1.0, 0.0], ...], 'frequency': 0.1, # seconds 'averages': 8, # Number of values to average }",
"name": "__init__",
"signature": "def __init__(self, aconfig, ... | 6 | stack_v2_sparse_classes_30k_train_021930 | Implement the Python class `AnalogClient` described below.
Class description:
Implement the AnalogClient class.
Method signatures and docstrings:
- def __init__(self, aconfig, handlers, data_store): Set up a thread to read in analog values aconfig: the configuration values to read in {'measurements': [['current', 'A'... | Implement the Python class `AnalogClient` described below.
Class description:
Implement the AnalogClient class.
Method signatures and docstrings:
- def __init__(self, aconfig, handlers, data_store): Set up a thread to read in analog values aconfig: the configuration values to read in {'measurements': [['current', 'A'... | 1e58588a4c792445d87bd95c463c6d338fcede5b | <|skeleton|>
class AnalogClient:
def __init__(self, aconfig, handlers, data_store):
"""Set up a thread to read in analog values aconfig: the configuration values to read in {'measurements': [['current', 'A', "P9_39", 1.0, 0.0], ...], 'frequency': 0.1, # seconds 'averages': 8, # Number of values to average ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalogClient:
def __init__(self, aconfig, handlers, data_store):
"""Set up a thread to read in analog values aconfig: the configuration values to read in {'measurements': [['current', 'A', "P9_39", 1.0, 0.0], ...], 'frequency': 0.1, # seconds 'averages': 8, # Number of values to average }"""
s... | the_stack_v2_python_sparse | PythonTools/hygen/logger/analogclient.py | BillMarty/PPI_Cdocs | train | 0 | |
8c4dccc1ed4379cdae536420387c6c488a205ec0 | [
"if not isinstance(data, np.ndarray):\n raise FrequencyError('data should be a numpy array')\nself.data = data\nself.sampling_rate = sampling_rate\nself.interval = 1000 / sampling_rate",
"phase_positive = True if self.data[0] >= 0 else False\ncur_pos = 0\nwhile cur_pos < len(self.data):\n dd = self.data[cur... | <|body_start_0|>
if not isinstance(data, np.ndarray):
raise FrequencyError('data should be a numpy array')
self.data = data
self.sampling_rate = sampling_rate
self.interval = 1000 / sampling_rate
<|end_body_0|>
<|body_start_1|>
phase_positive = True if self.data[0] >... | Frequency | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Frequency:
def __init__(self, data, sampling_rate):
"""An object for estimating the frequency modulation of a dataset. Args: data (ndarray): Numerical numpy array of datapoints sampling_rate (float): Sample rate in Hz of datapoints"""
<|body_0|>
def find_inversions(self):
... | stack_v2_sparse_classes_75kplus_train_071062 | 3,150 | no_license | [
{
"docstring": "An object for estimating the frequency modulation of a dataset. Args: data (ndarray): Numerical numpy array of datapoints sampling_rate (float): Sample rate in Hz of datapoints",
"name": "__init__",
"signature": "def __init__(self, data, sampling_rate)"
},
{
"docstring": "Find ph... | 4 | null | Implement the Python class `Frequency` described below.
Class description:
Implement the Frequency class.
Method signatures and docstrings:
- def __init__(self, data, sampling_rate): An object for estimating the frequency modulation of a dataset. Args: data (ndarray): Numerical numpy array of datapoints sampling_rate... | Implement the Python class `Frequency` described below.
Class description:
Implement the Frequency class.
Method signatures and docstrings:
- def __init__(self, data, sampling_rate): An object for estimating the frequency modulation of a dataset. Args: data (ndarray): Numerical numpy array of datapoints sampling_rate... | f8653fb6bb876754e0474bc034b6730fe3ed0882 | <|skeleton|>
class Frequency:
def __init__(self, data, sampling_rate):
"""An object for estimating the frequency modulation of a dataset. Args: data (ndarray): Numerical numpy array of datapoints sampling_rate (float): Sample rate in Hz of datapoints"""
<|body_0|>
def find_inversions(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Frequency:
def __init__(self, data, sampling_rate):
"""An object for estimating the frequency modulation of a dataset. Args: data (ndarray): Numerical numpy array of datapoints sampling_rate (float): Sample rate in Hz of datapoints"""
if not isinstance(data, np.ndarray):
raise Freq... | the_stack_v2_python_sparse | seismic/frequency/freq.py | t0mmyt/seismic-detector | train | 3 | |
af3a15a1d689a07b166ba0a904a6d65e908cb79b | [
"firstid = None\nwhile True:\n q = qry\n if firstid is not None:\n q = qry.filter(pk_attr > firstid)\n rec = None\n for rec in q.order_by(pk_attr).limit(maxrq):\n yield rec\n if rec is None:\n break\n firstid = pk_attr.__get__(rec, pk_attr) if rec else None",
"count_q = q.st... | <|body_start_0|>
firstid = None
while True:
q = qry
if firstid is not None:
q = qry.filter(pk_attr > firstid)
rec = None
for rec in q.order_by(pk_attr).limit(maxrq):
yield rec
if rec is None:
brea... | DbHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbHelper:
def yield_limit(qry, pk_attr, maxrq=100):
"""specialized windowed query generator (using LIMIT/OFFSET) This recipe is to select through a large number of rows thats too large to fetch at once. The technique depends on the primary key of the FROM clause being an integer value, a... | stack_v2_sparse_classes_75kplus_train_071063 | 4,676 | permissive | [
{
"docstring": "specialized windowed query generator (using LIMIT/OFFSET) This recipe is to select through a large number of rows thats too large to fetch at once. The technique depends on the primary key of the FROM clause being an integer value, and selects items using LIMIT.",
"name": "yield_limit",
... | 2 | stack_v2_sparse_classes_30k_test_001214 | Implement the Python class `DbHelper` described below.
Class description:
Implement the DbHelper class.
Method signatures and docstrings:
- def yield_limit(qry, pk_attr, maxrq=100): specialized windowed query generator (using LIMIT/OFFSET) This recipe is to select through a large number of rows thats too large to fet... | Implement the Python class `DbHelper` described below.
Class description:
Implement the DbHelper class.
Method signatures and docstrings:
- def yield_limit(qry, pk_attr, maxrq=100): specialized windowed query generator (using LIMIT/OFFSET) This recipe is to select through a large number of rows thats too large to fet... | 40bb31efdde0409f5851200f116e721f77ffc5ba | <|skeleton|>
class DbHelper:
def yield_limit(qry, pk_attr, maxrq=100):
"""specialized windowed query generator (using LIMIT/OFFSET) This recipe is to select through a large number of rows thats too large to fetch at once. The technique depends on the primary key of the FROM clause being an integer value, a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DbHelper:
def yield_limit(qry, pk_attr, maxrq=100):
"""specialized windowed query generator (using LIMIT/OFFSET) This recipe is to select through a large number of rows thats too large to fetch at once. The technique depends on the primary key of the FROM clause being an integer value, and selects ite... | the_stack_v2_python_sparse | zemanfeed/databaseutils.py | yolosec/zeman-parser | train | 1 | |
393e33585935b8e42c34584aeb807e722c2096c8 | [
"if matrix is None or rows < 1 or cols < 1 or (path is None):\n return False\nmem = [[False for i in range(cols)] for j in range(rows)]\ncur_path_length = 0\nfor row in range(rows):\n for col in range(cols):\n cur_path_length = 0\n res = self.has_path(matrix, row, col, rows, cols, cur_path_lengt... | <|body_start_0|>
if matrix is None or rows < 1 or cols < 1 or (path is None):
return False
mem = [[False for i in range(cols)] for j in range(rows)]
cur_path_length = 0
for row in range(rows):
for col in range(cols):
cur_path_length = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPath(self, matrix, rows, cols, path):
"""寻找字符矩阵中相邻元素是否可以组成给定的path Arguments: matrix {list} -- 字符矩阵 rows {int} -- 矩阵总行数 cols {int} -- 矩阵总列数 path {str} -- 给定字符串路径 Returns: bool -- 是否存在路径"""
<|body_0|>
def has_path(self, matrix, row, col, rows, cols, cur_path_l... | stack_v2_sparse_classes_75kplus_train_071064 | 2,736 | no_license | [
{
"docstring": "寻找字符矩阵中相邻元素是否可以组成给定的path Arguments: matrix {list} -- 字符矩阵 rows {int} -- 矩阵总行数 cols {int} -- 矩阵总列数 path {str} -- 给定字符串路径 Returns: bool -- 是否存在路径",
"name": "hasPath",
"signature": "def hasPath(self, matrix, rows, cols, path)"
},
{
"docstring": "矩阵路径搜索函数 Arguments: matrix {list} -- ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPath(self, matrix, rows, cols, path): 寻找字符矩阵中相邻元素是否可以组成给定的path Arguments: matrix {list} -- 字符矩阵 rows {int} -- 矩阵总行数 cols {int} -- 矩阵总列数 path {str} -- 给定字符串路径 Returns: bool... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPath(self, matrix, rows, cols, path): 寻找字符矩阵中相邻元素是否可以组成给定的path Arguments: matrix {list} -- 字符矩阵 rows {int} -- 矩阵总行数 cols {int} -- 矩阵总列数 path {str} -- 给定字符串路径 Returns: bool... | 88045c7618ad84cbbd38dff00be763bccaaa3fad | <|skeleton|>
class Solution:
def hasPath(self, matrix, rows, cols, path):
"""寻找字符矩阵中相邻元素是否可以组成给定的path Arguments: matrix {list} -- 字符矩阵 rows {int} -- 矩阵总行数 cols {int} -- 矩阵总列数 path {str} -- 给定字符串路径 Returns: bool -- 是否存在路径"""
<|body_0|>
def has_path(self, matrix, row, col, rows, cols, cur_path_l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasPath(self, matrix, rows, cols, path):
"""寻找字符矩阵中相邻元素是否可以组成给定的path Arguments: matrix {list} -- 字符矩阵 rows {int} -- 矩阵总行数 cols {int} -- 矩阵总列数 path {str} -- 给定字符串路径 Returns: bool -- 是否存在路径"""
if matrix is None or rows < 1 or cols < 1 or (path is None):
return False
... | the_stack_v2_python_sparse | 12_find_str_path_in_matrix.py | Mountain-AI/python-to-the-offer | train | 0 | |
4fdb3d81aae1488105dd2a6ed7c0395561a42e43 | [
"Scheduling.setDefaults(self)\nself.max_visits_goal = 250000\nself.restart_lost_sequences = True\nself.restart_complete_sequences = True",
"pexConfig.Config.validate(self)\nif self.max_visits_goal < 1:\n raise ValueError('Maximum Visits Goal should be greater than zero.')"
] | <|body_start_0|>
Scheduling.setDefaults(self)
self.max_visits_goal = 250000
self.restart_lost_sequences = True
self.restart_complete_sequences = True
<|end_body_0|>
<|body_start_1|>
pexConfig.Config.validate(self)
if self.max_visits_goal < 1:
raise ValueError... | Configuration for a Sequence proposal's scheduling needs. | SequenceScheduling | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceScheduling:
"""Configuration for a Sequence proposal's scheduling needs."""
def setDefaults(self):
"""Default specification for scheduling information."""
<|body_0|>
def validate(self):
"""Validate configuration parameters."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_071065 | 1,406 | no_license | [
{
"docstring": "Default specification for scheduling information.",
"name": "setDefaults",
"signature": "def setDefaults(self)"
},
{
"docstring": "Validate configuration parameters.",
"name": "validate",
"signature": "def validate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047600 | Implement the Python class `SequenceScheduling` described below.
Class description:
Configuration for a Sequence proposal's scheduling needs.
Method signatures and docstrings:
- def setDefaults(self): Default specification for scheduling information.
- def validate(self): Validate configuration parameters. | Implement the Python class `SequenceScheduling` described below.
Class description:
Configuration for a Sequence proposal's scheduling needs.
Method signatures and docstrings:
- def setDefaults(self): Default specification for scheduling information.
- def validate(self): Validate configuration parameters.
<|skeleto... | d6988cb11b79f0a41bc8509fc2c0c57ec67ab579 | <|skeleton|>
class SequenceScheduling:
"""Configuration for a Sequence proposal's scheduling needs."""
def setDefaults(self):
"""Default specification for scheduling information."""
<|body_0|>
def validate(self):
"""Validate configuration parameters."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequenceScheduling:
"""Configuration for a Sequence proposal's scheduling needs."""
def setDefaults(self):
"""Default specification for scheduling information."""
Scheduling.setDefaults(self)
self.max_visits_goal = 250000
self.restart_lost_sequences = True
self.res... | the_stack_v2_python_sparse | python/lsst/sims/schedulerConfig/proposal/sequence_scheduling.py | lsst-sims/sims_schedulerConfig | train | 1 |
049835d87fada23eef46d43b92a0d23c98b36672 | [
"collection_query = Collection.objects.filter(pk=collection_id)\nif not collection_query.exists():\n raise exceptions.ValidationError('Collection id does not exist')\ncollection = collection_query.first()\nif not user.has_perm('edit_collection', obj=collection):\n if user.is_authenticated:\n raise exce... | <|body_start_0|>
collection_query = Collection.objects.filter(pk=collection_id)
if not collection_query.exists():
raise exceptions.ValidationError('Collection id does not exist')
collection = collection_query.first()
if not user.has_perm('edit_collection', obj=collection):
... | API view for entities. | EntityViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityViewSet:
"""API view for entities."""
def _get_collection_for_user(self, collection_id, user):
"""Check that collection exists and user has `edit` permission."""
<|body_0|>
def _get_entities(self, user, ids):
"""Return entities queryset based on provided en... | stack_v2_sparse_classes_75kplus_train_071066 | 4,913 | permissive | [
{
"docstring": "Check that collection exists and user has `edit` permission.",
"name": "_get_collection_for_user",
"signature": "def _get_collection_for_user(self, collection_id, user)"
},
{
"docstring": "Return entities queryset based on provided entity ids.",
"name": "_get_entities",
"... | 6 | stack_v2_sparse_classes_30k_test_000507 | Implement the Python class `EntityViewSet` described below.
Class description:
API view for entities.
Method signatures and docstrings:
- def _get_collection_for_user(self, collection_id, user): Check that collection exists and user has `edit` permission.
- def _get_entities(self, user, ids): Return entities queryset... | Implement the Python class `EntityViewSet` described below.
Class description:
API view for entities.
Method signatures and docstrings:
- def _get_collection_for_user(self, collection_id, user): Check that collection exists and user has `edit` permission.
- def _get_entities(self, user, ids): Return entities queryset... | b52d1223a98efe676758e6b65c4dd691696edb3d | <|skeleton|>
class EntityViewSet:
"""API view for entities."""
def _get_collection_for_user(self, collection_id, user):
"""Check that collection exists and user has `edit` permission."""
<|body_0|>
def _get_entities(self, user, ids):
"""Return entities queryset based on provided en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntityViewSet:
"""API view for entities."""
def _get_collection_for_user(self, collection_id, user):
"""Check that collection exists and user has `edit` permission."""
collection_query = Collection.objects.filter(pk=collection_id)
if not collection_query.exists():
rais... | the_stack_v2_python_sparse | resolwe/flow/views/entity.py | hadalin/resolwe | train | 0 |
1c7a8fe3bcfcbd92657f470ce4e921f1e554c5a0 | [
"super(InitRiseVelFromDropletSizeFromDist, self).__init__(**kwargs)\nif distribution:\n self.distribution = distribution\nelse:\n raise TypeError('InitRiseVelFromDropletSizeFromDist requires a distribution for droplet sizes')\nself.water_viscosity = water_viscosity\nself.water_density = water_density\nself.ar... | <|body_start_0|>
super(InitRiseVelFromDropletSizeFromDist, self).__init__(**kwargs)
if distribution:
self.distribution = distribution
else:
raise TypeError('InitRiseVelFromDropletSizeFromDist requires a distribution for droplet sizes')
self.water_viscosity = water... | InitRiseVelFromDropletSizeFromDist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity ... | stack_v2_sparse_classes_75kplus_train_071067 | 15,769 | no_license | [
{
"docstring": "Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity from droplet size. Even though the droplet size is not changing over time, it is still stored in data array, as it can be useful for post-pro... | 2 | stack_v2_sparse_classes_30k_train_035553 | Implement the Python class `InitRiseVelFromDropletSizeFromDist` described below.
Class description:
Implement the InitRiseVelFromDropletSizeFromDist class.
Method signatures and docstrings:
- def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs): Set the droplet size from a dist... | Implement the Python class `InitRiseVelFromDropletSizeFromDist` described below.
Class description:
Implement the InitRiseVelFromDropletSizeFromDist class.
Method signatures and docstrings:
- def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs): Set the droplet size from a dist... | 9fd9ce3aab0d3a16ead2aa773a140c905beb3ef1 | <|skeleton|>
class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity from droplet s... | the_stack_v2_python_sparse | py_gnome/gnome/spill/initializers.py | calypso-science/PyGnome | train | 0 | |
69ca788be8767ce87ae06f432912259dc4651fc2 | [
"user = UserProfile.objects.filter(Q(email=email) | Q(username=username)).first()\nif user is None:\n raise AuthenticationError('Not user found with this email.')\nif not user.is_active:\n raise AuthenticationError('This account is deactivate.')\nif not user.approved:\n raise AuthenticationError('This acco... | <|body_start_0|>
user = UserProfile.objects.filter(Q(email=email) | Q(username=username)).first()
if user is None:
raise AuthenticationError('Not user found with this email.')
if not user.is_active:
raise AuthenticationError('This account is deactivate.')
if not u... | Serializer for the user authentication object. | AuthTokenSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthTokenSerializer:
"""Serializer for the user authentication object."""
def authenticate_user(self, email: str=None, username: str=None, password: str=None) -> Any:
"""Authenticate with username and password. Args: email: username: password: Returns: User."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_071068 | 2,704 | no_license | [
{
"docstring": "Authenticate with username and password. Args: email: username: password: Returns: User.",
"name": "authenticate_user",
"signature": "def authenticate_user(self, email: str=None, username: str=None, password: str=None) -> Any"
},
{
"docstring": "Validate a member with credentials... | 2 | stack_v2_sparse_classes_30k_train_051833 | Implement the Python class `AuthTokenSerializer` described below.
Class description:
Serializer for the user authentication object.
Method signatures and docstrings:
- def authenticate_user(self, email: str=None, username: str=None, password: str=None) -> Any: Authenticate with username and password. Args: email: use... | Implement the Python class `AuthTokenSerializer` described below.
Class description:
Serializer for the user authentication object.
Method signatures and docstrings:
- def authenticate_user(self, email: str=None, username: str=None, password: str=None) -> Any: Authenticate with username and password. Args: email: use... | 47c9a2a3c724589b77299ca33aa60a291ada33ef | <|skeleton|>
class AuthTokenSerializer:
"""Serializer for the user authentication object."""
def authenticate_user(self, email: str=None, username: str=None, password: str=None) -> Any:
"""Authenticate with username and password. Args: email: username: password: Returns: User."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthTokenSerializer:
"""Serializer for the user authentication object."""
def authenticate_user(self, email: str=None, username: str=None, password: str=None) -> Any:
"""Authenticate with username and password. Args: email: username: password: Returns: User."""
user = UserProfile.objects.... | the_stack_v2_python_sparse | core/backend/endpoints/user/serializers.py | msadour/german_memo | train | 0 |
2e365ddc3c90c6567859d56853ce40152caebf40 | [
"self.__front_view_ctrl_point = _cfg.ROI.CPT_FV\nself.__top_view_ctrl_point = _cfg.ROI.CPT_TOP\nself.__warped_size = _cfg.ROI.WARPED_SIZE",
"fv_ctrl_point = np.array(self.__front_view_ctrl_point).astype(dtype=np.float32)\ntop_ctrl_point = np.array(self.__top_view_ctrl_point).astype(dtype=np.float32)\nwarp_transfo... | <|body_start_0|>
self.__front_view_ctrl_point = _cfg.ROI.CPT_FV
self.__top_view_ctrl_point = _cfg.ROI.CPT_TOP
self.__warped_size = _cfg.ROI.WARPED_SIZE
<|end_body_0|>
<|body_start_1|>
fv_ctrl_point = np.array(self.__front_view_ctrl_point).astype(dtype=np.float32)
top_ctrl_point ... | PerspectiveTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerspectiveTransformer:
def __init__(self, _cfg):
"""Set the control point of front view and top view image eg. __C.ROI.CPT_FV = [(98, 701), (770, 701), (291, 541), (645, 541)] __C.ROI.CPT_TOP = [(425, 701), (525, 701), (425, 600), (525, 600)] :param _cfg:"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_071069 | 5,039 | permissive | [
{
"docstring": "Set the control point of front view and top view image eg. __C.ROI.CPT_FV = [(98, 701), (770, 701), (291, 541), (645, 541)] __C.ROI.CPT_TOP = [(425, 701), (525, 701), (425, 600), (525, 600)] :param _cfg:",
"name": "__init__",
"signature": "def __init__(self, _cfg)"
},
{
"docstrin... | 6 | null | Implement the Python class `PerspectiveTransformer` described below.
Class description:
Implement the PerspectiveTransformer class.
Method signatures and docstrings:
- def __init__(self, _cfg): Set the control point of front view and top view image eg. __C.ROI.CPT_FV = [(98, 701), (770, 701), (291, 541), (645, 541)] ... | Implement the Python class `PerspectiveTransformer` described below.
Class description:
Implement the PerspectiveTransformer class.
Method signatures and docstrings:
- def __init__(self, _cfg): Set the control point of front view and top view image eg. __C.ROI.CPT_FV = [(98, 701), (770, 701), (291, 541), (645, 541)] ... | b66a1a856ba69b0a0a82c7b53dd192e4906a375b | <|skeleton|>
class PerspectiveTransformer:
def __init__(self, _cfg):
"""Set the control point of front view and top view image eg. __C.ROI.CPT_FV = [(98, 701), (770, 701), (291, 541), (645, 541)] __C.ROI.CPT_TOP = [(425, 701), (525, 701), (425, 600), (525, 600)] :param _cfg:"""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PerspectiveTransformer:
def __init__(self, _cfg):
"""Set the control point of front view and top view image eg. __C.ROI.CPT_FV = [(98, 701), (770, 701), (291, 541), (645, 541)] __C.ROI.CPT_TOP = [(425, 701), (525, 701), (425, 600), (525, 600)] :param _cfg:"""
self.__front_view_ctrl_point = _cf... | the_stack_v2_python_sparse | Extract_line_candidates/inverse_perspective_map.py | robin1987z/DVCNN_Lane_Detection | train | 0 | |
e9026ed6ef1e56b0b6f19169b742fbe6354340b1 | [
"for h in self._all:\n if h is not None:\n h.detach_()",
"for e in self._all:\n a, br, d = e.size()\n sentStates = e.view(a, beam_size, br // beam_size, d)[:, :, idx]\n sentStates.data.copy_(sentStates.data.index_select(1, positions))"
] | <|body_start_0|>
for h in self._all:
if h is not None:
h.detach_()
<|end_body_0|>
<|body_start_1|>
for e in self._all:
a, br, d = e.size()
sentStates = e.view(a, beam_size, br // beam_size, d)[:, :, idx]
sentStates.data.copy_(sentStates.da... | DecoderState is a base class for models, used during translation for storing translation states. | DecoderState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderState:
"""DecoderState is a base class for models, used during translation for storing translation states."""
def detach(self):
"""Detaches all Variables from the graph that created it, making it a leaf."""
<|body_0|>
def beam_update(self, idx, positions, beam_siz... | stack_v2_sparse_classes_75kplus_train_071070 | 39,461 | no_license | [
{
"docstring": "Detaches all Variables from the graph that created it, making it a leaf.",
"name": "detach",
"signature": "def detach(self)"
},
{
"docstring": "Update when beam advances.",
"name": "beam_update",
"signature": "def beam_update(self, idx, positions, beam_size)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038188 | Implement the Python class `DecoderState` described below.
Class description:
DecoderState is a base class for models, used during translation for storing translation states.
Method signatures and docstrings:
- def detach(self): Detaches all Variables from the graph that created it, making it a leaf.
- def beam_updat... | Implement the Python class `DecoderState` described below.
Class description:
DecoderState is a base class for models, used during translation for storing translation states.
Method signatures and docstrings:
- def detach(self): Detaches all Variables from the graph that created it, making it a leaf.
- def beam_updat... | 8b159fcbf1bc9faad5a2ef1c0690090037143899 | <|skeleton|>
class DecoderState:
"""DecoderState is a base class for models, used during translation for storing translation states."""
def detach(self):
"""Detaches all Variables from the graph that created it, making it a leaf."""
<|body_0|>
def beam_update(self, idx, positions, beam_siz... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderState:
"""DecoderState is a base class for models, used during translation for storing translation states."""
def detach(self):
"""Detaches all Variables from the graph that created it, making it a leaf."""
for h in self._all:
if h is not None:
h.detach_... | the_stack_v2_python_sparse | disf_gen_coarse2fine/table/Models.py | JingfengYang/Disfluency-Generation-and-Detection | train | 5 |
7b6bfea4bdd1d379164831142d04323c47aaf368 | [
"l, r = (0, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n if nums[m] == target:\n return m\n if nums[m] < nums[r]:\n if nums[m] < target <= nums[r]:\n l = m + 1\n else:\n r = m - 1\n elif nums[l] <= target < nums[m]:\n r = m - 1\n else:\n ... | <|body_start_0|>
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
if nums[m] < nums[r]:
if nums[m] < target <= nums[r]:
l = m + 1
else:
r = m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l,... | stack_v2_sparse_classes_75kplus_train_071071 | 1,611 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search1",
"signature": "def search1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041533 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
<|skel... | 763674fcbe271af3d21eed790c3968c4d33f7b09 | <|skeleton|>
class Solution:
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
l, r = (0, len(nums) - 1)
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return m
if nums[m] < nums[r]:
if nums... | the_stack_v2_python_sparse | 33_search_in_rotated_sorted_array/33.py | guzhoudiaoke/leetcode_python3 | train | 0 | |
bcab507ed6594002169ec19204752a07ed547fef | [
"if 'estimator' in self.parameters:\n key = self.parameters['estimator']\n self.parameters['estimator'] = self.library.component[key]\nreturn self",
"try:\n self.contents.parameters = self.contents.parameters.finalize(project=project)\nexcept AttributeError:\n pass\nself.adjust_parameters(project=proj... | <|body_start_0|>
if 'estimator' in self.parameters:
key = self.parameters['estimator']
self.parameters['estimator'] = self.library.component[key]
return self
<|end_body_0|>
<|body_start_1|>
try:
self.contents.parameters = self.contents.parameters.finalize(pro... | Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicus. For example, if an amicus instance needs settings from a Configuration... | Reduce | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reduce:
"""Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicus. For example, if an amicus instance n... | stack_v2_sparse_classes_75kplus_train_071072 | 4,911 | permissive | [
{
"docstring": "[summary] Args: project (amicus.Project): [description] Returns: [type]: [description]",
"name": "adjust_parameters",
"signature": "def adjust_parameters(self, project: amicus.Project) -> None"
},
{
"docstring": "[summary] Args: project (amicus.Project): [description] Returns: am... | 2 | stack_v2_sparse_classes_30k_train_041088 | Implement the Python class `Reduce` described below.
Class description:
Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicu... | Implement the Python class `Reduce` described below.
Class description:
Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicu... | 0de6d90c34b8402f4464dcba784349514b3b8e42 | <|skeleton|>
class Reduce:
"""Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicus. For example, if an amicus instance n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Reduce:
"""Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicus. For example, if an amicus instance needs settings... | the_stack_v2_python_sparse | amicus/simplify/analyst/reduce.py | WithPrecedent/amicus | train | 1 |
dd40ef9d678f5f8da92653c5e185af88ab9c967c | [
"pmodel = multi_gpu_model(ser_model, gpus)\nself.__dict__.update(pmodel.__dict__)\nself._smodel = ser_model",
"if 'load' in attrname or 'save' in attrname:\n return getattr(self._smodel, attrname)\nreturn super(ModelMGPU, self).__getattribute__(attrname)"
] | <|body_start_0|>
pmodel = multi_gpu_model(ser_model, gpus)
self.__dict__.update(pmodel.__dict__)
self._smodel = ser_model
<|end_body_0|>
<|body_start_1|>
if 'load' in attrname or 'save' in attrname:
return getattr(self._smodel, attrname)
return super(ModelMGPU, self)... | ModelMGPU | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelMGPU:
def __init__(self, ser_model, gpus=N_GPUS):
"""Copied from https://github.com/keras-team/keras/issues/2436"""
<|body_0|>
def __getattribute__(self, attrname):
"""Override load and save methods to be used from the serial-model. The serial-model holds refere... | stack_v2_sparse_classes_75kplus_train_071073 | 1,500 | permissive | [
{
"docstring": "Copied from https://github.com/keras-team/keras/issues/2436",
"name": "__init__",
"signature": "def __init__(self, ser_model, gpus=N_GPUS)"
},
{
"docstring": "Override load and save methods to be used from the serial-model. The serial-model holds references to the weights in the ... | 2 | stack_v2_sparse_classes_30k_train_029912 | Implement the Python class `ModelMGPU` described below.
Class description:
Implement the ModelMGPU class.
Method signatures and docstrings:
- def __init__(self, ser_model, gpus=N_GPUS): Copied from https://github.com/keras-team/keras/issues/2436
- def __getattribute__(self, attrname): Override load and save methods t... | Implement the Python class `ModelMGPU` described below.
Class description:
Implement the ModelMGPU class.
Method signatures and docstrings:
- def __init__(self, ser_model, gpus=N_GPUS): Copied from https://github.com/keras-team/keras/issues/2436
- def __getattribute__(self, attrname): Override load and save methods t... | c5af073f064db67d92b22705899c0d0263caec58 | <|skeleton|>
class ModelMGPU:
def __init__(self, ser_model, gpus=N_GPUS):
"""Copied from https://github.com/keras-team/keras/issues/2436"""
<|body_0|>
def __getattribute__(self, attrname):
"""Override load and save methods to be used from the serial-model. The serial-model holds refere... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelMGPU:
def __init__(self, ser_model, gpus=N_GPUS):
"""Copied from https://github.com/keras-team/keras/issues/2436"""
pmodel = multi_gpu_model(ser_model, gpus)
self.__dict__.update(pmodel.__dict__)
self._smodel = ser_model
def __getattribute__(self, attrname):
"... | the_stack_v2_python_sparse | cgsa/dl/utils.py | gghidiu/CGSA | train | 0 | |
821c242fe3f06cc779fcf4e29287f6805b691f55 | [
"self._device_type = device_type\nself._profile_plist_obj = None\nself._min_os_version = None\nself._max_os_version = None",
"if not self._profile_plist_obj:\n xcode_version = xcode_info_util.GetXcodeVersionNumber()\n platform_path = xcode_info_util.GetSdkPlatformPath(ios_constants.SDK.IPHONEOS)\n if xco... | <|body_start_0|>
self._device_type = device_type
self._profile_plist_obj = None
self._min_os_version = None
self._max_os_version = None
<|end_body_0|>
<|body_start_1|>
if not self._profile_plist_obj:
xcode_version = xcode_info_util.GetXcodeVersionNumber()
... | The object for simulator device type's profile. | SimTypeProfile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimTypeProfile:
"""The object for simulator device type's profile."""
def __init__(self, device_type):
"""Constructor of SimulatorProfile object. Args: device_type: string, device type of the new simulator. The value corresponds to the output of `xcrun simctl list devicetypes`. E.g.,... | stack_v2_sparse_classes_75kplus_train_071074 | 3,799 | permissive | [
{
"docstring": "Constructor of SimulatorProfile object. Args: device_type: string, device type of the new simulator. The value corresponds to the output of `xcrun simctl list devicetypes`. E.g., iPhone 6, iPad Air, etc.",
"name": "__init__",
"signature": "def __init__(self, device_type)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_045039 | Implement the Python class `SimTypeProfile` described below.
Class description:
The object for simulator device type's profile.
Method signatures and docstrings:
- def __init__(self, device_type): Constructor of SimulatorProfile object. Args: device_type: string, device type of the new simulator. The value correspond... | Implement the Python class `SimTypeProfile` described below.
Class description:
The object for simulator device type's profile.
Method signatures and docstrings:
- def __init__(self, device_type): Constructor of SimulatorProfile object. Args: device_type: string, device type of the new simulator. The value correspond... | b7698df3d435b6491b4b4c0f9fc7a63fbed5e3a6 | <|skeleton|>
class SimTypeProfile:
"""The object for simulator device type's profile."""
def __init__(self, device_type):
"""Constructor of SimulatorProfile object. Args: device_type: string, device type of the new simulator. The value corresponds to the output of `xcrun simctl list devicetypes`. E.g.,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimTypeProfile:
"""The object for simulator device type's profile."""
def __init__(self, device_type):
"""Constructor of SimulatorProfile object. Args: device_type: string, device type of the new simulator. The value corresponds to the output of `xcrun simctl list devicetypes`. E.g., iPhone 6, iP... | the_stack_v2_python_sparse | xctestrunner/simulator_control/simtype_profile.py | google/xctestrunner | train | 142 |
52dfbaa9f1c2815b455ed874bc63f5b16d215baa | [
"cleaned_data = super(ResetPasswordForm, self).clean()\npassword = cleaned_data.get('password')\npassword_confirmation = cleaned_data.get('password_confirmation')\nif password and password_confirmation:\n if password != password_confirmation:\n self.add_error('password_confirmation', 'Does not match passw... | <|body_start_0|>
cleaned_data = super(ResetPasswordForm, self).clean()
password = cleaned_data.get('password')
password_confirmation = cleaned_data.get('password_confirmation')
if password and password_confirmation:
if password != password_confirmation:
self.a... | Reset password form class. | ResetPasswordForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordForm:
"""Reset password form class."""
def clean(self):
"""Clean data and add custom validation."""
<|body_0|>
def submit(self):
"""Find user by token and change his password."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cleaned_... | stack_v2_sparse_classes_75kplus_train_071075 | 1,443 | no_license | [
{
"docstring": "Clean data and add custom validation.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Find user by token and change his password.",
"name": "submit",
"signature": "def submit(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021233 | Implement the Python class `ResetPasswordForm` described below.
Class description:
Reset password form class.
Method signatures and docstrings:
- def clean(self): Clean data and add custom validation.
- def submit(self): Find user by token and change his password. | Implement the Python class `ResetPasswordForm` described below.
Class description:
Reset password form class.
Method signatures and docstrings:
- def clean(self): Clean data and add custom validation.
- def submit(self): Find user by token and change his password.
<|skeleton|>
class ResetPasswordForm:
"""Reset p... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class ResetPasswordForm:
"""Reset password form class."""
def clean(self):
"""Clean data and add custom validation."""
<|body_0|>
def submit(self):
"""Find user by token and change his password."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResetPasswordForm:
"""Reset password form class."""
def clean(self):
"""Clean data and add custom validation."""
cleaned_data = super(ResetPasswordForm, self).clean()
password = cleaned_data.get('password')
password_confirmation = cleaned_data.get('password_confirmation')
... | the_stack_v2_python_sparse | app/authorization/forms/reset_password.py | vsokoltsov/Interview360Server | train | 2 |
0c2a099823d5ccba1ae9c71384818ac57ce242a9 | [
"super(AnalyticAcquisitionFunction, self).__init__(model=model)\nself.posterior_transform = None\nself.maximize = maximize\nself.objective_index = objective_index\nself.constraints = constraints\nself.register_buffer('best_f', torch.as_tensor(best_f))\n_preprocess_constraint_bounds(self, constraints=constraints)\ns... | <|body_start_0|>
super(AnalyticAcquisitionFunction, self).__init__(model=model)
self.posterior_transform = None
self.maximize = maximize
self.objective_index = objective_index
self.constraints = constraints
self.register_buffer('best_f', torch.as_tensor(best_f))
_... | Constrained Expected Improvement (feasibility-weighted). Computes the analytic expected improvement for a Normal posterior distribution, weighted by a probability of feasibility. The objective and constraints are assumed to be independent and have Gaussian posterior distributions. Only supports non-batch mode (i.e. `q=... | ConstrainedExpectedImprovement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstrainedExpectedImprovement:
"""Constrained Expected Improvement (feasibility-weighted). Computes the analytic expected improvement for a Normal posterior distribution, weighted by a probability of feasibility. The objective and constraints are assumed to be independent and have Gaussian poste... | stack_v2_sparse_classes_75kplus_train_071076 | 46,601 | permissive | [
{
"docstring": "Analytic Constrained Expected Improvement. Args: model: A fitted multi-output model. best_f: Either a scalar or a `b`-dim Tensor (batch mode) representing the best feasible function value observed so far (assumed noiseless). objective_index: The index of the objective. constraints: A dictionary ... | 2 | stack_v2_sparse_classes_30k_train_010369 | Implement the Python class `ConstrainedExpectedImprovement` described below.
Class description:
Constrained Expected Improvement (feasibility-weighted). Computes the analytic expected improvement for a Normal posterior distribution, weighted by a probability of feasibility. The objective and constraints are assumed to... | Implement the Python class `ConstrainedExpectedImprovement` described below.
Class description:
Constrained Expected Improvement (feasibility-weighted). Computes the analytic expected improvement for a Normal posterior distribution, weighted by a probability of feasibility. The objective and constraints are assumed to... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class ConstrainedExpectedImprovement:
"""Constrained Expected Improvement (feasibility-weighted). Computes the analytic expected improvement for a Normal posterior distribution, weighted by a probability of feasibility. The objective and constraints are assumed to be independent and have Gaussian poste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConstrainedExpectedImprovement:
"""Constrained Expected Improvement (feasibility-weighted). Computes the analytic expected improvement for a Normal posterior distribution, weighted by a probability of feasibility. The objective and constraints are assumed to be independent and have Gaussian posterior distribu... | the_stack_v2_python_sparse | botorch/acquisition/analytic.py | pytorch/botorch | train | 2,891 |
639a3fa148c31ef2c6d05d59a76c6c4f2d9c2a95 | [
"self.hostname = host\nself.translation = Translator(config, self.hostname)\nself.ifindexes = ifindexes\nself.lookup = lookup\nself.config = config",
"port_data = self.translation.ethernet_data()\ndata = Port(port_data, self.hostname, self.config, self.lookup, ifindexes=self.ifindexes).data()\ntable = PortTable(d... | <|body_start_0|>
self.hostname = host
self.translation = Translator(config, self.hostname)
self.ifindexes = ifindexes
self.lookup = lookup
self.config = config
<|end_body_0|>
<|body_start_1|>
port_data = self.translation.ethernet_data()
data = Port(port_data, sel... | Class that creates the device's various HTML tables. | Device | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Device:
"""Class that creates the device's various HTML tables."""
def __init__(self, host, config, lookup, ifindexes=None):
"""Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, ... | stack_v2_sparse_classes_75kplus_train_071077 | 18,522 | permissive | [
{
"docstring": "Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, then do all. Returns: None",
"name": "__init__",
"signature": "def __init__(self, host, config, lookup, ifindexes=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_009351 | Implement the Python class `Device` described below.
Class description:
Class that creates the device's various HTML tables.
Method signatures and docstrings:
- def __init__(self, host, config, lookup, ifindexes=None): Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to pr... | Implement the Python class `Device` described below.
Class description:
Class that creates the device's various HTML tables.
Method signatures and docstrings:
- def __init__(self, host, config, lookup, ifindexes=None): Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to pr... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class Device:
"""Class that creates the device's various HTML tables."""
def __init__(self, host, config, lookup, ifindexes=None):
"""Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Device:
"""Class that creates the device's various HTML tables."""
def __init__(self, host, config, lookup, ifindexes=None):
"""Initialize the class. Args: config: Configuration object lookup: Lookup object host: Hostname to process ifindexes: List of ifindexes to retrieve. If None, then do all. ... | the_stack_v2_python_sparse | switchmap/www/pages/device.py | PalisadoesFoundation/switchmap-ng | train | 8 |
1cf1c50200bf7db66a330ac402c21562b213dc3c | [
"if self._isConstant:\n return np.full(len(x), self.getCalibrationMean())\nelse:\n bf = self.computeScaledCalibration()\n return self.getCalibrationMean() * bf.evaluate(x, y)",
"scale = self.getLocalCalibrationArray(x, y)\nnanoJansky = instFluxes * scale * units.nJy\nreturn nanoJansky.to(units.ABmag)",
... | <|body_start_0|>
if self._isConstant:
return np.full(len(x), self.getCalibrationMean())
else:
bf = self.computeScaledCalibration()
return self.getCalibrationMean() * bf.evaluate(x, y)
<|end_body_0|>
<|body_start_1|>
scale = self.getLocalCalibrationArray(x, y)... | PhotoCalib | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhotoCalib:
def getLocalCalibrationArray(self, x, y):
"""Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `... | stack_v2_sparse_classes_75kplus_train_071078 | 3,309 | no_license | [
{
"docstring": "Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `np.ndarray` (N,) Array of local calibration values (nJy/counts)."... | 3 | stack_v2_sparse_classes_30k_train_053054 | Implement the Python class `PhotoCalib` described below.
Class description:
Implement the PhotoCalib class.
Method signatures and docstrings:
- def getLocalCalibrationArray(self, x, y): Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x valu... | Implement the Python class `PhotoCalib` described below.
Class description:
Implement the PhotoCalib class.
Method signatures and docstrings:
- def getLocalCalibrationArray(self, x, y): Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x valu... | 5b0a8152295a779573e119dde2297b13acc35365 | <|skeleton|>
class PhotoCalib:
def getLocalCalibrationArray(self, x, y):
"""Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PhotoCalib:
def getLocalCalibrationArray(self, x, y):
"""Get the local calibration values (nJy/counts) for numpy arrays (pixels). Parameters ---------- x : `np.ndarray` (N,) Array of x values (pixels). y : `np.ndarray` (N,) Array of y values (pixels). Returns ------- localCalibration : `np.ndarray` (N... | the_stack_v2_python_sparse | python/lsst/afw/image/_photoCalibContinued.py | lsst/afw | train | 18 | |
638f555a601eee3b590f8aca01350c63e376805b | [
"self._num_masks = num_masks\nself._mask_height = mask_height\nself._mask_width = mask_width\nself._num_conv_layers = num_conv_layers\nself._depths = depths\nself._conv_hyperparams_fn = conv_hyperparams_fn",
"with slim.arg_scope(self._conv_hyperparams_fn()):\n upsampled_features = tf.image.resize_bilinear(feat... | <|body_start_0|>
self._num_masks = num_masks
self._mask_height = mask_height
self._mask_width = mask_width
self._num_conv_layers = num_conv_layers
self._depths = depths
self._conv_hyperparams_fn = conv_hyperparams_fn
<|end_body_0|>
<|body_start_1|>
with slim.arg_... | RCNN Mask Predictor. Generates mask predictions for the mask branch in a Mask RCNN network. It takes as input a feature map of shape [batch_num_proposals, height, width, channels], where the slice [i, :, :, :] holds the features of the ith proposal from the RPN, and outputs mask predictions tensor of shape [batch_num_p... | RcnnMaskPredictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RcnnMaskPredictor:
"""RCNN Mask Predictor. Generates mask predictions for the mask branch in a Mask RCNN network. It takes as input a feature map of shape [batch_num_proposals, height, width, channels], where the slice [i, :, :, :] holds the features of the ith proposal from the RPN, and outputs ... | stack_v2_sparse_classes_75kplus_train_071079 | 4,726 | no_license | [
{
"docstring": "Constructor. Args: conv_hyperparams_fn: a callable that, when called, creates a dict holding arguments to `slim.arg_scope`. num_masks: int scalar, num of masks to be predicted per feature map. Typically set to `num_classes` or 1. mask_height: int scalar, mask height. mask_width: int scalar, mask... | 2 | stack_v2_sparse_classes_30k_val_000524 | Implement the Python class `RcnnMaskPredictor` described below.
Class description:
RCNN Mask Predictor. Generates mask predictions for the mask branch in a Mask RCNN network. It takes as input a feature map of shape [batch_num_proposals, height, width, channels], where the slice [i, :, :, :] holds the features of the ... | Implement the Python class `RcnnMaskPredictor` described below.
Class description:
RCNN Mask Predictor. Generates mask predictions for the mask branch in a Mask RCNN network. It takes as input a feature map of shape [batch_num_proposals, height, width, channels], where the slice [i, :, :, :] holds the features of the ... | 5a53e02c690632bcf140d1b17327959609aab395 | <|skeleton|>
class RcnnMaskPredictor:
"""RCNN Mask Predictor. Generates mask predictions for the mask branch in a Mask RCNN network. It takes as input a feature map of shape [batch_num_proposals, height, width, channels], where the slice [i, :, :, :] holds the features of the ith proposal from the RPN, and outputs ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RcnnMaskPredictor:
"""RCNN Mask Predictor. Generates mask predictions for the mask branch in a Mask RCNN network. It takes as input a feature map of shape [batch_num_proposals, height, width, channels], where the slice [i, :, :, :] holds the features of the ith proposal from the RPN, and outputs mask predicti... | the_stack_v2_python_sparse | core/mask_predictors.py | chao-ji/tf-detection | train | 2 |
08129cdf4610205c67008af816ffa118ac669692 | [
"Shop_Item.__init__(self, item_id, item_name, unit_price)\nList_Item.__init__(self, qty, request)\nself.butcher_name = butcher_name\nself.exp_date = exp_date\nself.wight = weight",
"res = Shop_Item.__repr__(self)\nres += '\\n' + List_Item.__repr__(self)\nres += '\\n' + 'butcher: ' + self.butcher_name + ', exp: ' ... | <|body_start_0|>
Shop_Item.__init__(self, item_id, item_name, unit_price)
List_Item.__init__(self, qty, request)
self.butcher_name = butcher_name
self.exp_date = exp_date
self.wight = weight
<|end_body_0|>
<|body_start_1|>
res = Shop_Item.__repr__(self)
res += '\... | Represents a meat item. Attributes: butcher name, exp. date, weight in grams | Meat_Item | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meat_Item:
"""Represents a meat item. Attributes: butcher name, exp. date, weight in grams"""
def __init__(self, butcher_name, exp_date, weight, item_id, item_name, unit_price, qty, request=''):
"""Constructor for a meat item"""
<|body_0|>
def __repr__(self):
"""... | stack_v2_sparse_classes_75kplus_train_071080 | 927 | no_license | [
{
"docstring": "Constructor for a meat item",
"name": "__init__",
"signature": "def __init__(self, butcher_name, exp_date, weight, item_id, item_name, unit_price, qty, request='')"
},
{
"docstring": "Returns a string, representing this item",
"name": "__repr__",
"signature": "def __repr_... | 2 | stack_v2_sparse_classes_30k_train_044222 | Implement the Python class `Meat_Item` described below.
Class description:
Represents a meat item. Attributes: butcher name, exp. date, weight in grams
Method signatures and docstrings:
- def __init__(self, butcher_name, exp_date, weight, item_id, item_name, unit_price, qty, request=''): Constructor for a meat item
-... | Implement the Python class `Meat_Item` described below.
Class description:
Represents a meat item. Attributes: butcher name, exp. date, weight in grams
Method signatures and docstrings:
- def __init__(self, butcher_name, exp_date, weight, item_id, item_name, unit_price, qty, request=''): Constructor for a meat item
-... | 195b3af17a073324b5e51c2b7695aedb8bb15db9 | <|skeleton|>
class Meat_Item:
"""Represents a meat item. Attributes: butcher name, exp. date, weight in grams"""
def __init__(self, butcher_name, exp_date, weight, item_id, item_name, unit_price, qty, request=''):
"""Constructor for a meat item"""
<|body_0|>
def __repr__(self):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Meat_Item:
"""Represents a meat item. Attributes: butcher name, exp. date, weight in grams"""
def __init__(self, butcher_name, exp_date, weight, item_id, item_name, unit_price, qty, request=''):
"""Constructor for a meat item"""
Shop_Item.__init__(self, item_id, item_name, unit_price)
... | the_stack_v2_python_sparse | assign.8/Meat_Item.py | rulidor/Python-Course | train | 0 |
aef499a01cb90d14f70e7b19f8501bddbce1854c | [
"n = len(nums)\nlo, hi = (0, n - 1)\nwhile lo < hi and nums[lo] <= nums[lo + 1]:\n lo += 1\nwhile lo < hi and nums[hi - 1] <= nums[hi]:\n hi -= 1\nif hi <= lo:\n return 0\nmini = float('inf')\nmaxa = -float('inf')\nfor i in range(lo, hi + 1):\n mini = min(mini, nums[i])\n maxa = max(maxa, nums[i])\nw... | <|body_start_0|>
n = len(nums)
lo, hi = (0, n - 1)
while lo < hi and nums[lo] <= nums[lo + 1]:
lo += 1
while lo < hi and nums[hi - 1] <= nums[hi]:
hi -= 1
if hi <= lo:
return 0
mini = float('inf')
maxa = -float('inf')
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value... | stack_v2_sparse_classes_75kplus_train_071081 | 2,142 | no_license | [
{
"docstring": "Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value nums[lo - 1] <= min && max <= nums[hi + 1]",
"name": "findUnsortedSubarr... | 2 | stack_v2_sparse_classes_30k_train_021964 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums: List[int]) -> int: Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums: List[int]) -> int: Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""Sorted at both ends Then search for the two ends by nums[i+1] > nums[i] on the left side (right side similar) Problem: may over-include, consider 1 2 5 9 4 6 ... need to shrink from 1 2 5 9 to 1 2 according to min value nums[lo - 1] ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/581 Shortest Unsorted Continuous Subarray.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
9f4187c92f7bb91162f0f26b7aab242d6188eae4 | [
"self.outlook_mailbox_list = outlook_mailbox_list\nself.pst_params = pst_params\nself.target_folder_path = target_folder_path\nself.target_mailbox = target_mailbox",
"if dictionary is None:\n return None\noutlook_mailbox_list = None\nif dictionary.get('outlookMailboxList') != None:\n outlook_mailbox_list = ... | <|body_start_0|>
self.outlook_mailbox_list = outlook_mailbox_list
self.pst_params = pst_params
self.target_folder_path = target_folder_path
self.target_mailbox = target_mailbox
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
outlook_mailbox... | Implementation of the 'OutlookRestoreParameters' model. Specifies information needed for recovering Mailboxes in O365Outlook environment. Attributes: outlook_mailbox_list (list of OutlookMailbox): Specifies the list of mailboxes to be restored. pst_params (PstParameters): Specifies the PST conversion specific parameter... | OutlookRestoreParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutlookRestoreParameters:
"""Implementation of the 'OutlookRestoreParameters' model. Specifies information needed for recovering Mailboxes in O365Outlook environment. Attributes: outlook_mailbox_list (list of OutlookMailbox): Specifies the list of mailboxes to be restored. pst_params (PstParamete... | stack_v2_sparse_classes_75kplus_train_071082 | 3,440 | permissive | [
{
"docstring": "Constructor for the OutlookRestoreParameters class",
"name": "__init__",
"signature": "def __init__(self, outlook_mailbox_list=None, pst_params=None, target_folder_path=None, target_mailbox=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictio... | 2 | stack_v2_sparse_classes_30k_train_018985 | Implement the Python class `OutlookRestoreParameters` described below.
Class description:
Implementation of the 'OutlookRestoreParameters' model. Specifies information needed for recovering Mailboxes in O365Outlook environment. Attributes: outlook_mailbox_list (list of OutlookMailbox): Specifies the list of mailboxes ... | Implement the Python class `OutlookRestoreParameters` described below.
Class description:
Implementation of the 'OutlookRestoreParameters' model. Specifies information needed for recovering Mailboxes in O365Outlook environment. Attributes: outlook_mailbox_list (list of OutlookMailbox): Specifies the list of mailboxes ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OutlookRestoreParameters:
"""Implementation of the 'OutlookRestoreParameters' model. Specifies information needed for recovering Mailboxes in O365Outlook environment. Attributes: outlook_mailbox_list (list of OutlookMailbox): Specifies the list of mailboxes to be restored. pst_params (PstParamete... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutlookRestoreParameters:
"""Implementation of the 'OutlookRestoreParameters' model. Specifies information needed for recovering Mailboxes in O365Outlook environment. Attributes: outlook_mailbox_list (list of OutlookMailbox): Specifies the list of mailboxes to be restored. pst_params (PstParameters): Specifie... | the_stack_v2_python_sparse | cohesity_management_sdk/models/outlook_restore_parameters.py | cohesity/management-sdk-python | train | 24 |
8467dcdd46c26c027ca3888d2f2c2983aa9fe9d6 | [
"n = len(A)\nindices = sorted(range(n), key=lambda i: A[i])\nres = 0\npre = n\nfor i in indices:\n if i < pre:\n pre = i\n else:\n res = max(res, i - pre)\nreturn res",
"stack = []\nfor i, a in enumerate(A):\n if not stack or (stack and A[stack[-1]] > a):\n stack.append(i)\nres = 0\n... | <|body_start_0|>
n = len(A)
indices = sorted(range(n), key=lambda i: A[i])
res = 0
pre = n
for i in indices:
if i < pre:
pre = i
else:
res = max(res, i - pre)
return res
<|end_body_0|>
<|body_start_1|>
stack... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A: List[int]) -> int:
"""求一个最长的上坡 索引排序 @param A: @return:"""
<|body_0|>
def maxWidthRamp2(self, A: List[int]) -> int:
"""单调栈 @param A: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(A)
indi... | stack_v2_sparse_classes_75kplus_train_071083 | 1,773 | no_license | [
{
"docstring": "求一个最长的上坡 索引排序 @param A: @return:",
"name": "maxWidthRamp1",
"signature": "def maxWidthRamp1(self, A: List[int]) -> int"
},
{
"docstring": "单调栈 @param A: @return:",
"name": "maxWidthRamp2",
"signature": "def maxWidthRamp2(self, A: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_002978 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A: List[int]) -> int: 求一个最长的上坡 索引排序 @param A: @return:
- def maxWidthRamp2(self, A: List[int]) -> int: 单调栈 @param A: @return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A: List[int]) -> int: 求一个最长的上坡 索引排序 @param A: @return:
- def maxWidthRamp2(self, A: List[int]) -> int: 单调栈 @param A: @return:
<|skeleton|>
class Solution... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A: List[int]) -> int:
"""求一个最长的上坡 索引排序 @param A: @return:"""
<|body_0|>
def maxWidthRamp2(self, A: List[int]) -> int:
"""单调栈 @param A: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxWidthRamp1(self, A: List[int]) -> int:
"""求一个最长的上坡 索引排序 @param A: @return:"""
n = len(A)
indices = sorted(range(n), key=lambda i: A[i])
res = 0
pre = n
for i in indices:
if i < pre:
pre = i
else:
... | the_stack_v2_python_sparse | LeetCode/栈/单调栈(Monotone Stack)/962. 最大宽度坡.py | yiming1012/MyLeetCode | train | 2 | |
7c94050f616b6974e51fc1f6b470941d9f266181 | [
"self.host = host\nself.database = database\nself.user = user\nself.password = password\nself.dump_command_path = dump_command_path\nself.log = setup_rotating_logger('dump_mysql', size=50 * 1000 * 1000, directory=log_directory)",
"alist = [self.dump_command_path, '--skip-extended-insert', '--protocol=tcp', '-h' +... | <|body_start_0|>
self.host = host
self.database = database
self.user = user
self.password = password
self.dump_command_path = dump_command_path
self.log = setup_rotating_logger('dump_mysql', size=50 * 1000 * 1000, directory=log_directory)
<|end_body_0|>
<|body_start_1|>
... | Dumps MySQL database to SQL file. Can send the file to an S3 bucket. | DumpMySQL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpMySQL:
"""Dumps MySQL database to SQL file. Can send the file to an S3 bucket."""
def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'):
"""Constructor."""
<|body_0|>
def get_dump_cmd(self, destinati... | stack_v2_sparse_classes_75kplus_train_071084 | 4,878 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.')"
},
{
"docstring": "Return list/command to dump this environment's database to SQL.",
"name": "get_dump_c... | 5 | stack_v2_sparse_classes_30k_train_037555 | Implement the Python class `DumpMySQL` described below.
Class description:
Dumps MySQL database to SQL file. Can send the file to an S3 bucket.
Method signatures and docstrings:
- def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'): Constructor.
- ... | Implement the Python class `DumpMySQL` described below.
Class description:
Dumps MySQL database to SQL file. Can send the file to an S3 bucket.
Method signatures and docstrings:
- def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'): Constructor.
- ... | 63f6fbd3e768bf55d79ac96964aa3bf7702f3f9a | <|skeleton|>
class DumpMySQL:
"""Dumps MySQL database to SQL file. Can send the file to an S3 bucket."""
def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'):
"""Constructor."""
<|body_0|>
def get_dump_cmd(self, destinati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DumpMySQL:
"""Dumps MySQL database to SQL file. Can send the file to an S3 bucket."""
def __init__(self, database, user, password, host='localhost', dump_command_path='/usr/bin/mysqldump', log_directory='.'):
"""Constructor."""
self.host = host
self.database = database
sel... | the_stack_v2_python_sparse | bag/dump_mysql.py | nandoflorestan/bag | train | 24 |
5b525e156f4d8539e739fedf616f904d724db93e | [
"total = DailySpendings()\nfor field in self.fields_to_total:\n setattr(total, field, queryset.aggregate(Sum(field)).items()[0][1])\nreturn total",
"super(DailySpendingsList, self).get_results(request)\ntotal = self.get_total_values(self.queryset)\nlen(self.result_list)\nself.result_list._result_cache.insert(0... | <|body_start_0|>
total = DailySpendings()
for field in self.fields_to_total:
setattr(total, field, queryset.aggregate(Sum(field)).items()[0][1])
return total
<|end_body_0|>
<|body_start_1|>
super(DailySpendingsList, self).get_results(request)
total = self.get_total_v... | DailySpendingsList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DailySpendingsList:
def get_total_values(self, queryset):
"""Get the totals"""
<|body_0|>
def get_results(self, request):
"""The model admin gets queryset results from this method and then displays it in the template"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_071085 | 6,899 | no_license | [
{
"docstring": "Get the totals",
"name": "get_total_values",
"signature": "def get_total_values(self, queryset)"
},
{
"docstring": "The model admin gets queryset results from this method and then displays it in the template",
"name": "get_results",
"signature": "def get_results(self, req... | 2 | stack_v2_sparse_classes_30k_train_049947 | Implement the Python class `DailySpendingsList` described below.
Class description:
Implement the DailySpendingsList class.
Method signatures and docstrings:
- def get_total_values(self, queryset): Get the totals
- def get_results(self, request): The model admin gets queryset results from this method and then display... | Implement the Python class `DailySpendingsList` described below.
Class description:
Implement the DailySpendingsList class.
Method signatures and docstrings:
- def get_total_values(self, queryset): Get the totals
- def get_results(self, request): The model admin gets queryset results from this method and then display... | 32069c1702e2a8ae9e449a6a06c9095ed4011f91 | <|skeleton|>
class DailySpendingsList:
def get_total_values(self, queryset):
"""Get the totals"""
<|body_0|>
def get_results(self, request):
"""The model admin gets queryset results from this method and then displays it in the template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DailySpendingsList:
def get_total_values(self, queryset):
"""Get the totals"""
total = DailySpendings()
for field in self.fields_to_total:
setattr(total, field, queryset.aggregate(Sum(field)).items()[0][1])
return total
def get_results(self, request):
"... | the_stack_v2_python_sparse | kanary/ui/account/admin.py | sorlandet/code | train | 0 | |
9c52cc6e4a5c6a6dd4c6a1ba19eb2676952f572e | [
"try:\n raw_version = self.client.get('/version')['version']\nexcept KeyError:\n raise VersionNotFoundException('Cannot Find Version at api/v1/version')\nreturn get_version_from_string(raw_version)",
"logger.debug('Validating client and server versions')\nserver_version = self.get_server_version()\nclient_v... | <|body_start_0|>
try:
raw_version = self.client.get('/version')['version']
except KeyError:
raise VersionNotFoundException('Cannot Find Version at api/v1/version')
return get_version_from_string(raw_version)
<|end_body_0|>
<|body_start_1|>
logger.debug('Validatin... | OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata | OMetaServerMixin | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OMetaServerMixin:
"""OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata"""
def get_server_version(self) -> str:
"""Run endpoint /version to check server version :return: Server version"""
<|body_0|>
def validate_versions(self) -> None... | stack_v2_sparse_classes_75kplus_train_071086 | 2,191 | permissive | [
{
"docstring": "Run endpoint /version to check server version :return: Server version",
"name": "get_server_version",
"signature": "def get_server_version(self) -> str"
},
{
"docstring": "Validate Server & Client versions. They should match. Otherwise, raise VersionMismatchException",
"name"... | 2 | stack_v2_sparse_classes_30k_train_010277 | Implement the Python class `OMetaServerMixin` described below.
Class description:
OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata
Method signatures and docstrings:
- def get_server_version(self) -> str: Run endpoint /version to check server version :return: Server version
- def... | Implement the Python class `OMetaServerMixin` described below.
Class description:
OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata
Method signatures and docstrings:
- def get_server_version(self) -> str: Run endpoint /version to check server version :return: Server version
- def... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class OMetaServerMixin:
"""OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata"""
def get_server_version(self) -> str:
"""Run endpoint /version to check server version :return: Server version"""
<|body_0|>
def validate_versions(self) -> None... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OMetaServerMixin:
"""OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata"""
def get_server_version(self) -> str:
"""Run endpoint /version to check server version :return: Server version"""
try:
raw_version = self.client.get('/version')['vers... | the_stack_v2_python_sparse | govern/data-meta/OpenMetadata/ingestion/src/metadata/ingestion/ometa/mixins/server_mixin.py | alldatacenter/alldata | train | 774 |
1e6f8e6fcb1ebc92cfb21fa658aafd2eedd5c2c6 | [
"Questionnaire.__init__(self, df)\nself.names = ['CAS', 'OCS']\nself.labels = ['The coronavirus anxiety scale', 'Obsession with COVID scale']\nself.values = {'CAS': {}, 'OCS': {}}\nself.new_df = pd.DataFrame(0, index=self.df.index, columns=self.names)",
"corona_df = pd.DataFrame(index=self.df.index, columns=self.... | <|body_start_0|>
Questionnaire.__init__(self, df)
self.names = ['CAS', 'OCS']
self.labels = ['The coronavirus anxiety scale', 'Obsession with COVID scale']
self.values = {'CAS': {}, 'OCS': {}}
self.new_df = pd.DataFrame(0, index=self.df.index, columns=self.names)
<|end_body_0|>
... | A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire | CoronaEnxiety | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoronaEnxiety:
"""A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire"""
def __init__(self, df):
"""Init... | stack_v2_sparse_classes_75kplus_train_071087 | 1,813 | no_license | [
{
"docstring": "Init the following arguments: names = the new columns' names (after grading) labels = labels for each column to be written in the SPSS output file values = explanation for the values in each SPSS column - empty for this questionaire new_df = new DataFrame with the graded values Parameters ------... | 2 | stack_v2_sparse_classes_30k_test_000774 | Implement the Python class `CoronaEnxiety` described below.
Class description:
A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire
Method ... | Implement the Python class `CoronaEnxiety` described below.
Class description:
A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire
Method ... | 26b8a2847d7202b61e67e2cd0074278a46a9f8f3 | <|skeleton|>
class CoronaEnxiety:
"""A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire"""
def __init__(self, df):
"""Init... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoronaEnxiety:
"""A class used to represent the Corona Enxiety Questionnaire Attributes ---------- df : DataFrame A Pandas data frame with the specific columns for the questionnaire Methods ------- grade() Calculates the grading of the questionnaire"""
def __init__(self, df):
"""Init the followin... | the_stack_v2_python_sparse | Questionnaires/CoronaEnxiety.py | TechnionENIC/ENIC_scoring_program | train | 0 |
1c81e9ec23cb582f548b34151d71b95d6f8477a1 | [
"l, res = (len(s), [])\ndp = [[0 for _ in range(l)] for _ in range(l)]\nfor i in range(l):\n for j in range(i + 1):\n if i == j:\n dp[j][i] = 1\n elif i - j == 1 and s[i] == s[j]:\n dp[j][i] = 1\n elif i - j > 1 and s[i] == s[j] and dp[j + 1][i - 1]:\n dp[j][... | <|body_start_0|>
l, res = (len(s), [])
dp = [[0 for _ in range(l)] for _ in range(l)]
for i in range(l):
for j in range(i + 1):
if i == j:
dp[j][i] = 1
elif i - j == 1 and s[i] == s[j]:
dp[j][i] = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partition(self, s: str) -> List[List[str]]:
"""用动态规划记录所有字串是否是回文 回溯递归 回溯问题抓住三个要点: 1.选择,当前你有什么选择,一个选择代表一个分支,基于一种选择,又会展开出一些选择 2.约束条件,利用它去做剪枝,减少不必要的搜索,让你的搜索树“瘦身” 3.目标,明确了何时将部分解加入解集,结束当前的递归 模板 choose -- explore -- unchoose: 1.用 for 循环枚举出当前的选择 2.作出一个选择,基于这个选择,继续递归 3.递归结束了,撤销这个选择,... | stack_v2_sparse_classes_75kplus_train_071088 | 3,512 | no_license | [
{
"docstring": "用动态规划记录所有字串是否是回文 回溯递归 回溯问题抓住三个要点: 1.选择,当前你有什么选择,一个选择代表一个分支,基于一种选择,又会展开出一些选择 2.约束条件,利用它去做剪枝,减少不必要的搜索,让你的搜索树“瘦身” 3.目标,明确了何时将部分解加入解集,结束当前的递归 模板 choose -- explore -- unchoose: 1.用 for 循环枚举出当前的选择 2.作出一个选择,基于这个选择,继续递归 3.递归结束了,撤销这个选择,进入下一轮迭代 Args: s (str): [description] Returns: List[List[str]]: [descr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s: str) -> List[List[str]]: 用动态规划记录所有字串是否是回文 回溯递归 回溯问题抓住三个要点: 1.选择,当前你有什么选择,一个选择代表一个分支,基于一种选择,又会展开出一些选择 2.约束条件,利用它去做剪枝,减少不必要的搜索,让你的搜索树“瘦身” 3.目标,明确了何时将部分解加入解集,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s: str) -> List[List[str]]: 用动态规划记录所有字串是否是回文 回溯递归 回溯问题抓住三个要点: 1.选择,当前你有什么选择,一个选择代表一个分支,基于一种选择,又会展开出一些选择 2.约束条件,利用它去做剪枝,减少不必要的搜索,让你的搜索树“瘦身” 3.目标,明确了何时将部分解加入解集,... | 8343f4258d20661f70f0462c358ef8b118a03de4 | <|skeleton|>
class Solution:
def partition(self, s: str) -> List[List[str]]:
"""用动态规划记录所有字串是否是回文 回溯递归 回溯问题抓住三个要点: 1.选择,当前你有什么选择,一个选择代表一个分支,基于一种选择,又会展开出一些选择 2.约束条件,利用它去做剪枝,减少不必要的搜索,让你的搜索树“瘦身” 3.目标,明确了何时将部分解加入解集,结束当前的递归 模板 choose -- explore -- unchoose: 1.用 for 循环枚举出当前的选择 2.作出一个选择,基于这个选择,继续递归 3.递归结束了,撤销这个选择,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def partition(self, s: str) -> List[List[str]]:
"""用动态规划记录所有字串是否是回文 回溯递归 回溯问题抓住三个要点: 1.选择,当前你有什么选择,一个选择代表一个分支,基于一种选择,又会展开出一些选择 2.约束条件,利用它去做剪枝,减少不必要的搜索,让你的搜索树“瘦身” 3.目标,明确了何时将部分解加入解集,结束当前的递归 模板 choose -- explore -- unchoose: 1.用 for 循环枚举出当前的选择 2.作出一个选择,基于这个选择,继续递归 3.递归结束了,撤销这个选择,进入下一轮迭代 Args: ... | the_stack_v2_python_sparse | python/131_分割回文串.py | Aiooon/MyLeetcode | train | 0 | |
bb465f5d005cbb9f57d0eb9d46c868a745f791b8 | [
"if not root:\n return 'null'\nresult = ''\nfront = [root]\nnextfront = []\nnotallnull = 1\nwhile front and notallnull:\n notallnull = 0\n for cur in front:\n if not cur:\n result += ',null'\n else:\n result += ',' + str(cur.val)\n nextfront.append(cur.left)\n... | <|body_start_0|>
if not root:
return 'null'
result = ''
front = [root]
nextfront = []
notallnull = 1
while front and notallnull:
notallnull = 0
for cur in front:
if not cur:
result += ',null'
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_071089 | 1,765 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d68b5ac6359a06e144fc6273978d91c5f73093f1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'null'
result = ''
front = [root]
nextfront = []
notallnull = 1
while front and notallnull:
notallnull... | the_stack_v2_python_sparse | python/297_serialize_and_deserialize_binary_tree.py | jianq1994/leetcode | train | 0 | |
511c16c70b9a87c43de2a28773d220f8c0e157ba | [
"if request.user.is_authenticated and hasattr(request.user, 'profile'):\n return True\nreturn False",
"if type(obj) == UserProfileModel:\n if obj.account == request.user:\n return True\n return False\nif obj.user.account == request.user:\n return True\nreturn False"
] | <|body_start_0|>
if request.user.is_authenticated and hasattr(request.user, 'profile'):
return True
return False
<|end_body_0|>
<|body_start_1|>
if type(obj) == UserProfileModel:
if obj.account == request.user:
return True
return False
... | The Permission class used by UserAddressView. | UserAddressPermissions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAddressPermissions:
"""The Permission class used by UserAddressView."""
def has_permission(self, request, view):
"""Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin."""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus_train_071090 | 1,859 | permissive | [
{
"docstring": "Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Checks if the user has the permissions to see... | 2 | stack_v2_sparse_classes_30k_train_042610 | Implement the Python class `UserAddressPermissions` described below.
Class description:
The Permission class used by UserAddressView.
Method signatures and docstrings:
- def has_permission(self, request, view): Checks if the user is authenticated and has a valid profile, because that account may be other type like a ... | Implement the Python class `UserAddressPermissions` described below.
Class description:
The Permission class used by UserAddressView.
Method signatures and docstrings:
- def has_permission(self, request, view): Checks if the user is authenticated and has a valid profile, because that account may be other type like a ... | 7c361a31c5225c6ad649fcf92e323bdb10cc4c16 | <|skeleton|>
class UserAddressPermissions:
"""The Permission class used by UserAddressView."""
def has_permission(self, request, view):
"""Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin."""
<|body_0|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserAddressPermissions:
"""The Permission class used by UserAddressView."""
def has_permission(self, request, view):
"""Checks if the user is authenticated and has a valid profile, because that account may be other type like a driver, shop or an admin."""
if request.user.is_authenticated ... | the_stack_v2_python_sparse | users/permissions.py | ahmed-alllam/Koshkie-Server | train | 0 |
f9e6c811164e2451e7420f7a8a9a4f295323e0e9 | [
"SlipTimeFn.__init__(self, name)\nModuleTimeHistorySlipFn.__init__(self)\nself._loggingPrefix = 'THSF '\nreturn",
"SlipTimeFn._configure(self)\nModuleTimeHistorySlipFn.dbAmplitude(self, self.inventory.dbSlip)\nModuleTimeHistorySlipFn.dbSlipTime(self, self.inventory.dbSlipTime)\nModuleTimeHistorySlipFn.dbTimeHisto... | <|body_start_0|>
SlipTimeFn.__init__(self, name)
ModuleTimeHistorySlipFn.__init__(self)
self._loggingPrefix = 'THSF '
return
<|end_body_0|>
<|body_start_1|>
SlipTimeFn._configure(self)
ModuleTimeHistorySlipFn.dbAmplitude(self, self.inventory.dbSlip)
ModuleTimeHis... | User-defined slip-time function with spatially variable amplitude and start time. Inventory Properties @li None Facilities @li slip Spatial database of slip amplitude. @li slip_time Spatial database of slip initiation time. @li time_history Temporal database for slip time history function. Factory: slip_time_... | TimeHistorySlipFn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeHistorySlipFn:
"""User-defined slip-time function with spatially variable amplitude and start time. Inventory Properties @li None Facilities @li slip Spatial database of slip amplitude. @li slip_time Spatial database of slip initiation time. @li time_history Temporal database for sl... | stack_v2_sparse_classes_75kplus_train_071091 | 3,009 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, name='timehistoryslipfn')"
},
{
"docstring": "Setup members using inventory.",
"name": "_configure",
"signature": "def _configure(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046544 | Implement the Python class `TimeHistorySlipFn` described below.
Class description:
User-defined slip-time function with spatially variable amplitude and start time. Inventory Properties @li None Facilities @li slip Spatial database of slip amplitude. @li slip_time Spatial database of slip initiation time. @li ... | Implement the Python class `TimeHistorySlipFn` described below.
Class description:
User-defined slip-time function with spatially variable amplitude and start time. Inventory Properties @li None Facilities @li slip Spatial database of slip amplitude. @li slip_time Spatial database of slip initiation time. @li ... | 67bfe2e75e0a20bb55c93eb98bef7a9b3694523a | <|skeleton|>
class TimeHistorySlipFn:
"""User-defined slip-time function with spatially variable amplitude and start time. Inventory Properties @li None Facilities @li slip Spatial database of slip amplitude. @li slip_time Spatial database of slip initiation time. @li time_history Temporal database for sl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeHistorySlipFn:
"""User-defined slip-time function with spatially variable amplitude and start time. Inventory Properties @li None Facilities @li slip Spatial database of slip amplitude. @li slip_time Spatial database of slip initiation time. @li time_history Temporal database for slip time histo... | the_stack_v2_python_sparse | pylith/faults/obsolete/TimeHistorySlipFn.py | fjiaqi/pylith | train | 0 |
9c4216ca49b61b3f643287da22cf6294008e1743 | [
"super(MultiboxLoss, self).__init__()\nself.iou_threshold = iou_threshold\nself.neg_pos_ratio = neg_pos_ratio\nself.center_variance = center_variance\nself.size_variance = size_variance\nself.priors = priors\nself.priors.to(device)",
"num_classes = confidence.size(2)\nwith torch.no_grad():\n loss = -F.log_soft... | <|body_start_0|>
super(MultiboxLoss, self).__init__()
self.iou_threshold = iou_threshold
self.neg_pos_ratio = neg_pos_ratio
self.center_variance = center_variance
self.size_variance = size_variance
self.priors = priors
self.priors.to(device)
<|end_body_0|>
<|body... | MultiboxLoss | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiboxLoss:
def __init__(self, priors, iou_threshold, neg_pos_ratio, center_variance, size_variance, device):
"""Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss."""
<|body_0|>
def forward(self, confidence, pr... | stack_v2_sparse_classes_75kplus_train_071092 | 4,465 | permissive | [
{
"docstring": "Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss.",
"name": "__init__",
"signature": "def __init__(self, priors, iou_threshold, neg_pos_ratio, center_variance, size_variance, device)"
},
{
"docstring": "Compute class... | 2 | stack_v2_sparse_classes_30k_train_037304 | Implement the Python class `MultiboxLoss` described below.
Class description:
Implement the MultiboxLoss class.
Method signatures and docstrings:
- def __init__(self, priors, iou_threshold, neg_pos_ratio, center_variance, size_variance, device): Implement SSD Multibox Loss. Basically, Multibox loss combines classific... | Implement the Python class `MultiboxLoss` described below.
Class description:
Implement the MultiboxLoss class.
Method signatures and docstrings:
- def __init__(self, priors, iou_threshold, neg_pos_ratio, center_variance, size_variance, device): Implement SSD Multibox Loss. Basically, Multibox loss combines classific... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class MultiboxLoss:
def __init__(self, priors, iou_threshold, neg_pos_ratio, center_variance, size_variance, device):
"""Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss."""
<|body_0|>
def forward(self, confidence, pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiboxLoss:
def __init__(self, priors, iou_threshold, neg_pos_ratio, center_variance, size_variance, device):
"""Implement SSD Multibox Loss. Basically, Multibox loss combines classification loss and Smooth L1 regression loss."""
super(MultiboxLoss, self).__init__()
self.iou_threshol... | the_stack_v2_python_sparse | PyTorch/dev/cv/detection/MobileNetV3-SSD_ID0408_for_PyTorch/vision/nn/multibox_loss.py | Ascend/ModelZoo-PyTorch | train | 23 | |
3a1ffe30dabec0aca9083ff140f84bb1e4ee0d94 | [
"item = ZiruItem()\nitem['room_href'] = response.url\nitem['room_name'] = response.xpath(\"//div[@class='room_name']/h2/text()\").extract_first().strip()\nitem['room_addr'] = response.xpath(\"//div[@class='room_name']/p/span/text()\").extract_first().replace(' ', '')\nitem['room_area'] = response.xpath(\"//ul[@clas... | <|body_start_0|>
item = ZiruItem()
item['room_href'] = response.url
item['room_name'] = response.xpath("//div[@class='room_name']/h2/text()").extract_first().strip()
item['room_addr'] = response.xpath("//div[@class='room_name']/p/span/text()").extract_first().replace(' ', '')
ite... | ZrSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZrSpider:
def parse_house_list(self, response):
"""此函数获取房屋列表"""
<|body_0|>
def parse_price(self, response):
"""获取房屋的租金 押金 服务费"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
item = ZiruItem()
item['room_href'] = response.url
item['ro... | stack_v2_sparse_classes_75kplus_train_071093 | 2,586 | no_license | [
{
"docstring": "此函数获取房屋列表",
"name": "parse_house_list",
"signature": "def parse_house_list(self, response)"
},
{
"docstring": "获取房屋的租金 押金 服务费",
"name": "parse_price",
"signature": "def parse_price(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022877 | Implement the Python class `ZrSpider` described below.
Class description:
Implement the ZrSpider class.
Method signatures and docstrings:
- def parse_house_list(self, response): 此函数获取房屋列表
- def parse_price(self, response): 获取房屋的租金 押金 服务费 | Implement the Python class `ZrSpider` described below.
Class description:
Implement the ZrSpider class.
Method signatures and docstrings:
- def parse_house_list(self, response): 此函数获取房屋列表
- def parse_price(self, response): 获取房屋的租金 押金 服务费
<|skeleton|>
class ZrSpider:
def parse_house_list(self, response):
... | ff398f85658a7ff3b5e5336aa9bc247d8e60c213 | <|skeleton|>
class ZrSpider:
def parse_house_list(self, response):
"""此函数获取房屋列表"""
<|body_0|>
def parse_price(self, response):
"""获取房屋的租金 押金 服务费"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZrSpider:
def parse_house_list(self, response):
"""此函数获取房屋列表"""
item = ZiruItem()
item['room_href'] = response.url
item['room_name'] = response.xpath("//div[@class='room_name']/h2/text()").extract_first().strip()
item['room_addr'] = response.xpath("//div[@class='room_na... | the_stack_v2_python_sparse | code/project/ziru/ziru/spiders/zr.py | BrandonSong/spider | train | 0 | |
06623973c5f6948e5bdb0a0e73bf8342aef83f6d | [
"self.size = int(input())\nself.weights = np.zeros((self.size,))\nfor i, value in enumerate(input().strip().split(' ')):\n self.weights[i] = int(value)",
"padding = int((self.size - 1) / 2)\nimg_1D = self.create_circular_array(img)\nresult = np.zeros((img.shape[0] * img.shape[1],))\nweights = np.flip(self.weig... | <|body_start_0|>
self.size = int(input())
self.weights = np.zeros((self.size,))
for i, value in enumerate(input().strip().split(' ')):
self.weights[i] = int(value)
<|end_body_0|>
<|body_start_1|>
padding = int((self.size - 1) / 2)
img_1D = self.create_circular_array(... | Filter1D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filter1D:
def __init__(self):
"""Reads inputs"""
<|body_0|>
def apply_filter(self, img):
"""Transforms the image in a 1D vector, applies 1D convolution with the specified weights and transforms the array to a 2D array again @param img: image to be filtered @return fi... | stack_v2_sparse_classes_75kplus_train_071094 | 8,121 | no_license | [
{
"docstring": "Reads inputs",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Transforms the image in a 1D vector, applies 1D convolution with the specified weights and transforms the array to a 2D array again @param img: image to be filtered @return filtered image",
... | 3 | null | Implement the Python class `Filter1D` described below.
Class description:
Implement the Filter1D class.
Method signatures and docstrings:
- def __init__(self): Reads inputs
- def apply_filter(self, img): Transforms the image in a 1D vector, applies 1D convolution with the specified weights and transforms the array to... | Implement the Python class `Filter1D` described below.
Class description:
Implement the Filter1D class.
Method signatures and docstrings:
- def __init__(self): Reads inputs
- def apply_filter(self, img): Transforms the image in a 1D vector, applies 1D convolution with the specified weights and transforms the array to... | 2a4adef88508c6d9b134920f758044dece09a58e | <|skeleton|>
class Filter1D:
def __init__(self):
"""Reads inputs"""
<|body_0|>
def apply_filter(self, img):
"""Transforms the image in a 1D vector, applies 1D convolution with the specified weights and transforms the array to a 2D array again @param img: image to be filtered @return fi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Filter1D:
def __init__(self):
"""Reads inputs"""
self.size = int(input())
self.weights = np.zeros((self.size,))
for i, value in enumerate(input().strip().split(' ')):
self.weights[i] = int(value)
def apply_filter(self, img):
"""Transforms the image in a... | the_stack_v2_python_sparse | SCC5830/ex2/src/imagefiltering.py | damaresende/USP | train | 0 | |
92ee5365ebc532914c8dd3d8a20bee06eec3bf95 | [
"if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] == 0):\n return 0\ngrid[i][j] = 0\ncount = 1\ncount += self.helper(grid, i - 1, j)\ncount += self.helper(grid, i + 1, j)\ncount += self.helper(grid, i, j - 1)\ncount += self.helper(grid, i, j + 1)\nreturn count",
"max_island = 0\nfor i ... | <|body_start_0|>
if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] == 0):
return 0
grid[i][j] = 0
count = 1
count += self.helper(grid, i - 1, j)
count += self.helper(grid, i + 1, j)
count += self.helper(grid, i, j - 1)
count += ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, grid: List[List[int]], i: int, j: int) -> int:
"""帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数"""
<|body_0|>
def max_area_island(self, grid: List[List[int]]) -> int:
"""最大岛屿 Args: grid: 二维数组 Returns: 最大岛屿"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_071095 | 3,200 | permissive | [
{
"docstring": "帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数",
"name": "helper",
"signature": "def helper(self, grid: List[List[int]], i: int, j: int) -> int"
},
{
"docstring": "最大岛屿 Args: grid: 二维数组 Returns: 最大岛屿",
"name": "max_area_island",
"signature": "def max_area_island(s... | 2 | stack_v2_sparse_classes_30k_train_026077 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, grid: List[List[int]], i: int, j: int) -> int: 帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数
- def max_area_island(self, grid: List[List[int]]) -> int: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, grid: List[List[int]], i: int, j: int) -> int: 帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数
- def max_area_island(self, grid: List[List[int]]) -> int: ... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def helper(self, grid: List[List[int]], i: int, j: int) -> int:
"""帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数"""
<|body_0|>
def max_area_island(self, grid: List[List[int]]) -> int:
"""最大岛屿 Args: grid: 二维数组 Returns: 最大岛屿"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def helper(self, grid: List[List[int]], i: int, j: int) -> int:
"""帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数"""
if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] == 0):
return 0
grid[i][j] = 0
count = 1
count +=... | the_stack_v2_python_sparse | src/leetcodepython/array/max_area_island_695.py | zhangyu345293721/leetcode | train | 101 | |
1b3abc5be857c96ee9c182982bbd26baaa399f86 | [
"super().__init__()\nself.h = h\nself.dm = dm\nself.depth = int(dm / h)\nself.Wq = tf.keras.layers.Dense(units=dm)\nself.Wk = tf.keras.layers.Dense(units=dm)\nself.Wv = tf.keras.layers.Dense(units=dm)\nself.linear = tf.keras.layers.Dense(units=dm)",
"batch = tf.shape(Q)[0]\nq = self.Wq(Q)\nq = tf.reshape(q, (batc... | <|body_start_0|>
super().__init__()
self.h = h
self.dm = dm
self.depth = int(dm / h)
self.Wq = tf.keras.layers.Dense(units=dm)
self.Wk = tf.keras.layers.Dense(units=dm)
self.Wv = tf.keras.layers.Dense(units=dm)
self.linear = tf.keras.layers.Dense(units=dm)... | class MultiHeadAttention | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""class MultiHeadAttention"""
def __init__(self, dm, h):
"""Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads."""
<|body_0|>
def call(self, Q, K, V, mask):
"""call method. Arg... | stack_v2_sparse_classes_75kplus_train_071096 | 2,042 | no_license | [
{
"docstring": "Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads.",
"name": "__init__",
"signature": "def __init__(self, dm, h)"
},
{
"docstring": "call method. Args: Q: (tf.Tensor) containing the input to generate the query mat... | 2 | stack_v2_sparse_classes_30k_train_046018 | Implement the Python class `MultiHeadAttention` described below.
Class description:
class MultiHeadAttention
Method signatures and docstrings:
- def __init__(self, dm, h): Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads.
- def call(self, Q, K, V, ma... | Implement the Python class `MultiHeadAttention` described below.
Class description:
class MultiHeadAttention
Method signatures and docstrings:
- def __init__(self, dm, h): Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads.
- def call(self, Q, K, V, ma... | 75274394adb52d740f6cd4000cc00bbde44b9b72 | <|skeleton|>
class MultiHeadAttention:
"""class MultiHeadAttention"""
def __init__(self, dm, h):
"""Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads."""
<|body_0|>
def call(self, Q, K, V, mask):
"""call method. Arg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
"""class MultiHeadAttention"""
def __init__(self, dm, h):
"""Initializer. Args: dm: (int) representing the dimensionality of the model. h: (int) representing the number of heads."""
super().__init__()
self.h = h
self.dm = dm
self.depth = int(dm ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/6-multihead_attention.py | jdarangop/holbertonschool-machine_learning | train | 2 |
ce36afc4ac9909106200c14ec0e609bc9bc94007 | [
"parser = argparse.ArgumentParser(description='molp solver app')\nparser.add_argument('-m', '--model-file-path', help='sets the path to the model file (.lp format)')\nparser.add_argument('-s', '--solver-package', choices=[SolverPackage.GUROBI.value], help='sets the solver package to use')\nparser.add_argument('-w',... | <|body_start_0|>
parser = argparse.ArgumentParser(description='molp solver app')
parser.add_argument('-m', '--model-file-path', help='sets the path to the model file (.lp format)')
parser.add_argument('-s', '--solver-package', choices=[SolverPackage.GUROBI.value], help='sets the solver package t... | Implements the command line application for the molp solver executor | MolpSolverApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MolpSolverApp:
"""Implements the command line application for the molp solver executor"""
def _parse_args(self):
"""Parses and returns the arguments"""
<|body_0|>
def run(self):
"""Runs the command line application"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_071097 | 2,293 | permissive | [
{
"docstring": "Parses and returns the arguments",
"name": "_parse_args",
"signature": "def _parse_args(self)"
},
{
"docstring": "Runs the command line application",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015890 | Implement the Python class `MolpSolverApp` described below.
Class description:
Implements the command line application for the molp solver executor
Method signatures and docstrings:
- def _parse_args(self): Parses and returns the arguments
- def run(self): Runs the command line application | Implement the Python class `MolpSolverApp` described below.
Class description:
Implements the command line application for the molp solver executor
Method signatures and docstrings:
- def _parse_args(self): Parses and returns the arguments
- def run(self): Runs the command line application
<|skeleton|>
class MolpSol... | 465ea7aaa62157411f9f181b994f4d7e6b8a2e33 | <|skeleton|>
class MolpSolverApp:
"""Implements the command line application for the molp solver executor"""
def _parse_args(self):
"""Parses and returns the arguments"""
<|body_0|>
def run(self):
"""Runs the command line application"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MolpSolverApp:
"""Implements the command line application for the molp solver executor"""
def _parse_args(self):
"""Parses and returns the arguments"""
parser = argparse.ArgumentParser(description='molp solver app')
parser.add_argument('-m', '--model-file-path', help='sets the pat... | the_stack_v2_python_sparse | src/molp/executor.py | gokhanceyhan/momilp | train | 2 |
7d9df751b4567a648cdbdc9ec243668579c3a92c | [
"start = (0, 0)\ntarget = (5, 5)\npickup = None\ngrid = [[NOT_VISITED] * 6 for _ in range(6)]\nweights = [[1] * 6 for _ in range(6)]\nheuristic = lambda r, c: abs(target[0] - r) + abs(target[1] - c)\ninstance = ASTAR(start, target, pickup, grid, weights, heuristic)\ninstance.finding_shortest_path = True\nwhile inst... | <|body_start_0|>
start = (0, 0)
target = (5, 5)
pickup = None
grid = [[NOT_VISITED] * 6 for _ in range(6)]
weights = [[1] * 6 for _ in range(6)]
heuristic = lambda r, c: abs(target[0] - r) + abs(target[1] - c)
instance = ASTAR(start, target, pickup, grid, weights,... | TestAstar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAstar:
def test_no_weights(self):
"""Tests basic functionality of Astar on a graph with no weights"""
<|body_0|>
def test_weights(self):
"""Tests Astar functionality on a weighted graph"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start = (0,... | stack_v2_sparse_classes_75kplus_train_071098 | 2,244 | no_license | [
{
"docstring": "Tests basic functionality of Astar on a graph with no weights",
"name": "test_no_weights",
"signature": "def test_no_weights(self)"
},
{
"docstring": "Tests Astar functionality on a weighted graph",
"name": "test_weights",
"signature": "def test_weights(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053970 | Implement the Python class `TestAstar` described below.
Class description:
Implement the TestAstar class.
Method signatures and docstrings:
- def test_no_weights(self): Tests basic functionality of Astar on a graph with no weights
- def test_weights(self): Tests Astar functionality on a weighted graph | Implement the Python class `TestAstar` described below.
Class description:
Implement the TestAstar class.
Method signatures and docstrings:
- def test_no_weights(self): Tests basic functionality of Astar on a graph with no weights
- def test_weights(self): Tests Astar functionality on a weighted graph
<|skeleton|>
c... | 4a59159eadf3a64ec1b125c3da57bbedefc8a0db | <|skeleton|>
class TestAstar:
def test_no_weights(self):
"""Tests basic functionality of Astar on a graph with no weights"""
<|body_0|>
def test_weights(self):
"""Tests Astar functionality on a weighted graph"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAstar:
def test_no_weights(self):
"""Tests basic functionality of Astar on a graph with no weights"""
start = (0, 0)
target = (5, 5)
pickup = None
grid = [[NOT_VISITED] * 6 for _ in range(6)]
weights = [[1] * 6 for _ in range(6)]
heuristic = lambda r... | the_stack_v2_python_sparse | unittests/astar_unittest.py | AdithiRao/Graph-Algorithm-Visualizer | train | 0 | |
2d17ec183c32c6f7863763fe2b1139cce77f89a0 | [
"self.database = database\nself.max_rows = max_rows\nself.allowed_rpm = rpm\nself.create_review_language_table()",
"with GearbestMySQLManager(self.database) as mgr:\n logger.info('Retrieving reviews...')\n cur = mgr.execute_selection_query(SELECT_REVIEWS_QUERY, [self.max_rows])\n reviews = cur.fetchall()... | <|body_start_0|>
self.database = database
self.max_rows = max_rows
self.allowed_rpm = rpm
self.create_review_language_table()
<|end_body_0|>
<|body_start_1|>
with GearbestMySQLManager(self.database) as mgr:
logger.info('Retrieving reviews...')
cur = mgr.e... | GearbestEnricher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GearbestEnricher:
def __init__(self, max_rows, rpm, database='gearbest'):
"""Main initiazlization method. :param max_rows: Max rows allowed by the plan. :param rpm: Maximum amount of requests per minute for the API. :param database: The database to write into."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_071099 | 3,406 | no_license | [
{
"docstring": "Main initiazlization method. :param max_rows: Max rows allowed by the plan. :param rpm: Maximum amount of requests per minute for the API. :param database: The database to write into.",
"name": "__init__",
"signature": "def __init__(self, max_rows, rpm, database='gearbest')"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_002599 | Implement the Python class `GearbestEnricher` described below.
Class description:
Implement the GearbestEnricher class.
Method signatures and docstrings:
- def __init__(self, max_rows, rpm, database='gearbest'): Main initiazlization method. :param max_rows: Max rows allowed by the plan. :param rpm: Maximum amount of ... | Implement the Python class `GearbestEnricher` described below.
Class description:
Implement the GearbestEnricher class.
Method signatures and docstrings:
- def __init__(self, max_rows, rpm, database='gearbest'): Main initiazlization method. :param max_rows: Max rows allowed by the plan. :param rpm: Maximum amount of ... | f1b937f97e0b6d399972d54a6bd6915fe53d8efb | <|skeleton|>
class GearbestEnricher:
def __init__(self, max_rows, rpm, database='gearbest'):
"""Main initiazlization method. :param max_rows: Max rows allowed by the plan. :param rpm: Maximum amount of requests per minute for the API. :param database: The database to write into."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GearbestEnricher:
def __init__(self, max_rows, rpm, database='gearbest'):
"""Main initiazlization method. :param max_rows: Max rows allowed by the plan. :param rpm: Maximum amount of requests per minute for the API. :param database: The database to write into."""
self.database = database
... | the_stack_v2_python_sparse | enrichment/gearbest_enricher.py | sokolster/gearbest-scraper | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.