blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e0d5131221bbcf0b806cce2dfb3dae8b44cdc75e | [
"val = 0\nfor i in range(len(A)):\n for j in reversed(range(i + 1 + val, len(A))):\n if A[i] <= A[j]:\n val = max(val, j - i)\n break\nreturn val",
"from collections import defaultdict\ndp = defaultdict(int)\ndp[0] = 0\nval = 0\nfor i in range(1, len(A)):\n for j in range(i):\n ... | <|body_start_0|>
val = 0
for i in range(len(A)):
for j in reversed(range(i + 1 + val, len(A))):
if A[i] <= A[j]:
val = max(val, j - i)
break
return val
<|end_body_0|>
<|body_start_1|>
from collections import defaultdict... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def maxWidthRamp(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
val = 0
for i in range(len(A)):
fo... | stack_v2_sparse_classes_36k_train_021500 | 868 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "maxWidthRamp1",
"signature": "def maxWidthRamp1(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "maxWidthRamp",
"signature": "def maxWidthRamp(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004315 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A): :type A: List[int] :rtype: int
- def maxWidthRamp(self, A): :type A: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxWidthRamp1(self, A): :type A: List[int] :rtype: int
- def maxWidthRamp(self, A): :type A: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxWidthRamp1(self, ... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def maxWidthRamp1(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def maxWidthRamp(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxWidthRamp1(self, A):
""":type A: List[int] :rtype: int"""
val = 0
for i in range(len(A)):
for j in reversed(range(i + 1 + val, len(A))):
if A[i] <= A[j]:
val = max(val, j - i)
break
return val
... | the_stack_v2_python_sparse | maximum-width-ramp/solution.py | uxlsl/leetcode_practice | train | 0 | |
dbf4c6bb8984a5fb75df28f25a3c3cdad35c4ce1 | [
"super(ResUnit, self).__init__(name=name)\nself._depth = depth\nself._num_layers = 2\nself._kernel_shapes = [kernel_shape] * 2\nself._strides = [stride, 1]\nself._padding = snt.SAME\nself._activation = activation\nself._extra_params = extra_params\nself._downsample_input = False\nif stride != 1:\n self._downsamp... | <|body_start_0|>
super(ResUnit, self).__init__(name=name)
self._depth = depth
self._num_layers = 2
self._kernel_shapes = [kernel_shape] * 2
self._strides = [stride, 1]
self._padding = snt.SAME
self._activation = activation
self._extra_params = extra_params... | ResUnit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUnit:
def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf func... | stack_v2_sparse_classes_36k_train_021501 | 48,282 | permissive | [
{
"docstring": "Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf function): activation used for the internal layers. **extra_params: all the additional keyword arguments will be passed to snt.Conv2D lay... | 2 | stack_v2_sparse_classes_30k_train_017615 | Implement the Python class `ResUnit` described below.
Class description:
Implement the ResUnit class.
Method signatures and docstrings:
- def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params): Args: depth (int): the depth of the resUnit. name (str): module nam... | Implement the Python class `ResUnit` described below.
Class description:
Implement the ResUnit class.
Method signatures and docstrings:
- def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params): Args: depth (int): the depth of the resUnit. name (str): module nam... | a10c33346803239db8a64c104db7f22ec4e05bef | <|skeleton|>
class ResUnit:
def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf func... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResUnit:
def __init__(self, depth, name='resUnit', kernel_shape=[3, 3], stride=1, activation=tf.nn.relu, **extra_params):
"""Args: depth (int): the depth of the resUnit. name (str): module name. kernel_shape (int or [int,int]): the kernel size stride (int): the stride activation (tf function): activat... | the_stack_v2_python_sparse | argo/core/utils/utils_modules.py | ricvo/argo | train | 0 | |
222a0e0f0d48a7dc7dff860d04a3684c5ea142ec | [
"if self.success_url:\n return self.success_url\nelse:\n return reverse('contact')",
"if form.send():\n messages.success(self.request, \"Thanks for your email, we'll respond shortly!\")\nreturn super(ContactFormView, self).form_valid(form)"
] | <|body_start_0|>
if self.success_url:
return self.success_url
else:
return reverse('contact')
<|end_body_0|>
<|body_start_1|>
if form.send():
messages.success(self.request, "Thanks for your email, we'll respond shortly!")
return super(ContactFormView,... | A Web View that allows an email contact form to be displayed and on successful completion of the form, sends the email to the managers. @ivar template_name: The name of a template that renders the form @ivar form_class: The class of the contact form @ivar success_url: Where to redirect the user when the form is sent. | ContactFormView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactFormView:
"""A Web View that allows an email contact form to be displayed and on successful completion of the form, sends the email to the managers. @ivar template_name: The name of a template that renders the form @ivar form_class: The class of the contact form @ivar success_url: Where to... | stack_v2_sparse_classes_36k_train_021502 | 2,212 | permissive | [
{
"docstring": "Determine the success url to redirect the user to on form_valid- If it is not explicitly set on the class, reverse the url from the class name (as set in urls.py). @return: The url to redirect the user to on success. @rtype: C{str}",
"name": "get_success_url",
"signature": "def get_succe... | 2 | stack_v2_sparse_classes_30k_train_012297 | Implement the Python class `ContactFormView` described below.
Class description:
A Web View that allows an email contact form to be displayed and on successful completion of the form, sends the email to the managers. @ivar template_name: The name of a template that renders the form @ivar form_class: The class of the c... | Implement the Python class `ContactFormView` described below.
Class description:
A Web View that allows an email contact form to be displayed and on successful completion of the form, sends the email to the managers. @ivar template_name: The name of a template that renders the form @ivar form_class: The class of the c... | 430f053b5d126d73ed064ede7aeaf1b779a71764 | <|skeleton|>
class ContactFormView:
"""A Web View that allows an email contact form to be displayed and on successful completion of the form, sends the email to the managers. @ivar template_name: The name of a template that renders the form @ivar form_class: The class of the contact form @ivar success_url: Where to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactFormView:
"""A Web View that allows an email contact form to be displayed and on successful completion of the form, sends the email to the managers. @ivar template_name: The name of a template that renders the form @ivar form_class: The class of the contact form @ivar success_url: Where to redirect the... | the_stack_v2_python_sparse | feedback/views.py | kgrant360/geekchicprogramming.com | train | 0 |
907336419f490cd9fc41b3d49c321248e593c6a7 | [
"super().__init__(model_config, observation_space)\nif not critic_separate_model:\n self.value_model = None\nelse:\n self.value_model = self._create_model_from_config(model_config, observation_space)\nself.actor = get_dist_layer_class(action_space)(action_space, self.model.out_size)\nself.critic = linear(self... | <|body_start_0|>
super().__init__(model_config, observation_space)
if not critic_separate_model:
self.value_model = None
else:
self.value_model = self._create_model_from_config(model_config, observation_space)
self.actor = get_dist_layer_class(action_space)(action... | ActorCriticPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActorCriticPolicy:
def __init__(self, model_config, observation_space, action_space, critic_separate_model=False):
"""Initialize an actor-critic policy Args: model_config: The configuration for creating the model observation_space: The observation space defining the model input action_sp... | stack_v2_sparse_classes_36k_train_021503 | 4,264 | permissive | [
{
"docstring": "Initialize an actor-critic policy Args: model_config: The configuration for creating the model observation_space: The observation space defining the model input action_space: The action space for outputting actons as critic_separate_model: Whether to use a duplicate/separate model for the critic... | 5 | stack_v2_sparse_classes_30k_val_000826 | Implement the Python class `ActorCriticPolicy` described below.
Class description:
Implement the ActorCriticPolicy class.
Method signatures and docstrings:
- def __init__(self, model_config, observation_space, action_space, critic_separate_model=False): Initialize an actor-critic policy Args: model_config: The config... | Implement the Python class `ActorCriticPolicy` described below.
Class description:
Implement the ActorCriticPolicy class.
Method signatures and docstrings:
- def __init__(self, model_config, observation_space, action_space, critic_separate_model=False): Initialize an actor-critic policy Args: model_config: The config... | d1722ffd4cf7b4599655b8d9c64abc243919afc9 | <|skeleton|>
class ActorCriticPolicy:
def __init__(self, model_config, observation_space, action_space, critic_separate_model=False):
"""Initialize an actor-critic policy Args: model_config: The configuration for creating the model observation_space: The observation space defining the model input action_sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActorCriticPolicy:
def __init__(self, model_config, observation_space, action_space, critic_separate_model=False):
"""Initialize an actor-critic policy Args: model_config: The configuration for creating the model observation_space: The observation space defining the model input action_space: The actio... | the_stack_v2_python_sparse | rltime/policies/torch/actor_critic.py | frederikschubert/rltime | train | 0 | |
14c670249fcfe0073d2b3d8e4ede77fca6ad09b3 | [
"super().__init__()\nself.feature_extractor = backbone\nself.detection = detection\nself.auxiliary = auxiliary",
"x = self.feature_extractor(x)\naux_out = []\nif self.auxiliary:\n x, scene, depth, normals = self.auxiliary(x)\n aux_out.extend([scene, depth, normals])\nlocs, confs = self.detection(x)\nreturn ... | <|body_start_0|>
super().__init__()
self.feature_extractor = backbone
self.detection = detection
self.auxiliary = auxiliary
<|end_body_0|>
<|body_start_1|>
x = self.feature_extractor(x)
aux_out = []
if self.auxiliary:
x, scene, depth, normals = self.a... | Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector | Network | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
"""Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector"""
def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Opt... | stack_v2_sparse_classes_36k_train_021504 | 3,381 | permissive | [
{
"docstring": "Args: backbone: backbone used to obtain the base feature map detection: detection layer of Network auxiliary: auxiliary block used for MTL",
"name": "__init__",
"signature": "def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Optional[torch.nn.Module]=No... | 2 | stack_v2_sparse_classes_30k_train_016081 | Implement the Python class `Network` described below.
Class description:
Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector
Method signatures and docstrings:
- def __init__(self, b... | Implement the Python class `Network` described below.
Class description:
Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector
Method signatures and docstrings:
- def __init__(self, b... | 6f4c86d3fec7fe3b0ce65d2687d144e9698e964f | <|skeleton|>
class Network:
"""Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector"""
def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Opt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Network:
"""Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector"""
def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Optional[torch.n... | the_stack_v2_python_sparse | rock/model/network.py | Shweta200126/rock-pytorch | train | 0 |
23345a776cf8013a11a56718ea6e5a526e25653e | [
"dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]\ndp[-1][-1] = True\nfor i in range(len(text), -1, -1):\n for j in range(len(pattern) - 1, -1, -1):\n first_match = i < len(text) and pattern[j] in {text[i], '.'}\n if j + 1 < len(pattern) and pattern[j + 1] == '*':\n dp[i... | <|body_start_0|>
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
for i in range(len(text), -1, -1):
for j in range(len(pattern) - 1, -1, -1):
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j + 1 < le... | PatternMatching | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatternMatching:
def is_match(self, text: str, pattern: str) -> bool:
"""Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:"""
<|body_0|>
def is_match_(self, text: str, pattern: str) -> bool:
"... | stack_v2_sparse_classes_36k_train_021505 | 1,884 | no_license | [
{
"docstring": "Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:",
"name": "is_match",
"signature": "def is_match(self, text: str, pattern: str) -> bool"
},
{
"docstring": "Approach: Recursion :param text: :param pattern... | 2 | null | Implement the Python class `PatternMatching` described below.
Class description:
Implement the PatternMatching class.
Method signatures and docstrings:
- def is_match(self, text: str, pattern: str) -> bool: Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param patt... | Implement the Python class `PatternMatching` described below.
Class description:
Implement the PatternMatching class.
Method signatures and docstrings:
- def is_match(self, text: str, pattern: str) -> bool: Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param patt... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class PatternMatching:
def is_match(self, text: str, pattern: str) -> bool:
"""Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:"""
<|body_0|>
def is_match_(self, text: str, pattern: str) -> bool:
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatternMatching:
def is_match(self, text: str, pattern: str) -> bool:
"""Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:"""
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
... | the_stack_v2_python_sparse | math_and_srings/regular_expression_matching.py | Shiv2157k/leet_code | train | 1 | |
49a923f7c6e7b9b2b8380b5d1eb8db957abf3a30 | [
"sprays: List[Dict[str, Any]] = []\nsprays = Sprays.IDs(self, sprays)\nsprays = Sprays.Table(self, sprays)\nUtility.WriteFile(self, f'{self.eXAssets}/sprays.json', sprays)\nlog.info(f'Compiled {len(sprays):,} Sprays')",
"ids: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{self.iXAssets}/loot/sprays_ids.csv', Spr... | <|body_start_0|>
sprays: List[Dict[str, Any]] = []
sprays = Sprays.IDs(self, sprays)
sprays = Sprays.Table(self, sprays)
Utility.WriteFile(self, f'{self.eXAssets}/sprays.json', sprays)
log.info(f'Compiled {len(sprays):,} Sprays')
<|end_body_0|>
<|body_start_1|>
ids: List... | Spray XAssets. | Sprays | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sprays:
"""Spray XAssets."""
def Compile(self: Any) -> None:
"""Compile the Spray XAssets."""
<|body_0|>
def IDs(self: Any, sprays: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the loot/sprays_ids.csv XAsset."""
<|body_1|>
def Table(self... | stack_v2_sparse_classes_36k_train_021506 | 2,554 | permissive | [
{
"docstring": "Compile the Spray XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the loot/sprays_ids.csv XAsset.",
"name": "IDs",
"signature": "def IDs(self: Any, sprays: List[Dict[str, Any]]) -> List[Dict[str, Any]]"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_009302 | Implement the Python class `Sprays` described below.
Class description:
Spray XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Spray XAssets.
- def IDs(self: Any, sprays: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the loot/sprays_ids.csv XAsset.
- def Table(self: An... | Implement the Python class `Sprays` described below.
Class description:
Spray XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Spray XAssets.
- def IDs(self: Any, sprays: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the loot/sprays_ids.csv XAsset.
- def Table(self: An... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class Sprays:
"""Spray XAssets."""
def Compile(self: Any) -> None:
"""Compile the Spray XAssets."""
<|body_0|>
def IDs(self: Any, sprays: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the loot/sprays_ids.csv XAsset."""
<|body_1|>
def Table(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sprays:
"""Spray XAssets."""
def Compile(self: Any) -> None:
"""Compile the Spray XAssets."""
sprays: List[Dict[str, Any]] = []
sprays = Sprays.IDs(self, sprays)
sprays = Sprays.Table(self, sprays)
Utility.WriteFile(self, f'{self.eXAssets}/sprays.json', sprays)
... | the_stack_v2_python_sparse | ModernWarfare/XAssets/sprays.py | dbuentello/Hyde | train | 0 |
6c73348fd47e3b88dc8bc266cd828aa1ef973510 | [
"self.expiry_time_usecs = expiry_time_usecs\nself.snapshot_target_settings = snapshot_target_settings\nself.uid = uid",
"if dictionary is None:\n return None\nexpiry_time_usecs = dictionary.get('expiryTimeUsecs')\nsnapshot_target_settings = cohesity_management_sdk.models.snapshot_target_settings.SnapshotTarget... | <|body_start_0|>
self.expiry_time_usecs = expiry_time_usecs
self.snapshot_target_settings = snapshot_target_settings
self.uid = uid
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
expiry_time_usecs = dictionary.get('expiryTimeUsecs')
snapsh... | Implementation of the 'ReplicaInfo' model. Specifies the Replication information about a snapshot. Attributes: expiry_time_usecs (long|int): Specifies the expiration time of the snapshot within the target location. snapshot_target_settings (SnapshotTargetSettings): Specifies the snapshot target settings for the given s... | ReplicaInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplicaInfo:
"""Implementation of the 'ReplicaInfo' model. Specifies the Replication information about a snapshot. Attributes: expiry_time_usecs (long|int): Specifies the expiration time of the snapshot within the target location. snapshot_target_settings (SnapshotTargetSettings): Specifies the s... | stack_v2_sparse_classes_36k_train_021507 | 2,484 | permissive | [
{
"docstring": "Constructor for the ReplicaInfo class",
"name": "__init__",
"signature": "def __init__(self, expiry_time_usecs=None, snapshot_target_settings=None, uid=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repres... | 2 | null | Implement the Python class `ReplicaInfo` described below.
Class description:
Implementation of the 'ReplicaInfo' model. Specifies the Replication information about a snapshot. Attributes: expiry_time_usecs (long|int): Specifies the expiration time of the snapshot within the target location. snapshot_target_settings (S... | Implement the Python class `ReplicaInfo` described below.
Class description:
Implementation of the 'ReplicaInfo' model. Specifies the Replication information about a snapshot. Attributes: expiry_time_usecs (long|int): Specifies the expiration time of the snapshot within the target location. snapshot_target_settings (S... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ReplicaInfo:
"""Implementation of the 'ReplicaInfo' model. Specifies the Replication information about a snapshot. Attributes: expiry_time_usecs (long|int): Specifies the expiration time of the snapshot within the target location. snapshot_target_settings (SnapshotTargetSettings): Specifies the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplicaInfo:
"""Implementation of the 'ReplicaInfo' model. Specifies the Replication information about a snapshot. Attributes: expiry_time_usecs (long|int): Specifies the expiration time of the snapshot within the target location. snapshot_target_settings (SnapshotTargetSettings): Specifies the snapshot targe... | the_stack_v2_python_sparse | cohesity_management_sdk/models/replica_info.py | cohesity/management-sdk-python | train | 24 |
7a0e7fbe18b4ba8923087c5614d4b846b20c62dc | [
"assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))\nC = self.COEFFS[imt]\nmean = self._compute_mean(C, rup.mag, dists.rjb)\nstddevs = self._compute_stddevs(C, dists.rjb.size, stddev_types)\nmean = clip_mean(imt, mean)\nreturn (mean, stddevs)",
"ffc = self._comp... | <|body_start_0|>
assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))
C = self.COEFFS[imt]
mean = self._compute_mean(C, rup.mag, dists.rjb)
stddevs = self._compute_stddevs(C, dists.rjb.size, stddev_types)
mean = clip_mean(imt, mea... | Implements GMPE developed by G. R. Toro, N. A. Abrahamson, J. F. Sneider and published in "Model of Strong Ground Motions from Earthquakes in Central and Eastern North America: Best Estimates and Uncertainties" (Seismological Research Letters, Volume 68, Number 1, 1997) as utilized by the National Seismic Hazard Mappin... | ToroEtAl1997MblgNSHMP2008 | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToroEtAl1997MblgNSHMP2008:
"""Implements GMPE developed by G. R. Toro, N. A. Abrahamson, J. F. Sneider and published in "Model of Strong Ground Motions from Earthquakes in Central and Eastern North America: Best Estimates and Uncertainties" (Seismological Research Letters, Volume 68, Number 1, 19... | stack_v2_sparse_classes_36k_train_021508 | 7,600 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Compute ground moti... | 4 | stack_v2_sparse_classes_30k_val_000686 | Implement the Python class `ToroEtAl1997MblgNSHMP2008` described below.
Class description:
Implements GMPE developed by G. R. Toro, N. A. Abrahamson, J. F. Sneider and published in "Model of Strong Ground Motions from Earthquakes in Central and Eastern North America: Best Estimates and Uncertainties" (Seismological Re... | Implement the Python class `ToroEtAl1997MblgNSHMP2008` described below.
Class description:
Implements GMPE developed by G. R. Toro, N. A. Abrahamson, J. F. Sneider and published in "Model of Strong Ground Motions from Earthquakes in Central and Eastern North America: Best Estimates and Uncertainties" (Seismological Re... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class ToroEtAl1997MblgNSHMP2008:
"""Implements GMPE developed by G. R. Toro, N. A. Abrahamson, J. F. Sneider and published in "Model of Strong Ground Motions from Earthquakes in Central and Eastern North America: Best Estimates and Uncertainties" (Seismological Research Letters, Volume 68, Number 1, 19... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToroEtAl1997MblgNSHMP2008:
"""Implements GMPE developed by G. R. Toro, N. A. Abrahamson, J. F. Sneider and published in "Model of Strong Ground Motions from Earthquakes in Central and Eastern North America: Best Estimates and Uncertainties" (Seismological Research Letters, Volume 68, Number 1, 1997) as utiliz... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/toro_1997.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
f60aad1c7ce9ff847622bc74ff6317ce3c564279 | [
"embed = discord.Embed(description=contents, color=self.received_mail)\nembed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)\nembed.set_footer(text='User ID: {author_id}'.format(author_id=ctx.author.id))\nreturn embed",
"embed.color = self.sent_mail\nembed.title = 'Message Sent'\nreturn embed",
"em... | <|body_start_0|>
embed = discord.Embed(description=contents, color=self.received_mail)
embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
embed.set_footer(text='User ID: {author_id}'.format(author_id=ctx.author.id))
return embed
<|end_body_0|>
<|body_start_1|>
emb... | Embed models for all things that gets sent | EmbedModels | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbedModels:
"""Embed models for all things that gets sent"""
def embed_to_moderators(self, ctx: commands.Context, contents: str):
"""Embed that get's sent to staff This is not the embed that the user is shown."""
<|body_0|>
def mod_embed_for_user(self, embed):
"... | stack_v2_sparse_classes_36k_train_021509 | 4,020 | no_license | [
{
"docstring": "Embed that get's sent to staff This is not the embed that the user is shown.",
"name": "embed_to_moderators",
"signature": "def embed_to_moderators(self, ctx: commands.Context, contents: str)"
},
{
"docstring": "Embed that shows to user what they sent to staff This is shown to th... | 4 | stack_v2_sparse_classes_30k_train_014140 | Implement the Python class `EmbedModels` described below.
Class description:
Embed models for all things that gets sent
Method signatures and docstrings:
- def embed_to_moderators(self, ctx: commands.Context, contents: str): Embed that get's sent to staff This is not the embed that the user is shown.
- def mod_embed_... | Implement the Python class `EmbedModels` described below.
Class description:
Embed models for all things that gets sent
Method signatures and docstrings:
- def embed_to_moderators(self, ctx: commands.Context, contents: str): Embed that get's sent to staff This is not the embed that the user is shown.
- def mod_embed_... | a17df50e77b2946b271c29958eefb36d36fad714 | <|skeleton|>
class EmbedModels:
"""Embed models for all things that gets sent"""
def embed_to_moderators(self, ctx: commands.Context, contents: str):
"""Embed that get's sent to staff This is not the embed that the user is shown."""
<|body_0|>
def mod_embed_for_user(self, embed):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmbedModels:
"""Embed models for all things that gets sent"""
def embed_to_moderators(self, ctx: commands.Context, contents: str):
"""Embed that get's sent to staff This is not the embed that the user is shown."""
embed = discord.Embed(description=contents, color=self.received_mail)
... | the_stack_v2_python_sparse | mailsystem/embedmodel.py | kablekompany/Sharky | train | 0 |
c1b2094dd89632c919a0c11c5d605c5dc7b90710 | [
"try:\n for item in payload:\n user_record = UserRecord.create_user(email=item['email'], password=item['password'], display_name=item['display_name'], phone_number=item['phone_number'], auth=web_sdk.auth)\n user_record.make_claims({'complete_register': item['complete_register']})\n user = Us... | <|body_start_0|>
try:
for item in payload:
user_record = UserRecord.create_user(email=item['email'], password=item['password'], display_name=item['display_name'], phone_number=item['phone_number'], auth=web_sdk.auth)
user_record.make_claims({'complete_register': item[... | UserSeed | UserSeed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSeed:
"""UserSeed"""
def up(self):
"""up"""
<|body_0|>
def down(self):
"""down"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
for item in payload:
user_record = UserRecord.create_user(email=item['email'], pa... | stack_v2_sparse_classes_36k_train_021510 | 5,514 | no_license | [
{
"docstring": "up",
"name": "up",
"signature": "def up(self)"
},
{
"docstring": "down",
"name": "down",
"signature": "def down(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018510 | Implement the Python class `UserSeed` described below.
Class description:
UserSeed
Method signatures and docstrings:
- def up(self): up
- def down(self): down | Implement the Python class `UserSeed` described below.
Class description:
UserSeed
Method signatures and docstrings:
- def up(self): up
- def down(self): down
<|skeleton|>
class UserSeed:
"""UserSeed"""
def up(self):
"""up"""
<|body_0|>
def down(self):
"""down"""
<|body_... | 828cb0109415b293a38f5c8ea6c11ce4a469a8ea | <|skeleton|>
class UserSeed:
"""UserSeed"""
def up(self):
"""up"""
<|body_0|>
def down(self):
"""down"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSeed:
"""UserSeed"""
def up(self):
"""up"""
try:
for item in payload:
user_record = UserRecord.create_user(email=item['email'], password=item['password'], display_name=item['display_name'], phone_number=item['phone_number'], auth=web_sdk.auth)
... | the_stack_v2_python_sparse | src/seeds/user.py | andresbermeoq/server | train | 0 |
ecf0e1889c0920e9e40c245e3381e4ab07b56dc4 | [
"super(CollaborativeMemoryNetwork, self).__init__()\nself.config = config\nself.device = device\nself.emb_dim = config['emb_dim']\nself.neighborhood = item_user_list\nself.max_neighbors = max([len(x) for x in item_user_list.values()])\nconfig['max_neighbors'] = self.max_neighbors\nself.user_memory = nn.Embedding(us... | <|body_start_0|>
super(CollaborativeMemoryNetwork, self).__init__()
self.config = config
self.device = device
self.emb_dim = config['emb_dim']
self.neighborhood = item_user_list
self.max_neighbors = max([len(x) for x in item_user_list.values()])
config['max_neighb... | CollaborativeMemoryNetwork Class. | CollaborativeMemoryNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollaborativeMemoryNetwork:
"""CollaborativeMemoryNetwork Class."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list, device):
"""Initialize CollaborativeMemoryNetwork Class."""
<|body_0|>
def output_module(self, input):
"""Missing Doc.... | stack_v2_sparse_classes_36k_train_021511 | 9,498 | permissive | [
{
"docstring": "Initialize CollaborativeMemoryNetwork Class.",
"name": "__init__",
"signature": "def __init__(self, config, user_embeddings, item_embeddings, item_user_list, device)"
},
{
"docstring": "Missing Doc.",
"name": "output_module",
"signature": "def output_module(self, input)"
... | 4 | null | Implement the Python class `CollaborativeMemoryNetwork` described below.
Class description:
CollaborativeMemoryNetwork Class.
Method signatures and docstrings:
- def __init__(self, config, user_embeddings, item_embeddings, item_user_list, device): Initialize CollaborativeMemoryNetwork Class.
- def output_module(self,... | Implement the Python class `CollaborativeMemoryNetwork` described below.
Class description:
CollaborativeMemoryNetwork Class.
Method signatures and docstrings:
- def __init__(self, config, user_embeddings, item_embeddings, item_user_list, device): Initialize CollaborativeMemoryNetwork Class.
- def output_module(self,... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class CollaborativeMemoryNetwork:
"""CollaborativeMemoryNetwork Class."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list, device):
"""Initialize CollaborativeMemoryNetwork Class."""
<|body_0|>
def output_module(self, input):
"""Missing Doc.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollaborativeMemoryNetwork:
"""CollaborativeMemoryNetwork Class."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list, device):
"""Initialize CollaborativeMemoryNetwork Class."""
super(CollaborativeMemoryNetwork, self).__init__()
self.config = config
... | the_stack_v2_python_sparse | beta_rec/models/cmn.py | beta-team/beta-recsys | train | 156 |
16465b38ee303d2cc803fbcc06584a3357ac0c66 | [
"memo = {}\n\ndef dp(k, n):\n if (k, n) not in memo:\n if not n:\n ans = 0\n elif k == 1:\n ans = n\n else:\n low, high = (1, n)\n while low + 1 < high:\n temp = (low + high) // 2\n t1 = dp(k - 1, temp - 1)\n ... | <|body_start_0|>
memo = {}
def dp(k, n):
if (k, n) not in memo:
if not n:
ans = 0
elif k == 1:
ans = n
else:
low, high = (1, n)
while low + 1 < high:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def super_egg_drop(cls, k: int, n: int) -> int:
"""O(kn*logn), O(kn)"""
<|body_0|>
def super_egg_drop_v2(cls, k: int, n: int) -> int:
"""O(kn), O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
memo = {}
def dp(k, n):
... | stack_v2_sparse_classes_36k_train_021512 | 3,072 | no_license | [
{
"docstring": "O(kn*logn), O(kn)",
"name": "super_egg_drop",
"signature": "def super_egg_drop(cls, k: int, n: int) -> int"
},
{
"docstring": "O(kn), O(n)",
"name": "super_egg_drop_v2",
"signature": "def super_egg_drop_v2(cls, k: int, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_020455 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def super_egg_drop(cls, k: int, n: int) -> int: O(kn*logn), O(kn)
- def super_egg_drop_v2(cls, k: int, n: int) -> int: O(kn), O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def super_egg_drop(cls, k: int, n: int) -> int: O(kn*logn), O(kn)
- def super_egg_drop_v2(cls, k: int, n: int) -> int: O(kn), O(n)
<|skeleton|>
class Solution:
def super_eg... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def super_egg_drop(cls, k: int, n: int) -> int:
"""O(kn*logn), O(kn)"""
<|body_0|>
def super_egg_drop_v2(cls, k: int, n: int) -> int:
"""O(kn), O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def super_egg_drop(cls, k: int, n: int) -> int:
"""O(kn*logn), O(kn)"""
memo = {}
def dp(k, n):
if (k, n) not in memo:
if not n:
ans = 0
elif k == 1:
ans = n
else:
... | the_stack_v2_python_sparse | 02-算法思想/数学/887.鸡蛋掉落(H).py | jh-lau/leetcode_in_python | train | 0 | |
6496fcc5c465ff63b3b1a46d5da4b7c5875d666c | [
"q = collections.deque()\nq.append(root)\nres = []\nwhile q:\n curr = q.popleft()\n if curr:\n res.append(curr.val)\n q.append(curr.left)\n q.append(curr.right)\n else:\n res.append(None)\nreturn str(res)",
"orig = eval(data)\nroot = TreeNode(orig[0]) if orig and orig[0] != No... | <|body_start_0|>
q = collections.deque()
q.append(root)
res = []
while q:
curr = q.popleft()
if curr:
res.append(curr.val)
q.append(curr.left)
q.append(curr.right)
else:
res.append(None)
... | 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):
"""apply bfs and index for decoding string"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
q = collec... | stack_v2_sparse_classes_36k_train_021513 | 1,405 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "apply bfs and index for decoding string",
"name": "deserialize",
"signature": "def deserialize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005463 | 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): apply bfs and index for decoding string | 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): apply bfs and index for decoding string
<|skeleton|>
clas... | 7609fbd164e3dbedc11308fdc24b57b5097ade81 | <|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):
"""apply bfs and index for decoding string"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
q = collections.deque()
q.append(root)
res = []
while q:
curr = q.popleft()
if curr:
res.append(curr.val)
... | the_stack_v2_python_sparse | python/297_serialize_and_deserialize_binary_tree.py | MakrisHuang/LeetCode | train | 0 | |
d6d3e3347597b7f18194051f3caf3b130f161e34 | [
"self.response_xml: Optional[Element] = response_xml\nself.raw: Dict[str, Any] = {}\n\ndef extract_text(prop_name: str) -> Optional[str]:\n text = prop(response_xml, MAPPING_PROPS[prop_name], relative=True) if response_xml else None\n self.raw[prop_name] = text\n return text\ncreated = extract_text('create... | <|body_start_0|>
self.response_xml: Optional[Element] = response_xml
self.raw: Dict[str, Any] = {}
def extract_text(prop_name: str) -> Optional[str]:
text = prop(response_xml, MAPPING_PROPS[prop_name], relative=True) if response_xml else None
self.raw[prop_name] = text
... | Parses <d:propstat> data into certain properties. Only supports a certain set of properties to extract. Others are ignored. | DAVProperties | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAVProperties:
"""Parses <d:propstat> data into certain properties. Only supports a certain set of properties to extract. Others are ignored."""
def __init__(self, response_xml: Optional[Element]=None):
"""Parses props to certain attributes. Args: response_xml: <d:propstat> element""... | stack_v2_sparse_classes_36k_train_021514 | 9,248 | permissive | [
{
"docstring": "Parses props to certain attributes. Args: response_xml: <d:propstat> element",
"name": "__init__",
"signature": "def __init__(self, response_xml: Optional[Element]=None)"
},
{
"docstring": "Returns all properties that it supports parsing. Args: raw: Provides raw data instead.",
... | 2 | stack_v2_sparse_classes_30k_train_019167 | Implement the Python class `DAVProperties` described below.
Class description:
Parses <d:propstat> data into certain properties. Only supports a certain set of properties to extract. Others are ignored.
Method signatures and docstrings:
- def __init__(self, response_xml: Optional[Element]=None): Parses props to certa... | Implement the Python class `DAVProperties` described below.
Class description:
Parses <d:propstat> data into certain properties. Only supports a certain set of properties to extract. Others are ignored.
Method signatures and docstrings:
- def __init__(self, response_xml: Optional[Element]=None): Parses props to certa... | ee6940486c557f9be2e6b967b28656e30c3598dd | <|skeleton|>
class DAVProperties:
"""Parses <d:propstat> data into certain properties. Only supports a certain set of properties to extract. Others are ignored."""
def __init__(self, response_xml: Optional[Element]=None):
"""Parses props to certain attributes. Args: response_xml: <d:propstat> element""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DAVProperties:
"""Parses <d:propstat> data into certain properties. Only supports a certain set of properties to extract. Others are ignored."""
def __init__(self, response_xml: Optional[Element]=None):
"""Parses props to certain attributes. Args: response_xml: <d:propstat> element"""
sel... | the_stack_v2_python_sparse | python_fsspec_WebDAV/webdav4/multistatus.py | philip-shen/note_python | train | 0 |
ef5b7cf85a12f231ba18e16859e72ff226528d31 | [
"self.config = cf\nself.res = rf\nself.ft_mode = mode\nself.ckpt_interval = interval\nself.fault_model = model\nself.tag = tag\nself.trials = trial_tracker(t)\nself.gen_launch_str()",
"c = '-c'\ncval = self.config\nr = '-r'\nrval = self.res\nl = '-l'\nlval = self.tag\nf = '-f'\nb = '-b'\nself.launch_str = ['pytho... | <|body_start_0|>
self.config = cf
self.res = rf
self.ft_mode = mode
self.ckpt_interval = interval
self.fault_model = model
self.tag = tag
self.trials = trial_tracker(t)
self.gen_launch_str()
<|end_body_0|>
<|body_start_1|>
c = '-c'
cval = ... | experiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class experiment:
def __init__(self, cf, rf, mode, interval, model, t, tag):
"""create a new experiment - cf = config file name - rf = resource file name - mode = fault tolerance mode - interval = checkpoint interval for C/R FT modes - t = # of trials - tag = identifier for the log file"""
... | stack_v2_sparse_classes_36k_train_021515 | 19,091 | permissive | [
{
"docstring": "create a new experiment - cf = config file name - rf = resource file name - mode = fault tolerance mode - interval = checkpoint interval for C/R FT modes - t = # of trials - tag = identifier for the log file",
"name": "__init__",
"signature": "def __init__(self, cf, rf, mode, interval, m... | 3 | stack_v2_sparse_classes_30k_train_020475 | Implement the Python class `experiment` described below.
Class description:
Implement the experiment class.
Method signatures and docstrings:
- def __init__(self, cf, rf, mode, interval, model, t, tag): create a new experiment - cf = config file name - rf = resource file name - mode = fault tolerance mode - interval ... | Implement the Python class `experiment` described below.
Class description:
Implement the experiment class.
Method signatures and docstrings:
- def __init__(self, cf, rf, mode, interval, model, t, tag): create a new experiment - cf = config file name - rf = resource file name - mode = fault tolerance mode - interval ... | 6f02737d4754731a25dd33759594402ea7f4cfba | <|skeleton|>
class experiment:
def __init__(self, cf, rf, mode, interval, model, t, tag):
"""create a new experiment - cf = config file name - rf = resource file name - mode = fault tolerance mode - interval = checkpoint interval for C/R FT modes - t = # of trials - tag = identifier for the log file"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class experiment:
def __init__(self, cf, rf, mode, interval, model, t, tag):
"""create a new experiment - cf = config file name - rf = resource file name - mode = fault tolerance mode - interval = checkpoint interval for C/R FT modes - t = # of trials - tag = identifier for the log file"""
self.conf... | the_stack_v2_python_sparse | ipsframework/utils/RUS/run_exps.py | HPC-SimTools/IPS-framework | train | 11 | |
410c3e5bbb8252eee783021c754ad1383cc0864a | [
"self.product_code = product_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price",
"output_dict = {}\noutput_dict['product_code'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['r... | <|body_start_0|>
self.product_code = product_code
self.description = description
self.market_price = market_price
self.rental_price = rental_price
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['product_code'] = self.product_code
output_dict['descri... | Class for creating inventory object Methods: return_as_dictionary: Convert inventory object to a dictionary with keys for each attribute name and values for attribute value | Inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inventory:
"""Class for creating inventory object Methods: return_as_dictionary: Convert inventory object to a dictionary with keys for each attribute name and values for attribute value"""
def __init__(self, product_code, description, market_price, rental_price):
"""Create instance ... | stack_v2_sparse_classes_36k_train_021516 | 1,525 | no_license | [
{
"docstring": "Create instance of inventory object Args: product_code (alphanumeric): Unique product code description (string): Description of product market_price (numeric): Product price rental_price (numeric): Product rental price",
"name": "__init__",
"signature": "def __init__(self, product_code, ... | 2 | null | Implement the Python class `Inventory` described below.
Class description:
Class for creating inventory object Methods: return_as_dictionary: Convert inventory object to a dictionary with keys for each attribute name and values for attribute value
Method signatures and docstrings:
- def __init__(self, product_code, d... | Implement the Python class `Inventory` described below.
Class description:
Class for creating inventory object Methods: return_as_dictionary: Convert inventory object to a dictionary with keys for each attribute name and values for attribute value
Method signatures and docstrings:
- def __init__(self, product_code, d... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Inventory:
"""Class for creating inventory object Methods: return_as_dictionary: Convert inventory object to a dictionary with keys for each attribute name and values for attribute value"""
def __init__(self, product_code, description, market_price, rental_price):
"""Create instance ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inventory:
"""Class for creating inventory object Methods: return_as_dictionary: Convert inventory object to a dictionary with keys for each attribute name and values for attribute value"""
def __init__(self, product_code, description, market_price, rental_price):
"""Create instance of inventory ... | the_stack_v2_python_sparse | students/gregdevore/lesson01/assignment/inventory_management/inventory_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
f5db68abd6750d1e54d880c9e6213cd066d1e701 | [
"if proxy:\n PROXY_IP = proxy['IP']\n PROXY_USER = proxy['USER']\n PROXY_PASSWORD = proxy['PASSWORD']\n PROXY_PORT = proxy['PORT']\n proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + '@' + PROXY_IP + ':' + PROXY_PORT\n proxy_support = urllib2.ProxyHandler({'http': proxy_url})\n opener... | <|body_start_0|>
if proxy:
PROXY_IP = proxy['IP']
PROXY_USER = proxy['USER']
PROXY_PASSWORD = proxy['PASSWORD']
PROXY_PORT = proxy['PORT']
proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + '@' + PROXY_IP + ':' + PROXY_PORT
proxy_s... | Comment. | DesktopWallpaper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DesktopWallpaper:
"""Comment."""
def __init__(self, proxy=None):
"""Comment"""
<|body_0|>
def readnatgeo(self):
"""Comment"""
<|body_1|>
def lookforwallpaper(self, content):
"""Comment"""
<|body_2|>
def downloadjpg(self, wallpape... | stack_v2_sparse_classes_36k_train_021517 | 2,117 | no_license | [
{
"docstring": "Comment",
"name": "__init__",
"signature": "def __init__(self, proxy=None)"
},
{
"docstring": "Comment",
"name": "readnatgeo",
"signature": "def readnatgeo(self)"
},
{
"docstring": "Comment",
"name": "lookforwallpaper",
"signature": "def lookforwallpaper(s... | 4 | null | Implement the Python class `DesktopWallpaper` described below.
Class description:
Comment.
Method signatures and docstrings:
- def __init__(self, proxy=None): Comment
- def readnatgeo(self): Comment
- def lookforwallpaper(self, content): Comment
- def downloadjpg(self, wallpaper): Comment | Implement the Python class `DesktopWallpaper` described below.
Class description:
Comment.
Method signatures and docstrings:
- def __init__(self, proxy=None): Comment
- def readnatgeo(self): Comment
- def lookforwallpaper(self, content): Comment
- def downloadjpg(self, wallpaper): Comment
<|skeleton|>
class DesktopW... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class DesktopWallpaper:
"""Comment."""
def __init__(self, proxy=None):
"""Comment"""
<|body_0|>
def readnatgeo(self):
"""Comment"""
<|body_1|>
def lookforwallpaper(self, content):
"""Comment"""
<|body_2|>
def downloadjpg(self, wallpape... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DesktopWallpaper:
"""Comment."""
def __init__(self, proxy=None):
"""Comment"""
if proxy:
PROXY_IP = proxy['IP']
PROXY_USER = proxy['USER']
PROXY_PASSWORD = proxy['PASSWORD']
PROXY_PORT = proxy['PORT']
proxy_url = 'http://' + PROX... | the_stack_v2_python_sparse | ExtractFeatures/Data/kracekumar/getpicture.py | vivekaxl/LexisNexis | train | 9 |
bf39ff7a8923716007dba8836708fa272d543c38 | [
"if data != []:\n return cls({key: value['value'] for key, value in data.items()})\nreturn cls()",
"norm_data = {}\nfor key, value in data.items():\n if isinstance(value, str):\n norm_data[key] = {'language': key, 'value': value}\n else:\n norm_data[key] = value\nreturn norm_data",
"data ... | <|body_start_0|>
if data != []:
return cls({key: value['value'] for key, value in data.items()})
return cls()
<|end_body_0|>
<|body_start_1|>
norm_data = {}
for key, value in data.items():
if isinstance(value, str):
norm_data[key] = {'language': k... | A structure holding language data for a Wikibase entity. Language data are mappings from a language to a string. It can be labels, descriptions and others. | LanguageDict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageDict:
"""A structure holding language data for a Wikibase entity. Language data are mappings from a language to a string. It can be labels, descriptions and others."""
def fromJSON(cls, data, repo=None):
"""Construct a new LanguageDict from JSON."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_021518 | 18,327 | permissive | [
{
"docstring": "Construct a new LanguageDict from JSON.",
"name": "fromJSON",
"signature": "def fromJSON(cls, data, repo=None)"
},
{
"docstring": "Helper function to expand data into the Wikibase API structure. :param data: Data to normalize :return: The dict with normalized data",
"name": "... | 3 | null | Implement the Python class `LanguageDict` described below.
Class description:
A structure holding language data for a Wikibase entity. Language data are mappings from a language to a string. It can be labels, descriptions and others.
Method signatures and docstrings:
- def fromJSON(cls, data, repo=None): Construct a ... | Implement the Python class `LanguageDict` described below.
Class description:
A structure holding language data for a Wikibase entity. Language data are mappings from a language to a string. It can be labels, descriptions and others.
Method signatures and docstrings:
- def fromJSON(cls, data, repo=None): Construct a ... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class LanguageDict:
"""A structure holding language data for a Wikibase entity. Language data are mappings from a language to a string. It can be labels, descriptions and others."""
def fromJSON(cls, data, repo=None):
"""Construct a new LanguageDict from JSON."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageDict:
"""A structure holding language data for a Wikibase entity. Language data are mappings from a language to a string. It can be labels, descriptions and others."""
def fromJSON(cls, data, repo=None):
"""Construct a new LanguageDict from JSON."""
if data != []:
retu... | the_stack_v2_python_sparse | pywikibot/page/_collections.py | wikimedia/pywikibot | train | 432 |
79ba25a03aa71658629fd2745792fa0b271d2524 | [
"assert node.next is None\ninsertBefore = dummyHead\nwhile insertBefore.next and insertBefore.next.val < node.val:\n insertBefore = insertBefore.next\nnode.next = insertBefore.next\ninsertBefore.next = node\nreturn node",
"dummyHead = ListNode(float('-inf'))\nlastNode = None\ntail = dummyHead\nwhile head:\n ... | <|body_start_0|>
assert node.next is None
insertBefore = dummyHead
while insertBefore.next and insertBefore.next.val < node.val:
insertBefore = insertBefore.next
node.next = insertBefore.next
insertBefore.next = node
return node
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertListNode(self, dummyHead, node):
"""insert node to the list starting at dummyHead.next return node"""
<|body_0|>
def insertionSortList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_021519 | 1,274 | no_license | [
{
"docstring": "insert node to the list starting at dummyHead.next return node",
"name": "insertListNode",
"signature": "def insertListNode(self, dummyHead, node)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "insertionSortList",
"signature": "def insertionSortList(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertListNode(self, dummyHead, node): insert node to the list starting at dummyHead.next return node
- def insertionSortList(self, head): :type head: ListNode :rtype: ListNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertListNode(self, dummyHead, node): insert node to the list starting at dummyHead.next return node
- def insertionSortList(self, head): :type head: ListNode :rtype: ListNo... | 6e051eb554d9cf6f424f1e0a77f3072adf7f64c4 | <|skeleton|>
class Solution:
def insertListNode(self, dummyHead, node):
"""insert node to the list starting at dummyHead.next return node"""
<|body_0|>
def insertionSortList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def insertListNode(self, dummyHead, node):
"""insert node to the list starting at dummyHead.next return node"""
assert node.next is None
insertBefore = dummyHead
while insertBefore.next and insertBefore.next.val < node.val:
insertBefore = insertBefore.next... | the_stack_v2_python_sparse | 147. Insertion Sort List.py | vincent-kangzhou/LeetCode-Python | train | 0 | |
e16a73e00c67504fd8dfa0146663247228754521 | [
"self.board = root_board\nself.archive = {}\nself.queue = Queue()",
"print('solving...\\nthis board: \\n')\nprint(self.board)\nself.archive[hash(self.board)] = 1\nself.queue.put(self.board)\nwhile not self.queue.empty():\n parent_board = self.queue.get()\n if validator.check_endstate(parent_board):\n ... | <|body_start_0|>
self.board = root_board
self.archive = {}
self.queue = Queue()
<|end_body_0|>
<|body_start_1|>
print('solving...\nthis board: \n')
print(self.board)
self.archive[hash(self.board)] = 1
self.queue.put(self.board)
while not self.queue.empty(... | Defines the Breadth class | Breadth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Breadth:
"""Defines the Breadth class"""
def __init__(self, root_board):
"""Breadth always contains a root board, an archive and a queue"""
<|body_0|>
def solve(self):
"""Solves root board using BFS"""
<|body_1|>
def try_move(self, board, car):
... | stack_v2_sparse_classes_36k_train_021520 | 2,163 | no_license | [
{
"docstring": "Breadth always contains a root board, an archive and a queue",
"name": "__init__",
"signature": "def __init__(self, root_board)"
},
{
"docstring": "Solves root board using BFS",
"name": "solve",
"signature": "def solve(self)"
},
{
"docstring": "Tries moving a car ... | 3 | stack_v2_sparse_classes_30k_train_010332 | Implement the Python class `Breadth` described below.
Class description:
Defines the Breadth class
Method signatures and docstrings:
- def __init__(self, root_board): Breadth always contains a root board, an archive and a queue
- def solve(self): Solves root board using BFS
- def try_move(self, board, car): Tries mov... | Implement the Python class `Breadth` described below.
Class description:
Defines the Breadth class
Method signatures and docstrings:
- def __init__(self, root_board): Breadth always contains a root board, an archive and a queue
- def solve(self): Solves root board using BFS
- def try_move(self, board, car): Tries mov... | 3bbd8f4176c60d002683ec6e18516196980a304f | <|skeleton|>
class Breadth:
"""Defines the Breadth class"""
def __init__(self, root_board):
"""Breadth always contains a root board, an archive and a queue"""
<|body_0|>
def solve(self):
"""Solves root board using BFS"""
<|body_1|>
def try_move(self, board, car):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Breadth:
"""Defines the Breadth class"""
def __init__(self, root_board):
"""Breadth always contains a root board, an archive and a queue"""
self.board = root_board
self.archive = {}
self.queue = Queue()
def solve(self):
"""Solves root board using BFS"""
... | the_stack_v2_python_sparse | breadth.py | JuliaAnten/Exit | train | 1 |
67a888397b98fd9b109ce461ef8254bead765592 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.b2xIdentityUserFlow'.casefold():\n from ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | IdentityUserFlow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityUserFlow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlow:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k_train_021521 | 2,998 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: IdentityUserFlow",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_009562 | Implement the Python class `IdentityUserFlow` described below.
Class description:
Implement the IdentityUserFlow class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlow: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `IdentityUserFlow` described below.
Class description:
Implement the IdentityUserFlow class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlow: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IdentityUserFlow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlow:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityUserFlow:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlow:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Identi... | the_stack_v2_python_sparse | msgraph/generated/models/identity_user_flow.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
027b65a1279a658506f7bfb84d73d3d5821c9715 | [
"model = GCN(n_tasks=n_tasks, graph_conv_layers=graph_conv_layers, activation=activation, residual=residual, batchnorm=batchnorm, dropout=dropout, predictor_hidden_feats=predictor_hidden_feats, predictor_dropout=predictor_dropout, mode=mode, number_atom_features=number_atom_features, n_classes=n_classes)\nif mode =... | <|body_start_0|>
model = GCN(n_tasks=n_tasks, graph_conv_layers=graph_conv_layers, activation=activation, residual=residual, batchnorm=batchnorm, dropout=dropout, predictor_hidden_feats=predictor_hidden_feats, predictor_dropout=predictor_dropout, mode=mode, number_atom_features=number_atom_features, n_classes=n... | Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where the weights are computed by apply... | GCNModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCNModel:
"""Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, whe... | stack_v2_sparse_classes_36k_train_021522 | 14,944 | permissive | [
{
"docstring": "Parameters ---------- n_tasks: int Number of tasks. graph_conv_layers: list of int Width of channels for GCN layers. graph_conv_layers[i] gives the width of channel for the i-th GCN layer. If not specified, the default value will be [64, 64]. activation: callable The activation function to apply... | 2 | stack_v2_sparse_classes_30k_train_009962 | Implement the Python class `GCNModel` described below.
Class description:
Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the... | Implement the Python class `GCNModel` described below.
Class description:
Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class GCNModel:
"""Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GCNModel:
"""Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where the weight... | the_stack_v2_python_sparse | deepchem/models/torch_models/gcn.py | deepchem/deepchem | train | 4,876 |
e09a961e144f4f93d4ae10fcab6dbc4668e97652 | [
"if not self.segments:\n self.warnings.append('sql() save failed with no segments?')\n return\nfor seg in self.segments:\n if not seg.ugcs:\n continue\n _sql_segment(self, txn, seg)",
"channels = self.get_channels()\nfor ugc in segment.ugcs:\n sugc = str(ugc)\n channels.append(f'{self.afo... | <|body_start_0|>
if not self.segments:
self.warnings.append('sql() save failed with no segments?')
return
for seg in self.segments:
if not seg.ugcs:
continue
_sql_segment(self, txn, seg)
<|end_body_0|>
<|body_start_1|>
channels = s... | A Special Weather Statement | SPSProduct | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SPSProduct:
"""A Special Weather Statement"""
def sql(self, txn):
"""Do database save in the case of a polygon"""
<|body_0|>
def _get_channels(self, segment):
"""Returns a list of channels for this SPS."""
<|body_1|>
def get_jabbers(self, uri, _uri2=... | stack_v2_sparse_classes_36k_train_021523 | 5,789 | permissive | [
{
"docstring": "Do database save in the case of a polygon",
"name": "sql",
"signature": "def sql(self, txn)"
},
{
"docstring": "Returns a list of channels for this SPS.",
"name": "_get_channels",
"signature": "def _get_channels(self, segment)"
},
{
"docstring": "return the standa... | 3 | stack_v2_sparse_classes_30k_train_012097 | Implement the Python class `SPSProduct` described below.
Class description:
A Special Weather Statement
Method signatures and docstrings:
- def sql(self, txn): Do database save in the case of a polygon
- def _get_channels(self, segment): Returns a list of channels for this SPS.
- def get_jabbers(self, uri, _uri2=None... | Implement the Python class `SPSProduct` described below.
Class description:
A Special Weather Statement
Method signatures and docstrings:
- def sql(self, txn): Do database save in the case of a polygon
- def _get_channels(self, segment): Returns a list of channels for this SPS.
- def get_jabbers(self, uri, _uri2=None... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class SPSProduct:
"""A Special Weather Statement"""
def sql(self, txn):
"""Do database save in the case of a polygon"""
<|body_0|>
def _get_channels(self, segment):
"""Returns a list of channels for this SPS."""
<|body_1|>
def get_jabbers(self, uri, _uri2=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SPSProduct:
"""A Special Weather Statement"""
def sql(self, txn):
"""Do database save in the case of a polygon"""
if not self.segments:
self.warnings.append('sql() save failed with no segments?')
return
for seg in self.segments:
if not seg.ugcs:... | the_stack_v2_python_sparse | src/pyiem/nws/products/sps.py | akrherz/pyIEM | train | 38 |
083b4d2ef37f45594e501aaebf5bab50273e4ce4 | [
"if root is None:\n return u'{}'\nl = self.serialize(root.left)\nr = self.serialize(root.right)\nreturn u'{}{}:[{},{}]{}'.format('{', root.val, l, r, '}')",
"if data == '{}':\n return None\nval, i, l = (None, 0, len(data))\nfor i in range(1, l):\n if data[i] == ':':\n val = int(data[1:i])\n ... | <|body_start_0|>
if root is None:
return u'{}'
l = self.serialize(root.left)
r = self.serialize(root.right)
return u'{}{}:[{},{}]{}'.format('{', root.val, l, r, '}')
<|end_body_0|>
<|body_start_1|>
if data == '{}':
return None
val, i, l = (None, 0... | 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_36k_train_021524 | 4,963 | 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_train_017353 | 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:... | d2e8b2dca40fc955045eb62e576c776bad8ee5f1 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return u'{}'
l = self.serialize(root.left)
r = self.serialize(root.right)
return u'{}{}:[{},{}]{}'.format('{', root.val, l, r, '}')
... | the_stack_v2_python_sparse | delete-node-in-a-bst/solution.py | childe/leetcode | train | 2 | |
8960662bddd264077443793e3af03a51ebe73105 | [
"user_input = None\nwhile user_input != 2 or user_input != 1:\n print('=== Pokemon Tamagotchi Game===')\n print('1. Hatch a random Pokemon')\n print('2. Quit')\n user_input = int(input('\\nSelect action: '))\n if user_input == 1:\n PokemonController.set_pet(PokemonCreator.hatch_pet())\n ... | <|body_start_0|>
user_input = None
while user_input != 2 or user_input != 1:
print('=== Pokemon Tamagotchi Game===')
print('1. Hatch a random Pokemon')
print('2. Quit')
user_input = int(input('\nSelect action: '))
if user_input == 1:
... | Print game menu for user interaction and input. | GameUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameUI:
"""Print game menu for user interaction and input."""
def display_start_menu():
"""Display start menu (with no Pokemon hatched). :return: None"""
<|body_0|>
def display_food_items():
"""Display list of available Food items. :return: None"""
<|body... | stack_v2_sparse_classes_36k_train_021525 | 4,596 | no_license | [
{
"docstring": "Display start menu (with no Pokemon hatched). :return: None",
"name": "display_start_menu",
"signature": "def display_start_menu()"
},
{
"docstring": "Display list of available Food items. :return: None",
"name": "display_food_items",
"signature": "def display_food_items(... | 5 | stack_v2_sparse_classes_30k_train_006801 | Implement the Python class `GameUI` described below.
Class description:
Print game menu for user interaction and input.
Method signatures and docstrings:
- def display_start_menu(): Display start menu (with no Pokemon hatched). :return: None
- def display_food_items(): Display list of available Food items. :return: N... | Implement the Python class `GameUI` described below.
Class description:
Print game menu for user interaction and input.
Method signatures and docstrings:
- def display_start_menu(): Display start menu (with no Pokemon hatched). :return: None
- def display_food_items(): Display list of available Food items. :return: N... | b7695cc7cf0860aa9c8bf492b1bd06bd88b9af41 | <|skeleton|>
class GameUI:
"""Print game menu for user interaction and input."""
def display_start_menu():
"""Display start menu (with no Pokemon hatched). :return: None"""
<|body_0|>
def display_food_items():
"""Display list of available Food items. :return: None"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameUI:
"""Print game menu for user interaction and input."""
def display_start_menu():
"""Display start menu (with no Pokemon hatched). :return: None"""
user_input = None
while user_input != 2 or user_input != 1:
print('=== Pokemon Tamagotchi Game===')
pri... | the_stack_v2_python_sparse | Assignments/Assignment 1/gameui.py | sakshambhardwaj523/Python-OOP-Projects | train | 0 |
f36b7b45750fae80c24ce5c88fa0f0a32f575951 | [
"m = len(dungeon)\nn = len(dungeon[0])\nF = [[sys.maxint for _ in xrange(n + 1)] for _ in xrange(m + 1)]\nfor i in xrange(m - 1, -1, -1):\n for j in xrange(n - 1, -1, -1):\n if i == m - 1 and j == n - 1:\n F[i][j] = max(1, 1 - dungeon[i][j])\n else:\n path = min(F[i + 1][j], F... | <|body_start_0|>
m = len(dungeon)
n = len(dungeon[0])
F = [[sys.maxint for _ in xrange(n + 1)] for _ in xrange(m + 1)]
for i in xrange(m - 1, -1, -1):
for j in xrange(n - 1, -1, -1):
if i == m - 1 and j == n - 1:
F[i][j] = max(1, 1 - dungeo... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
"""dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with minimum HP required F[i][j] = max(1, path-dungeon[i][j]) # adjust for current cell :type dungeon: ... | stack_v2_sparse_classes_36k_train_021526 | 3,214 | permissive | [
{
"docstring": "dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with minimum HP required F[i][j] = max(1, path-dungeon[i][j]) # adjust for current cell :type dungeon: list[list[int] :rtype: int",
"name": "calculateMinimumHP... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with m... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
"""dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with minimum HP required F[i][j] = max(1, path-dungeon[i][j]) # adjust for current cell :type dungeon: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculateMinimumHP(self, dungeon):
"""dp Let F represent the HP Starting backward DP transition function: path = min(F[i+1][j], F[i][j+1]) # choose the right or down path with minimum HP required F[i][j] = max(1, path-dungeon[i][j]) # adjust for current cell :type dungeon: list[list[int]... | the_stack_v2_python_sparse | 174 Dungeon Game.py | Aminaba123/LeetCode | train | 1 | |
6e2d01a30ec210e96623e2cda8d11110f6e1dc1f | [
"n = len(A)\nMX = [-float('inf') for _ in range(n + 1)]\nMI = [float('inf') for _ in range(n + 1)]\nfor i in range(n):\n MX[i + 1] = max(M[i], A[i])\nfor i in range(n - 1, -1, -1):\n MI[i] = min(MI[i + 1], A[i])\nfor l in range(1, n + 1):\n if MX[l] <= MI[l]:\n return l\nraise",
"MX = [0 for _ in ... | <|body_start_0|>
n = len(A)
MX = [-float('inf') for _ in range(n + 1)]
MI = [float('inf') for _ in range(n + 1)]
for i in range(n):
MX[i + 1] = max(M[i], A[i])
for i in range(n - 1, -1, -1):
MI[i] = min(MI[i + 1], A[i])
for l in range(1, n + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
"""max(left) <= min(right) similar to 2 in terms of keyboard stroke count"""
<|body_0|>
def partitionDisjoint_2(self, A: List[int]) -> int:
"""max(left) <= min(right)"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_021527 | 1,705 | no_license | [
{
"docstring": "max(left) <= min(right) similar to 2 in terms of keyboard stroke count",
"name": "partitionDisjoint",
"signature": "def partitionDisjoint(self, A: List[int]) -> int"
},
{
"docstring": "max(left) <= min(right)",
"name": "partitionDisjoint_2",
"signature": "def partitionDis... | 2 | stack_v2_sparse_classes_30k_train_011314 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partitionDisjoint(self, A: List[int]) -> int: max(left) <= min(right) similar to 2 in terms of keyboard stroke count
- def partitionDisjoint_2(self, A: List[int]) -> int: max... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partitionDisjoint(self, A: List[int]) -> int: max(left) <= min(right) similar to 2 in terms of keyboard stroke count
- def partitionDisjoint_2(self, A: List[int]) -> int: max... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
"""max(left) <= min(right) similar to 2 in terms of keyboard stroke count"""
<|body_0|>
def partitionDisjoint_2(self, A: List[int]) -> int:
"""max(left) <= min(right)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
"""max(left) <= min(right) similar to 2 in terms of keyboard stroke count"""
n = len(A)
MX = [-float('inf') for _ in range(n + 1)]
MI = [float('inf') for _ in range(n + 1)]
for i in range(n):
MX[i +... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/915 Partition Array into Disjoint Intervals.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
e8fddd0613d5575bde1256ad470d7904aec19f56 | [
"self.root = path\nself.appinfo = appinfo\nself.deploy = deploy\nself.custom = custom\nself.entrypoint = entrypoint\nself.server = server\nself.artifact_to_deploy = artifact_to_deploy\nif self.deploy:\n self.notify = log.info\nelse:\n self.notify = log.status.Print",
"cleaner = fingerprinting.Cleaner()\nif ... | <|body_start_0|>
self.root = path
self.appinfo = appinfo
self.deploy = deploy
self.custom = custom
self.entrypoint = entrypoint
self.server = server
self.artifact_to_deploy = artifact_to_deploy
if self.deploy:
self.notify = log.info
els... | JavaConfigurator | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JavaConfigurator:
def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom):
"""Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. dep... | stack_v2_sparse_classes_36k_train_021528 | 7,446 | permissive | [
{
"docstring": "Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. deploy: (bool) True if run in deployment mode. entrypoint: (str) Name of the entrypoint to generate. server: (str) Name of ... | 5 | stack_v2_sparse_classes_30k_train_018393 | Implement the Python class `JavaConfigurator` described below.
Class description:
Implement the JavaConfigurator class.
Method signatures and docstrings:
- def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom): Constructor. Args: path: (str) Root path of the source tree. appinfo: (... | Implement the Python class `JavaConfigurator` described below.
Class description:
Implement the JavaConfigurator class.
Method signatures and docstrings:
- def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom): Constructor. Args: path: (str) Root path of the source tree. appinfo: (... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class JavaConfigurator:
def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom):
"""Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. dep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JavaConfigurator:
def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom):
"""Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. deploy: (bool) Tr... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/appengine/lib/runtimes/java.py | twistedpair/google-cloud-sdk | train | 58 | |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertEncoder, self).__init__()\nself.output_attentions = config.output_attentions\nself.output_hidden_states = config.output_hidden_states\nself.layer = nn.CellList([BertLayer(config) for _ in range(config.num_hidden_layers)])",
"all_hidden_states = ()\nall_attentions = ()\nfor i, layer_module in enumerate(... | <|body_start_0|>
super(BertEncoder, self).__init__()
self.output_attentions = config.output_attentions
self.output_hidden_states = config.output_hidden_states
self.layer = nn.CellList([BertLayer(config) for _ in range(config.num_hidden_layers)])
<|end_body_0|>
<|body_start_1|>
a... | bert encoder | BertEncoder | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertEncoder:
"""bert encoder"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None):
"""construct fun"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_021529 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None)"... | 2 | null | Implement the Python class `BertEncoder` described below.
Class description:
bert encoder
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): construct fun | Implement the Python class `BertEncoder` described below.
Class description:
bert encoder
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None): construct fun
<|skelet... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertEncoder:
"""bert encoder"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None):
"""construct fun"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertEncoder:
"""bert encoder"""
def __init__(self, config):
"""init fun"""
super(BertEncoder, self).__init__()
self.output_attentions = config.output_attentions
self.output_hidden_states = config.output_hidden_states
self.layer = nn.CellList([BertLayer(config) for ... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
0e5e7d507e358cab8c33d98a1957c9316c750f38 | [
"merge_df = graph.merge_by_year(1807)\nself.assertEqual(['Country', 'Region', 'Income'], merge_df.columns.values.tolist())\nself.assertEqual(merge_df.ix[0, 'Country'], 'Algeria')\nself.assertEqual(merge_df.ix[0, 'Region'], 'AFRICA')\nself.assertEqual(merge_df.ix[0, 'Income'], 766.121479698518)",
"self.assertEqual... | <|body_start_0|>
merge_df = graph.merge_by_year(1807)
self.assertEqual(['Country', 'Region', 'Income'], merge_df.columns.values.tolist())
self.assertEqual(merge_df.ix[0, 'Country'], 'Algeria')
self.assertEqual(merge_df.ix[0, 'Region'], 'AFRICA')
self.assertEqual(merge_df.ix[0, 'I... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_merge_by_year(self):
"""Unit test for the merge_by_year function."""
<|body_0|>
def test_year_string_to_int(self):
"""Unit test for the year_string_to_int function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
merge_df = graph.merg... | stack_v2_sparse_classes_36k_train_021530 | 1,235 | no_license | [
{
"docstring": "Unit test for the merge_by_year function.",
"name": "test_merge_by_year",
"signature": "def test_merge_by_year(self)"
},
{
"docstring": "Unit test for the year_string_to_int function.",
"name": "test_year_string_to_int",
"signature": "def test_year_string_to_int(self)"
... | 2 | stack_v2_sparse_classes_30k_train_020689 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_merge_by_year(self): Unit test for the merge_by_year function.
- def test_year_string_to_int(self): Unit test for the year_string_to_int function. | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_merge_by_year(self): Unit test for the merge_by_year function.
- def test_year_string_to_int(self): Unit test for the year_string_to_int function.
<|skeleton|>
class Test:
... | f5bb1e51de4f84ab3dd62d3073aee4f56534afa1 | <|skeleton|>
class Test:
def test_merge_by_year(self):
"""Unit test for the merge_by_year function."""
<|body_0|>
def test_year_string_to_int(self):
"""Unit test for the year_string_to_int function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test_merge_by_year(self):
"""Unit test for the merge_by_year function."""
merge_df = graph.merge_by_year(1807)
self.assertEqual(['Country', 'Region', 'Income'], merge_df.columns.values.tolist())
self.assertEqual(merge_df.ix[0, 'Country'], 'Algeria')
self.asser... | the_stack_v2_python_sparse | lj1035/package/test.py | ds-ga-1007/assignment9 | train | 2 | |
dfff7838dedec8e7d133091486f27547d4492eeb | [
"self.datastore_id = datastore_id\nself.disable_network = disable_network\nself.network_id = network_id\nself.powered_on = powered_on\nself.prefix = prefix\nself.preserve_tags = preserve_tags\nself.resource_id = resource_id\nself.suffix = suffix",
"if dictionary is None:\n return None\ndatastore_id = dictionar... | <|body_start_0|>
self.datastore_id = datastore_id
self.disable_network = disable_network
self.network_id = network_id
self.powered_on = powered_on
self.prefix = prefix
self.preserve_tags = preserve_tags
self.resource_id = resource_id
self.suffix = suffix
<... | Implementation of the 'HypervRestoreParameters' model. Specifies information needed when restoring VMs in HyperV enviroment. This field defines the HyperV specific params for restore tasks of type kRecoverVMs. Attributes: datastore_id (long|int): A datastore entity where the object's files should be restored to. This f... | HypervRestoreParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypervRestoreParameters:
"""Implementation of the 'HypervRestoreParameters' model. Specifies information needed when restoring VMs in HyperV enviroment. This field defines the HyperV specific params for restore tasks of type kRecoverVMs. Attributes: datastore_id (long|int): A datastore entity whe... | stack_v2_sparse_classes_36k_train_021531 | 5,678 | permissive | [
{
"docstring": "Constructor for the HypervRestoreParameters class",
"name": "__init__",
"signature": "def __init__(self, datastore_id=None, disable_network=None, network_id=None, powered_on=None, prefix=None, preserve_tags=None, resource_id=None, suffix=None)"
},
{
"docstring": "Creates an insta... | 2 | null | Implement the Python class `HypervRestoreParameters` described below.
Class description:
Implementation of the 'HypervRestoreParameters' model. Specifies information needed when restoring VMs in HyperV enviroment. This field defines the HyperV specific params for restore tasks of type kRecoverVMs. Attributes: datastor... | Implement the Python class `HypervRestoreParameters` described below.
Class description:
Implementation of the 'HypervRestoreParameters' model. Specifies information needed when restoring VMs in HyperV enviroment. This field defines the HyperV specific params for restore tasks of type kRecoverVMs. Attributes: datastor... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class HypervRestoreParameters:
"""Implementation of the 'HypervRestoreParameters' model. Specifies information needed when restoring VMs in HyperV enviroment. This field defines the HyperV specific params for restore tasks of type kRecoverVMs. Attributes: datastore_id (long|int): A datastore entity whe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HypervRestoreParameters:
"""Implementation of the 'HypervRestoreParameters' model. Specifies information needed when restoring VMs in HyperV enviroment. This field defines the HyperV specific params for restore tasks of type kRecoverVMs. Attributes: datastore_id (long|int): A datastore entity where the object... | the_stack_v2_python_sparse | cohesity_management_sdk/models/hyperv_restore_parameters.py | cohesity/management-sdk-python | train | 24 |
4199eda2ca0aa78dc913b9ede078bd66d3296303 | [
"if not root:\n return 0\np_list, num = ([root], 1)\nwhile True:\n c_list = list()\n for i in p_list:\n if not i.left and (not i.right):\n return num\n if i.left:\n c_list.append(i.left)\n if i.right:\n c_list.append(i.right)\n num += 1\n p_list =... | <|body_start_0|>
if not root:
return 0
p_list, num = ([root], 1)
while True:
c_list = list()
for i in p_list:
if not i.left and (not i.right):
return num
if i.left:
c_list.append(i.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""BFS"""
<|body_0|>
def minDepthDfs(self, root: TreeNode) -> int:
"""DFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
p_list, num = ([root], 1)
... | stack_v2_sparse_classes_36k_train_021532 | 3,231 | no_license | [
{
"docstring": "BFS",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "DFS",
"name": "minDepthDfs",
"signature": "def minDepthDfs(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_018720 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: BFS
- def minDepthDfs(self, root: TreeNode) -> int: DFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: BFS
- def minDepthDfs(self, root: TreeNode) -> int: DFS
<|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
... | d265eb981a7586d46d0ced3accc2ea186dc7691c | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""BFS"""
<|body_0|>
def minDepthDfs(self, root: TreeNode) -> int:
"""DFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""BFS"""
if not root:
return 0
p_list, num = ([root], 1)
while True:
c_list = list()
for i in p_list:
if not i.left and (not i.right):
return num
... | the_stack_v2_python_sparse | pythonCode/No101-150/no111.py | odinfor/leetcode | train | 0 | |
76d61f95b2f041bdddabff067593ee2c7547499a | [
"from torch.nn import LeakyReLU\nfrom torch.nn import Conv2d\nsuper().__init__()\nself.batch_discriminator = MinibatchStdDev()\nself.conv_1 = Conv2d(in_channels + 1, in_channels, (3, 3), padding=1, bias=True)\nself.conv_2 = Conv2d(in_channels, in_channels, (4, 4), bias=True)\nself.conv_3 = Conv2d(in_channels, 1, (1... | <|body_start_0|>
from torch.nn import LeakyReLU
from torch.nn import Conv2d
super().__init__()
self.batch_discriminator = MinibatchStdDev()
self.conv_1 = Conv2d(in_channels + 1, in_channels, (3, 3), padding=1, bias=True)
self.conv_2 = Conv2d(in_channels, in_channels, (4, ... | Final block for the Discriminator | DisFinalBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisFinalBlock:
"""Final block for the Discriminator"""
def __init__(self, in_channels):
"""constructor of the class :param in_channels: number of input channels"""
<|body_0|>
def forward(self, x):
"""forward pass of the FinalBlock :param x: input :return: y => ou... | stack_v2_sparse_classes_36k_train_021533 | 14,685 | no_license | [
{
"docstring": "constructor of the class :param in_channels: number of input channels",
"name": "__init__",
"signature": "def __init__(self, in_channels)"
},
{
"docstring": "forward pass of the FinalBlock :param x: input :return: y => output",
"name": "forward",
"signature": "def forward... | 2 | stack_v2_sparse_classes_30k_test_000259 | Implement the Python class `DisFinalBlock` described below.
Class description:
Final block for the Discriminator
Method signatures and docstrings:
- def __init__(self, in_channels): constructor of the class :param in_channels: number of input channels
- def forward(self, x): forward pass of the FinalBlock :param x: i... | Implement the Python class `DisFinalBlock` described below.
Class description:
Final block for the Discriminator
Method signatures and docstrings:
- def __init__(self, in_channels): constructor of the class :param in_channels: number of input channels
- def forward(self, x): forward pass of the FinalBlock :param x: i... | 428abe1fefe5ea4ef00290155e7e59657bc83444 | <|skeleton|>
class DisFinalBlock:
"""Final block for the Discriminator"""
def __init__(self, in_channels):
"""constructor of the class :param in_channels: number of input channels"""
<|body_0|>
def forward(self, x):
"""forward pass of the FinalBlock :param x: input :return: y => ou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DisFinalBlock:
"""Final block for the Discriminator"""
def __init__(self, in_channels):
"""constructor of the class :param in_channels: number of input channels"""
from torch.nn import LeakyReLU
from torch.nn import Conv2d
super().__init__()
self.batch_discriminato... | the_stack_v2_python_sparse | src/msg_stylegan2.py | blakecheng/lafin | train | 0 |
57907e00fe7c0f0640b6dc179f5328c91cb93f63 | [
"if SHA1_RE.search(activation_key.lower()):\n try:\n profile = self.get(activation_key=activation_key)\n except self.model.DoesNotExist:\n return False\n if not profile.activation_key_expired():\n user = profile.user\n user.is_active = True\n user.save()\n profile.... | <|body_start_0|>
if SHA1_RE.search(activation_key.lower()):
try:
profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not profile.activation_key_expired():
user = profile.user
... | Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. | RegistrationManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
"""Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts."""
def activate_user(self, acti... | stack_v2_sparse_classes_36k_train_021534 | 6,749 | permissive | [
{
"docstring": "Validate an activation key and activate the corresponding user if valid. Returns the user account on success, ``False`` on failure.",
"name": "activate_user",
"signature": "def activate_user(self, activation_key)"
},
{
"docstring": "Query for all profiles which are expired and co... | 5 | stack_v2_sparse_classes_30k_test_000568 | Implement the Python class `RegistrationManager` described below.
Class description:
Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive account... | Implement the Python class `RegistrationManager` described below.
Class description:
Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive account... | 4d8abe7bafefae06a0e462e6a47631c2f8a1d361 | <|skeleton|>
class RegistrationManager:
"""Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts."""
def activate_user(self, acti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationManager:
"""Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts."""
def activate_user(self, activation_key):
... | the_stack_v2_python_sparse | virtual/lib/python3.6/site-packages/registration/models.py | virginiah894/Instagram-clone | train | 3 |
22da4b02a550dfe725e5d5dfe30029c09932cfd4 | [
"self.data = dat\nself.cov = cov\nself.z = z\nself.prior = prior\nzc = z.cpu().numpy()\nzc = np.insert(zc, 0, 0)\nself.dz = torch.tensor(zc[1:] - zc[:-1], device=ddevice)\nself.LikeFunc = Likelihood(dat, cov)\nself.zdim = z.shape[0]",
"mod = modelo(theta, self.z, self.dz, self.zdim)\nself.u = -self.LikeFunc.get_l... | <|body_start_0|>
self.data = dat
self.cov = cov
self.z = z
self.prior = prior
zc = z.cpu().numpy()
zc = np.insert(zc, 0, 0)
self.dz = torch.tensor(zc[1:] - zc[:-1], device=ddevice)
self.LikeFunc = Likelihood(dat, cov)
self.zdim = z.shape[0]
<|end_b... | Potential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
<|body_0|>
def value(self, theta):
"""Returns pote... | stack_v2_sparse_classes_36k_train_021535 | 13,126 | no_license | [
{
"docstring": "Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior.",
"name": "__init__",
"signature": "def __init__(self, dat, cov, z, prior)"
},
{
"docstring": "Returns potential log val... | 3 | stack_v2_sparse_classes_30k_train_008378 | Implement the Python class `Potential` described below.
Class description:
Implement the Potential class.
Method signatures and docstrings:
- def __init__(self, dat, cov, z, prior): Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift... | Implement the Python class `Potential` described below.
Class description:
Implement the Potential class.
Method signatures and docstrings:
- def __init__(self, dat, cov, z, prior): Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift... | 8789f692d81c5435a5888b6b151ccf6187d5a064 | <|skeleton|>
class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
<|body_0|>
def value(self, theta):
"""Returns pote... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
self.data = dat
self.cov = cov
self.z = z
self.prior ... | the_stack_v2_python_sparse | p18/mcmc.py | fluowhy/MCMC-methods | train | 1 | |
16958f9766fa7c89e9f20f8567ec030538d2398c | [
"self.chn = 0\nself.chn_items = []\nself.fs = -1\nself.fs_bands = {'delta': (1, 4), 'theta': (4, 8), 'alpha': (8, 14), 'beta': (14, 30), 'gamma': (30, 45)}",
"lp = self.fs_bands[band][0]\nhp = self.fs_bands[band][1]\nif l == 0 and h != 0:\n if self.fs_bands[band][0] < h < hp:\n hp = h\n elif h < hp:\... | <|body_start_0|>
self.chn = 0
self.chn_items = []
self.fs = -1
self.fs_bands = {'delta': (1, 4), 'theta': (4, 8), 'alpha': (8, 14), 'beta': (14, 30), 'gamma': (30, 45)}
<|end_body_0|>
<|body_start_1|>
lp = self.fs_bands[band][0]
hp = self.fs_bands[band][1]
if l =... | Class to hold relevant information for computing statistics | SignalStatsInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalStatsInfo:
"""Class to hold relevant information for computing statistics"""
def __init__(self):
"""Constructor. fs_bands - holds dict of bands, can be expanded"""
<|body_0|>
def _get_power_for_band(self, sig, s, f, band, l, h):
"""Returns the power in the ... | stack_v2_sparse_classes_36k_train_021536 | 2,715 | no_license | [
{
"docstring": "Constructor. fs_bands - holds dict of bands, can be expanded",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns the power in the given fs band. Args: sig: the signal to use s: where to start in samples f: where to end in samples band: which type of... | 3 | null | Implement the Python class `SignalStatsInfo` described below.
Class description:
Class to hold relevant information for computing statistics
Method signatures and docstrings:
- def __init__(self): Constructor. fs_bands - holds dict of bands, can be expanded
- def _get_power_for_band(self, sig, s, f, band, l, h): Retu... | Implement the Python class `SignalStatsInfo` described below.
Class description:
Class to hold relevant information for computing statistics
Method signatures and docstrings:
- def __init__(self): Constructor. fs_bands - holds dict of bands, can be expanded
- def _get_power_for_band(self, sig, s, f, band, l, h): Retu... | 099920716fdab891592ccc7f324445f088827298 | <|skeleton|>
class SignalStatsInfo:
"""Class to hold relevant information for computing statistics"""
def __init__(self):
"""Constructor. fs_bands - holds dict of bands, can be expanded"""
<|body_0|>
def _get_power_for_band(self, sig, s, f, band, l, h):
"""Returns the power in the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalStatsInfo:
"""Class to hold relevant information for computing statistics"""
def __init__(self):
"""Constructor. fs_bands - holds dict of bands, can be expanded"""
self.chn = 0
self.chn_items = []
self.fs = -1
self.fs_bands = {'delta': (1, 4), 'theta': (4, 8)... | the_stack_v2_python_sparse | visualization/signalStats_info.py | jcraley/jhu-eeg | train | 2 |
0cb010fec95294db88560c917b9bb2ec7568225b | [
"form.instance.noodle = Noodle.objects.get(pk=self.kwargs['id'])\nform.instance.type = 'ND'\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['name'] = Noodle.objects.get(pk=self.kwargs['id']).name\nreturn context"
] | <|body_start_0|>
form.instance.noodle = Noodle.objects.get(pk=self.kwargs['id'])
form.instance.type = 'ND'
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['name'] = Noodle.objects.get(pk=self.kwargs['id']).name... | Class based view for reporting noodles | NoodleReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoodleReportForm:
"""Class based view for reporting noodles"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_021537 | 10,733 | permissive | [
{
"docstring": "Ensures hidden form values are filled",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Passes item name to template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005570 | Implement the Python class `NoodleReportForm` described below.
Class description:
Class based view for reporting noodles
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template | Implement the Python class `NoodleReportForm` described below.
Class description:
Class based view for reporting noodles
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template
<|skeleton|>
class Noodle... | 6bf8e75a1f279ac584daa4ee19927ffccaa67551 | <|skeleton|>
class NoodleReportForm:
"""Class based view for reporting noodles"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoodleReportForm:
"""Class based view for reporting noodles"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
form.instance.noodle = Noodle.objects.get(pk=self.kwargs['id'])
form.instance.type = 'ND'
return super().form_valid(form)
def get_con... | the_stack_v2_python_sparse | rameniaapp/views/report.py | awlane/ramenia | train | 0 |
e1f1adea0a74380a433b20370dd4ef4fb09bf4b9 | [
"self.pathCKPT = PATH_TO_CKPT\nself.pathLabels = PATH_TO_LABELS\nself.numClasses = 3",
"with tf.device('/device:GPU:0'):\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(self.pathCKPT, 'rb') as fid:\n serialized... | <|body_start_0|>
self.pathCKPT = PATH_TO_CKPT
self.pathLabels = PATH_TO_LABELS
self.numClasses = 3
<|end_body_0|>
<|body_start_1|>
with tf.device('/device:GPU:0'):
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.G... | The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lights :ivar numClasses: number of classes used :iv... | TrafficLightDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lig... | stack_v2_sparse_classes_36k_train_021538 | 3,854 | no_license | [
{
"docstring": "Sets the paths to any necessary files for the neural network to function",
"name": "__init__",
"signature": "def __init__(self, PATH_TO_CKPT='tf/frozen_inference_graph.pb', PATH_TO_LABELS='tf/traffic_light.pbtxt')"
},
{
"docstring": "Performs all of the operations to set up the n... | 3 | stack_v2_sparse_classes_30k_train_017440 | Implement the Python class `TrafficLightDetector` described below.
Class description:
The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLab... | Implement the Python class `TrafficLightDetector` described below.
Class description:
The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLab... | 576b799fd6f85768cc4e0ad44b0a787fb5c80b29 | <|skeleton|>
class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrafficLightDetector:
"""The TrafficLightDetector class contains all of the required set up and detection functions required to determine if a traffic light is present and if it is green or not. :ivar pathCKPT: path to the frozen neural network :ivar pathLabels: path to the labels for traffic lights :ivar num... | the_stack_v2_python_sparse | MV/trafficLightDetector.py | bohongbobo/draft-GUI | train | 0 |
02750f0b556f67633c6ec837313a57df7cfd37a7 | [
"self.node_1 = BinaryTree(1)\nself.node_2 = BinaryTree(2)\nself.node_3 = BinaryTree(3)\nself.node_4 = BinaryTree(4)\nself.node_5 = BinaryTree(5)\nself.node_6 = BinaryTree(6)\nself.node_7 = BinaryTree(7)\nself.node_8 = BinaryTree(8)\nself.node_1.left = self.node_2\nself.node_1.right = self.node_3\nself.node_2.left =... | <|body_start_0|>
self.node_1 = BinaryTree(1)
self.node_2 = BinaryTree(2)
self.node_3 = BinaryTree(3)
self.node_4 = BinaryTree(4)
self.node_5 = BinaryTree(5)
self.node_6 = BinaryTree(6)
self.node_7 = BinaryTree(7)
self.node_8 = BinaryTree(8)
self.no... | Class with unittests for HeightBalancedBinaryTree.py | test_HeightBalancedBinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_HeightBalancedBinaryTree:
"""Class with unittests for HeightBalancedBinaryTree.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly. Input cannot be empty string."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_021539 | 1,438 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if method works properly. Input cannot be empty string.",
"name": "test_user_input",
"signature": "def test_user_input(self)"
}
] | 2 | null | Implement the Python class `test_HeightBalancedBinaryTree` described below.
Class description:
Class with unittests for HeightBalancedBinaryTree.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. Input cannot be empty string. | Implement the Python class `test_HeightBalancedBinaryTree` described below.
Class description:
Class with unittests for HeightBalancedBinaryTree.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. Input cannot be empty string.
<|skeleto... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_HeightBalancedBinaryTree:
"""Class with unittests for HeightBalancedBinaryTree.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly. Input cannot be empty string."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_HeightBalancedBinaryTree:
"""Class with unittests for HeightBalancedBinaryTree.py"""
def setUp(self):
"""Sets up input."""
self.node_1 = BinaryTree(1)
self.node_2 = BinaryTree(2)
self.node_3 = BinaryTree(3)
self.node_4 = BinaryTree(4)
self.node_5 = Bin... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/HeightBalancedBinaryTree/test_HeightBalancedBinaryTree.py | JakubKazimierski/PythonPortfolio | train | 9 |
6963248aec84bdc4b2a8788171a15d5e244bc693 | [
"headers = {'Authorization': self.Authorization, 'agentId': '037e6d16010f11ea907c00163e129bed', 'grp': 'carsir_app', 'Content-Type': 'application/json; charset=utf-8'}\nrequest_json = {'purchasePrice': purchasePrice, 'usableAmount': usableAmount, 'carInfoId': carInfoId}\nr = requests.post(headers=headers, url=self.... | <|body_start_0|>
headers = {'Authorization': self.Authorization, 'agentId': '037e6d16010f11ea907c00163e129bed', 'grp': 'carsir_app', 'Content-Type': 'application/json; charset=utf-8'}
request_json = {'purchasePrice': purchasePrice, 'usableAmount': usableAmount, 'carInfoId': carInfoId}
r = reques... | 测试配资额上限 | TestReservePrice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestReservePrice:
"""测试配资额上限"""
def test_public_car(self, purchasePrice, usableAmount, carInfoId, carPriceOver):
""":param purchasePrice: :param usableAmount: :param carInfoId: :param carPriceOver: :return:"""
<|body_0|>
def test_person_car(self, purchasePrice, usableAmo... | stack_v2_sparse_classes_36k_train_021540 | 3,788 | no_license | [
{
"docstring": ":param purchasePrice: :param usableAmount: :param carInfoId: :param carPriceOver: :return:",
"name": "test_public_car",
"signature": "def test_public_car(self, purchasePrice, usableAmount, carInfoId, carPriceOver)"
},
{
"docstring": ":param purchasePrice: :param usableAmount: :pa... | 2 | null | Implement the Python class `TestReservePrice` described below.
Class description:
测试配资额上限
Method signatures and docstrings:
- def test_public_car(self, purchasePrice, usableAmount, carInfoId, carPriceOver): :param purchasePrice: :param usableAmount: :param carInfoId: :param carPriceOver: :return:
- def test_person_ca... | Implement the Python class `TestReservePrice` described below.
Class description:
测试配资额上限
Method signatures and docstrings:
- def test_public_car(self, purchasePrice, usableAmount, carInfoId, carPriceOver): :param purchasePrice: :param usableAmount: :param carInfoId: :param carPriceOver: :return:
- def test_person_ca... | df9d96009cbdf84176efbf4b02f43cb1d5208524 | <|skeleton|>
class TestReservePrice:
"""测试配资额上限"""
def test_public_car(self, purchasePrice, usableAmount, carInfoId, carPriceOver):
""":param purchasePrice: :param usableAmount: :param carInfoId: :param carPriceOver: :return:"""
<|body_0|>
def test_person_car(self, purchasePrice, usableAmo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestReservePrice:
"""测试配资额上限"""
def test_public_car(self, purchasePrice, usableAmount, carInfoId, carPriceOver):
""":param purchasePrice: :param usableAmount: :param carInfoId: :param carPriceOver: :return:"""
headers = {'Authorization': self.Authorization, 'agentId': '037e6d16010f11ea907... | the_stack_v2_python_sparse | carsir_test/easy_shou/test_price_calculation.py | 606keng/weeds_study | train | 1 |
e41c2460f7feed261955fe031e00d484d5c107f1 | [
"self.model = ThreeDEPN()\nself.model.load_state_dict(torch.load(ckpt, map_location='cpu'))\nself.model.eval()\nself.truncation_distance = 3",
"input_sdf = np.clip(input_sdf, a_min=-self.truncation_distance, a_max=self.truncation_distance)\ntarget_df = np.clip(target_df, a_min=0, a_max=self.truncation_distance)\n... | <|body_start_0|>
self.model = ThreeDEPN()
self.model.load_state_dict(torch.load(ckpt, map_location='cpu'))
self.model.eval()
self.truncation_distance = 3
<|end_body_0|>
<|body_start_1|>
input_sdf = np.clip(input_sdf, a_min=-self.truncation_distance, a_max=self.truncation_distanc... | InferenceHandler3DEPN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InferenceHandler3DEPN:
def __init__(self, ckpt):
""":param ckpt: checkpoint path to weights of the trained network"""
<|body_0|>
def infer_single(self, input_sdf, target_df):
"""Reconstruct a full shape given a partial observation :param input_sdf: Input grid with pa... | stack_v2_sparse_classes_36k_train_021541 | 1,860 | no_license | [
{
"docstring": ":param ckpt: checkpoint path to weights of the trained network",
"name": "__init__",
"signature": "def __init__(self, ckpt)"
},
{
"docstring": "Reconstruct a full shape given a partial observation :param input_sdf: Input grid with partial SDF of shape 32x32x32 :param target_df: T... | 2 | stack_v2_sparse_classes_30k_train_015137 | Implement the Python class `InferenceHandler3DEPN` described below.
Class description:
Implement the InferenceHandler3DEPN class.
Method signatures and docstrings:
- def __init__(self, ckpt): :param ckpt: checkpoint path to weights of the trained network
- def infer_single(self, input_sdf, target_df): Reconstruct a f... | Implement the Python class `InferenceHandler3DEPN` described below.
Class description:
Implement the InferenceHandler3DEPN class.
Method signatures and docstrings:
- def __init__(self, ckpt): :param ckpt: checkpoint path to weights of the trained network
- def infer_single(self, input_sdf, target_df): Reconstruct a f... | a98d61403017317eb2b5da9760f78a19c76622e4 | <|skeleton|>
class InferenceHandler3DEPN:
def __init__(self, ckpt):
""":param ckpt: checkpoint path to weights of the trained network"""
<|body_0|>
def infer_single(self, input_sdf, target_df):
"""Reconstruct a full shape given a partial observation :param input_sdf: Input grid with pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InferenceHandler3DEPN:
def __init__(self, ckpt):
""":param ckpt: checkpoint path to weights of the trained network"""
self.model = ThreeDEPN()
self.model.load_state_dict(torch.load(ckpt, map_location='cpu'))
self.model.eval()
self.truncation_distance = 3
def infer_... | the_stack_v2_python_sparse | E3/exercise_3/inference/infer_3depn.py | nazmicancalik/ml3d | train | 7 | |
0960020f36e83c50446ef6ea1006b6c5531c6f8d | [
"if legacy_pyroot:\n l = ROOT.Long(pylong(42))\n self.assertEqual(l, pylong(42))\n self.assertEqual(l / 7, pylong(6))\n self.assertEqual(l * pylong(1), l)\n import math\n d = ROOT.Double(math.pi)\n self.assertEqual(d, math.pi)\n self.assertEqual(d * math.pi, math.pi * math.pi)",
"SetLongTh... | <|body_start_0|>
if legacy_pyroot:
l = ROOT.Long(pylong(42))
self.assertEqual(l, pylong(42))
self.assertEqual(l / 7, pylong(6))
self.assertEqual(l * pylong(1), l)
import math
d = ROOT.Double(math.pi)
self.assertEqual(d, math.pi)... | Cpp03PassByNonConstRef | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cpp03PassByNonConstRef:
def test1TestPlaceHolders(self):
"""Test usage of Long/Double place holders"""
<|body_0|>
def test2PassBuiltinsByNonConstRef(self):
"""Test parameter passing of builtins through non-const reference"""
<|body_1|>
def test3PassBuilt... | stack_v2_sparse_classes_36k_train_021542 | 30,462 | no_license | [
{
"docstring": "Test usage of Long/Double place holders",
"name": "test1TestPlaceHolders",
"signature": "def test1TestPlaceHolders(self)"
},
{
"docstring": "Test parameter passing of builtins through non-const reference",
"name": "test2PassBuiltinsByNonConstRef",
"signature": "def test2P... | 3 | stack_v2_sparse_classes_30k_train_004973 | Implement the Python class `Cpp03PassByNonConstRef` described below.
Class description:
Implement the Cpp03PassByNonConstRef class.
Method signatures and docstrings:
- def test1TestPlaceHolders(self): Test usage of Long/Double place holders
- def test2PassBuiltinsByNonConstRef(self): Test parameter passing of builtin... | Implement the Python class `Cpp03PassByNonConstRef` described below.
Class description:
Implement the Cpp03PassByNonConstRef class.
Method signatures and docstrings:
- def test1TestPlaceHolders(self): Test usage of Long/Double place holders
- def test2PassBuiltinsByNonConstRef(self): Test parameter passing of builtin... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class Cpp03PassByNonConstRef:
def test1TestPlaceHolders(self):
"""Test usage of Long/Double place holders"""
<|body_0|>
def test2PassBuiltinsByNonConstRef(self):
"""Test parameter passing of builtins through non-const reference"""
<|body_1|>
def test3PassBuilt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cpp03PassByNonConstRef:
def test1TestPlaceHolders(self):
"""Test usage of Long/Double place holders"""
if legacy_pyroot:
l = ROOT.Long(pylong(42))
self.assertEqual(l, pylong(42))
self.assertEqual(l / 7, pylong(6))
self.assertEqual(l * pylong(1), ... | the_stack_v2_python_sparse | python/cpp/PyROOT_advancedtests.py | root-project/roottest | train | 41 | |
1b8b79444ecbd7eab4216982a7028412f22af6c5 | [
"value = encode_value(value, flags)\nresponse = await self._write(key, value, flags=flags)\nreturn response.body is True",
"value = encode_value(value, flags)\nindex = extract_attr(index, keys=['ModifyIndex', 'Index'])\nresponse = await self._write(key, value, flags=flags, cas=index)\nreturn response.body is True... | <|body_start_0|>
value = encode_value(value, flags)
response = await self._write(key, value, flags=flags)
return response.body is True
<|end_body_0|>
<|body_start_1|>
value = encode_value(value, flags)
index = extract_attr(index, keys=['ModifyIndex', 'Index'])
response =... | WriteMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteMixin:
async def set(self, key, value, *, flags=None):
"""Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags flags (int): Flags to set with value Returns: bool: ``True`` on success"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_021543 | 19,443 | permissive | [
{
"docstring": "Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags flags (int): Flags to set with value Returns: bool: ``True`` on success",
"name": "set",
"signature": "async def set(self, key, value, *, flags=None)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_014561 | Implement the Python class `WriteMixin` described below.
Class description:
Implement the WriteMixin class.
Method signatures and docstrings:
- async def set(self, key, value, *, flags=None): Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags ... | Implement the Python class `WriteMixin` described below.
Class description:
Implement the WriteMixin class.
Method signatures and docstrings:
- async def set(self, key, value, *, flags=None): Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags ... | 02f7a529d7dc2e49bed942111067aa5faf320e90 | <|skeleton|>
class WriteMixin:
async def set(self, key, value, *, flags=None):
"""Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags flags (int): Flags to set with value Returns: bool: ``True`` on success"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WriteMixin:
async def set(self, key, value, *, flags=None):
"""Sets the key to the given value. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags flags (int): Flags to set with value Returns: bool: ``True`` on success"""
value = encode_value(value, fl... | the_stack_v2_python_sparse | aioconsul/client/kv_endpoint.py | johnnoone/aioconsul | train | 8 | |
000498a1823629beb68bbcae66e7749f8557b707 | [
"if 'intf_type' not in kwargs or not kwargs['intf_type']:\n raise ValueError(\"'intf_type' not present in kwargs\")\nintf_type = kwargs['intf_type']\naddress_type = kwargs['address_type']\nif address_type == 'mac' and intf_type in ['vlan', 'ethernet', 'port_channel']:\n return intf_type.replace('_', '-')\nif ... | <|body_start_0|>
if 'intf_type' not in kwargs or not kwargs['intf_type']:
raise ValueError("'intf_type' not present in kwargs")
intf_type = kwargs['intf_type']
address_type = kwargs['address_type']
if address_type == 'mac' and intf_type in ['vlan', 'ethernet', 'port_channel']... | The AclParamParser class parses kwargs which are common for all the three ACL Types. Attributes: None | AclParamParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AclParamParser:
"""The AclParamParser class parses kwargs which are common for all the three ACL Types. Attributes: None"""
def parse_intf_type(self, **kwargs):
"""parse supported intf_type param Args: kwargs contains: intf_type(string): Allowed intf_type are, - port_channel - ve - l... | stack_v2_sparse_classes_36k_train_021544 | 4,856 | permissive | [
{
"docstring": "parse supported intf_type param Args: kwargs contains: intf_type(string): Allowed intf_type are, - port_channel - ve - loopback - ethernet - management - vlan Returns: Return parsed string on success Raise: Raise ValueError exception Examples:",
"name": "parse_intf_type",
"signature": "d... | 3 | null | Implement the Python class `AclParamParser` described below.
Class description:
The AclParamParser class parses kwargs which are common for all the three ACL Types. Attributes: None
Method signatures and docstrings:
- def parse_intf_type(self, **kwargs): parse supported intf_type param Args: kwargs contains: intf_typ... | Implement the Python class `AclParamParser` described below.
Class description:
The AclParamParser class parses kwargs which are common for all the three ACL Types. Attributes: None
Method signatures and docstrings:
- def parse_intf_type(self, **kwargs): parse supported intf_type param Args: kwargs contains: intf_typ... | 54e872bcbe77f2ae840d845dadb7c5b9c12482ed | <|skeleton|>
class AclParamParser:
"""The AclParamParser class parses kwargs which are common for all the three ACL Types. Attributes: None"""
def parse_intf_type(self, **kwargs):
"""parse supported intf_type param Args: kwargs contains: intf_type(string): Allowed intf_type are, - port_channel - ve - l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AclParamParser:
"""The AclParamParser class parses kwargs which are common for all the three ACL Types. Attributes: None"""
def parse_intf_type(self, **kwargs):
"""parse supported intf_type param Args: kwargs contains: intf_type(string): Allowed intf_type are, - port_channel - ve - loopback - eth... | the_stack_v2_python_sparse | pyswitch/raw/slxos/ver_17s/aclparam_parser.py | ScottJWalter/PySwitchLib | train | 0 |
ec0d46d892c9793f75478aabad6e7faac6fc278d | [
"super().__init__()\nself.p = p\nif self.p == 0 or self.p == 1:\n self.classifier['stochastic'] = False",
"if len(self.history) == 0:\n return C\nif opponent.history[-1] == D:\n return D\nif self.p == 0:\n return C\nif self.p == 1:\n return D\nchoice = self._random.random_choice(1 - self.p)\nreturn... | <|body_start_0|>
super().__init__()
self.p = p
if self.p == 0 or self.p == 1:
self.classifier['stochastic'] = False
<|end_body_0|>
<|body_start_1|>
if len(self.history) == 0:
return C
if opponent.history[-1] == D:
return D
if self.p ==... | Like tit-for-tat, but it occasionally defects with a small probability. Names: - Naive Prober: [Li2011]_ | NaiveProber | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveProber:
"""Like tit-for-tat, but it occasionally defects with a small probability. Names: - Naive Prober: [Li2011]_"""
def __init__(self, p: float=0.1) -> None:
"""Parameters ---------- p, float The probability to defect randomly"""
<|body_0|>
def strategy(self, opp... | stack_v2_sparse_classes_36k_train_021545 | 11,183 | permissive | [
{
"docstring": "Parameters ---------- p, float The probability to defect randomly",
"name": "__init__",
"signature": "def __init__(self, p: float=0.1) -> None"
},
{
"docstring": "Actual strategy definition that determines player's action.",
"name": "strategy",
"signature": "def strategy(... | 2 | null | Implement the Python class `NaiveProber` described below.
Class description:
Like tit-for-tat, but it occasionally defects with a small probability. Names: - Naive Prober: [Li2011]_
Method signatures and docstrings:
- def __init__(self, p: float=0.1) -> None: Parameters ---------- p, float The probability to defect r... | Implement the Python class `NaiveProber` described below.
Class description:
Like tit-for-tat, but it occasionally defects with a small probability. Names: - Naive Prober: [Li2011]_
Method signatures and docstrings:
- def __init__(self, p: float=0.1) -> None: Parameters ---------- p, float The probability to defect r... | fa748627cd4f0333bb2dbfcb1454372a78a9098a | <|skeleton|>
class NaiveProber:
"""Like tit-for-tat, but it occasionally defects with a small probability. Names: - Naive Prober: [Li2011]_"""
def __init__(self, p: float=0.1) -> None:
"""Parameters ---------- p, float The probability to defect randomly"""
<|body_0|>
def strategy(self, opp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NaiveProber:
"""Like tit-for-tat, but it occasionally defects with a small probability. Names: - Naive Prober: [Li2011]_"""
def __init__(self, p: float=0.1) -> None:
"""Parameters ---------- p, float The probability to defect randomly"""
super().__init__()
self.p = p
if se... | the_stack_v2_python_sparse | axelrod/strategies/prober.py | Axelrod-Python/Axelrod | train | 673 |
31195e5d926d58617a266730c21bab9c64ddde6f | [
"if user_id is None or not isinstance(user_id, str):\n return None\nid = str(uuid.uuid4())\nself.user_id_by_session_id[id] = user_id\nreturn id",
"if session_id is None or not isinstance(session_id, str):\n return None\nreturn SessionAuth.user_id_by_session_id.get(session_id)",
"cookie = self.session_cook... | <|body_start_0|>
if user_id is None or not isinstance(user_id, str):
return None
id = str(uuid.uuid4())
self.user_id_by_session_id[id] = user_id
return id
<|end_body_0|>
<|body_start_1|>
if session_id is None or not isinstance(session_id, str):
return Non... | Empty class | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""Empty class"""
def create_session(self, user_id: str=None) -> str:
"""creates a Session ID for an user_id"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""returns a User ID based on a Session ID"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_021546 | 1,565 | no_license | [
{
"docstring": "creates a Session ID for an user_id",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "returns a User ID based on a Session ID",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, ... | 4 | stack_v2_sparse_classes_30k_train_011160 | Implement the Python class `SessionAuth` described below.
Class description:
Empty class
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: creates a Session ID for an user_id
- def user_id_for_session_id(self, session_id: str=None) -> str: returns a User ID based on a Session ID
... | Implement the Python class `SessionAuth` described below.
Class description:
Empty class
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: creates a Session ID for an user_id
- def user_id_for_session_id(self, session_id: str=None) -> str: returns a User ID based on a Session ID
... | a09732a4f270d3dbeaf6ff1eb46c7bc0b71eaf4a | <|skeleton|>
class SessionAuth:
"""Empty class"""
def create_session(self, user_id: str=None) -> str:
"""creates a Session ID for an user_id"""
<|body_0|>
def user_id_for_session_id(self, session_id: str=None) -> str:
"""returns a User ID based on a Session ID"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionAuth:
"""Empty class"""
def create_session(self, user_id: str=None) -> str:
"""creates a Session ID for an user_id"""
if user_id is None or not isinstance(user_id, str):
return None
id = str(uuid.uuid4())
self.user_id_by_session_id[id] = user_id
... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | I7RANK/holbertonschool-web_back_end | train | 0 |
5c8b2c4019f2be6a2b9dcd3a3a5553f25d0a30ad | [
"if self.method == 'sample':\n for _ in range(self.n_sample):\n point = self.sample()\n kpis = self._score(point)\n yield (point, kpis)\nelse:\n for _ in range(self.n_sample):\n self.sample(set_initial=True)\n for point in self.optimizer.optimize_function(self._score, self.p... | <|body_start_0|>
if self.method == 'sample':
for _ in range(self.n_sample):
point = self.sample()
kpis = self._score(point)
yield (point, kpis)
else:
for _ in range(self.n_sample):
self.sample(set_initial=True)
... | An engine for random (Monte Carlo) sampling and optimization. To get a picture of the overall parameter-space the user might want to randomly sample points. If the parameter-space contains many local minima (or maxima) the user might want to optimize from multiple random initial points, to discover those locals. Notes ... | MonteCarloEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonteCarloEngine:
"""An engine for random (Monte Carlo) sampling and optimization. To get a picture of the overall parameter-space the user might want to randomly sample points. If the parameter-space contains many local minima (or maxima) the user might want to optimize from multiple random init... | stack_v2_sparse_classes_36k_train_021547 | 4,766 | permissive | [
{
"docstring": "Generates sampling/optimization results. Yields ---------- optimization result: tuple(np.array, np.array, list) Point of evaluation, objective value",
"name": "optimize",
"signature": "def optimize(self, *vargs)"
},
{
"docstring": "Generate a random point in parameter space. Para... | 2 | stack_v2_sparse_classes_30k_train_011237 | Implement the Python class `MonteCarloEngine` described below.
Class description:
An engine for random (Monte Carlo) sampling and optimization. To get a picture of the overall parameter-space the user might want to randomly sample points. If the parameter-space contains many local minima (or maxima) the user might wan... | Implement the Python class `MonteCarloEngine` described below.
Class description:
An engine for random (Monte Carlo) sampling and optimization. To get a picture of the overall parameter-space the user might want to randomly sample points. If the parameter-space contains many local minima (or maxima) the user might wan... | c56d47521233e369d42fe82282ed8e113a3747f7 | <|skeleton|>
class MonteCarloEngine:
"""An engine for random (Monte Carlo) sampling and optimization. To get a picture of the overall parameter-space the user might want to randomly sample points. If the parameter-space contains many local minima (or maxima) the user might want to optimize from multiple random init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonteCarloEngine:
"""An engine for random (Monte Carlo) sampling and optimization. To get a picture of the overall parameter-space the user might want to randomly sample points. If the parameter-space contains many local minima (or maxima) the user might want to optimize from multiple random initial points, t... | the_stack_v2_python_sparse | monte_carlo/mco/monte_carlo_engine.py | force-h2020/force-bdss-plugin-enthought-example | train | 0 |
9bfcbd5218623d123f45bd79352697db1d2b2f0f | [
"super().__init__()\nself.device = device\nself.word_embedding = nn.Embedding(source_vocab_size, word_embedding_size)\nself.pos_embedding = nn.Embedding(max_length, word_embedding_size)\nself.encoder_layers = nn.ModuleList([EncoderLayer(word_embedding_size, num_heads, pf_dim, dropout_value, device) for _ in range(n... | <|body_start_0|>
super().__init__()
self.device = device
self.word_embedding = nn.Embedding(source_vocab_size, word_embedding_size)
self.pos_embedding = nn.Embedding(max_length, word_embedding_size)
self.encoder_layers = nn.ModuleList([EncoderLayer(word_embedding_size, num_heads,... | Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, source_vocab_size: int, word_embedding_size: int, num_layers: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device, max_length: int=100):
"""Constructs the Encoder Parameters ---------- source_vocab_size : int The vocab size in the sour... | stack_v2_sparse_classes_36k_train_021548 | 5,240 | permissive | [
{
"docstring": "Constructs the Encoder Parameters ---------- source_vocab_size : int The vocab size in the source language word_embedding_size : int The word embedding size num_layers : int The number of DecoderLayer layers num_heads : int The number of heads for each attention layer pf_dim : int The dimension ... | 2 | stack_v2_sparse_classes_30k_train_000411 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, source_vocab_size: int, word_embedding_size: int, num_layers: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device, max_length: int=100):... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, source_vocab_size: int, word_embedding_size: int, num_layers: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device, max_length: int=100):... | da9cecce49498c4f79946a631206985f99daaed3 | <|skeleton|>
class Encoder:
def __init__(self, source_vocab_size: int, word_embedding_size: int, num_layers: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device, max_length: int=100):
"""Constructs the Encoder Parameters ---------- source_vocab_size : int The vocab size in the sour... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, source_vocab_size: int, word_embedding_size: int, num_layers: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device, max_length: int=100):
"""Constructs the Encoder Parameters ---------- source_vocab_size : int The vocab size in the source language wo... | the_stack_v2_python_sparse | Translator/src/model/encoder.py | add54/Translator | train | 0 | |
6eb9c5de530dbb60867ddf3369fef3c3a078463e | [
"self.capacity = capacity\nself.map = {}\nself.tail = Node(None, None)\nself.head = Node(None, None)\nself.head.next = self.tail\nself.tail.pre = self.head",
"if key in self.map:\n node = self.map[key]\n self.put(node.key, node.value)\n return node.val\nreturn -1",
"if key in self.map:\n self._del(k... | <|body_start_0|>
self.capacity = capacity
self.map = {}
self.tail = Node(None, None)
self.head = Node(None, None)
self.head.next = self.tail
self.tail.pre = self.head
<|end_body_0|>
<|body_start_1|>
if key in self.map:
node = self.map[key]
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
def... | stack_v2_sparse_classes_36k_train_021549 | 1,492 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 4 | stack_v2_sparse_classes_30k_train_018273 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
- def... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
- def... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.map = {}
self.tail = Node(None, None)
self.head = Node(None, None)
self.head.next = self.tail
self.tail.pre = self.head
def get(self, key):
""":t... | the_stack_v2_python_sparse | problems/LRUCache.py | joddiy/leetcode | train | 1 | |
850fe38158bbbc1431e7caffced93164aeeb79d6 | [
"for command in ServerCommands.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 ServerCommands.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 m... | AdminCommands contains all the commands for processing the commands from the parent process. | ServerCommands | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerCommands:
"""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|>
d... | stack_v2_sparse_classes_36k_train_021550 | 13,913 | 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_015584 | Implement the Python class `ServerCommands` 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 ... | Implement the Python class `ServerCommands` 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 ... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class ServerCommands:
"""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|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerCommands:
"""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 ServerCommands.... | the_stack_v2_python_sparse | nvflare/private/fed/server/server_commands.py | NVIDIA/NVFlare | train | 442 |
ea80d87a827b3b9aede4785482d75850801cd44e | [
"context = {}\nif getattr(settings, 'WEB_ANALYTICS', None):\n context['web_analytics_providers'] = json.dumps(list(getattr(settings, 'WEB_ANALYTICS', {}).keys()))\nreturn context",
"context = {}\nif hasattr(request, 'current_page'):\n if getattr(settings, 'WEB_ANALYTICS', None):\n context['WEB_ANALYT... | <|body_start_0|>
context = {}
if getattr(settings, 'WEB_ANALYTICS', None):
context['web_analytics_providers'] = json.dumps(list(getattr(settings, 'WEB_ANALYTICS', {}).keys()))
return context
<|end_body_0|>
<|body_start_1|>
context = {}
if hasattr(request, 'current_pa... | Context processor to add Web Analytics tracking information to Richie CMS templates and frontend. | WebAnalyticsContextProcessor | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebAnalyticsContextProcessor:
"""Context processor to add Web Analytics tracking information to Richie CMS templates and frontend."""
def frontend_context_processor(self, request: HttpRequest) -> dict:
"""Additional web analytics information for the frontend react"""
<|body_0... | stack_v2_sparse_classes_36k_train_021551 | 8,256 | permissive | [
{
"docstring": "Additional web analytics information for the frontend react",
"name": "frontend_context_processor",
"signature": "def frontend_context_processor(self, request: HttpRequest) -> dict"
},
{
"docstring": "Real implementation of the context processor for the Web Analytics core app sub... | 3 | null | Implement the Python class `WebAnalyticsContextProcessor` described below.
Class description:
Context processor to add Web Analytics tracking information to Richie CMS templates and frontend.
Method signatures and docstrings:
- def frontend_context_processor(self, request: HttpRequest) -> dict: Additional web analyti... | Implement the Python class `WebAnalyticsContextProcessor` described below.
Class description:
Context processor to add Web Analytics tracking information to Richie CMS templates and frontend.
Method signatures and docstrings:
- def frontend_context_processor(self, request: HttpRequest) -> dict: Additional web analyti... | f2d46fc46b271eb3b4d565039a29c15ba15f027c | <|skeleton|>
class WebAnalyticsContextProcessor:
"""Context processor to add Web Analytics tracking information to Richie CMS templates and frontend."""
def frontend_context_processor(self, request: HttpRequest) -> dict:
"""Additional web analytics information for the frontend react"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebAnalyticsContextProcessor:
"""Context processor to add Web Analytics tracking information to Richie CMS templates and frontend."""
def frontend_context_processor(self, request: HttpRequest) -> dict:
"""Additional web analytics information for the frontend react"""
context = {}
... | the_stack_v2_python_sparse | src/richie/apps/core/context_processors.py | openfun/richie | train | 238 |
368888fb1e64c4db439ab918cff26e087df5c3cc | [
"logging.debug('Page Parse started on:{}'.format(response.url))\ntitles = response.xpath('//a[contains(@href,\"/s/\")]')\nfor title in titles:\n item = items.MonkPageItem()\n title_text = title.xpath('text()').extract()[0]\n title_url = response.urljoin(title.xpath('@href').extract()[0])\n item['url'] =... | <|body_start_0|>
logging.debug('Page Parse started on:{}'.format(response.url))
titles = response.xpath('//a[contains(@href,"/s/")]')
for title in titles:
item = items.MonkPageItem()
title_text = title.xpath('text()').extract()[0]
title_url = response.urljoin(... | FanfictionSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FanfictionSpider:
def parse_page(self, response):
""":rtype: object :param response:"""
<|body_0|>
def parse_story_page(self, response):
""":param response: :rtype: MonkStoryItem"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logging.debug('Page Pa... | stack_v2_sparse_classes_36k_train_021552 | 2,963 | no_license | [
{
"docstring": ":rtype: object :param response:",
"name": "parse_page",
"signature": "def parse_page(self, response)"
},
{
"docstring": ":param response: :rtype: MonkStoryItem",
"name": "parse_story_page",
"signature": "def parse_story_page(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017742 | Implement the Python class `FanfictionSpider` described below.
Class description:
Implement the FanfictionSpider class.
Method signatures and docstrings:
- def parse_page(self, response): :rtype: object :param response:
- def parse_story_page(self, response): :param response: :rtype: MonkStoryItem | Implement the Python class `FanfictionSpider` described below.
Class description:
Implement the FanfictionSpider class.
Method signatures and docstrings:
- def parse_page(self, response): :rtype: object :param response:
- def parse_story_page(self, response): :param response: :rtype: MonkStoryItem
<|skeleton|>
class... | 54ca3becfc3ddd1002f2e0fed51061e4f5872dc3 | <|skeleton|>
class FanfictionSpider:
def parse_page(self, response):
""":rtype: object :param response:"""
<|body_0|>
def parse_story_page(self, response):
""":param response: :rtype: MonkStoryItem"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FanfictionSpider:
def parse_page(self, response):
""":rtype: object :param response:"""
logging.debug('Page Parse started on:{}'.format(response.url))
titles = response.xpath('//a[contains(@href,"/s/")]')
for title in titles:
item = items.MonkPageItem()
... | the_stack_v2_python_sparse | lib/Monk/Monk/spiders/fan_spider.py | geekman2/GutenTag | train | 3 | |
e270144ca54ab5fba77c49ebc0a5dd127302b0b7 | [
"res = [[]]\nfor num in nums:\n res = res + [[num] + i for i in res]\nreturn res",
"dic = dict()\nfor num in nums:\n dic[num] = dic.get(num, 0) + 1\nres = [[]]\nfor i, v in dic.items():\n tmp = res.copy()\n for j in res:\n tmp.extend((j + [i] * (k + 1) for k in range(v)))\n res = tmp\nreturn... | <|body_start_0|>
res = [[]]
for num in nums:
res = res + [[num] + i for i in res]
return res
<|end_body_0|>
<|body_start_1|>
dic = dict()
for num in nums:
dic[num] = dic.get(num, 0) + 1
res = [[]]
for i, v in dic.items():
tmp =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""78. 子集 无重复"""
<|body_0|>
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""90. 子集 II 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。"""
<|body... | stack_v2_sparse_classes_36k_train_021553 | 1,094 | no_license | [
{
"docstring": "78. 子集 无重复",
"name": "subsets",
"signature": "def subsets(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "90. 子集 II 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums: List[int]) -> List[List[int]]: 78. 子集 无重复
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 90. 子集 II 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums: List[int]) -> List[List[int]]: 78. 子集 无重复
- def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 90. 子集 II 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的... | 330330ef6bc42eeb17f4dea53c30d230506b4e8f | <|skeleton|>
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""78. 子集 无重复"""
<|body_0|>
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""90. 子集 II 给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
"""78. 子集 无重复"""
res = [[]]
for num in nums:
res = res + [[num] + i for i in res]
return res
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
"""90. 子集 II 给你一个整数数组 nums ,其中可能包... | the_stack_v2_python_sparse | Code/leetcode_everyday/0331.py | NiceToMeeetU/ToGetReady | train | 0 | |
74b26613aa5e69863760bfda100f0ba2940b51c4 | [
"super().__init__(**kwargs)\nself.conv1d_1 = tf.keras.layers.Conv1D(config.intermediate_size, kernel_size=config.intermediate_kernel_size, kernel_initializer=get_initializer(config.initializer_range), padding='same', name='conv1d_1')\nself.conv1d_2 = tf.keras.layers.Conv1D(config.hidden_size, kernel_size=config.int... | <|body_start_0|>
super().__init__(**kwargs)
self.conv1d_1 = tf.keras.layers.Conv1D(config.intermediate_size, kernel_size=config.intermediate_kernel_size, kernel_initializer=get_initializer(config.initializer_range), padding='same', name='conv1d_1')
self.conv1d_2 = tf.keras.layers.Conv1D(config.h... | Intermediate representation module. | TFFastSpeechIntermediate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFFastSpeechIntermediate:
"""Intermediate representation module."""
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs):
"""Call logic."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(**... | stack_v2_sparse_classes_36k_train_021554 | 17,606 | permissive | [
{
"docstring": "Init variables.",
"name": "__init__",
"signature": "def __init__(self, config, **kwargs)"
},
{
"docstring": "Call logic.",
"name": "call",
"signature": "def call(self, inputs)"
}
] | 2 | null | Implement the Python class `TFFastSpeechIntermediate` described below.
Class description:
Intermediate representation module.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs): Call logic. | Implement the Python class `TFFastSpeechIntermediate` described below.
Class description:
Intermediate representation module.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs): Call logic.
<|skeleton|>
class TFFastSpeechIntermediate:
"""Intermediat... | 4343c409340c608a426cc6f0926fbe2c1661783e | <|skeleton|>
class TFFastSpeechIntermediate:
"""Intermediate representation module."""
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs):
"""Call logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFFastSpeechIntermediate:
"""Intermediate representation module."""
def __init__(self, config, **kwargs):
"""Init variables."""
super().__init__(**kwargs)
self.conv1d_1 = tf.keras.layers.Conv1D(config.intermediate_size, kernel_size=config.intermediate_kernel_size, kernel_initializ... | the_stack_v2_python_sparse | malaya_speech/train/model/fastspeech/model_aligner.py | Ariffleng/malaya-speech | train | 0 |
74b7a2645a942a62f64ae3ac21624e634266f178 | [
"l1 = len(nums1)\nl2 = len(nums2)\nif l1 < l2:\n l1, l2 = (l2, l1)\n nums1, nums2 = (nums2, nums1)\nm1 = l1 // 2\nm2 = l2 // 2\nif l2 <= 4:\n for i in range(l2):\n self.insert(nums1, nums2[i])\n if (l1 + l2) % 2 == 1:\n return float(nums1[(l1 + l2) // 2])\n else:\n return (nums1[... | <|body_start_0|>
l1 = len(nums1)
l2 = len(nums2)
if l1 < l2:
l1, l2 = (l2, l1)
nums1, nums2 = (nums2, nums1)
m1 = l1 // 2
m2 = l2 // 2
if l2 <= 4:
for i in range(l2):
self.insert(nums1, nums2[i])
if (l1 + l2)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def insert(self, nums, a):
""":type nums1: List[int] :type a: int :rtype: None"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_021555 | 2,008 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type a: int :rtype: None",
"name": "insert",
"signature": "def insert(s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def insert(self, nums, a): :type nums1: List[int] :type a: int :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def insert(self, nums, a): :type nums1: List[int] :type a: int :rtyp... | af3faf95c53cb97d0ffa9a93367e27926c0b17ba | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def insert(self, nums, a):
""":type nums1: List[int] :type a: int :rtype: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
l1 = len(nums1)
l2 = len(nums2)
if l1 < l2:
l1, l2 = (l2, l1)
nums1, nums2 = (nums2, nums1)
m1 = l1 // 2
m2 = l2 /... | the_stack_v2_python_sparse | 1-50/4.py | ccfarm/leetcode | train | 0 | |
a11d2c019b897fb2844bc4cc5126b39c6c7047a8 | [
"try:\n return np.sqrt(self.energy / self.component.mass)\nexcept FloatingPointError:\n return np.zeros(self.frequency.amount)",
"try:\n return 20 * np.log10(self.velocity / (5 * 10 ** (-8)))\nexcept FloatingPointError:\n return np.zeros(self.frequency.amount)"
] | <|body_start_0|>
try:
return np.sqrt(self.energy / self.component.mass)
except FloatingPointError:
return np.zeros(self.frequency.amount)
<|end_body_0|>
<|body_start_1|>
try:
return 20 * np.log10(self.velocity / (5 * 10 ** (-8)))
except FloatingPointE... | Abstract base class for all Structural subsystems. | SubsystemStructural | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubsystemStructural:
"""Abstract base class for all Structural subsystems."""
def velocity(self):
"""Vibrational velocity :math:`v`. .. math:: v = \\sqrt{\\frac{E}{m}}"""
<|body_0|>
def velocity_level(self):
"""Velocity level. .. math:: L_v = 20 \\log_{10}{\\frac... | stack_v2_sparse_classes_36k_train_021556 | 876 | no_license | [
{
"docstring": "Vibrational velocity :math:`v`. .. math:: v = \\\\sqrt{\\\\frac{E}{m}}",
"name": "velocity",
"signature": "def velocity(self)"
},
{
"docstring": "Velocity level. .. math:: L_v = 20 \\\\log_{10}{\\\\frac{v}{v_0}}",
"name": "velocity_level",
"signature": "def velocity_level... | 2 | stack_v2_sparse_classes_30k_train_013787 | Implement the Python class `SubsystemStructural` described below.
Class description:
Abstract base class for all Structural subsystems.
Method signatures and docstrings:
- def velocity(self): Vibrational velocity :math:`v`. .. math:: v = \\sqrt{\\frac{E}{m}}
- def velocity_level(self): Velocity level. .. math:: L_v =... | Implement the Python class `SubsystemStructural` described below.
Class description:
Abstract base class for all Structural subsystems.
Method signatures and docstrings:
- def velocity(self): Vibrational velocity :math:`v`. .. math:: v = \\sqrt{\\frac{E}{m}}
- def velocity_level(self): Velocity level. .. math:: L_v =... | e30b6dc59d8ab02cd41924f7b6c14d0d1e77e19e | <|skeleton|>
class SubsystemStructural:
"""Abstract base class for all Structural subsystems."""
def velocity(self):
"""Vibrational velocity :math:`v`. .. math:: v = \\sqrt{\\frac{E}{m}}"""
<|body_0|>
def velocity_level(self):
"""Velocity level. .. math:: L_v = 20 \\log_{10}{\\frac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubsystemStructural:
"""Abstract base class for all Structural subsystems."""
def velocity(self):
"""Vibrational velocity :math:`v`. .. math:: v = \\sqrt{\\frac{E}{m}}"""
try:
return np.sqrt(self.energy / self.component.mass)
except FloatingPointError:
retu... | the_stack_v2_python_sparse | Sea/model/subsystems/SubsystemStructural.py | python-acoustics/Sea | train | 7 |
ba8e876a89132c06552098984ae7b9385fc2ba82 | [
"if not board:\n return\nrow = len(board)\ncol = len(board[0])\ndummy = row * col\nunion = UnionFind()\nfor i in range(row):\n for j in range(col):\n if board[i][j] == 'O':\n if i == 0 or i == row - 1 or j == 0 or (j == col - 1):\n union.add(i * col + j)\n union... | <|body_start_0|>
if not board:
return
row = len(board)
col = len(board[0])
dummy = row * col
union = UnionFind()
for i in range(row):
for j in range(col):
if board[i][j] == 'O':
if i == 0 or i == row - 1 or j == ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def solve1(self, board: List[List[str]]) -> None:
"""dfs方式 :param self: :param board: :return:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_021557 | 4,283 | no_license | [
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "solve",
"signature": "def solve(self, board: List[List[str]]) -> None"
},
{
"docstring": "dfs方式 :param self: :param board: :return:",
"name": "solve1",
"signature": "def solve1(self, board: List[List[str]])... | 2 | stack_v2_sparse_classes_30k_train_019264 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def solve1(self, board: List[List[str]]) -> None: dfs方式 :param self: :pa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def solve1(self, board: List[List[str]]) -> None: dfs方式 :param self: :pa... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def solve1(self, board: List[List[str]]) -> None:
"""dfs方式 :param self: :param board: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
if not board:
return
row = len(board)
col = len(board[0])
dummy = row * col
union = UnionFind()
for i in range(row):
... | the_stack_v2_python_sparse | datastructure/union_find/Solve.py | yinhuax/leet_code | train | 0 | |
2eb340c30d5cd2e26a29c62a11c79a58f7a68bce | [
"request = RequestFactory().get('/')\ncontext = {'request': request}\ncommon_bundle = (chunk for chunk in FAKE_COMMON_BUNDLE)\nget_bundle = Mock(return_value=common_bundle)\nloader = Mock(get_bundle=get_bundle)\nbundle_name = 'bundle_name'\nwith patch('ui.templatetags.render_bundle.get_loader', return_value=loader)... | <|body_start_0|>
request = RequestFactory().get('/')
context = {'request': request}
common_bundle = (chunk for chunk in FAKE_COMMON_BUNDLE)
get_bundle = Mock(return_value=common_bundle)
loader = Mock(get_bundle=get_bundle)
bundle_name = 'bundle_name'
with patch('u... | Tests for render_bundle | TestRenderBundle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRenderBundle:
"""Tests for render_bundle"""
def test_debug(self):
"""If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL"""
<|body_0|>
def test_production(self):
"""If USE_WEBPACK_DEV_SERVER=False, return a static URL for production"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_021558 | 3,850 | permissive | [
{
"docstring": "If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL",
"name": "test_debug",
"signature": "def test_debug(self)"
},
{
"docstring": "If USE_WEBPACK_DEV_SERVER=False, return a static URL for production",
"name": "test_production",
"signature": "def test_production(self)"... | 3 | stack_v2_sparse_classes_30k_train_015094 | Implement the Python class `TestRenderBundle` described below.
Class description:
Tests for render_bundle
Method signatures and docstrings:
- def test_debug(self): If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL
- def test_production(self): If USE_WEBPACK_DEV_SERVER=False, return a static URL for production
-... | Implement the Python class `TestRenderBundle` described below.
Class description:
Tests for render_bundle
Method signatures and docstrings:
- def test_debug(self): If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL
- def test_production(self): If USE_WEBPACK_DEV_SERVER=False, return a static URL for production
-... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class TestRenderBundle:
"""Tests for render_bundle"""
def test_debug(self):
"""If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL"""
<|body_0|>
def test_production(self):
"""If USE_WEBPACK_DEV_SERVER=False, return a static URL for production"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRenderBundle:
"""Tests for render_bundle"""
def test_debug(self):
"""If USE_WEBPACK_DEV_SERVER=True, return a hot reload URL"""
request = RequestFactory().get('/')
context = {'request': request}
common_bundle = (chunk for chunk in FAKE_COMMON_BUNDLE)
get_bundle... | the_stack_v2_python_sparse | ui/templatetags/render_bundle_test.py | mitodl/micromasters | train | 35 |
61f395fce5519c9c301b9a8683904e3f5f72c6e5 | [
"self.capacity = capacity\nself.stack = {}\nself.accessed = []",
"if key in self.accessed:\n i = self.accessed.index(key)\n self.accessed = self.accessed[:i] + self.accessed[i + 1:]\nself.accessed.append(key)\nif len(self.accessed) > self.capacity:\n del self.accessed[0]\nif key in self.stack.keys():\n ... | <|body_start_0|>
self.capacity = capacity
self.stack = {}
self.accessed = []
<|end_body_0|>
<|body_start_1|>
if key in self.accessed:
i = self.accessed.index(key)
self.accessed = self.accessed[:i] + self.accessed[i + 1:]
self.accessed.append(key)
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_021559 | 1,576 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 33519e4c560285f4954f225c3b8f0b489ccd47c8 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.stack = {}
self.accessed = []
def get(self, key):
""":type key: int :rtype: int"""
if key in self.accessed:
i = self.accessed.index(key)
... | the_stack_v2_python_sparse | lru_cache.py | chandrap08/leetcode | train | 0 | |
753a81471fb52b8e60e24106398a3c5cc360dbff | [
"data_dict = {}\nfor key, value in request.POST.items():\n data_dict[key] = value\nsign = data_dict.pop('sign', None)\nalipay = AliPay(appid='', app_notify_url='http://127.0.0.1:8000/alipay_return/', app_private_key_path=private_key, alipay_public_key_path=ali_key, debug=True, return_url='http://127.0.0.1:8000/a... | <|body_start_0|>
data_dict = {}
for key, value in request.POST.items():
data_dict[key] = value
sign = data_dict.pop('sign', None)
alipay = AliPay(appid='', app_notify_url='http://127.0.0.1:8000/alipay_return/', app_private_key_path=private_key, alipay_public_key_path=ali_key,... | AliPayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliPayView:
def post(self, request):
"""处理支付宝的notify_url"""
<|body_0|>
def get(self, request):
"""处理支付宝的return_url返回"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data_dict = {}
for key, value in request.POST.items():
data_dict... | stack_v2_sparse_classes_36k_train_021560 | 10,394 | no_license | [
{
"docstring": "处理支付宝的notify_url",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "处理支付宝的return_url返回",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009431 | Implement the Python class `AliPayView` described below.
Class description:
Implement the AliPayView class.
Method signatures and docstrings:
- def post(self, request): 处理支付宝的notify_url
- def get(self, request): 处理支付宝的return_url返回 | Implement the Python class `AliPayView` described below.
Class description:
Implement the AliPayView class.
Method signatures and docstrings:
- def post(self, request): 处理支付宝的notify_url
- def get(self, request): 处理支付宝的return_url返回
<|skeleton|>
class AliPayView:
def post(self, request):
"""处理支付宝的notify_u... | 5620f09cd6d2a99e7643d5ec0b6bc9e1203be6fe | <|skeleton|>
class AliPayView:
def post(self, request):
"""处理支付宝的notify_url"""
<|body_0|>
def get(self, request):
"""处理支付宝的return_url返回"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AliPayView:
def post(self, request):
"""处理支付宝的notify_url"""
data_dict = {}
for key, value in request.POST.items():
data_dict[key] = value
sign = data_dict.pop('sign', None)
alipay = AliPay(appid='', app_notify_url='http://127.0.0.1:8000/alipay_return/', app_... | the_stack_v2_python_sparse | apps/trade/views.py | DzrJob/gulishop | train | 0 | |
a3c337ea4b88cf59c96679c27be64b5d67581014 | [
"if 'airportdProcessDLILEvent' in action:\n network_interface = text.split()[0]\n return 'Interface {0:s} turn up.'.format(network_interface)\nif 'doAutoJoin' in action:\n match = self._CONNECTED_RE.match(text)\n if match:\n ssid = match.group(1)[1:-1]\n else:\n ssid = 'Unknown'\n re... | <|body_start_0|>
if 'airportdProcessDLILEvent' in action:
network_interface = text.split()[0]
return 'Interface {0:s} turn up.'.format(network_interface)
if 'doAutoJoin' in action:
match = self._CONNECTED_RE.match(text)
if match:
ssid = mat... | Text parser plugin MacOS Wi-Fi log (wifi.log) files. | MacOSWiFiLogTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacOSWiFiLogTextPlugin:
"""Text parser plugin MacOS Wi-Fi log (wifi.log) files."""
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a f... | stack_v2_sparse_classes_36k_train_021561 | 9,805 | permissive | [
{
"docstring": "Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a formatted string representing the known (or common) action. If the action is not known the original log text is returned.",
"name":... | 4 | stack_v2_sparse_classes_30k_train_020033 | Implement the Python class `MacOSWiFiLogTextPlugin` described below.
Class description:
Text parser plugin MacOS Wi-Fi log (wifi.log) files.
Method signatures and docstrings:
- def _GetAction(self, action, text): Parse the well known actions for easy reading. Args: action (str): the function or action called by the a... | Implement the Python class `MacOSWiFiLogTextPlugin` described below.
Class description:
Text parser plugin MacOS Wi-Fi log (wifi.log) files.
Method signatures and docstrings:
- def _GetAction(self, action, text): Parse the well known actions for easy reading. Args: action (str): the function or action called by the a... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class MacOSWiFiLogTextPlugin:
"""Text parser plugin MacOS Wi-Fi log (wifi.log) files."""
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MacOSWiFiLogTextPlugin:
"""Text parser plugin MacOS Wi-Fi log (wifi.log) files."""
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): text from a log line. Returns: str: a formatted stri... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/macos_wifi.py | log2timeline/plaso | train | 1,506 |
a73de47b65448323d0a45d8b512bcd1f869e8882 | [
"user = request.user\ntry:\n video_client = user.video_client\n if timezone.now() > video_client.expires_at:\n video_client.delete()\n raise ValueError()\nexcept (AttributeError, ValueError):\n try:\n video_client = create_video_client(user)\n except (ValidationError, IntegrityError... | <|body_start_0|>
user = request.user
try:
video_client = user.video_client
if timezone.now() > video_client.expires_at:
video_client.delete()
raise ValueError()
except (AttributeError, ValueError):
try:
video_cli... | Shoutit Twilio API Resources. | ShoutitTwilioViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identit... | stack_v2_sparse_classes_36k_train_021562 | 7,701 | no_license | [
{
"docstring": "Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { \"token\": \"eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE\", \"identity\": \"7c6ca4737db3447f936037374473e61f\" } </code></pre> ---",
"name": "video_auth",
"sign... | 4 | stack_v2_sparse_classes_30k_train_002088 | Implement the Python class `ShoutitTwilioViewSet` described below.
Class description:
Shoutit Twilio API Resources.
Method signatures and docstrings:
- def video_auth(self, request): Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAi... | Implement the Python class `ShoutitTwilioViewSet` described below.
Class description:
Shoutit Twilio API Resources.
Method signatures and docstrings:
- def video_auth(self, request): Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAi... | f3c95585ac639b45c28521712ed33a178ab36ea4 | <|skeleton|>
class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShoutitTwilioViewSet:
"""Shoutit Twilio API Resources."""
def video_auth(self, request):
"""Create a video chat endpoint. ###REQUIRES AUTH ###Response <pre><code> { "token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCIsICJjdHkiOiAidHdpbGlvLWZwYTt2PTEifQ.eyJpc3MiOiAiU0s3MDFlYzE", "identity": "7c6ca473... | the_stack_v2_python_sparse | src/shoutit_twilio/views.py | shoutit/shoutit-api | train | 0 |
927cfb4caa0cb5d264566bb912be25e92c0a168a | [
"parser.add_argument('metric_name', help='The name of the log-based metric to update.')\nconfig_group = parser.add_argument_group(help='Data about the metric to update.', mutex=True, required=True)\nlegacy_mode_group = config_group.add_argument_group(help='Arguments to specify information about simple counter logs-... | <|body_start_0|>
parser.add_argument('metric_name', help='The name of the log-based metric to update.')
config_group = parser.add_argument_group(help='Data about the metric to update.', mutex=True, required=True)
legacy_mode_group = config_group.add_argument_group(help='Arguments to specify info... | Updates the definition of a logs-based metric. | UpdateBeta | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateBeta:
"""Updates the definition of a logs-based metric."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the argum... | stack_v2_sparse_classes_36k_train_021563 | 7,286 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated... | 2 | stack_v2_sparse_classes_30k_train_007243 | Implement the Python class `UpdateBeta` described below.
Class description:
Updates the definition of a logs-based metric.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse nam... | Implement the Python class `UpdateBeta` described below.
Class description:
Updates the definition of a logs-based metric.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse nam... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class UpdateBeta:
"""Updates the definition of a logs-based metric."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the argum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateBeta:
"""Updates the definition of a logs-based metric."""
def Args(parser):
"""Register flags for this command."""
parser.add_argument('metric_name', help='The name of the log-based metric to update.')
config_group = parser.add_argument_group(help='Data about the metric to ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/logging/metrics/update.py | bopopescu/socialliteapp | train | 0 |
dcb3401a9110b7c3383f2bb9d596bd8f0e54e97d | [
"account_config = config['global']['account']\nregion = account_config['region']\nprefix = account_config['prefix']\nkms_key_alias = account_config.get('kms_key_alias', '{}_streamalert_secrets'.format(prefix))\nif 'alias/' in kms_key_alias:\n kms_key_alias = kms_key_alias.split('/')[1]\nprovider = OutputCredenti... | <|body_start_0|>
account_config = config['global']['account']
region = account_config['region']
prefix = account_config['prefix']
kms_key_alias = account_config.get('kms_key_alias', '{}_streamalert_secrets'.format(prefix))
if 'alias/' in kms_key_alias:
kms_key_alias =... | OutputSharedMethods | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputSharedMethods:
def save_credentials(service, config, properties):
"""Save credentials for the provided service Args: service (str): The name of the service the output belongs too config (StreamAlert.config): The configuration of StreamAlert properties (OrderedDict): Contains variou... | stack_v2_sparse_classes_36k_train_021564 | 19,044 | permissive | [
{
"docstring": "Save credentials for the provided service Args: service (str): The name of the service the output belongs too config (StreamAlert.config): The configuration of StreamAlert properties (OrderedDict): Contains various OutputProperty items Returns: bool: False if errors occurred, True otherwise",
... | 2 | stack_v2_sparse_classes_30k_train_010636 | Implement the Python class `OutputSharedMethods` described below.
Class description:
Implement the OutputSharedMethods class.
Method signatures and docstrings:
- def save_credentials(service, config, properties): Save credentials for the provided service Args: service (str): The name of the service the output belongs... | Implement the Python class `OutputSharedMethods` described below.
Class description:
Implement the OutputSharedMethods class.
Method signatures and docstrings:
- def save_credentials(service, config, properties): Save credentials for the provided service Args: service (str): The name of the service the output belongs... | 75ba140d2e1aa6e903313d88326920adcb8bff45 | <|skeleton|>
class OutputSharedMethods:
def save_credentials(service, config, properties):
"""Save credentials for the provided service Args: service (str): The name of the service the output belongs too config (StreamAlert.config): The configuration of StreamAlert properties (OrderedDict): Contains variou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputSharedMethods:
def save_credentials(service, config, properties):
"""Save credentials for the provided service Args: service (str): The name of the service the output belongs too config (StreamAlert.config): The configuration of StreamAlert properties (OrderedDict): Contains various OutputProper... | the_stack_v2_python_sparse | streamalert_cli/outputs/handler.py | avmi/streamalert | train | 0 | |
8b7fbc5989259f2e14ad2a647bbf5310d28e9996 | [
"indices = _ExampleVector.GetIndices()\nall_indices = np.concatenate((indices.foo, indices.bar, indices.baz))\nself.assertEqual(set(all_indices), set(range(_ExampleVector.GetDim())))",
"foo = np.matrix([[1.0], [2.0], [3.0]])\nbar = np.matrix([[4.0], [5.0], [6.0]])\nbaz = np.matrix([[7.0], [8.0], [9.0]])\nexample_... | <|body_start_0|>
indices = _ExampleVector.GetIndices()
all_indices = np.concatenate((indices.foo, indices.bar, indices.baz))
self.assertEqual(set(all_indices), set(range(_ExampleVector.GetDim())))
<|end_body_0|>
<|body_start_1|>
foo = np.matrix([[1.0], [2.0], [3.0]])
bar = np.ma... | TypeUtilTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeUtilTest:
def testGetIndices(self):
"""Simple test of NamedVector.GetIndices()."""
<|body_0|>
def testStateToVector(self):
"""Simple test of NamedVector.ToVector and NamedVector.FromVector."""
<|body_1|>
def testFlatState(self):
"""Simple tes... | stack_v2_sparse_classes_36k_train_021565 | 2,784 | permissive | [
{
"docstring": "Simple test of NamedVector.GetIndices().",
"name": "testGetIndices",
"signature": "def testGetIndices(self)"
},
{
"docstring": "Simple test of NamedVector.ToVector and NamedVector.FromVector.",
"name": "testStateToVector",
"signature": "def testStateToVector(self)"
},
... | 3 | stack_v2_sparse_classes_30k_test_000208 | Implement the Python class `TypeUtilTest` described below.
Class description:
Implement the TypeUtilTest class.
Method signatures and docstrings:
- def testGetIndices(self): Simple test of NamedVector.GetIndices().
- def testStateToVector(self): Simple test of NamedVector.ToVector and NamedVector.FromVector.
- def te... | Implement the Python class `TypeUtilTest` described below.
Class description:
Implement the TypeUtilTest class.
Method signatures and docstrings:
- def testGetIndices(self): Simple test of NamedVector.GetIndices().
- def testStateToVector(self): Simple test of NamedVector.ToVector and NamedVector.FromVector.
- def te... | 818ae8b7119b200a28af6b3669a3045f30e0dc64 | <|skeleton|>
class TypeUtilTest:
def testGetIndices(self):
"""Simple test of NamedVector.GetIndices()."""
<|body_0|>
def testStateToVector(self):
"""Simple test of NamedVector.ToVector and NamedVector.FromVector."""
<|body_1|>
def testFlatState(self):
"""Simple tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeUtilTest:
def testGetIndices(self):
"""Simple test of NamedVector.GetIndices()."""
indices = _ExampleVector.GetIndices()
all_indices = np.concatenate((indices.foo, indices.bar, indices.baz))
self.assertEqual(set(all_indices), set(range(_ExampleVector.GetDim())))
def te... | the_stack_v2_python_sparse | analysis/control/type_util_test.py | ghomsy/makani | train | 0 | |
2eabf0c8d916c2c52158cb59b755dab3fda09f07 | [
"self.args = args\nself.kubeconfig = '/tmp/admin.kubeconfig'\nself.oc = OCUtil(namespace=self.args.namespace, config_file=self.kubeconfig)",
"result = 1\nzabbix_data_sync_inventory_hosts_names = []\nfor host in zabbix_data_sync_inventory_hosts:\n zabbix_data_sync_inventory_hosts_names.append(host['name'])\ndes... | <|body_start_0|>
self.args = args
self.kubeconfig = '/tmp/admin.kubeconfig'
self.oc = OCUtil(namespace=self.args.namespace, config_file=self.kubeconfig)
<|end_body_0|>
<|body_start_1|>
result = 1
zabbix_data_sync_inventory_hosts_names = []
for host in zabbix_data_sync_in... | this will check the zabbix data and compare it with the real world | ZabbixInfo | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZabbixInfo:
"""this will check the zabbix data and compare it with the real world"""
def __init__(self, args=None):
"""initial for the InfraNodePodStatus"""
<|body_0|>
def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):
"""check the situation"... | stack_v2_sparse_classes_36k_train_021566 | 4,174 | permissive | [
{
"docstring": "initial for the InfraNodePodStatus",
"name": "__init__",
"signature": "def __init__(self, args=None)"
},
{
"docstring": "check the situation",
"name": "check_all_hosts",
"signature": "def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_007367 | Implement the Python class `ZabbixInfo` described below.
Class description:
this will check the zabbix data and compare it with the real world
Method signatures and docstrings:
- def __init__(self, args=None): initial for the InfraNodePodStatus
- def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):... | Implement the Python class `ZabbixInfo` described below.
Class description:
this will check the zabbix data and compare it with the real world
Method signatures and docstrings:
- def __init__(self, args=None): initial for the InfraNodePodStatus
- def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class ZabbixInfo:
"""this will check the zabbix data and compare it with the real world"""
def __init__(self, args=None):
"""initial for the InfraNodePodStatus"""
<|body_0|>
def check_all_hosts(self, zabbix_data_sync_inventory_hosts, clusterid):
"""check the situation"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZabbixInfo:
"""this will check the zabbix data and compare it with the real world"""
def __init__(self, args=None):
"""initial for the InfraNodePodStatus"""
self.args = args
self.kubeconfig = '/tmp/admin.kubeconfig'
self.oc = OCUtil(namespace=self.args.namespace, config_fi... | the_stack_v2_python_sparse | scripts/monitoring/cron-send-zabbix-inventory-check.py | openshift/openshift-tools | train | 170 |
dd69f71536378ea9601707c65bb1bfdf872d7648 | [
"super().__init__(*args, **kwargs)\nassert isinstance(self, cmd2.Cmd)\nself._pybridge = cmd2.py_bridge.PyBridge(self)",
"assert isinstance(self, cmd2.Cmd) and isinstance(self, ExternalTestMixin)\ntry:\n self._in_py = True\n return self._pybridge(command, echo=echo)\nfinally:\n self._in_py = False",
"fo... | <|body_start_0|>
super().__init__(*args, **kwargs)
assert isinstance(self, cmd2.Cmd)
self._pybridge = cmd2.py_bridge.PyBridge(self)
<|end_body_0|>
<|body_start_1|>
assert isinstance(self, cmd2.Cmd) and isinstance(self, ExternalTestMixin)
try:
self._in_py = True
... | A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python | ExternalTestMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalTestMixin:
"""A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python"""
def __init__(self, *args, **kwargs):
""":type self: cmd2.Cmd :param args: :param kwargs:"""
<|body_0|>
def app_cmd(self, command: str, echo: Optiona... | stack_v2_sparse_classes_36k_train_021567 | 2,000 | permissive | [
{
"docstring": ":type self: cmd2.Cmd :param args: :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Run the application command :param command: The application command as it would be written on the cmd2 application prompt :param echo: Flag... | 4 | stack_v2_sparse_classes_30k_train_007252 | Implement the Python class `ExternalTestMixin` described below.
Class description:
A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :type self: cmd2.Cmd :param args: :param kwargs:
- def app_cmd(s... | Implement the Python class `ExternalTestMixin` described below.
Class description:
A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): :type self: cmd2.Cmd :param args: :param kwargs:
- def app_cmd(s... | 9886b82c71face043e1fac871a6cdbebbf0e864c | <|skeleton|>
class ExternalTestMixin:
"""A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python"""
def __init__(self, *args, **kwargs):
""":type self: cmd2.Cmd :param args: :param kwargs:"""
<|body_0|>
def app_cmd(self, command: str, echo: Optiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalTestMixin:
"""A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python"""
def __init__(self, *args, **kwargs):
""":type self: cmd2.Cmd :param args: :param kwargs:"""
super().__init__(*args, **kwargs)
assert isinstance(self, cmd2.Cmd... | the_stack_v2_python_sparse | plugins/ext_test/cmd2_ext_test/cmd2_ext_test.py | python-cmd2/cmd2 | train | 571 |
791746bda1f6f6f94b13b575a7d15037af6fb285 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ajr10_williami', 'ajr10_williami')\nrepo.dropCollection('ajr10_williami.k_means_trees')\nrepo.createCollection('ajr10_williami.k_means_trees')\ntrees_boston = repo['ajr10_williami.cleaned_trees_boston'].... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_williami', 'ajr10_williami')
repo.dropCollection('ajr10_williami.k_means_trees')
repo.createCollection('ajr10_williami.k_means_trees')
... | k_means_trees | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class k_means_trees:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this ... | stack_v2_sparse_classes_36k_train_021568 | 6,513 | no_license | [
{
"docstring": "Retrieve some data sets and store in mongodb collections.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing ... | 2 | null | Implement the Python class `k_means_trees` described below.
Class description:
Implement the k_means_trees class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets and store in mongodb collections.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Creat... | Implement the Python class `k_means_trees` described below.
Class description:
Implement the k_means_trees class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets and store in mongodb collections.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Creat... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class k_means_trees:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class k_means_trees:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_williami', 'ajr10_williami')
repo.dropColl... | the_stack_v2_python_sparse | ajr10_williami/k_means_trees.py | lingyigu/course-2017-spr-proj | train | 0 | |
9e64d080cd55242b09139f47866002d0f7223ca2 | [
"super(AbsoluteThreshold, self).__init__(self.__class__.__name__, time_series, baseline_time_series)\nself.absolute_threshold_value_upper = absolute_threshold_value_upper\nself.absolute_threshold_value_lower = absolute_threshold_value_lower\nif not self.absolute_threshold_value_lower and (not self.absolute_threshol... | <|body_start_0|>
super(AbsoluteThreshold, self).__init__(self.__class__.__name__, time_series, baseline_time_series)
self.absolute_threshold_value_upper = absolute_threshold_value_upper
self.absolute_threshold_value_lower = absolute_threshold_value_lower
if not self.absolute_threshold_va... | Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series. | AbsoluteThreshold | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbsoluteThreshold:
"""Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series."""
def __init__(self, time_series, absolute_threshold_value_upper=None, absolute_threshold_value_lower=None, baseline_time_series=None):
... | stack_v2_sparse_classes_36k_train_021569 | 2,914 | permissive | [
{
"docstring": "Initialize algorithm, check all required args are present :param time_series: The current time series dict to run anomaly detection on :param absolute_threshold_value_upper: Time series values above this are considered anomalies :param absolute_threshold_value_lower: Time series values below thi... | 2 | stack_v2_sparse_classes_30k_train_010425 | Implement the Python class `AbsoluteThreshold` described below.
Class description:
Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series.
Method signatures and docstrings:
- def __init__(self, time_series, absolute_threshold_value_upper=None,... | Implement the Python class `AbsoluteThreshold` described below.
Class description:
Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series.
Method signatures and docstrings:
- def __init__(self, time_series, absolute_threshold_value_upper=None,... | b0dc7df586394578d29389d306223523dc99c827 | <|skeleton|>
class AbsoluteThreshold:
"""Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series."""
def __init__(self, time_series, absolute_threshold_value_upper=None, absolute_threshold_value_lower=None, baseline_time_series=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbsoluteThreshold:
"""Anomalies are those data points that are above a pre-specified threshold value. This algorithm does not take baseline time series."""
def __init__(self, time_series, absolute_threshold_value_upper=None, absolute_threshold_value_lower=None, baseline_time_series=None):
"""Init... | the_stack_v2_python_sparse | src/luminol/algorithms/anomaly_detector_algorithms/absolute_threshold.py | linkedin/luminol | train | 1,159 |
2393e8acec7b61e9ad995fd1fa4a73c5336590ee | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('nhuang54_wud', 'nhuang54_wud')\ncrashLocations = repo.nhuang54_wud.crashRecord.find()\nlightLocations = repo.nhuang54_wud.streetlightLocation.find()\nbikeCrashes = [t for t in crashLocations if t['\"mode... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('nhuang54_wud', 'nhuang54_wud')
crashLocations = repo.nhuang54_wud.crashRecord.find()
lightLocations = repo.nhuang54_wud.streetlightLocation.find()... | transformBikeCrash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transformBikeCrash:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing every... | stack_v2_sparse_classes_36k_train_021570 | 5,979 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_020802 | Implement the Python class `transformBikeCrash` described below.
Class description:
Implement the transformBikeCrash class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTi... | Implement the Python class `transformBikeCrash` described below.
Class description:
Implement the transformBikeCrash class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTi... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class transformBikeCrash:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing every... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class transformBikeCrash:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('nhuang54_wud', 'nhuang54_wud')
... | the_stack_v2_python_sparse | nhuang54_wud/transformBikeCrash.py | maximega/course-2019-spr-proj | train | 2 | |
db0598b87c7494d6ba2dfd3531278ed6be57fd5a | [
"if isinstance(key, int):\n return Setting(key)\nif key not in Setting._member_map_:\n return extend_enum(Setting, key, default)\nreturn Setting[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 10 <= value <= 15:\n ... | <|body_start_0|>
if isinstance(key, int):
return Setting(key)
if key not in Setting._member_map_:
return extend_enum(Setting, key, default)
return Setting[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
ra... | [Setting] HTTP/2 Settings | Setting | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Setting:
"""[Setting] HTTP/2 Settings"""
def get(key: 'int | str', default: 'int'=-1) -> 'Setting':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int')... | stack_v2_sparse_classes_36k_train_021571 | 3,148 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'Setting'"
},
{
"docstring": "Lookup function used when value is not found. Arg... | 2 | stack_v2_sparse_classes_30k_train_019630 | Implement the Python class `Setting` described below.
Class description:
[Setting] HTTP/2 Settings
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Setting': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- ... | Implement the Python class `Setting` described below.
Class description:
[Setting] HTTP/2 Settings
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Setting': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- ... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class Setting:
"""[Setting] HTTP/2 Settings"""
def get(key: 'int | str', default: 'int'=-1) -> 'Setting':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int')... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Setting:
"""[Setting] HTTP/2 Settings"""
def get(key: 'int | str', default: 'int'=-1) -> 'Setting':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return Setting(key)
... | the_stack_v2_python_sparse | pcapkit/const/http/setting.py | JarryShaw/PyPCAPKit | train | 204 |
2f2dfb0b8031d58b5d6d87465367928fd01a259d | [
"try:\n user_preferences = get_user_preferences(request.user, username=username)\nexcept UserNotAuthorized:\n return Response(status=status.HTTP_403_FORBIDDEN)\nexcept UserNotFound:\n return Response(status=status.HTTP_404_NOT_FOUND)\nreturn Response(user_preferences)",
"if not request.data or not getatt... | <|body_start_0|>
try:
user_preferences = get_user_preferences(request.user, username=username)
except UserNotAuthorized:
return Response(status=status.HTTP_403_FORBIDDEN)
except UserNotFound:
return Response(status=status.HTTP_404_NOT_FOUND)
return Res... | **Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /api/user/v1/preferences/{username}/ with cont... | PreferencesView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferencesView:
"""**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /ap... | stack_v2_sparse_classes_36k_train_021572 | 11,020 | permissive | [
{
"docstring": "GET /api/user/v1/preferences/{username}/",
"name": "get",
"signature": "def get(self, request, username)"
},
{
"docstring": "PATCH /api/user/v1/preferences/{username}/",
"name": "patch",
"signature": "def patch(self, request, username)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015153 | Implement the Python class `PreferencesView` described below.
Class description:
**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/us... | Implement the Python class `PreferencesView` described below.
Class description:
**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/us... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class PreferencesView:
"""**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /ap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreferencesView:
"""**Use Cases** Get or update the user's preference information. Updates are only supported through merge patch. Preference values of null in a patch request are treated as requests to remove the preference. **Example Requests** GET /api/user/v1/preferences/{username}/ PATCH /api/user/v1/pre... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/user_api/preferences/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
823a0af036affbb935f7b75a2dcbe76d2cf04691 | [
"if isinstance(self._c, np.ndarray):\n return self._c\nelse:\n return self._c * np.ones((self.nz, self.nx), dtype=np.complex128)",
"if not hasattr(self, '_mgHelper'):\n sc = {key: self.systemConfig[key] for key in self.systemConfig}\n sc['freqs'] = self.freqs\n self._mgHelper = MultiGridHelper(sc)\... | <|body_start_0|>
if isinstance(self._c, np.ndarray):
return self._c
else:
return self._c * np.ones((self.nz, self.nx), dtype=np.complex128)
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_mgHelper'):
sc = {key: self.systemConfig[key] for key in self.sy... | Wrapper to carry out forward-modelling using the stored discretization over a series of frequencies, with multiple computation grids based on a target number of gridpoints per wavelength. | MultiGridMultiFreq | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiGridMultiFreq:
"""Wrapper to carry out forward-modelling using the stored discretization over a series of frequencies, with multiple computation grids based on a target number of gridpoints per wavelength."""
def c(self):
"""Complex wave velocity"""
<|body_0|>
def m... | stack_v2_sparse_classes_36k_train_021573 | 16,781 | permissive | [
{
"docstring": "Complex wave velocity",
"name": "c",
"signature": "def c(self)"
},
{
"docstring": "MultiGridHelper instance",
"name": "mgHelper",
"signature": "def mgHelper(self)"
},
{
"docstring": "Updates for frequency subProblems",
"name": "spUpdates",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_008750 | Implement the Python class `MultiGridMultiFreq` described below.
Class description:
Wrapper to carry out forward-modelling using the stored discretization over a series of frequencies, with multiple computation grids based on a target number of gridpoints per wavelength.
Method signatures and docstrings:
- def c(self... | Implement the Python class `MultiGridMultiFreq` described below.
Class description:
Wrapper to carry out forward-modelling using the stored discretization over a series of frequencies, with multiple computation grids based on a target number of gridpoints per wavelength.
Method signatures and docstrings:
- def c(self... | e4228be3947021f2b983c919c51bb1f67df90eb0 | <|skeleton|>
class MultiGridMultiFreq:
"""Wrapper to carry out forward-modelling using the stored discretization over a series of frequencies, with multiple computation grids based on a target number of gridpoints per wavelength."""
def c(self):
"""Complex wave velocity"""
<|body_0|>
def m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiGridMultiFreq:
"""Wrapper to carry out forward-modelling using the stored discretization over a series of frequencies, with multiple computation grids based on a target number of gridpoints per wavelength."""
def c(self):
"""Complex wave velocity"""
if isinstance(self._c, np.ndarray)... | the_stack_v2_python_sparse | zephyr/backend/distributors.py | uwoseis/zephyr | train | 18 |
3a9311c2ce6c3cac78b4ed40715d2210129273dd | [
"self.workflow = kwargs.pop('workflow', None)\nsuper().__init__(data, *args, **kwargs)\nself.fields['name'].label = _('View name')\nself.fields['description_text'].label = _('View Description')\nself.fields['columns'].label = _('Columns to show')\nself.fields['formula'].required = False\nself.fields['formula'].widg... | <|body_start_0|>
self.workflow = kwargs.pop('workflow', None)
super().__init__(data, *args, **kwargs)
self.fields['name'].label = _('View name')
self.fields['description_text'].label = _('View Description')
self.fields['columns'].label = _('Columns to show')
self.fields['... | Form to add a view. | ViewAddForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewAddForm:
"""Form to add a view."""
def __init__(self, data, *args, **kwargs):
"""Initialize the object, store the workflow and rename fields."""
<|body_0|>
def clean(self):
"""Check if three properties in the form. 1) Number of columns is not empty 2) There i... | stack_v2_sparse_classes_36k_train_021574 | 2,360 | permissive | [
{
"docstring": "Initialize the object, store the workflow and rename fields.",
"name": "__init__",
"signature": "def __init__(self, data, *args, **kwargs)"
},
{
"docstring": "Check if three properties in the form. 1) Number of columns is not empty 2) There is at least one key column 3) There is ... | 2 | stack_v2_sparse_classes_30k_train_009003 | Implement the Python class `ViewAddForm` described below.
Class description:
Form to add a view.
Method signatures and docstrings:
- def __init__(self, data, *args, **kwargs): Initialize the object, store the workflow and rename fields.
- def clean(self): Check if three properties in the form. 1) Number of columns is... | Implement the Python class `ViewAddForm` described below.
Class description:
Form to add a view.
Method signatures and docstrings:
- def __init__(self, data, *args, **kwargs): Initialize the object, store the workflow and rename fields.
- def clean(self): Check if three properties in the form. 1) Number of columns is... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class ViewAddForm:
"""Form to add a view."""
def __init__(self, data, *args, **kwargs):
"""Initialize the object, store the workflow and rename fields."""
<|body_0|>
def clean(self):
"""Check if three properties in the form. 1) Number of columns is not empty 2) There i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewAddForm:
"""Form to add a view."""
def __init__(self, data, *args, **kwargs):
"""Initialize the object, store the workflow and rename fields."""
self.workflow = kwargs.pop('workflow', None)
super().__init__(data, *args, **kwargs)
self.fields['name'].label = _('View nam... | the_stack_v2_python_sparse | ontask/table/forms.py | LucasFranciscoCorreia/ontask_b | train | 0 |
326e9dc664a17bc35cf07a23e0cf61b8bc552c25 | [
"if not matrix or not matrix[0]:\n return False\nm, n = (len(matrix), len(matrix[0]))\n\ndef binary_search(matrix, target, start, vertical):\n low = start\n high = len(matrix[0]) - 1 if vertical else len(matrix) - 1\n while low <= high:\n mid = low + high >> 1\n if vertical:\n i... | <|body_start_0|>
if not matrix or not matrix[0]:
return False
m, n = (len(matrix), len(matrix[0]))
def binary_search(matrix, target, start, vertical):
low = start
high = len(matrix[0]) - 1 if vertical else len(matrix) - 1
while low <= high:
... | Solution | [
"BSD-3-Clause"
] | 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 searchMatrix_v2(self, matrix, target):
"""Divide and conquer"""
<|body_1|>
def searchMatrix_v3(self, matrix, target):
... | stack_v2_sparse_classes_36k_train_021575 | 3,598 | permissive | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "Divide and conquer",
"name": "searchMatrix_v2",
"signature": "def searchMatrix_v2(self, matrix, target)"
},
... | 3 | null | 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 searchMatrix_v2(self, matrix, target): Divide and conquer
- def searchM... | 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 searchMatrix_v2(self, matrix, target): Divide and conquer
- def searchM... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_v2(self, matrix, target):
"""Divide and conquer"""
<|body_1|>
def searchMatrix_v3(self, matrix, target):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix or not matrix[0]:
return False
m, n = (len(matrix), len(matrix[0]))
def binary_search(matrix, target, start, vertical):
lo... | the_stack_v2_python_sparse | Leetcode/Intermediate/Sort and search/240_Search_a_2D_Matrix_II.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
44715e3c84e8f0823843e4f73902ded632be3255 | [
"super(VAE, self).__init__(name=name)\nself._encoder = encoder_net\nself._decoder = decoder_net\nself._latent_posterior_fn = posterior_fn\nself._output_dist_fn = output_dist_fn\nwith self._enter_variable_scope():\n self._loc = snt.Linear(latent_dimension)\n self._scale = snt.Linear(latent_dimension)\n self... | <|body_start_0|>
super(VAE, self).__init__(name=name)
self._encoder = encoder_net
self._decoder = decoder_net
self._latent_posterior_fn = posterior_fn
self._output_dist_fn = output_dist_fn
with self._enter_variable_scope():
self._loc = snt.Linear(latent_dimens... | Variational Autoencoder (VAE) as first introduced by Kingma and Welling (2014) Note: Make sure learning rate is inversely correlated with data size. If you're getting myserious crashes, try an order of magnitude smaller. Attributes: latent_prior (tfd.Distribution): Prior latent distribution. latent_posterior (tfd Distr... | VAE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VAE:
"""Variational Autoencoder (VAE) as first introduced by Kingma and Welling (2014) Note: Make sure learning rate is inversely correlated with data size. If you're getting myserious crashes, try an order of magnitude smaller. Attributes: latent_prior (tfd.Distribution): Prior latent distributi... | stack_v2_sparse_classes_36k_train_021576 | 7,052 | no_license | [
{
"docstring": "Initializes a Variational Autoencoder (VAE) as a callable. The expected range of input pixels (this class mostly expects image inputs) is [0,1]. Example: A small VAE:: import sonnet as snt import tensorflow as tf import sounds_deep.contrib.distributions.discretized_logistic as discretized_logist... | 3 | stack_v2_sparse_classes_30k_train_021535 | Implement the Python class `VAE` described below.
Class description:
Variational Autoencoder (VAE) as first introduced by Kingma and Welling (2014) Note: Make sure learning rate is inversely correlated with data size. If you're getting myserious crashes, try an order of magnitude smaller. Attributes: latent_prior (tfd... | Implement the Python class `VAE` described below.
Class description:
Variational Autoencoder (VAE) as first introduced by Kingma and Welling (2014) Note: Make sure learning rate is inversely correlated with data size. If you're getting myserious crashes, try an order of magnitude smaller. Attributes: latent_prior (tfd... | 85baa9f052872194f2383d0fdf4d4d86322aada2 | <|skeleton|>
class VAE:
"""Variational Autoencoder (VAE) as first introduced by Kingma and Welling (2014) Note: Make sure learning rate is inversely correlated with data size. If you're getting myserious crashes, try an order of magnitude smaller. Attributes: latent_prior (tfd.Distribution): Prior latent distributi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VAE:
"""Variational Autoencoder (VAE) as first introduced by Kingma and Welling (2014) Note: Make sure learning rate is inversely correlated with data size. If you're getting myserious crashes, try an order of magnitude smaller. Attributes: latent_prior (tfd.Distribution): Prior latent distribution. latent_po... | the_stack_v2_python_sparse | sounds_deep/contrib/models/vae.py | DrKwint/sounds-deep | train | 2 |
beb38cc997755610caf12d1abca076ead5e0cf6b | [
"super().__init__()\nif backbone in ['resnet18', 'resnet34']:\n max_channels = 512\nelif backbone in ['resnet50', 'resnet101']:\n max_channels = 2048\nelse:\n raise ValueError(f'unknown backbone: {backbone}.')\nkwargs = {}\nif backbone_pretrained:\n kwargs = {'weights': getattr(torchvision.models, f'Res... | <|body_start_0|>
super().__init__()
if backbone in ['resnet18', 'resnet34']:
max_channels = 512
elif backbone in ['resnet50', 'resnet101']:
max_channels = 2048
else:
raise ValueError(f'unknown backbone: {backbone}.')
kwargs = {}
if back... | Foreground-Aware Relation Network (FarSeg). This model can be used for binary- or multi-class object segmentation, such as building, road, ship, and airplane segmentation. It can be also extended as a change detection model. It features a foreground-scene relation module to model the relation between scene embedding, o... | FarSeg | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FarSeg:
"""Foreground-Aware Relation Network (FarSeg). This model can be used for binary- or multi-class object segmentation, such as building, road, ship, and airplane segmentation. It can be also extended as a change detection model. It features a foreground-scene relation module to model the r... | stack_v2_sparse_classes_36k_train_021577 | 8,033 | permissive | [
{
"docstring": "Initialize a new FarSeg model. Args: backbone: name of ResNet backbone, one of [\"resnet18\", \"resnet34\", \"resnet50\", \"resnet101\"] classes: number of output segmentation classes backbone_pretrained: whether to use pretrained weight for backbone",
"name": "__init__",
"signature": "d... | 2 | null | Implement the Python class `FarSeg` described below.
Class description:
Foreground-Aware Relation Network (FarSeg). This model can be used for binary- or multi-class object segmentation, such as building, road, ship, and airplane segmentation. It can be also extended as a change detection model. It features a foregrou... | Implement the Python class `FarSeg` described below.
Class description:
Foreground-Aware Relation Network (FarSeg). This model can be used for binary- or multi-class object segmentation, such as building, road, ship, and airplane segmentation. It can be also extended as a change detection model. It features a foregrou... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class FarSeg:
"""Foreground-Aware Relation Network (FarSeg). This model can be used for binary- or multi-class object segmentation, such as building, road, ship, and airplane segmentation. It can be also extended as a change detection model. It features a foreground-scene relation module to model the r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FarSeg:
"""Foreground-Aware Relation Network (FarSeg). This model can be used for binary- or multi-class object segmentation, such as building, road, ship, and airplane segmentation. It can be also extended as a change detection model. It features a foreground-scene relation module to model the relation betwe... | the_stack_v2_python_sparse | torchgeo/models/farseg.py | microsoft/torchgeo | train | 1,724 |
ffc6e5981af29a5bfa77a0890c1b5811e52b11ff | [
"self.words = words\nself.root = TrieNode()\nself.root_inv = TrieNode()\nfor i, word in enumerate(words):\n n = self.root\n for j, c in enumerate(word):\n n.index.add(i)\n ind = ord(c) - ord('a')\n if n.memo[ind] is None:\n n.memo[ind] = TrieNode()\n n = n.memo[ind]\n ... | <|body_start_0|>
self.words = words
self.root = TrieNode()
self.root_inv = TrieNode()
for i, word in enumerate(words):
n = self.root
for j, c in enumerate(word):
n.index.add(i)
ind = ord(c) - ord('a')
if n.memo[ind] ... | WordFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.words = words
self.root = Tri... | stack_v2_sparse_classes_36k_train_021578 | 2,698 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type prefix: str :type suffix: str :rtype: int",
"name": "f",
"signature": "def f(self, prefix, suffix)"
}
] | 2 | null | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
<|skeleton|>
class WordFilter:
def __in... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
self.words = words
self.root = TrieNode()
self.root_inv = TrieNode()
for i, word in enumerate(words):
n = self.root
for j, c in enumerate(word):
n.index.add(i)
... | the_stack_v2_python_sparse | python/leetcode/745_prefix_suffix_search.py | Levintsky/topcoder | train | 0 | |
41aa3625acb32f9245511111fa5308a800a24d0e | [
"if category.full_super_categories():\n return Category.join([getattr(cat, cls._functor_category)() for cat in category.full_super_categories()])\nelse:\n functor_category = getattr(category.__class__, cls._functor_category)\n if isinstance(functor_category, type) and issubclass(functor_category, Category)... | <|body_start_0|>
if category.full_super_categories():
return Category.join([getattr(cat, cls._functor_category)() for cat in category.full_super_categories()])
else:
functor_category = getattr(category.__class__, cls._functor_category)
if isinstance(functor_category, ... | HomsetsCategory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomsetsCategory:
def default_super_categories(cls, category):
"""Return the default super categories of ``category.Homsets()``. INPUT: - ``cls`` -- the category class for the functor `F` - ``category`` -- a category `Cat` OUTPUT: a category As for the other functorial constructions, if `... | stack_v2_sparse_classes_36k_train_021579 | 10,999 | no_license | [
{
"docstring": "Return the default super categories of ``category.Homsets()``. INPUT: - ``cls`` -- the category class for the functor `F` - ``category`` -- a category `Cat` OUTPUT: a category As for the other functorial constructions, if ``category`` implements a nested ``Homsets`` class, this method is used in... | 3 | null | Implement the Python class `HomsetsCategory` described below.
Class description:
Implement the HomsetsCategory class.
Method signatures and docstrings:
- def default_super_categories(cls, category): Return the default super categories of ``category.Homsets()``. INPUT: - ``cls`` -- the category class for the functor `... | Implement the Python class `HomsetsCategory` described below.
Class description:
Implement the HomsetsCategory class.
Method signatures and docstrings:
- def default_super_categories(cls, category): Return the default super categories of ``category.Homsets()``. INPUT: - ``cls`` -- the category class for the functor `... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class HomsetsCategory:
def default_super_categories(cls, category):
"""Return the default super categories of ``category.Homsets()``. INPUT: - ``cls`` -- the category class for the functor `F` - ``category`` -- a category `Cat` OUTPUT: a category As for the other functorial constructions, if `... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomsetsCategory:
def default_super_categories(cls, category):
"""Return the default super categories of ``category.Homsets()``. INPUT: - ``cls`` -- the category class for the functor `F` - ``category`` -- a category `Cat` OUTPUT: a category As for the other functorial constructions, if ``category`` im... | the_stack_v2_python_sparse | sage/src/sage/categories/homsets.py | bopopescu/geosci | train | 0 | |
941e98ff07461e22740d71915559cf01b78e7686 | [
"self.enter_mtz()\nself.myClick(self.find_element('累计奖金', *self.TOTAL_MONEY_ID))\nself.check_bill()",
"self.enter_mtz()\nself.myClick(self.find_element('累计奖金', *self.TOTAL_MONEY_ID))\nself.check_mtz_rhz()",
"self.enter_mtz()\nself.myClick(self.find_element('累计奖金', *self.TOTAL_MONEY_ID))\nself.myClick(self.swipe... | <|body_start_0|>
self.enter_mtz()
self.myClick(self.find_element('累计奖金', *self.TOTAL_MONEY_ID))
self.check_bill()
<|end_body_0|>
<|body_start_1|>
self.enter_mtz()
self.myClick(self.find_element('累计奖金', *self.TOTAL_MONEY_ID))
self.check_mtz_rhz()
<|end_body_1|>
<|body_st... | TotalMoney | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TotalMoney:
def test_mtz_bill(self):
"""萌团长_累计奖金_账单"""
<|body_0|>
def test_mtz_rhz(self):
"""萌团长_累计奖金_萌团长如何赚"""
<|body_1|>
def test_tx_buy_gift(self):
"""萌团长_累计奖金_购买礼包可提现_立即购买"""
<|body_2|>
def test_kd_income(self):
"""萌团长_[总... | stack_v2_sparse_classes_36k_train_021580 | 3,050 | no_license | [
{
"docstring": "萌团长_累计奖金_账单",
"name": "test_mtz_bill",
"signature": "def test_mtz_bill(self)"
},
{
"docstring": "萌团长_累计奖金_萌团长如何赚",
"name": "test_mtz_rhz",
"signature": "def test_mtz_rhz(self)"
},
{
"docstring": "萌团长_累计奖金_购买礼包可提现_立即购买",
"name": "test_tx_buy_gift",
"signatu... | 4 | null | Implement the Python class `TotalMoney` described below.
Class description:
Implement the TotalMoney class.
Method signatures and docstrings:
- def test_mtz_bill(self): 萌团长_累计奖金_账单
- def test_mtz_rhz(self): 萌团长_累计奖金_萌团长如何赚
- def test_tx_buy_gift(self): 萌团长_累计奖金_购买礼包可提现_立即购买
- def test_kd_income(self): 萌团长_[总收入|开店收入|萌... | Implement the Python class `TotalMoney` described below.
Class description:
Implement the TotalMoney class.
Method signatures and docstrings:
- def test_mtz_bill(self): 萌团长_累计奖金_账单
- def test_mtz_rhz(self): 萌团长_累计奖金_萌团长如何赚
- def test_tx_buy_gift(self): 萌团长_累计奖金_购买礼包可提现_立即购买
- def test_kd_income(self): 萌团长_[总收入|开店收入|萌... | b2066139eb0723eff69d971589b283b4b776c84c | <|skeleton|>
class TotalMoney:
def test_mtz_bill(self):
"""萌团长_累计奖金_账单"""
<|body_0|>
def test_mtz_rhz(self):
"""萌团长_累计奖金_萌团长如何赚"""
<|body_1|>
def test_tx_buy_gift(self):
"""萌团长_累计奖金_购买礼包可提现_立即购买"""
<|body_2|>
def test_kd_income(self):
"""萌团长_[总... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TotalMoney:
def test_mtz_bill(self):
"""萌团长_累计奖金_账单"""
self.enter_mtz()
self.myClick(self.find_element('累计奖金', *self.TOTAL_MONEY_ID))
self.check_bill()
def test_mtz_rhz(self):
"""萌团长_累计奖金_萌团长如何赚"""
self.enter_mtz()
self.myClick(self.find_element('累计... | the_stack_v2_python_sparse | TestCase/4_5/TC_Meng_TZ/test_total_money.py | testerSunshine/auto_md | train | 4 | |
95cad6bc97e4b68f43025f2b626ba23bd1422c78 | [
"self.name = name\nself.habitat = habitat\nself.weight = weight",
"if self.name == 'Toucan':\n print('Squawk!')\nelse:\n print('Tweet')",
"if self.habitat == 'South America':\n result = 'fruit'\nelif self.habitat == 'North America':\n result = 'bugs'\nelse:\n result = 'fish'\nreturn result"
] | <|body_start_0|>
self.name = name
self.habitat = habitat
self.weight = weight
<|end_body_0|>
<|body_start_1|>
if self.name == 'Toucan':
print('Squawk!')
else:
print('Tweet')
<|end_body_1|>
<|body_start_2|>
if self.habitat == 'South America':
... | Bird | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bird:
def __init__(self, name, habitat, weight):
"""Initialize bird object properties"""
<|body_0|>
def talk(self):
"""Print out sound made by bird"""
<|body_1|>
def diet(self):
"""Define diet of bird based on geography"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_021581 | 1,160 | no_license | [
{
"docstring": "Initialize bird object properties",
"name": "__init__",
"signature": "def __init__(self, name, habitat, weight)"
},
{
"docstring": "Print out sound made by bird",
"name": "talk",
"signature": "def talk(self)"
},
{
"docstring": "Define diet of bird based on geograp... | 3 | stack_v2_sparse_classes_30k_train_000165 | Implement the Python class `Bird` described below.
Class description:
Implement the Bird class.
Method signatures and docstrings:
- def __init__(self, name, habitat, weight): Initialize bird object properties
- def talk(self): Print out sound made by bird
- def diet(self): Define diet of bird based on geography | Implement the Python class `Bird` described below.
Class description:
Implement the Bird class.
Method signatures and docstrings:
- def __init__(self, name, habitat, weight): Initialize bird object properties
- def talk(self): Print out sound made by bird
- def diet(self): Define diet of bird based on geography
<|sk... | 9e700d718bac6be76b54aabec4eb775e11dd5a06 | <|skeleton|>
class Bird:
def __init__(self, name, habitat, weight):
"""Initialize bird object properties"""
<|body_0|>
def talk(self):
"""Print out sound made by bird"""
<|body_1|>
def diet(self):
"""Define diet of bird based on geography"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bird:
def __init__(self, name, habitat, weight):
"""Initialize bird object properties"""
self.name = name
self.habitat = habitat
self.weight = weight
def talk(self):
"""Print out sound made by bird"""
if self.name == 'Toucan':
print('Squawk!')
... | the_stack_v2_python_sparse | ch21/birds.py | Johanson20/Python4Geoprocessing | train | 0 | |
3aafd31696c766016ba8649ba40ce6bde1c3e019 | [
"self.world = world\nself.relative_robot_polygon = self.world._relative_robot_polygon\nself.robot_pose = start\nself.resolution = resolution\nself.obstacles_array = self.world.get_obstacles_array()\nlimits = self.world.get_limits()\nself.min_bound = min(limits)\nself.max_bound = max(limits)\nself.rrt = RrtStar(0.1,... | <|body_start_0|>
self.world = world
self.relative_robot_polygon = self.world._relative_robot_polygon
self.robot_pose = start
self.resolution = resolution
self.obstacles_array = self.world.get_obstacles_array()
limits = self.world.get_limits()
self.min_bound = min(... | RRTVisualizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RRTVisualizer:
def __init__(self, world, resolution, start, goal):
"""Initialize the map visualizer Args: world: the description of the map in which the robot evolves resolution: resolution of the visualizer start: starting pose [x,y,theta] for the RRT* search goal: goal pose [x,y,theta]... | stack_v2_sparse_classes_36k_train_021582 | 2,887 | no_license | [
{
"docstring": "Initialize the map visualizer Args: world: the description of the map in which the robot evolves resolution: resolution of the visualizer start: starting pose [x,y,theta] for the RRT* search goal: goal pose [x,y,theta] for the RRT* search",
"name": "__init__",
"signature": "def __init__(... | 3 | stack_v2_sparse_classes_30k_train_008935 | Implement the Python class `RRTVisualizer` described below.
Class description:
Implement the RRTVisualizer class.
Method signatures and docstrings:
- def __init__(self, world, resolution, start, goal): Initialize the map visualizer Args: world: the description of the map in which the robot evolves resolution: resolut... | Implement the Python class `RRTVisualizer` described below.
Class description:
Implement the RRTVisualizer class.
Method signatures and docstrings:
- def __init__(self, world, resolution, start, goal): Initialize the map visualizer Args: world: the description of the map in which the robot evolves resolution: resolut... | 4f2f48130ec3ae0af1b15d6d2df7da3cb339178d | <|skeleton|>
class RRTVisualizer:
def __init__(self, world, resolution, start, goal):
"""Initialize the map visualizer Args: world: the description of the map in which the robot evolves resolution: resolution of the visualizer start: starting pose [x,y,theta] for the RRT* search goal: goal pose [x,y,theta]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RRTVisualizer:
def __init__(self, world, resolution, start, goal):
"""Initialize the map visualizer Args: world: the description of the map in which the robot evolves resolution: resolution of the visualizer start: starting pose [x,y,theta] for the RRT* search goal: goal pose [x,y,theta] for the RRT* ... | the_stack_v2_python_sparse | python_code/projetS7_lib/ancien_code/rrt_visualizer.py | TariqBerrada/Robot-Navigation | train | 0 | |
d3c0e07290e3137d853a5ffcb16f63b2fa518d6a | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"direction = choice([1, -1])\ndistance = choice([0, 1, 2, 3, 4])\n'\\n 将移动方向乘以移动距离,以确定沿 x 和 y 轴移动的距离。\\n 如果 x_step 为正,将向右移动,为负将向左移动,而为零将垂直移动;\\n 如果 y_step 为正,就意味着向上移动,为负意味着向下移动,而为零意味着水平移动。\\n 如果 x_step 和 y_step... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
'\n 将移动方向乘以移动距离,以确定沿 x 和 y 轴移动的距离。\n 如果 x_step 为正,将向右移动,为负将向左移动,而为零将垂直移动;\... | 生成一个随机漫步数据的类 | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""生成一个随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def get_setp(self):
"""简化 方法fill_walk 中的 x_step 和 y_step 的过程"""
<|body_1|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k_train_021583 | 2,673 | no_license | [
{
"docstring": "初始化随机漫步的属性",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "简化 方法fill_walk 中的 x_step 和 y_step 的过程",
"name": "get_setp",
"signature": "def get_setp(self)"
},
{
"docstring": "计算随机漫步包含的所有点",
"name": "fill_walk",
"sig... | 3 | null | Implement the Python class `RandomWalk` described below.
Class description:
生成一个随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def get_setp(self): 简化 方法fill_walk 中的 x_step 和 y_step 的过程
- def fill_walk(self): 计算随机漫步包含的所有点 | Implement the Python class `RandomWalk` described below.
Class description:
生成一个随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def get_setp(self): 简化 方法fill_walk 中的 x_step 和 y_step 的过程
- def fill_walk(self): 计算随机漫步包含的所有点
<|skeleton|>
class RandomWalk:
"""生成一个随机漫步数据... | b514b3d7baa62fa7b801d26ff49266f02cb9cbd2 | <|skeleton|>
class RandomWalk:
"""生成一个随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def get_setp(self):
"""简化 方法fill_walk 中的 x_step 和 y_step 的过程"""
<|body_1|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""生成一个随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_setp(self):
"""简化 方法fill_walk 中的 x_step 和 y_step 的过程"""
direction = choice([1, -1])
... | the_stack_v2_python_sparse | Python:从入门到实践/从入门到实践代码/第15章 生成数据/15.3 随机漫步/random_walk.py | pangfeiyo/PythonLearn | train | 0 |
85310979df1a365a755a504e544a2a1f779fd344 | [
"self.particles = particles\nself.time = 0.0\nself.boundary = boundary\nself.g = g",
"self.time += dt\nself.particles.state[:, :2] += self.particles.state[:, 2:] * dt\ndist = squareform(pdist(self.particles.state[:, :2]))\ni, j = np.where(dist < 2 * self.particles.size)\ncollided = i < j\ni = i[collided]\nj = j[c... | <|body_start_0|>
self.particles = particles
self.time = 0.0
self.boundary = boundary
self.g = g
<|end_body_0|>
<|body_start_1|>
self.time += dt
self.particles.state[:, :2] += self.particles.state[:, 2:] * dt
dist = squareform(pdist(self.particles.state[:, :2]))
... | class that implements the basic fiels that contain particles and its properties and how it evolves in time. | Arena | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arena:
"""class that implements the basic fiels that contain particles and its properties and how it evolves in time."""
def __init__(self, particles, boundary, g=9.8):
"""particles : instance of Particles class boundary : boundary of Arena"""
<|body_0|>
def proceed(self... | stack_v2_sparse_classes_36k_train_021584 | 7,012 | permissive | [
{
"docstring": "particles : instance of Particles class boundary : boundary of Arena",
"name": "__init__",
"signature": "def __init__(self, particles, boundary, g=9.8)"
},
{
"docstring": "Proceed the Arena from time t to t + dt seconds Change the state of the particles in the arena accouding to ... | 2 | stack_v2_sparse_classes_30k_train_005939 | Implement the Python class `Arena` described below.
Class description:
class that implements the basic fiels that contain particles and its properties and how it evolves in time.
Method signatures and docstrings:
- def __init__(self, particles, boundary, g=9.8): particles : instance of Particles class boundary : boun... | Implement the Python class `Arena` described below.
Class description:
class that implements the basic fiels that contain particles and its properties and how it evolves in time.
Method signatures and docstrings:
- def __init__(self, particles, boundary, g=9.8): particles : instance of Particles class boundary : boun... | 46818eb405c283c563231d1816eab1f60f39b898 | <|skeleton|>
class Arena:
"""class that implements the basic fiels that contain particles and its properties and how it evolves in time."""
def __init__(self, particles, boundary, g=9.8):
"""particles : instance of Particles class boundary : boundary of Arena"""
<|body_0|>
def proceed(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Arena:
"""class that implements the basic fiels that contain particles and its properties and how it evolves in time."""
def __init__(self, particles, boundary, g=9.8):
"""particles : instance of Particles class boundary : boundary of Arena"""
self.particles = particles
self.time ... | the_stack_v2_python_sparse | StatisticalMechanics/brownian_motion.py | phy6boy/pyphy6 | train | 0 |
3fad24571cad04f19729b515c085fd97987488a5 | [
"hdulist = pyfits.open(path)\nif len(hdulist) != 1:\n raise Exception(\"Only one HDU object supported yet. Can't read '{0}'.\".format(path))\ncube = hdulist[0].data\nheader = dict(hdulist[0].header.items())\nheader['path'] = path\nhdulist.close()\nreturn Image(data_type='scalar', metadata=header, data=cube)",
... | <|body_start_0|>
hdulist = pyfits.open(path)
if len(hdulist) != 1:
raise Exception("Only one HDU object supported yet. Can't read '{0}'.".format(path))
cube = hdulist[0].data
header = dict(hdulist[0].header.items())
header['path'] = path
hdulist.close()
... | Define the Fits loader. | FITS | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FITS:
"""Define the Fits loader."""
def load(self, path):
"""A method that load the image data and associated metadata. Parameters ---------- path: str the path to the image to be loaded. Returns ------- image: Image the loaded image."""
<|body_0|>
def save(self, image, ... | stack_v2_sparse_classes_36k_train_021585 | 2,174 | permissive | [
{
"docstring": "A method that load the image data and associated metadata. Parameters ---------- path: str the path to the image to be loaded. Returns ------- image: Image the loaded image.",
"name": "load",
"signature": "def load(self, path)"
},
{
"docstring": "A method that save the image data... | 2 | stack_v2_sparse_classes_30k_val_000766 | Implement the Python class `FITS` described below.
Class description:
Define the Fits loader.
Method signatures and docstrings:
- def load(self, path): A method that load the image data and associated metadata. Parameters ---------- path: str the path to the image to be loaded. Returns ------- image: Image the loaded... | Implement the Python class `FITS` described below.
Class description:
Define the Fits loader.
Method signatures and docstrings:
- def load(self, path): A method that load the image data and associated metadata. Parameters ---------- path: str the path to the image to be loaded. Returns ------- image: Image the loaded... | d841ba00e903fe0900209f2a33d660ca270c9480 | <|skeleton|>
class FITS:
"""Define the Fits loader."""
def load(self, path):
"""A method that load the image data and associated metadata. Parameters ---------- path: str the path to the image to be loaded. Returns ------- image: Image the loaded image."""
<|body_0|>
def save(self, image, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FITS:
"""Define the Fits loader."""
def load(self, path):
"""A method that load the image data and associated metadata. Parameters ---------- path: str the path to the image to be loaded. Returns ------- image: Image the loaded image."""
hdulist = pyfits.open(path)
if len(hdulist)... | the_stack_v2_python_sparse | pysap/base/loaders/fits.py | CEA-COSMIC/pysap | train | 51 |
0ae6229273ce5fbbde426a7c5fcdd788f95e287c | [
"self.factory = RequestFactory()\nself.user = User.objects.create(username='Abdullah', email='abd@gmail.com', password=\"Abdullah's passwd\")\nself.trip = Trip.objects.create(title='Summer Break', passenger=self.user, arrive_at='BOS', terminal='G')",
"self.trip.save()\nrequest = self.factory.get('trips:all-trips'... | <|body_start_0|>
self.factory = RequestFactory()
self.user = User.objects.create(username='Abdullah', email='abd@gmail.com', password="Abdullah's passwd")
self.trip = Trip.objects.create(title='Summer Break', passenger=self.user, arrive_at='BOS', terminal='G')
<|end_body_0|>
<|body_start_1|>
... | Tests for the TripList view. | TripListTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripListTests:
"""Tests for the TripList view."""
def setUp(self):
"""Instantiate RequestFactory, Trip, and User objects to pass requests to the TripList view. Parameters: self(TripListTests): the calling object Returns: None"""
<|body_0|>
def test_get_list_page(self):
... | stack_v2_sparse_classes_36k_train_021586 | 10,206 | permissive | [
{
"docstring": "Instantiate RequestFactory, Trip, and User objects to pass requests to the TripList view. Parameters: self(TripListTests): the calling object Returns: None",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "A user is able to see all the Trips in the database on ... | 2 | stack_v2_sparse_classes_30k_train_019812 | Implement the Python class `TripListTests` described below.
Class description:
Tests for the TripList view.
Method signatures and docstrings:
- def setUp(self): Instantiate RequestFactory, Trip, and User objects to pass requests to the TripList view. Parameters: self(TripListTests): the calling object Returns: None
-... | Implement the Python class `TripListTests` described below.
Class description:
Tests for the TripList view.
Method signatures and docstrings:
- def setUp(self): Instantiate RequestFactory, Trip, and User objects to pass requests to the TripList view. Parameters: self(TripListTests): the calling object Returns: None
-... | 65d933c64a3bf830f51ac237f5781ddfb69f342c | <|skeleton|>
class TripListTests:
"""Tests for the TripList view."""
def setUp(self):
"""Instantiate RequestFactory, Trip, and User objects to pass requests to the TripList view. Parameters: self(TripListTests): the calling object Returns: None"""
<|body_0|>
def test_get_list_page(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TripListTests:
"""Tests for the TripList view."""
def setUp(self):
"""Instantiate RequestFactory, Trip, and User objects to pass requests to the TripList view. Parameters: self(TripListTests): the calling object Returns: None"""
self.factory = RequestFactory()
self.user = User.obj... | the_stack_v2_python_sparse | travelly/trips/tests.py | UPstartDeveloper/fiercely-souvenir | train | 0 |
d9ff5bf5731fae0aabf19b8f741baa73d863a7ae | [
"self.open_event = types.MethodType(event_handling_funcs['open_event'], self)\nself.close_event = types.MethodType(event_handling_funcs['close_event'], self)\nself.get_num_frames_in_event = types.MethodType(event_handling_funcs['get_num_frames_in_event'], self)\nself.data = None\nself.metadata = None\nself.timestam... | <|body_start_0|>
self.open_event = types.MethodType(event_handling_funcs['open_event'], self)
self.close_event = types.MethodType(event_handling_funcs['close_event'], self)
self.get_num_frames_in_event = types.MethodType(event_handling_funcs['get_num_frames_in_event'], self)
self.data = ... | See documentaion of the '__init__' function. | DataEvent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataEvent:
"""See documentaion of the '__init__' function."""
def __init__(self, event_handling_funcs, data_extraction_funcs):
"""Data event. This class stores all the information related to a data event. Methods to open, close and manipulate the event are attached to each instance o... | stack_v2_sparse_classes_36k_train_021587 | 4,637 | no_license | [
{
"docstring": "Data event. This class stores all the information related to a data event. Methods to open, close and manipulate the event are attached to each instance of this class at creation time, along with functions to extract data from it. Arguments: event_handling_funcs (Dict[str, Callable]): a dictiona... | 2 | stack_v2_sparse_classes_30k_train_001498 | Implement the Python class `DataEvent` described below.
Class description:
See documentaion of the '__init__' function.
Method signatures and docstrings:
- def __init__(self, event_handling_funcs, data_extraction_funcs): Data event. This class stores all the information related to a data event. Methods to open, close... | Implement the Python class `DataEvent` described below.
Class description:
See documentaion of the '__init__' function.
Method signatures and docstrings:
- def __init__(self, event_handling_funcs, data_extraction_funcs): Data event. This class stores all the information related to a data event. Methods to open, close... | 42385522e68116db0e03df19574e904a5d146a9c | <|skeleton|>
class DataEvent:
"""See documentaion of the '__init__' function."""
def __init__(self, event_handling_funcs, data_extraction_funcs):
"""Data event. This class stores all the information related to a data event. Methods to open, close and manipulate the event are attached to each instance o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataEvent:
"""See documentaion of the '__init__' function."""
def __init__(self, event_handling_funcs, data_extraction_funcs):
"""Data event. This class stores all the information related to a data event. Methods to open, close and manipulate the event are attached to each instance of this class ... | the_stack_v2_python_sparse | onda/utils/data_event.py | clydeph/onda | train | 2 |
b5e866617391bcc0108a073895f42f5cb6ef2f8b | [
"Frame.__init__(self, master)\nself.grid()\nself.create_widgets()",
"self.button1 = Button(self, text='This is the first button')\nself.button1.grid()\nself.button2 = Button(self)\nself.button2.grid()\nself.button2.configure(text='This is the second button')\nself.button3 = Button(self)\nself.button3.grid()\nself... | <|body_start_0|>
Frame.__init__(self, master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
self.button1 = Button(self, text='This is the first button')
self.button1.grid()
self.button2 = Button(self)
self.button2.grid()
self.button2.c... | A GUI application with three buttons. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame"""
<|body_0|>
def create_widgets(self):
"""create 3 buttons"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Frame.__init__(self, master)... | stack_v2_sparse_classes_36k_train_021588 | 828 | no_license | [
{
"docstring": "Initialize the Frame",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "create 3 buttons",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016435 | Implement the Python class `Application` described below.
Class description:
A GUI application with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize the Frame
- def create_widgets(self): create 3 buttons | Implement the Python class `Application` described below.
Class description:
A GUI application with three buttons.
Method signatures and docstrings:
- def __init__(self, master): Initialize the Frame
- def create_widgets(self): create 3 buttons
<|skeleton|>
class Application:
"""A GUI application with three butt... | b737076a68246f71f3dffe86f1805e5682d4481f | <|skeleton|>
class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame"""
<|body_0|>
def create_widgets(self):
"""create 3 buttons"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""A GUI application with three buttons."""
def __init__(self, master):
"""Initialize the Frame"""
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""create 3 buttons"""
self.button1 = Button(self, ... | the_stack_v2_python_sparse | three_buttons.py | tannce/IntroLab2015 | train | 0 |
6ab1a4416e04a823beecd4e9126d548b1b77eca5 | [
"user = flask.request.user\nobj = models.UserSettings.get_or_create(user.id)\nreturn flask_restful.marshal(obj.to_dict(), api_fields.SETTINGS_FIELDS, envelope='data')",
"args = reqparse.clean_args(api_args.SETTINGS_ARGS, strict=True)\nif isinstance(args, flask.Response):\n return args\nuser = flask.request.use... | <|body_start_0|>
user = flask.request.user
obj = models.UserSettings.get_or_create(user.id)
return flask_restful.marshal(obj.to_dict(), api_fields.SETTINGS_FIELDS, envelope='data')
<|end_body_0|>
<|body_start_1|>
args = reqparse.clean_args(api_args.SETTINGS_ARGS, strict=True)
if... | Returns or updates user settings. | UserSettingsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSettingsView:
"""Returns or updates user settings."""
def get(self):
"""Get user settings."""
<|body_0|>
def post(self):
"""Update user settings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = flask.request.user
obj = models.... | stack_v2_sparse_classes_36k_train_021589 | 20,797 | no_license | [
{
"docstring": "Get user settings.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update user settings.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009071 | Implement the Python class `UserSettingsView` described below.
Class description:
Returns or updates user settings.
Method signatures and docstrings:
- def get(self): Get user settings.
- def post(self): Update user settings. | Implement the Python class `UserSettingsView` described below.
Class description:
Returns or updates user settings.
Method signatures and docstrings:
- def get(self): Get user settings.
- def post(self): Update user settings.
<|skeleton|>
class UserSettingsView:
"""Returns or updates user settings."""
def g... | e3947eaf035c2b06b2cee22f18fdec81c434ee84 | <|skeleton|>
class UserSettingsView:
"""Returns or updates user settings."""
def get(self):
"""Get user settings."""
<|body_0|>
def post(self):
"""Update user settings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSettingsView:
"""Returns or updates user settings."""
def get(self):
"""Get user settings."""
user = flask.request.user
obj = models.UserSettings.get_or_create(user.id)
return flask_restful.marshal(obj.to_dict(), api_fields.SETTINGS_FIELDS, envelope='data')
def po... | the_stack_v2_python_sparse | eucaby_api/views.py | tayduivn/eucaby | train | 0 |
d7e0a5488bdab9610f67dcf7153d5ba8939d2e5b | [
"self.dp = []\nm = len(matrix)\nif m == 0:\n return\nn = len(matrix[0])\nif n == 0:\n return\nself.dp = [[0 for j in range(n)] for i in range(m)]\nself.dp[0][0] = matrix[0][0]\nfor j in range(1, n):\n self.dp[0][j] = matrix[0][j] + self.dp[0][j - 1]\nfor i in range(1, m):\n self.dp[i][0] = self.dp[i - 1... | <|body_start_0|>
self.dp = []
m = len(matrix)
if m == 0:
return
n = len(matrix[0])
if n == 0:
return
self.dp = [[0 for j in range(n)] for i in range(m)]
self.dp[0][0] = matrix[0][0]
for j in range(1, n):
self.dp[0][j] = ... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_021590 | 1,408 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_006085 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | dbaea33ae0bfc315f690623ed7e987e2ee0cc6cc | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.dp = []
m = len(matrix)
if m == 0:
return
n = len(matrix[0])
if n == 0:
return
self.dp = [[0 for j in range(n)] for i in range(m)]
self.dp[0][... | the_stack_v2_python_sparse | DynamicProgramming/leetcode304.py | childrenyoo/py_code_reposity | train | 0 | |
681963173f6c7101b5c9e3661089209d7d53d3aa | [
"if root is None:\n return 0\nlength1 = None\nlength2 = None\nif root.left is not None:\n length1 = self.maxPathSum(root.left)\nif root.right is not None:\n length2 = self.maxPathSum(root.right)\nlength3 = root.val + max(self.max_path(root.left), 0) + max(self.max_path(root.right), 0)\npool = []\nif length... | <|body_start_0|>
if root is None:
return 0
length1 = None
length2 = None
if root.left is not None:
length1 = self.maxPathSum(root.left)
if root.right is not None:
length2 = self.maxPathSum(root.right)
length3 = root.val + max(self.max_p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def max_path(self, root):
"""以root为根节点的树的最大的路径长度 :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
... | stack_v2_sparse_classes_36k_train_021591 | 2,367 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root)"
},
{
"docstring": "以root为根节点的树的最大的路径长度 :param root: :return:",
"name": "max_path",
"signature": "def max_path(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009004 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): :type root: TreeNode :rtype: int
- def max_path(self, root): 以root为根节点的树的最大的路径长度 :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): :type root: TreeNode :rtype: int
- def max_path(self, root): 以root为根节点的树的最大的路径长度 :param root: :return:
<|skeleton|>
class Solution:
def maxPathS... | 163b376acab84e28c74cb784d10fe39f11510921 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def max_path(self, root):
"""以root为根节点的树的最大的路径长度 :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
length1 = None
length2 = None
if root.left is not None:
length1 = self.maxPathSum(root.left)
if root.right is not None:
len... | the_stack_v2_python_sparse | code/124. Binary Tree Maximum Path Sum(H)/124. Binary Tree Maximum Path Sum(H).py | cathyxingchang/leetcode | train | 2 | |
9aa5098c2c2343f309200f5ab9c701ace3aec329 | [
"self.phase_diagram = phase_diagram\nself.mpcontribs = mpcontribs\nself.missing_compositions = missing_compositions\nself.query = query\nself.kwargs = kwargs\nself.phase_diagram.key = 'phase_diagram_id'\nself.missing_compositions.key = 'chemical_system'\nsuper().__init__(sources=[phase_diagram, mpcontribs], targets... | <|body_start_0|>
self.phase_diagram = phase_diagram
self.mpcontribs = mpcontribs
self.missing_compositions = missing_compositions
self.query = query
self.kwargs = kwargs
self.phase_diagram.key = 'phase_diagram_id'
self.missing_compositions.key = 'chemical_system'
... | Builder that finds compositions not found in the Materials Project for each chemical system. Based on the Text Mining project in MPContribs. | MissingCompositionsBuilder | [
"LicenseRef-scancode-hdf5",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MissingCompositionsBuilder:
"""Builder that finds compositions not found in the Materials Project for each chemical system. Based on the Text Mining project in MPContribs."""
def __init__(self, phase_diagram: S3Store, mpcontribs: MongoURIStore, missing_compositions: MongoStore, query: Option... | stack_v2_sparse_classes_36k_train_021592 | 8,663 | permissive | [
{
"docstring": "Arguments: phase_diagram: source store for chemsys data matsholar_store: source store for matscholar data missing_compositions: Target store to save the missing compositions query: dictionary to query the phase diagram store **kwargs: Additional keyword arguments",
"name": "__init__",
"s... | 6 | stack_v2_sparse_classes_30k_train_014317 | Implement the Python class `MissingCompositionsBuilder` described below.
Class description:
Builder that finds compositions not found in the Materials Project for each chemical system. Based on the Text Mining project in MPContribs.
Method signatures and docstrings:
- def __init__(self, phase_diagram: S3Store, mpcont... | Implement the Python class `MissingCompositionsBuilder` described below.
Class description:
Builder that finds compositions not found in the Materials Project for each chemical system. Based on the Text Mining project in MPContribs.
Method signatures and docstrings:
- def __init__(self, phase_diagram: S3Store, mpcont... | 90e121d5cf1b6b57a33233c927e1044c59354bc5 | <|skeleton|>
class MissingCompositionsBuilder:
"""Builder that finds compositions not found in the Materials Project for each chemical system. Based on the Text Mining project in MPContribs."""
def __init__(self, phase_diagram: S3Store, mpcontribs: MongoURIStore, missing_compositions: MongoStore, query: Option... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MissingCompositionsBuilder:
"""Builder that finds compositions not found in the Materials Project for each chemical system. Based on the Text Mining project in MPContribs."""
def __init__(self, phase_diagram: S3Store, mpcontribs: MongoURIStore, missing_compositions: MongoStore, query: Optional[Dict]=None... | the_stack_v2_python_sparse | emmet-builders/emmet/builders/matscholar/missing_compositions.py | materialsproject/emmet | train | 37 |
ff15af692b5610340095ce9fd1e4fe9f675dcf71 | [
"if not numbers or len(numbers) <= 0:\n return -1\nusedDic = set()\nfor i in range(len(numbers)):\n if numbers[i] < 0 or numbers[i] > len(numbers) - 1:\n return -1\n if numbers[i] not in usedDic:\n usedDic.add(numbers[i])\n else:\n return numbers[i]\nreturn -1",
"if not numbers or... | <|body_start_0|>
if not numbers or len(numbers) <= 0:
return -1
usedDic = set()
for i in range(len(numbers)):
if numbers[i] < 0 or numbers[i] > len(numbers) - 1:
return -1
if numbers[i] not in usedDic:
usedDic.add(numbers[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def duplicate1(self, numbers):
"""方法一:利用集合,时间复杂度O(n),空间复杂度O(n)"""
<|body_0|>
def duplicate2(self, numbers):
"""方法二:二分查找的变形,如下,时间复杂度O(nlogn),空间复杂度为O(1)"""
<|body_1|>
def countRange(self, numbers, length, start, end):
"""计算数组中的元素大于等于start... | stack_v2_sparse_classes_36k_train_021593 | 2,568 | no_license | [
{
"docstring": "方法一:利用集合,时间复杂度O(n),空间复杂度O(n)",
"name": "duplicate1",
"signature": "def duplicate1(self, numbers)"
},
{
"docstring": "方法二:二分查找的变形,如下,时间复杂度O(nlogn),空间复杂度为O(1)",
"name": "duplicate2",
"signature": "def duplicate2(self, numbers)"
},
{
"docstring": "计算数组中的元素大于等于start,小... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def duplicate1(self, numbers): 方法一:利用集合,时间复杂度O(n),空间复杂度O(n)
- def duplicate2(self, numbers): 方法二:二分查找的变形,如下,时间复杂度O(nlogn),空间复杂度为O(1)
- def countRange(self, numbers, length, start... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def duplicate1(self, numbers): 方法一:利用集合,时间复杂度O(n),空间复杂度O(n)
- def duplicate2(self, numbers): 方法二:二分查找的变形,如下,时间复杂度O(nlogn),空间复杂度为O(1)
- def countRange(self, numbers, length, start... | 060e809175cff96e91c694b93417c0c1d21719f0 | <|skeleton|>
class Solution:
def duplicate1(self, numbers):
"""方法一:利用集合,时间复杂度O(n),空间复杂度O(n)"""
<|body_0|>
def duplicate2(self, numbers):
"""方法二:二分查找的变形,如下,时间复杂度O(nlogn),空间复杂度为O(1)"""
<|body_1|>
def countRange(self, numbers, length, start, end):
"""计算数组中的元素大于等于start... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def duplicate1(self, numbers):
"""方法一:利用集合,时间复杂度O(n),空间复杂度O(n)"""
if not numbers or len(numbers) <= 0:
return -1
usedDic = set()
for i in range(len(numbers)):
if numbers[i] < 0 or numbers[i] > len(numbers) - 1:
return -1
... | the_stack_v2_python_sparse | ProgrammingOJ/CodingInterviewOffer_nowcoder_python/03_02_DuplicationInArrayNoEdit.py | PandoraLS/CodingInterview | train | 2 | |
e04a74fd21078da61cfc4cd4a72409108cfc4fd6 | [
"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... | Missing associated documentation comment in .proto file. | ChatManagerServicer | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatManagerServicer:
"""Missing associated documentation comment in .proto file."""
def create_chat(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_chat(self, request, context):
"""Missing associated docu... | stack_v2_sparse_classes_36k_train_021594 | 7,948 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "create_chat",
"signature": "def create_chat(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_chat",
"signature": "def get_chat(self, requ... | 4 | stack_v2_sparse_classes_30k_train_015496 | Implement the Python class `ChatManagerServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def create_chat(self, request, context): Missing associated documentation comment in .proto file.
- def get_chat(self, request, context): Mi... | Implement the Python class `ChatManagerServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def create_chat(self, request, context): Missing associated documentation comment in .proto file.
- def get_chat(self, request, context): Mi... | 7db858386f1a20e8d49bc16f53bfd7f1e4d03f7e | <|skeleton|>
class ChatManagerServicer:
"""Missing associated documentation comment in .proto file."""
def create_chat(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_chat(self, request, context):
"""Missing associated docu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChatManagerServicer:
"""Missing associated documentation comment in .proto file."""
def create_chat(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!'... | the_stack_v2_python_sparse | idm/api/proto/chat_manager_service_pb2_grpc.py | MrHamdu/hyperboria | train | 0 |
bec069374fa8aeccb9c709d91a59229897697fa3 | [
"self.deal = deal\nself.action = action\nself.bet = bet\nself.player = player",
"if self.player == CHANCE:\n return ', '.join((INT2STRING_CARD[c] for c in self.deal))\nelse:\n return INT2STRING_ACTION[self.action]"
] | <|body_start_0|>
self.deal = deal
self.action = action
self.bet = bet
self.player = player
<|end_body_0|>
<|body_start_1|>
if self.player == CHANCE:
return ', '.join((INT2STRING_CARD[c] for c in self.deal))
else:
return INT2STRING_ACTION[self.acti... | Action object of env: Texas Hold'em. | Action | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Action:
"""Action object of env: Texas Hold'em."""
def __init__(self, deal=None, action=None, bet=0, player=-1):
"""Init the action instance."""
<|body_0|>
def to_string(self):
"""Return a string representing this action."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_021595 | 10,184 | no_license | [
{
"docstring": "Init the action instance.",
"name": "__init__",
"signature": "def __init__(self, deal=None, action=None, bet=0, player=-1)"
},
{
"docstring": "Return a string representing this action.",
"name": "to_string",
"signature": "def to_string(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018787 | Implement the Python class `Action` described below.
Class description:
Action object of env: Texas Hold'em.
Method signatures and docstrings:
- def __init__(self, deal=None, action=None, bet=0, player=-1): Init the action instance.
- def to_string(self): Return a string representing this action. | Implement the Python class `Action` described below.
Class description:
Action object of env: Texas Hold'em.
Method signatures and docstrings:
- def __init__(self, deal=None, action=None, bet=0, player=-1): Init the action instance.
- def to_string(self): Return a string representing this action.
<|skeleton|>
class ... | 3514a0ea315b36dd9545bd2cfe36bd6c099ee1d7 | <|skeleton|>
class Action:
"""Action object of env: Texas Hold'em."""
def __init__(self, deal=None, action=None, bet=0, player=-1):
"""Init the action instance."""
<|body_0|>
def to_string(self):
"""Return a string representing this action."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Action:
"""Action object of env: Texas Hold'em."""
def __init__(self, deal=None, action=None, bet=0, player=-1):
"""Init the action instance."""
self.deal = deal
self.action = action
self.bet = bet
self.player = player
def to_string(self):
"""Return a ... | the_stack_v2_python_sparse | env/texas_holdem/texas_holdem_char.py | orange9426/FOGs | train | 1 |
036fb6800bf0d3d3d9f9a92a03b01f109b99584e | [
"self.delay = map(int, delay.split(':'))\nself.name = name\nself.active = True\nself.hash_value = hash_value\nself.last_run = datetime.datetime.now()\nif not len(self.delay) == 4:\n raise Exception('Timer delay have invalid format')",
"if self.active and self.last_run + datetime.timedelta(days=self.delay[0], h... | <|body_start_0|>
self.delay = map(int, delay.split(':'))
self.name = name
self.active = True
self.hash_value = hash_value
self.last_run = datetime.datetime.now()
if not len(self.delay) == 4:
raise Exception('Timer delay have invalid format')
<|end_body_0|>
<|... | VEE_timer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VEE_timer:
def __init__(self, name, delay, hash_value):
"""delay should be in format 00:00:00:00, where each digit - delay in day:hr:min:sec"""
<|body_0|>
def check(self):
"""Return true if since last run needed time already passed. Timer should be active"""
... | stack_v2_sparse_classes_36k_train_021596 | 762 | no_license | [
{
"docstring": "delay should be in format 00:00:00:00, where each digit - delay in day:hr:min:sec",
"name": "__init__",
"signature": "def __init__(self, name, delay, hash_value)"
},
{
"docstring": "Return true if since last run needed time already passed. Timer should be active",
"name": "ch... | 2 | null | Implement the Python class `VEE_timer` described below.
Class description:
Implement the VEE_timer class.
Method signatures and docstrings:
- def __init__(self, name, delay, hash_value): delay should be in format 00:00:00:00, where each digit - delay in day:hr:min:sec
- def check(self): Return true if since last run ... | Implement the Python class `VEE_timer` described below.
Class description:
Implement the VEE_timer class.
Method signatures and docstrings:
- def __init__(self, name, delay, hash_value): delay should be in format 00:00:00:00, where each digit - delay in day:hr:min:sec
- def check(self): Return true if since last run ... | c3bbadde24330fb2dff4aa2c32cc6b11e044fbc9 | <|skeleton|>
class VEE_timer:
def __init__(self, name, delay, hash_value):
"""delay should be in format 00:00:00:00, where each digit - delay in day:hr:min:sec"""
<|body_0|>
def check(self):
"""Return true if since last run needed time already passed. Timer should be active"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VEE_timer:
def __init__(self, name, delay, hash_value):
"""delay should be in format 00:00:00:00, where each digit - delay in day:hr:min:sec"""
self.delay = map(int, delay.split(':'))
self.name = name
self.active = True
self.hash_value = hash_value
self.last_run... | the_stack_v2_python_sparse | Libraries/VEE_timer.py | EAC-Technology/eApp-Builder | train | 0 | |
4661fbaf872a4cc934c09172b5814840eb6ff58d | [
"start_date, end_date = CommonAnalytics.convert_dates(self, start_date, end_date)\nrooms_available = CommonAnalytics.get_calendar_id_name(self, query)\nresult, number_of_meetings = ([], [])\nfor room in rooms_available:\n calendar_events = CommonAnalytics.get_all_events_in_a_room(self, room['calendar_id'], start... | <|body_start_0|>
start_date, end_date = CommonAnalytics.convert_dates(self, start_date, end_date)
rooms_available = CommonAnalytics.get_calendar_id_name(self, query)
result, number_of_meetings = ([], [])
for room in rooms_available:
calendar_events = CommonAnalytics.get_all_e... | Get room analytics :methods get_events_number_meetings_room_analytics get_least_used_rooms_analytics get_most_used_rooms_analytics get_meetings_per_room_analytics get_meetings_duration_analytics | RoomAnalytics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomAnalytics:
"""Get room analytics :methods get_events_number_meetings_room_analytics get_least_used_rooms_analytics get_most_used_rooms_analytics get_meetings_per_room_analytics get_meetings_duration_analytics"""
def get_events_number_meetings_room_analytics(self, query, start_date, end_d... | stack_v2_sparse_classes_36k_train_021597 | 5,205 | no_license | [
{
"docstring": "Get events in rooms and number of meetings per room :params - query - start_date, end_date(Time range)",
"name": "get_events_number_meetings_room_analytics",
"signature": "def get_events_number_meetings_room_analytics(self, query, start_date, end_date)"
},
{
"docstring": "Get ana... | 5 | null | Implement the Python class `RoomAnalytics` described below.
Class description:
Get room analytics :methods get_events_number_meetings_room_analytics get_least_used_rooms_analytics get_most_used_rooms_analytics get_meetings_per_room_analytics get_meetings_duration_analytics
Method signatures and docstrings:
- def get_... | Implement the Python class `RoomAnalytics` described below.
Class description:
Get room analytics :methods get_events_number_meetings_room_analytics get_least_used_rooms_analytics get_most_used_rooms_analytics get_meetings_per_room_analytics get_meetings_duration_analytics
Method signatures and docstrings:
- def get_... | 1e556408dfbcfd5bc0b4babadda9eb7dc14c6013 | <|skeleton|>
class RoomAnalytics:
"""Get room analytics :methods get_events_number_meetings_room_analytics get_least_used_rooms_analytics get_most_used_rooms_analytics get_meetings_per_room_analytics get_meetings_duration_analytics"""
def get_events_number_meetings_room_analytics(self, query, start_date, end_d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoomAnalytics:
"""Get room analytics :methods get_events_number_meetings_room_analytics get_least_used_rooms_analytics get_most_used_rooms_analytics get_meetings_per_room_analytics get_meetings_duration_analytics"""
def get_events_number_meetings_room_analytics(self, query, start_date, end_date):
... | the_stack_v2_python_sparse | helpers/calendar/analytics.py | migot01/mrm_api | train | 0 |
a162fc356dc8971635b2f9826c9cfb156eabc970 | [
"self.method = method\nself.mean = None\nself.std = None\nself.min = None\nself.max = None\nself.input_data_description = input_data_description\nself.which_variables = None\nself.name = 'normalization'",
"X_transf = []\nX = np.array(X)\n\"\\n if self.which_variables is not None:\\n print('stop ... | <|body_start_0|>
self.method = method
self.mean = None
self.std = None
self.min = None
self.max = None
self.input_data_description = input_data_description
self.which_variables = None
self.name = 'normalization'
<|end_body_0|>
<|body_start_1|>
X_t... | normalize_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class normalize_model:
def __init__(self, input_data_description=None, method='global_mean_std'):
"""Parameters ---------- input_data_description: dict Description of the input features method: string Seected method for normalization"""
<|body_0|>
def transform(self, X):
"... | stack_v2_sparse_classes_36k_train_021598 | 3,536 | permissive | [
{
"docstring": "Parameters ---------- input_data_description: dict Description of the input features method: string Seected method for normalization",
"name": "__init__",
"signature": "def __init__(self, input_data_description=None, method='global_mean_std')"
},
{
"docstring": "Normalizing data ... | 2 | null | Implement the Python class `normalize_model` described below.
Class description:
Implement the normalize_model class.
Method signatures and docstrings:
- def __init__(self, input_data_description=None, method='global_mean_std'): Parameters ---------- input_data_description: dict Description of the input features meth... | Implement the Python class `normalize_model` described below.
Class description:
Implement the normalize_model class.
Method signatures and docstrings:
- def __init__(self, input_data_description=None, method='global_mean_std'): Parameters ---------- input_data_description: dict Description of the input features meth... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class normalize_model:
def __init__(self, input_data_description=None, method='global_mean_std'):
"""Parameters ---------- input_data_description: dict Description of the input features method: string Seected method for normalization"""
<|body_0|>
def transform(self, X):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class normalize_model:
def __init__(self, input_data_description=None, method='global_mean_std'):
"""Parameters ---------- input_data_description: dict Description of the input features method: string Seected method for normalization"""
self.method = method
self.mean = None
self.std ... | the_stack_v2_python_sparse | MMLL/preprocessors/normalizer.py | Musketeer-H2020/MMLL-Robust | train | 0 | |
9c6baee092a34c2874f9e20f7c3b4eeab6c14928 | [
"self.code = code\nself.auto_refresh = auto_refresh\nself.client_id = client_id or os.environ.get('SPOTIFY_CLIENT_ID')\nself.client_secret = client_secret or os.environ.get('SPOTIFY_CLIENT_SECRET')\nself.redirect_uri = redirect_uri or os.environ.get('SPOTIFY_REDIRECT_URI')\nself.http_client = http_client or HttpCli... | <|body_start_0|>
self.code = code
self.auto_refresh = auto_refresh
self.client_id = client_id or os.environ.get('SPOTIFY_CLIENT_ID')
self.client_secret = client_secret or os.environ.get('SPOTIFY_CLIENT_SECRET')
self.redirect_uri = redirect_uri or os.environ.get('SPOTIFY_REDIRECT_... | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
def __init__(self, code, auto_refresh=True, client_id=None, client_secret=None, redirect_uri=None, http_client=None):
"""User access token :param str code: Auth token code :param bool auto_refresh: Refresh the token upon expiration :param str client_id: Client ID :param str client_... | stack_v2_sparse_classes_36k_train_021599 | 3,423 | permissive | [
{
"docstring": "User access token :param str code: Auth token code :param bool auto_refresh: Refresh the token upon expiration :param str client_id: Client ID :param str client_secret: Client Secret :param str redirect_uri: Application Redirect URI :param http_client: HTTP Client for requests",
"name": "__i... | 4 | stack_v2_sparse_classes_30k_train_017667 | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, code, auto_refresh=True, client_id=None, client_secret=None, redirect_uri=None, http_client=None): User access token :param str code: Auth token code :param bool auto_... | Implement the Python class `User` described below.
Class description:
Implement the User class.
Method signatures and docstrings:
- def __init__(self, code, auto_refresh=True, client_id=None, client_secret=None, redirect_uri=None, http_client=None): User access token :param str code: Auth token code :param bool auto_... | d92c71073b2515f3c850604114133a7d2022d1a4 | <|skeleton|>
class User:
def __init__(self, code, auto_refresh=True, client_id=None, client_secret=None, redirect_uri=None, http_client=None):
"""User access token :param str code: Auth token code :param bool auto_refresh: Refresh the token upon expiration :param str client_id: Client ID :param str client_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
def __init__(self, code, auto_refresh=True, client_id=None, client_secret=None, redirect_uri=None, http_client=None):
"""User access token :param str code: Auth token code :param bool auto_refresh: Refresh the token upon expiration :param str client_id: Client ID :param str client_secret: Client... | the_stack_v2_python_sparse | spotify/auth/user.py | jingming/spotify | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.