blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nassert use_masking != use_weighted_masking or not use_masking\nself.use_masking = use_masking\nself.use_weighted_masking = use_weighted_masking\nreduction = 'none' if self.use_weighted_masking else 'mean'\nself.l1_criterion = nn.L1Loss(reduction=reduction)\nself.mse_criterion = nn.MSELoss(reduc... | <|body_start_0|>
super().__init__()
assert use_masking != use_weighted_masking or not use_masking
self.use_masking = use_masking
self.use_weighted_masking = use_weighted_masking
reduction = 'none' if self.use_weighted_masking else 'mean'
self.l1_criterion = nn.L1Loss(redu... | Loss function module for Tacotron2. | Tacotron2Loss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tacotron2Loss:
"""Loss function module for Tacotron2."""
def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0):
"""Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_ma... | stack_v2_sparse_classes_75kplus_train_071900 | 46,210 | permissive | [
{
"docstring": "Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_masking (bool): Whether to apply weighted masking in loss calculation. bce_pos_weight (float): Weight of positive sample of stop token.",
"name": "__init__",... | 2 | stack_v2_sparse_classes_30k_train_010332 | Implement the Python class `Tacotron2Loss` described below.
Class description:
Loss function module for Tacotron2.
Method signatures and docstrings:
- def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply mas... | Implement the Python class `Tacotron2Loss` described below.
Class description:
Loss function module for Tacotron2.
Method signatures and docstrings:
- def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply mas... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class Tacotron2Loss:
"""Loss function module for Tacotron2."""
def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0):
"""Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tacotron2Loss:
"""Loss function module for Tacotron2."""
def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0):
"""Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_masking (bool):... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
8feb6212bc8a139fc2549f3e6564b158fca703b6 | [
"self.sparse = params['sparse']\nself.__init_environment(params['random_state'])\nself.__build_model(**params['model'])\nself.__build_components(**params['hyper'])\nreturn",
"random.seed(random_state)\nnp.random.seed(random_state)\ntorch.manual_seed(random_state)\ntorch.backends.cudnn.deterministic = True\ntorch.... | <|body_start_0|>
self.sparse = params['sparse']
self.__init_environment(params['random_state'])
self.__build_model(**params['model'])
self.__build_components(**params['hyper'])
return
<|end_body_0|>
<|body_start_1|>
random.seed(random_state)
np.random.seed(random... | GAT模型训练与预测 | Pipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipeline:
"""GAT模型训练与预测"""
def __init__(self, **params):
"""GAT模型训练与预测 加载GAT模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'sparse': False, 'random_state' 42, 'model': { 'input_dim': 1433, 'hidden_dim': 8, 'output_dim': 7, 'num_heads': 8, 'dropout': 0.6, 'alpha': 0.2 }, ... | stack_v2_sparse_classes_75kplus_train_071901 | 5,510 | permissive | [
{
"docstring": "GAT模型训练与预测 加载GAT模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'sparse': False, 'random_state' 42, 'model': { 'input_dim': 1433, 'hidden_dim': 8, 'output_dim': 7, 'num_heads': 8, 'dropout': 0.6, 'alpha': 0.2 }, 'hyper': { 'lr': 3e-3, 'epochs': 10, 'patience': 100, 'weight_decay': 5e... | 6 | stack_v2_sparse_classes_30k_train_030801 | Implement the Python class `Pipeline` described below.
Class description:
GAT模型训练与预测
Method signatures and docstrings:
- def __init__(self, **params): GAT模型训练与预测 加载GAT模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'sparse': False, 'random_state' 42, 'model': { 'input_dim': 1433, 'hidden_dim': 8, 'output_... | Implement the Python class `Pipeline` described below.
Class description:
GAT模型训练与预测
Method signatures and docstrings:
- def __init__(self, **params): GAT模型训练与预测 加载GAT模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'sparse': False, 'random_state' 42, 'model': { 'input_dim': 1433, 'hidden_dim': 8, 'output_... | ee16c37fd065ba4c732138096f715f04c0ad6fcf | <|skeleton|>
class Pipeline:
"""GAT模型训练与预测"""
def __init__(self, **params):
"""GAT模型训练与预测 加载GAT模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'sparse': False, 'random_state' 42, 'model': { 'input_dim': 1433, 'hidden_dim': 8, 'output_dim': 7, 'num_heads': 8, 'dropout': 0.6, 'alpha': 0.2 }, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pipeline:
"""GAT模型训练与预测"""
def __init__(self, **params):
"""GAT模型训练与预测 加载GAT模型, 生成训练必要组件实例 Input: ------ params: dict, 模型参数和超参数, 格式为: { 'sparse': False, 'random_state' 42, 'model': { 'input_dim': 1433, 'hidden_dim': 8, 'output_dim': 7, 'num_heads': 8, 'dropout': 0.6, 'alpha': 0.2 }, 'hyper': { 'l... | the_stack_v2_python_sparse | Node/GAT/script/pipeline.py | robbinc91/GNN-Pytorch | train | 0 |
883e4b40ce9d3ed4c00311e6c40aac692aad3cc2 | [
"if not head or not head.next:\n return head\ncount = 1\ncur = head\nwhile cur.next:\n cur = cur.next\n count += 1\nk = count - k % count\ncur.next = head\nwhile k > 0:\n cur = cur.next\n k -= 1\nhead = cur.next\ncur.next = None\nreturn head",
"nums = []\nguard = ListNode(next=head)\nwhile head:\n ... | <|body_start_0|>
if not head or not head.next:
return head
count = 1
cur = head
while cur.next:
cur = cur.next
count += 1
k = count - k % count
cur.next = head
while k > 0:
cur = cur.next
k -= 1
h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户"""
<|body_0|>
def rotateRight1(self, head: ListNode, k: int) -> ListNode:
"""执行用时: 44 ms , 在所有 Python3 提交中... | stack_v2_sparse_classes_75kplus_train_071902 | 2,485 | no_license | [
{
"docstring": "执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户",
"name": "rotateRight",
"signature": "def rotateRight(self, head: ListNode, k: int) -> ListNode"
},
{
"docstring": "执行用时: 44 ms , 在所有 Python3 提交中击败了 63.50% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交... | 2 | stack_v2_sparse_classes_30k_train_052858 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head: ListNode, k: int) -> ListNode: 执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户
- def rotateRight1(self, head:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head: ListNode, k: int) -> ListNode: 执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户
- def rotateRight1(self, head:... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户"""
<|body_0|>
def rotateRight1(self, head: ListNode, k: int) -> ListNode:
"""执行用时: 44 ms , 在所有 Python3 提交中... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""执行用时: 60 ms , 在所有 Python3 提交中击败了 5.44% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 67.75% 的用户"""
if not head or not head.next:
return head
count = 1
cur = head
while cur.next:
cur... | the_stack_v2_python_sparse | 旋转链表.py | nomboy/leetcode | train | 0 | |
71ce71839005959f906fa4da46af607b4be67f9e | [
"super(BinaryCrossEntropyLoss, self).__init__()\nself.weight = weight\nself.ignore_index = ignore_index\nself.reduction = reduction",
"targets = [t for target in targets for t in target['targets']]\ntargets = torch.stack(targets).float()\nlogits = torch.stack([torch.sum(cost * alignment) for cost, alignment in lo... | <|body_start_0|>
super(BinaryCrossEntropyLoss, self).__init__()
self.weight = weight
self.ignore_index = ignore_index
self.reduction = reduction
<|end_body_0|>
<|body_start_1|>
targets = [t for target in targets for t in target['targets']]
targets = torch.stack(targets).... | Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs | BinaryCrossEntropyLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryCrossEntropyLoss:
"""Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs"""
def __init__(self, weight: Optional[to... | stack_v2_sparse_classes_75kplus_train_071903 | 2,776 | permissive | [
{
"docstring": "Initialize the MultiLabelNLLLoss. Parameters ---------- weight : Optional[torch.Tensor] A manual rescaling weight given to each class. If given, has to be a Tensor of size N, where N is the number of classes. ignore_index : Optional[int], optional Specifies a target value that is ignored and doe... | 2 | stack_v2_sparse_classes_30k_train_049628 | Implement the Python class `BinaryCrossEntropyLoss` described below.
Class description:
Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs
Method... | Implement the Python class `BinaryCrossEntropyLoss` described below.
Class description:
Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs
Method... | 8d2bf06ba4c121863833094d5d4896bf34a9a73e | <|skeleton|>
class BinaryCrossEntropyLoss:
"""Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs"""
def __init__(self, weight: Optional[to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryCrossEntropyLoss:
"""Computes the hinge loss between aligned and un-aligned document pairs (for AskUbuntu). For each document, the loss is sum_ij |negative_similarity_i - positive_similarity_j + margin| i.e. sum over all positive/negative pairs"""
def __init__(self, weight: Optional[torch.Tensor]=N... | the_stack_v2_python_sparse | classify/metric/loss/bce.py | ManHieu/rationale-alignment | train | 0 |
5920b92c6e7c6384077bb29eecf3205edfe96457 | [
"start, end = timestamps\ntotal_frame_count, duration = _parse_video_metadata(sample, metadata)\nsupport = [etaf.timestamp_to_frame_number(start, duration, total_frame_count), etaf.timestamp_to_frame_number(end, duration, total_frame_count)]\nreturn cls(support=support, **kwargs)",
"first, last = self.support\nto... | <|body_start_0|>
start, end = timestamps
total_frame_count, duration = _parse_video_metadata(sample, metadata)
support = [etaf.timestamp_to_frame_number(start, duration, total_frame_count), etaf.timestamp_to_frame_number(end, duration, total_frame_count)]
return cls(support=support, **kw... | A temporal detection in a video whose support is defined by a start and end frame. Args: label (None): the label string support (None): the ``[first, last]`` frame numbers, inclusive confidence (None): a confidence in ``[0, 1]`` for the detection | TemporalDetection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporalDetection:
"""A temporal detection in a video whose support is defined by a start and end frame. Args: label (None): the label string support (None): the ``[first, last]`` frame numbers, inclusive confidence (None): a confidence in ``[0, 1]`` for the detection"""
def from_timestamps(... | stack_v2_sparse_classes_75kplus_train_071904 | 44,487 | permissive | [
{
"docstring": "Creates a :class:`TemporalDetection` instance from ``[start, stop]`` timestamps for the specified video. You must provide either ``sample`` or ``metadata`` to inform the conversion. Args: timestamps: the ``[start, stop]`` timestamps, in seconds or \"HH:MM:SS.XXX\" format sample (None): a video :... | 2 | stack_v2_sparse_classes_30k_train_029190 | Implement the Python class `TemporalDetection` described below.
Class description:
A temporal detection in a video whose support is defined by a start and end frame. Args: label (None): the label string support (None): the ``[first, last]`` frame numbers, inclusive confidence (None): a confidence in ``[0, 1]`` for the... | Implement the Python class `TemporalDetection` described below.
Class description:
A temporal detection in a video whose support is defined by a start and end frame. Args: label (None): the label string support (None): the ``[first, last]`` frame numbers, inclusive confidence (None): a confidence in ``[0, 1]`` for the... | f36c6fea26d5462719211337e5ae2837314da122 | <|skeleton|>
class TemporalDetection:
"""A temporal detection in a video whose support is defined by a start and end frame. Args: label (None): the label string support (None): the ``[first, last]`` frame numbers, inclusive confidence (None): a confidence in ``[0, 1]`` for the detection"""
def from_timestamps(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemporalDetection:
"""A temporal detection in a video whose support is defined by a start and end frame. Args: label (None): the label string support (None): the ``[first, last]`` frame numbers, inclusive confidence (None): a confidence in ``[0, 1]`` for the detection"""
def from_timestamps(cls, timestam... | the_stack_v2_python_sparse | fiftyone/core/labels.py | jrobinson-vs/fiftyone | train | 0 |
7411e0f9d0478028bdfe5c961e60c8ddcaee2529 | [
"content = []\nfor step, value in self.steps.items():\n content.append(value)\nreturn content",
"steps = []\nsteps_content = self.get_steps_contents()\nfor content in steps_content:\n if 'plugin' in content.keys():\n steps.append(content)\nreturn steps",
"plugins = []\nplugin_steps = self.get_plugi... | <|body_start_0|>
content = []
for step, value in self.steps.items():
content.append(value)
return content
<|end_body_0|>
<|body_start_1|>
steps = []
steps_content = self.get_steps_contents()
for content in steps_content:
if 'plugin' in content.key... | WorkflowVersion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowVersion:
def get_steps_contents(self) -> List[dict]:
"""get_step_contents parses the workflow version steps and grabs the contents of each step :return: List of step contents as dictionaries"""
<|body_0|>
def get_plugin_steps(self) -> List[dict]:
"""get_plugi... | stack_v2_sparse_classes_75kplus_train_071905 | 3,850 | permissive | [
{
"docstring": "get_step_contents parses the workflow version steps and grabs the contents of each step :return: List of step contents as dictionaries",
"name": "get_steps_contents",
"signature": "def get_steps_contents(self) -> List[dict]"
},
{
"docstring": "get_plugin_steps filters a collectio... | 3 | null | Implement the Python class `WorkflowVersion` described below.
Class description:
Implement the WorkflowVersion class.
Method signatures and docstrings:
- def get_steps_contents(self) -> List[dict]: get_step_contents parses the workflow version steps and grabs the contents of each step :return: List of step contents a... | Implement the Python class `WorkflowVersion` described below.
Class description:
Implement the WorkflowVersion class.
Method signatures and docstrings:
- def get_steps_contents(self) -> List[dict]: get_step_contents parses the workflow version steps and grabs the contents of each step :return: List of step contents a... | 556b736076ea611e5a8a93bd981cd2a99d5dbed8 | <|skeleton|>
class WorkflowVersion:
def get_steps_contents(self) -> List[dict]:
"""get_step_contents parses the workflow version steps and grabs the contents of each step :return: List of step contents as dictionaries"""
<|body_0|>
def get_plugin_steps(self) -> List[dict]:
"""get_plugi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowVersion:
def get_steps_contents(self) -> List[dict]:
"""get_step_contents parses the workflow version steps and grabs the contents of each step :return: List of step contents as dictionaries"""
content = []
for step, value in self.steps.items():
content.append(value... | the_stack_v2_python_sparse | icon_validator/workflow/model.py | rapid7/icon-integrations-validators | train | 7 | |
3b3cd26ca769fb0a2bcce5a47958584313cb319c | [
"self.mfd_type = 'Youngs & Coppersmith (1985) Characteristic'\nself.mfd_weight = mfd_conf['Model_Weight']\nself.bin_width = mfd_conf['MFD_spacing']\nself.mmin = mfd_conf['Minimum_Magnitude']\nself.mmax = None\nself.mmax_sigma = None\nself.b_value = mfd_conf['b_value'][0]\nself.b_value_sigma = mfd_conf['b_value'][1]... | <|body_start_0|>
self.mfd_type = 'Youngs & Coppersmith (1985) Characteristic'
self.mfd_weight = mfd_conf['Model_Weight']
self.bin_width = mfd_conf['MFD_spacing']
self.mmin = mfd_conf['Minimum_Magnitude']
self.mmax = None
self.mmax_sigma = None
self.b_value = mfd_c... | Calculates the activity rate on a fault with a given slip assuming the characteristic model described in Youngs & Coppersmith (1985) Eqs. 16 and 17 :param str mfd_type: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for subsequent logic tree processing) :param float bi... | YoungsCoppersmithCharacteristic | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YoungsCoppersmithCharacteristic:
"""Calculates the activity rate on a fault with a given slip assuming the characteristic model described in Youngs & Coppersmith (1985) Eqs. 16 and 17 :param str mfd_type: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribu... | stack_v2_sparse_classes_75kplus_train_071906 | 12,645 | permissive | [
{
"docstring": "Input core configuration parameters as specified in the configuration file :param dict mfd_conf: Configuration file containing the following attributes: * 'Model_Weight' - Logic tree weight of model type (float) * 'MFD_spacing' - Width of MFD bin (float) * 'Minimum_Magnitude' - Minimum magnitude... | 3 | stack_v2_sparse_classes_30k_train_006599 | Implement the Python class `YoungsCoppersmithCharacteristic` described below.
Class description:
Calculates the activity rate on a fault with a given slip assuming the characteristic model described in Youngs & Coppersmith (1985) Eqs. 16 and 17 :param str mfd_type: Type of magnitude frequency distribution :param float... | Implement the Python class `YoungsCoppersmithCharacteristic` described below.
Class description:
Calculates the activity rate on a fault with a given slip assuming the characteristic model described in Youngs & Coppersmith (1985) Eqs. 16 and 17 :param str mfd_type: Type of magnitude frequency distribution :param float... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class YoungsCoppersmithCharacteristic:
"""Calculates the activity rate on a fault with a given slip assuming the characteristic model described in Youngs & Coppersmith (1985) Eqs. 16 and 17 :param str mfd_type: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YoungsCoppersmithCharacteristic:
"""Calculates the activity rate on a fault with a given slip assuming the characteristic model described in Youngs & Coppersmith (1985) Eqs. 16 and 17 :param str mfd_type: Type of magnitude frequency distribution :param float mfd_weight: Weight of the mfd distribution (for sub... | the_stack_v2_python_sparse | openquake/hmtk/faults/mfd/youngs_coppersmith.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
c6d6416b48155a71f39ed8d7690fe58cea04646a | [
"filters = []\nif not start:\n start = datetime.now()\nif not end:\n now = datetime.now()\n year, month = divmod(now.month + 1, 12)\n if month == 0:\n month = 12\n year = year - 1\n end = now.replace(year=now.year + year, month=month)\nfilters.append(EventModel.start < end)\nfilters.app... | <|body_start_0|>
filters = []
if not start:
start = datetime.now()
if not end:
now = datetime.now()
year, month = divmod(now.month + 1, 12)
if month == 0:
month = 12
year = year - 1
end = now.replace(year... | Events | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Events:
def get(self, start: datetime=None, end: datetime=None):
"""## Get all events between start and end"""
<|body_0|>
def post(self, _transaction, **kwargs):
"""## Add a new event ***Requires Authentication***"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_071907 | 3,575 | no_license | [
{
"docstring": "## Get all events between start and end",
"name": "get",
"signature": "def get(self, start: datetime=None, end: datetime=None)"
},
{
"docstring": "## Add a new event ***Requires Authentication***",
"name": "post",
"signature": "def post(self, _transaction, **kwargs)"
}
... | 2 | null | Implement the Python class `Events` described below.
Class description:
Implement the Events class.
Method signatures and docstrings:
- def get(self, start: datetime=None, end: datetime=None): ## Get all events between start and end
- def post(self, _transaction, **kwargs): ## Add a new event ***Requires Authenticati... | Implement the Python class `Events` described below.
Class description:
Implement the Events class.
Method signatures and docstrings:
- def get(self, start: datetime=None, end: datetime=None): ## Get all events between start and end
- def post(self, _transaction, **kwargs): ## Add a new event ***Requires Authenticati... | 651b963ebfe4ff643ea5f3a8cbf79c4c7fceb67a | <|skeleton|>
class Events:
def get(self, start: datetime=None, end: datetime=None):
"""## Get all events between start and end"""
<|body_0|>
def post(self, _transaction, **kwargs):
"""## Add a new event ***Requires Authentication***"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Events:
def get(self, start: datetime=None, end: datetime=None):
"""## Get all events between start and end"""
filters = []
if not start:
start = datetime.now()
if not end:
now = datetime.now()
year, month = divmod(now.month + 1, 12)
... | the_stack_v2_python_sparse | server/resources/event.py | Website-Pfarre-Machstrasse/Backend | train | 1 | |
07d568d5e587a2dd2964e0f5136993d1f8d8aa8d | [
"if xml_path == None:\n script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n xml_path = script_path + '/../robot_description/' + self.default_xml_file\nMjRobot.__init__(self, xml_path, object_names=object_names, render=render, g_comp=g_comp, tool_mass=tool_mass, tool_mass_... | <|body_start_0|>
if xml_path == None:
script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
xml_path = script_path + '/../robot_description/' + self.default_xml_file
MjRobot.__init__(self, xml_path, object_names=object_names, render=render, g_com... | The 7 DoF, 80V Barret WAM robot | MjWam7 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MjWam7:
"""The 7 DoF, 80V Barret WAM robot"""
def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None):
"""The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of ... | stack_v2_sparse_classes_75kplus_train_071908 | 22,293 | no_license | [
{
"docstring": "The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of the default xml description file object_names: states of the listed objects are included in recordings render: whether or not to render the simulation g_comp: whether or not ... | 2 | stack_v2_sparse_classes_30k_train_043371 | Implement the Python class `MjWam7` described below.
Class description:
The 7 DoF, 80V Barret WAM robot
Method signatures and docstrings:
- def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None): The 7 DoF, 80V Barret WAM robot xml_path: to change the robots en... | Implement the Python class `MjWam7` described below.
Class description:
The 7 DoF, 80V Barret WAM robot
Method signatures and docstrings:
- def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None): The 7 DoF, 80V Barret WAM robot xml_path: to change the robots en... | dd7c19b347e8167f9f5e1cd4ae32fbec194dc046 | <|skeleton|>
class MjWam7:
"""The 7 DoF, 80V Barret WAM robot"""
def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None):
"""The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MjWam7:
"""The 7 DoF, 80V Barret WAM robot"""
def __init__(self, xml_path=None, object_names=[], render=True, g_comp=False, tool_mass=0, tool_mass_site=None):
"""The 7 DoF, 80V Barret WAM robot xml_path: to change the robots environment or end effector, provide a modified version of the default x... | the_stack_v2_python_sparse | mujoco_robots/robots.py | kploeger/mujoco_robots | train | 0 |
d448ae38e9c60446f77edf25aae476cb7fbe29bd | [
"vim_connection = pecan.request.vim.open_connection()\nvim_connection.send(rpc_request.serialize())\nmsg = vim_connection.receive()\nif msg is None:\n DLOG.error('No response received for %s.' % rpc_request)\n return httplib.INTERNAL_SERVER_ERROR\nresponse = rpc.RPCMessage.deserialize(msg)\nif rpc.RPC_MSG_RES... | <|body_start_0|>
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive()
if msg is None:
DLOG.error('No response received for %s.' % rpc_request)
return httplib.INTERNAL_SERVER_ERROR
... | Virtualised Resources - Computes Migrate API | ComputeMigrateAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeMigrateAPI:
"""Virtualised Resources - Computes Migrate API"""
def _do_migrate(rpc_request):
"""Return an image details"""
<|body_0|>
def post(self, compute_id, request_data):
"""Perform a migrate against a virtual compute resource"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_071909 | 23,213 | permissive | [
{
"docstring": "Return an image details",
"name": "_do_migrate",
"signature": "def _do_migrate(rpc_request)"
},
{
"docstring": "Perform a migrate against a virtual compute resource",
"name": "post",
"signature": "def post(self, compute_id, request_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031574 | Implement the Python class `ComputeMigrateAPI` described below.
Class description:
Virtualised Resources - Computes Migrate API
Method signatures and docstrings:
- def _do_migrate(rpc_request): Return an image details
- def post(self, compute_id, request_data): Perform a migrate against a virtual compute resource | Implement the Python class `ComputeMigrateAPI` described below.
Class description:
Virtualised Resources - Computes Migrate API
Method signatures and docstrings:
- def _do_migrate(rpc_request): Return an image details
- def post(self, compute_id, request_data): Perform a migrate against a virtual compute resource
<|... | 6dba3df3e3c4e5f4ae20ae0c4a48ae72e6d6e274 | <|skeleton|>
class ComputeMigrateAPI:
"""Virtualised Resources - Computes Migrate API"""
def _do_migrate(rpc_request):
"""Return an image details"""
<|body_0|>
def post(self, compute_id, request_data):
"""Perform a migrate against a virtual compute resource"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComputeMigrateAPI:
"""Virtualised Resources - Computes Migrate API"""
def _do_migrate(rpc_request):
"""Return an image details"""
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive()
if msg... | the_stack_v2_python_sparse | nfv/nfv-vim/nfv_vim/api/controllers/v1/virtualised_resources/_computes_api.py | starlingx/nfv | train | 3 |
98db7cb9c3df6058da52be6c2e1589e028090bd4 | [
"ys = numpy.arange(self.nely + 1)\nlefty_to_id = numpy.vectorize(lambda y: xy_to_id(0, y, self.nelx, self.nely))\nids = lefty_to_id(ys)\nfixed = numpy.union1d(2 * ids, 2 * ids + 1)\nreturn fixed",
"f = numpy.zeros((self.ndof, 1))\ndof_index = 2 * xy_to_id(self.nelx, self.nely // 2, self.nelx, self.nely) + 1\nf[do... | <|body_start_0|>
ys = numpy.arange(self.nely + 1)
lefty_to_id = numpy.vectorize(lambda y: xy_to_id(0, y, self.nelx, self.nely))
ids = lefty_to_id(ys)
fixed = numpy.union1d(2 * ids, 2 * ids + 1)
return fixed
<|end_body_0|>
<|body_start_1|>
f = numpy.zeros((self.ndof, 1))
... | Boundary conditions for a cantilever. | CantileverBoundaryConditions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CantileverBoundaryConditions:
"""Boundary conditions for a cantilever."""
def fixed_nodes(self):
""":obj:`numpy.ndarray`: Fixed nodes on the left."""
<|body_0|>
def forces(self):
""":obj:`numpy.ndarray`: Force vector in the middle right."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_071910 | 8,719 | no_license | [
{
"docstring": ":obj:`numpy.ndarray`: Fixed nodes on the left.",
"name": "fixed_nodes",
"signature": "def fixed_nodes(self)"
},
{
"docstring": ":obj:`numpy.ndarray`: Force vector in the middle right.",
"name": "forces",
"signature": "def forces(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042026 | Implement the Python class `CantileverBoundaryConditions` described below.
Class description:
Boundary conditions for a cantilever.
Method signatures and docstrings:
- def fixed_nodes(self): :obj:`numpy.ndarray`: Fixed nodes on the left.
- def forces(self): :obj:`numpy.ndarray`: Force vector in the middle right. | Implement the Python class `CantileverBoundaryConditions` described below.
Class description:
Boundary conditions for a cantilever.
Method signatures and docstrings:
- def fixed_nodes(self): :obj:`numpy.ndarray`: Fixed nodes on the left.
- def forces(self): :obj:`numpy.ndarray`: Force vector in the middle right.
<|s... | 067bf9b768e020b3de15fc1dee06c2ca36875619 | <|skeleton|>
class CantileverBoundaryConditions:
"""Boundary conditions for a cantilever."""
def fixed_nodes(self):
""":obj:`numpy.ndarray`: Fixed nodes on the left."""
<|body_0|>
def forces(self):
""":obj:`numpy.ndarray`: Force vector in the middle right."""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CantileverBoundaryConditions:
"""Boundary conditions for a cantilever."""
def fixed_nodes(self):
""":obj:`numpy.ndarray`: Fixed nodes on the left."""
ys = numpy.arange(self.nely + 1)
lefty_to_id = numpy.vectorize(lambda y: xy_to_id(0, y, self.nelx, self.nely))
ids = lefty_... | the_stack_v2_python_sparse | topopt/boundary_conditions.py | carloshernangarrido/topopt1 | train | 0 |
5cc2e67d948f786c3302c61c6071119f1bca556d | [
"rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))\nqm = QMCalculator(software='gaussian', method='pm6', fileStore=os.path.join(rmgpy_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=os.path.join(rmgpy_path, 'testing', 'qm', 'QMscratch'))\nif not os.path.exists(qm.settings.fileStore):\n os.makedir... | <|body_start_0|>
rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))
qm = QMCalculator(software='gaussian', method='pm6', fileStore=os.path.join(rmgpy_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=os.path.join(rmgpy_path, 'testing', 'qm', 'QMscratch'))
if not os.path.exists(qm.se... | Contains unit tests for the Geometry class. | TestGaussianMolPM6 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGaussianMolPM6:
"""Contains unit tests for the Geometry class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_generate_thermo_data(self):
"""Test that generate_thermo_data() works correctly for gaussian PM6."... | stack_v2_sparse_classes_75kplus_train_071911 | 7,452 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that generate_thermo_data() works correctly for gaussian PM6.",
"name": "test_generate_thermo_data",
"signature": "def test_generate_thermo_data(s... | 3 | null | Implement the Python class `TestGaussianMolPM6` described below.
Class description:
Contains unit tests for the Geometry class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_generate_thermo_data(self): Test that generate_thermo_data() works correct... | Implement the Python class `TestGaussianMolPM6` described below.
Class description:
Contains unit tests for the Geometry class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_generate_thermo_data(self): Test that generate_thermo_data() works correct... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestGaussianMolPM6:
"""Contains unit tests for the Geometry class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_generate_thermo_data(self):
"""Test that generate_thermo_data() works correctly for gaussian PM6."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGaussianMolPM6:
"""Contains unit tests for the Geometry class."""
def setUp(self):
"""A function run before each unit test in this class."""
rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))
qm = QMCalculator(software='gaussian', method='pm6', fileStore=os.path.joi... | the_stack_v2_python_sparse | rmgpy/qm/gaussianTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
976f59d18c1045eba62cf62cf5751470ab55d2ab | [
"cls._verify_message(raw_message)\ncontent = raw_message[4:-4]\nraw_values = content.split('\\x00')\nterminator = raw_values.pop()\nif terminator != 'z':\n raise sungrow.BadBinaryMessage('last field is %s, not terminator (\"z\")' % terminator)\nkeys = cls.names\nif len(raw_values) != len(keys):\n raise sungro... | <|body_start_0|>
cls._verify_message(raw_message)
content = raw_message[4:-4]
raw_values = content.split('\x00')
terminator = raw_values.pop()
if terminator != 'z':
raise sungrow.BadBinaryMessage('last field is %s, not terminator ("z")' % terminator)
keys = cl... | Sungrow charge controller configuration page | ConfigurationPage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationPage:
"""Sungrow charge controller configuration page"""
def from_bytes(cls, raw_message):
"""Create message from native-format bytestring"""
<|body_0|>
def to_bytes(self):
"""Produce native-format bytestring from message"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_071912 | 10,242 | permissive | [
{
"docstring": "Create message from native-format bytestring",
"name": "from_bytes",
"signature": "def from_bytes(cls, raw_message)"
},
{
"docstring": "Produce native-format bytestring from message",
"name": "to_bytes",
"signature": "def to_bytes(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009812 | Implement the Python class `ConfigurationPage` described below.
Class description:
Sungrow charge controller configuration page
Method signatures and docstrings:
- def from_bytes(cls, raw_message): Create message from native-format bytestring
- def to_bytes(self): Produce native-format bytestring from message | Implement the Python class `ConfigurationPage` described below.
Class description:
Sungrow charge controller configuration page
Method signatures and docstrings:
- def from_bytes(cls, raw_message): Create message from native-format bytestring
- def to_bytes(self): Produce native-format bytestring from message
<|skel... | 482707c82aa813c6e6f951d28e836d70df6cf56c | <|skeleton|>
class ConfigurationPage:
"""Sungrow charge controller configuration page"""
def from_bytes(cls, raw_message):
"""Create message from native-format bytestring"""
<|body_0|>
def to_bytes(self):
"""Produce native-format bytestring from message"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigurationPage:
"""Sungrow charge controller configuration page"""
def from_bytes(cls, raw_message):
"""Create message from native-format bytestring"""
cls._verify_message(raw_message)
content = raw_message[4:-4]
raw_values = content.split('\x00')
terminator = r... | the_stack_v2_python_sparse | sungrow-0.1b7/sungrow/sungrow_charge_controller.py | ottermegazord/mit_peatflux | train | 0 |
8a8aa4b3549b0f2df95944d885ffb94b84fda4d4 | [
"params = super().get_default_params()\nparams.get('optimizer').hyper_space = hyper_spaces.choice(['adam', 'adagrad', 'rmsprop'])\nreturn params",
"x_in = self._make_inputs()\nx = keras.layers.concatenate(x_in)\nx_out = self._make_output_layer()(x)\nself._backend = keras.models.Model(inputs=x_in, outputs=x_out)"
... | <|body_start_0|>
params = super().get_default_params()
params.get('optimizer').hyper_space = hyper_spaces.choice(['adam', 'adagrad', 'rmsprop'])
return params
<|end_body_0|>
<|body_start_1|>
x_in = self._make_inputs()
x = keras.layers.concatenate(x_in)
x_out = self._make... | Naive model with a simplest structure for testing purposes. Bare minimum functioning model. The best choice to get things rolling. The worst choice to fit and evaluate performance. | Naive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Naive:
"""Naive model with a simplest structure for testing purposes. Bare minimum functioning model. The best choice to get things rolling. The worst choice to fit and evaluate performance."""
def get_default_params(cls):
"""Default parameters."""
<|body_0|>
def build(s... | stack_v2_sparse_classes_75kplus_train_071913 | 909 | permissive | [
{
"docstring": "Default parameters.",
"name": "get_default_params",
"signature": "def get_default_params(cls)"
},
{
"docstring": "Build.",
"name": "build",
"signature": "def build(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021679 | Implement the Python class `Naive` described below.
Class description:
Naive model with a simplest structure for testing purposes. Bare minimum functioning model. The best choice to get things rolling. The worst choice to fit and evaluate performance.
Method signatures and docstrings:
- def get_default_params(cls): D... | Implement the Python class `Naive` described below.
Class description:
Naive model with a simplest structure for testing purposes. Bare minimum functioning model. The best choice to get things rolling. The worst choice to fit and evaluate performance.
Method signatures and docstrings:
- def get_default_params(cls): D... | 1f763062c6cc861e93ccdba23d0f1f0171f74145 | <|skeleton|>
class Naive:
"""Naive model with a simplest structure for testing purposes. Bare minimum functioning model. The best choice to get things rolling. The worst choice to fit and evaluate performance."""
def get_default_params(cls):
"""Default parameters."""
<|body_0|>
def build(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Naive:
"""Naive model with a simplest structure for testing purposes. Bare minimum functioning model. The best choice to get things rolling. The worst choice to fit and evaluate performance."""
def get_default_params(cls):
"""Default parameters."""
params = super().get_default_params()
... | the_stack_v2_python_sparse | matchzoo/models/naive.py | JRetza/MatchZoo | train | 1 |
55d2b623ca652b53b8b06e7f37e36ab615b38eda | [
"super().__init__()\nself.conv_blocks = nn.ModuleList()\nself.out_blocks = nn.ModuleList()\nself.depth = depth\nself.multiscale_depth = multiscale_depth\ntch = in_channels\nfor curr_channels, curr_dilations in zip(channels, dilations):\n block = [nn.ReplicationPad2d(curr_dilations), nn.Conv2d(tch, curr_channels,... | <|body_start_0|>
super().__init__()
self.conv_blocks = nn.ModuleList()
self.out_blocks = nn.ModuleList()
self.depth = depth
self.multiscale_depth = multiscale_depth
tch = in_channels
for curr_channels, curr_dilations in zip(channels, dilations):
block ... | Recurrent State Initializer (RSI) module of Recurrent Variational Network as presented in Yiasemis, George, et al. The RSI module learns to initialize the recurrent hidden state :math:`h_0`, input of the first RecurrentVarNetBlock of the RecurrentVarNet. References ---------- .. Yiasemis, George, et al. “Recurrent Vari... | RecurrentInit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurrentInit:
"""Recurrent State Initializer (RSI) module of Recurrent Variational Network as presented in Yiasemis, George, et al. The RSI module learns to initialize the recurrent hidden state :math:`h_0`, input of the first RecurrentVarNetBlock of the RecurrentVarNet. References ---------- ..... | stack_v2_sparse_classes_75kplus_train_071914 | 8,536 | permissive | [
{
"docstring": "Inits RecurrentInit. Parameters ---------- in_channels: Input channels. int out_channels: Number of hidden channels of the recurrent unit of RecurrentVarNet Block. int channels: Channels :math:`n_d` in the convolutional layers of initializer. Tuple[int, ...] dilations: Dilations :math:`p` of the... | 2 | null | Implement the Python class `RecurrentInit` described below.
Class description:
Recurrent State Initializer (RSI) module of Recurrent Variational Network as presented in Yiasemis, George, et al. The RSI module learns to initialize the recurrent hidden state :math:`h_0`, input of the first RecurrentVarNetBlock of the Re... | Implement the Python class `RecurrentInit` described below.
Class description:
Recurrent State Initializer (RSI) module of Recurrent Variational Network as presented in Yiasemis, George, et al. The RSI module learns to initialize the recurrent hidden state :math:`h_0`, input of the first RecurrentVarNetBlock of the Re... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class RecurrentInit:
"""Recurrent State Initializer (RSI) module of Recurrent Variational Network as presented in Yiasemis, George, et al. The RSI module learns to initialize the recurrent hidden state :math:`h_0`, input of the first RecurrentVarNetBlock of the RecurrentVarNet. References ---------- ..... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecurrentInit:
"""Recurrent State Initializer (RSI) module of Recurrent Variational Network as presented in Yiasemis, George, et al. The RSI module learns to initialize the recurrent hidden state :math:`h_0`, input of the first RecurrentVarNetBlock of the RecurrentVarNet. References ---------- .. Yiasemis, Ge... | the_stack_v2_python_sparse | mridc/collections/reconstruction/models/recurrentvarnet/recurrentvarnet.py | wdika/mridc | train | 40 |
c78151eb3c60ca31a6a8f4f4fb7d62fee98840ab | [
"utilities.validate_list(resource)\nget_pkgs_cmd = '%s -qa' % cls.PKG_MGR\nrpm_out = client_object.connection.request(get_pkgs_cmd).response_data.strip().split('\\n')\npkgs_re = '(%s)' % '|'.join(resource)\nmatching_pkgs = []\nfor pkg in rpm_out:\n if re.match(pkgs_re, pkg):\n matching_pkgs.append(pkg)\np... | <|body_start_0|>
utilities.validate_list(resource)
get_pkgs_cmd = '%s -qa' % cls.PKG_MGR
rpm_out = client_object.connection.request(get_pkgs_cmd).response_data.strip().split('\n')
pkgs_re = '(%s)' % '|'.join(resource)
matching_pkgs = []
for pkg in rpm_out:
if ... | Package management class for RHEL. | RHEL64PackageImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RHEL64PackageImpl:
"""Package management class for RHEL."""
def _find_pkgs(cls, client_object, resource=None):
"""Helper for finding packages on the host. @type resource: list @param resource: List of name(s)/regex of packages to find. @rtype: list @return: List of matching packages.... | stack_v2_sparse_classes_75kplus_train_071915 | 3,664 | no_license | [
{
"docstring": "Helper for finding packages on the host. @type resource: list @param resource: List of name(s)/regex of packages to find. @rtype: list @return: List of matching packages.",
"name": "_find_pkgs",
"signature": "def _find_pkgs(cls, client_object, resource=None)"
},
{
"docstring": "R... | 3 | null | Implement the Python class `RHEL64PackageImpl` described below.
Class description:
Package management class for RHEL.
Method signatures and docstrings:
- def _find_pkgs(cls, client_object, resource=None): Helper for finding packages on the host. @type resource: list @param resource: List of name(s)/regex of packages ... | Implement the Python class `RHEL64PackageImpl` described below.
Class description:
Package management class for RHEL.
Method signatures and docstrings:
- def _find_pkgs(cls, client_object, resource=None): Helper for finding packages on the host. @type resource: list @param resource: List of name(s)/regex of packages ... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class RHEL64PackageImpl:
"""Package management class for RHEL."""
def _find_pkgs(cls, client_object, resource=None):
"""Helper for finding packages on the host. @type resource: list @param resource: List of name(s)/regex of packages to find. @rtype: list @return: List of matching packages.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RHEL64PackageImpl:
"""Package management class for RHEL."""
def _find_pkgs(cls, client_object, resource=None):
"""Helper for finding packages on the host. @type resource: list @param resource: List of name(s)/regex of packages to find. @rtype: list @return: List of matching packages."""
u... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/kvm/cmd/rhel64_package_impl.py | Cloudxtreme/MyProject | train | 0 |
803a0427e3ee2aaab2045733e5d20792598516ba | [
"self.name = groupname\nself.quoteIDs = []\nself.avgPos = []\nself.avgNeg = []\nself.netSent = []\nfor d in data:\n self.quoteIDs.append(d['quote_id'])\n self.avgPos.append(d['avgPos'])\n self.avgNeg.append(d['avgNeg'])\n self.netSent.append(d['netSent'])\nself.overallpos = np.average(self.avgPos)\nself... | <|body_start_0|>
self.name = groupname
self.quoteIDs = []
self.avgPos = []
self.avgNeg = []
self.netSent = []
for d in data:
self.quoteIDs.append(d['quote_id'])
self.avgPos.append(d['avgPos'])
self.avgNeg.append(d['avgNeg'])
... | This is used to compute the sentiment scores for a group of items | GroupSentiments | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupSentiments:
"""This is used to compute the sentiment scores for a group of items"""
def __init__(self, data, groupname):
"""Args: data: a list of dictionaries that have been prepared by ItemSentiments to be saved groupname: the name that the result will be stored with/ or the na... | stack_v2_sparse_classes_75kplus_train_071916 | 8,919 | permissive | [
{
"docstring": "Args: data: a list of dictionaries that have been prepared by ItemSentiments to be saved groupname: the name that the result will be stored with/ or the name to retrieve",
"name": "__init__",
"signature": "def __init__(self, data, groupname)"
},
{
"docstring": "Saves the results ... | 2 | null | Implement the Python class `GroupSentiments` described below.
Class description:
This is used to compute the sentiment scores for a group of items
Method signatures and docstrings:
- def __init__(self, data, groupname): Args: data: a list of dictionaries that have been prepared by ItemSentiments to be saved groupname... | Implement the Python class `GroupSentiments` described below.
Class description:
This is used to compute the sentiment scores for a group of items
Method signatures and docstrings:
- def __init__(self, data, groupname): Args: data: a list of dictionaries that have been prepared by ItemSentiments to be saved groupname... | 8c5dc7a57eac611b555058736d609f2f204cb836 | <|skeleton|>
class GroupSentiments:
"""This is used to compute the sentiment scores for a group of items"""
def __init__(self, data, groupname):
"""Args: data: a list of dictionaries that have been prepared by ItemSentiments to be saved groupname: the name that the result will be stored with/ or the na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupSentiments:
"""This is used to compute the sentiment scores for a group of items"""
def __init__(self, data, groupname):
"""Args: data: a list of dictionaries that have been prepared by ItemSentiments to be saved groupname: the name that the result will be stored with/ or the name to retriev... | the_stack_v2_python_sparse | SentimentTools/SentimentAnalysis.py | AdamSwenson/TwitterProject | train | 0 |
b96dd6ce42c868c6a39665f53cb6644ae4a6d34f | [
"self.login()\nfor annotation_type in ['comment', 'label']:\n event = {'_type': 'test_event', '_index': 'test', '_id': 'test'}\n data = dict(annotation='test', annotation_type=annotation_type, events=[event])\n response = self.client.post(self.resource_url, data=json.dumps(data), content_type='application/... | <|body_start_0|>
self.login()
for annotation_type in ['comment', 'label']:
event = {'_type': 'test_event', '_index': 'test', '_id': 'test'}
data = dict(annotation='test', annotation_type=annotation_type, events=[event])
response = self.client.post(self.resource_url, d... | Test EventAnnotationResource. | EventAnnotationResourceTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventAnnotationResourceTest:
"""Test EventAnnotationResource."""
def test_post_annotate_resource(self):
"""Authenticated request to create an annotation."""
<|body_0|>
def test_post_annotate_invalid_index_resource(self):
"""Authenticated request to create an anno... | stack_v2_sparse_classes_75kplus_train_071917 | 36,779 | permissive | [
{
"docstring": "Authenticated request to create an annotation.",
"name": "test_post_annotate_resource",
"signature": "def test_post_annotate_resource(self)"
},
{
"docstring": "Authenticated request to create an annotation, but in the wrong index.",
"name": "test_post_annotate_invalid_index_r... | 2 | stack_v2_sparse_classes_30k_train_020568 | Implement the Python class `EventAnnotationResourceTest` described below.
Class description:
Test EventAnnotationResource.
Method signatures and docstrings:
- def test_post_annotate_resource(self): Authenticated request to create an annotation.
- def test_post_annotate_invalid_index_resource(self): Authenticated requ... | Implement the Python class `EventAnnotationResourceTest` described below.
Class description:
Test EventAnnotationResource.
Method signatures and docstrings:
- def test_post_annotate_resource(self): Authenticated request to create an annotation.
- def test_post_annotate_invalid_index_resource(self): Authenticated requ... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class EventAnnotationResourceTest:
"""Test EventAnnotationResource."""
def test_post_annotate_resource(self):
"""Authenticated request to create an annotation."""
<|body_0|>
def test_post_annotate_invalid_index_resource(self):
"""Authenticated request to create an anno... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventAnnotationResourceTest:
"""Test EventAnnotationResource."""
def test_post_annotate_resource(self):
"""Authenticated request to create an annotation."""
self.login()
for annotation_type in ['comment', 'label']:
event = {'_type': 'test_event', '_index': 'test', '_id... | the_stack_v2_python_sparse | timesketch/api/v1/resources_test.py | google/timesketch | train | 2,263 |
d6e778a1b8f7d7589dbeb940667b7b8ddbec4bb7 | [
"active_id = self._context.get('active_id')\nresult = super(TransferVehicle, self).default_get(fields)\nif active_id:\n student = self.env['student.student'].browse(active_id)\n if 'name' in fields:\n result.update({'name': student.id})\nreturn result",
"for rec in self:\n if rec.participation_id:... | <|body_start_0|>
active_id = self._context.get('active_id')
result = super(TransferVehicle, self).default_get(fields)
if active_id:
student = self.env['student.student'].browse(active_id)
if 'name' in fields:
result.update({'name': student.id})
ret... | TransferVehicle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransferVehicle:
def default_get(self, fields):
"""Override method to get student."""
<|body_0|>
def onchange_participation_id(self):
"""Method to get transport id and vehicle of participant."""
<|body_1|>
def vehicle_transfer(self):
"""Method to... | stack_v2_sparse_classes_75kplus_train_071918 | 2,957 | no_license | [
{
"docstring": "Override method to get student.",
"name": "default_get",
"signature": "def default_get(self, fields)"
},
{
"docstring": "Method to get transport id and vehicle of participant.",
"name": "onchange_participation_id",
"signature": "def onchange_participation_id(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_001526 | Implement the Python class `TransferVehicle` described below.
Class description:
Implement the TransferVehicle class.
Method signatures and docstrings:
- def default_get(self, fields): Override method to get student.
- def onchange_participation_id(self): Method to get transport id and vehicle of participant.
- def v... | Implement the Python class `TransferVehicle` described below.
Class description:
Implement the TransferVehicle class.
Method signatures and docstrings:
- def default_get(self, fields): Override method to get student.
- def onchange_participation_id(self): Method to get transport id and vehicle of participant.
- def v... | 6a9793f3a15da9eed40bf840b1d9a46457c5fd55 | <|skeleton|>
class TransferVehicle:
def default_get(self, fields):
"""Override method to get student."""
<|body_0|>
def onchange_participation_id(self):
"""Method to get transport id and vehicle of participant."""
<|body_1|>
def vehicle_transfer(self):
"""Method to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransferVehicle:
def default_get(self, fields):
"""Override method to get student."""
active_id = self._context.get('active_id')
result = super(TransferVehicle, self).default_get(fields)
if active_id:
student = self.env['student.student'].browse(active_id)
... | the_stack_v2_python_sparse | school_transport/wizard/transfer_vehicle.py | JayVora-SerpentCS/OdooEduERP | train | 121 | |
ef68ceb806997a8623391a963ba4bb78eca564b6 | [
"super().__init__(data_list)\nclean_data_list = list()\nself.since = date_range[0]\nself.until = date_range[1]\nfor line in self.raw_df.iterrows():\n commit = line[1].to_dict()\n commit = self._clean_commit(commit)\n if source_code_obj is None or source_code_obj.is_source_code(commit):\n clean_data_... | <|body_start_0|>
super().__init__(data_list)
clean_data_list = list()
self.since = date_range[0]
self.until = date_range[1]
for line in self.raw_df.iterrows():
commit = line[1].to_dict()
commit = self._clean_commit(commit)
if source_code_obj is... | Commit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Commit:
def __init__(self, data_list, date_range=(None, None), source_code_obj=None):
"""Initilizes self.df, the dataframe with one commit per row. The source_code_exclude_list parameter is a list which contains file extensions which are to be ignored. All possible file extensions are al... | stack_v2_sparse_classes_75kplus_train_071919 | 3,123 | no_license | [
{
"docstring": "Initilizes self.df, the dataframe with one commit per row. The source_code_exclude_list parameter is a list which contains file extensions which are to be ignored. All possible file extensions are allowed. For files without a standard \".xyz\" extension, like LICENCE or AUTHORS, the \"others\" e... | 2 | null | Implement the Python class `Commit` described below.
Class description:
Implement the Commit class.
Method signatures and docstrings:
- def __init__(self, data_list, date_range=(None, None), source_code_obj=None): Initilizes self.df, the dataframe with one commit per row. The source_code_exclude_list parameter is a l... | Implement the Python class `Commit` described below.
Class description:
Implement the Commit class.
Method signatures and docstrings:
- def __init__(self, data_list, date_range=(None, None), source_code_obj=None): Initilizes self.df, the dataframe with one commit per row. The source_code_exclude_list parameter is a l... | 930e7fef17c5c9f4a220c60d5df4ec7c51a1097a | <|skeleton|>
class Commit:
def __init__(self, data_list, date_range=(None, None), source_code_obj=None):
"""Initilizes self.df, the dataframe with one commit per row. The source_code_exclude_list parameter is a list which contains file extensions which are to be ignored. All possible file extensions are al... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Commit:
def __init__(self, data_list, date_range=(None, None), source_code_obj=None):
"""Initilizes self.df, the dataframe with one commit per row. The source_code_exclude_list parameter is a list which contains file extensions which are to be ignored. All possible file extensions are allowed. For fil... | the_stack_v2_python_sparse | Weekly_Work/Week2/Commit.py | Polaris000/GSoC_19_Perceval_Implementations | train | 3 | |
99299dff1b7fdb975df19e78f60b188816256fbd | [
"if self.parent() is not other.parent():\n raise TypeError('the parents must be the same')\nreturn self.base_ring().sum((self[i] * c for i, c in other))",
"L = self.parent()\nc = self['delta']\nself = self - L.term('delta', c)\nreturn 2 * self / self.inner_product(self) + L.term('deltacheck', c)"
] | <|body_start_0|>
if self.parent() is not other.parent():
raise TypeError('the parents must be the same')
return self.base_ring().sum((self[i] * c for i, c in other))
<|end_body_0|>
<|body_start_1|>
L = self.parent()
c = self['delta']
self = self - L.term('delta', c)
... | Element | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Element:
def inner_product(self, other):
"""Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sage: matrix([[x.inner_product(y) for x in B] for y in B]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0... | stack_v2_sparse_classes_75kplus_train_071920 | 19,054 | no_license | [
{
"docstring": "Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sage: matrix([[x.inner_product(y) for x in B] for y in B]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1] sage: x = e.an_element(); x 2*e[... | 2 | stack_v2_sparse_classes_30k_train_019484 | Implement the Python class `Element` described below.
Class description:
Implement the Element class.
Method signatures and docstrings:
- def inner_product(self, other): Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sag... | Implement the Python class `Element` described below.
Class description:
Implement the Element class.
Method signatures and docstrings:
- def inner_product(self, other): Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sag... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class Element:
def inner_product(self, other):
"""Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sage: matrix([[x.inner_product(y) for x in B] for y in B]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Element:
def inner_product(self, other):
"""Implement the canonical inner product of ``self`` with ``other``. EXAMPLES:: sage: e = RootSystem(['B',3,1]).ambient_space() sage: B = e.basis() sage: matrix([[x.inner_product(y) for x in B] for y in B]) [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0... | the_stack_v2_python_sparse | sage/src/sage/combinat/root_system/type_affine.py | bopopescu/geosci | train | 0 | |
b9145842440778a3f8f01b37f50387049c066b83 | [
"captures: List[UsageCapture] = []\nstack: List[Any] = []\nexclude = set() if exclude is None else exclude\n\ndef finder(part):\n if isinstance(part, Variable) and part.variable == var:\n use = part\n work = list(stack)\n while True:\n item = work.pop()\n if isinstance(... | <|body_start_0|>
captures: List[UsageCapture] = []
stack: List[Any] = []
exclude = set() if exclude is None else exclude
def finder(part):
if isinstance(part, Variable) and part.variable == var:
use = part
work = list(stack)
wh... | Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter. | Lifter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lifter:
"""Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter."""
def capture_usages(base: Block, var: ChunkVariable, recursive: ... | stack_v2_sparse_classes_75kplus_train_071921 | 9,836 | no_license | [
{
"docstring": "Find and capture all the usages (and their contexts) of a variable in a block.",
"name": "capture_usages",
"signature": "def capture_usages(base: Block, var: ChunkVariable, recursive: bool=True, exclude: Optional[Set[Block]]=None) -> List['UsageCapture']"
},
{
"docstring": "Retur... | 3 | stack_v2_sparse_classes_30k_train_050446 | Implement the Python class `Lifter` described below.
Class description:
Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter.
Method signatures and docstring... | Implement the Python class `Lifter` described below.
Class description:
Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter.
Method signatures and docstring... | 4d37cc16f61af70920c36389fae0c6955b5d9551 | <|skeleton|>
class Lifter:
"""Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter."""
def capture_usages(base: Block, var: ChunkVariable, recursive: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lifter:
"""Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter."""
def capture_usages(base: Block, var: ChunkVariable, recursive: bool=True, ex... | the_stack_v2_python_sparse | vulnspec/interpret/lifter.py | jedevc/fyp | train | 0 |
b25d1b5cc1517e6c97a58ce721be3d5e9e19b965 | [
"now_date = date.today()\ncount = User.objects.all().count()\nreturn Response({'count': count, 'date': now_date})",
"cur_date = timezone.now()\nshanghai_date = cur_date.astimezone(tz=pytz.timezone(settings.TIME_ZONE))\nshanghai_0_date = shanghai_date.replace(hour=0, minute=0, second=0, microsecond=0)\ncount = Use... | <|body_start_0|>
now_date = date.today()
count = User.objects.all().count()
return Response({'count': count, 'date': now_date})
<|end_body_0|>
<|body_start_1|>
cur_date = timezone.now()
shanghai_date = cur_date.astimezone(tz=pytz.timezone(settings.TIME_ZONE))
shanghai_0_... | HomeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeView:
def total_count(self, request):
"""用户总数"""
<|body_0|>
def day_increment(self, request):
"""日增用户"""
<|body_1|>
def day_active(self, request):
"""日活跃用户"""
<|body_2|>
def day_orders(self, request):
"""日下单用户"""
... | stack_v2_sparse_classes_75kplus_train_071922 | 4,177 | no_license | [
{
"docstring": "用户总数",
"name": "total_count",
"signature": "def total_count(self, request)"
},
{
"docstring": "日增用户",
"name": "day_increment",
"signature": "def day_increment(self, request)"
},
{
"docstring": "日活跃用户",
"name": "day_active",
"signature": "def day_active(sel... | 5 | stack_v2_sparse_classes_30k_train_045318 | Implement the Python class `HomeView` described below.
Class description:
Implement the HomeView class.
Method signatures and docstrings:
- def total_count(self, request): 用户总数
- def day_increment(self, request): 日增用户
- def day_active(self, request): 日活跃用户
- def day_orders(self, request): 日下单用户
- def month_increment(... | Implement the Python class `HomeView` described below.
Class description:
Implement the HomeView class.
Method signatures and docstrings:
- def total_count(self, request): 用户总数
- def day_increment(self, request): 日增用户
- def day_active(self, request): 日活跃用户
- def day_orders(self, request): 日下单用户
- def month_increment(... | 9d82325ec18ac050e5b076e6e24f6613945bee89 | <|skeleton|>
class HomeView:
def total_count(self, request):
"""用户总数"""
<|body_0|>
def day_increment(self, request):
"""日增用户"""
<|body_1|>
def day_active(self, request):
"""日活跃用户"""
<|body_2|>
def day_orders(self, request):
"""日下单用户"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HomeView:
def total_count(self, request):
"""用户总数"""
now_date = date.today()
count = User.objects.all().count()
return Response({'count': count, 'date': now_date})
def day_increment(self, request):
"""日增用户"""
cur_date = timezone.now()
shanghai_date ... | the_stack_v2_python_sparse | meiduo_mall/apps/meiduo_admin/views/home_views.py | four-leaf-clover1/meiduo_mall | train | 0 | |
4144f6c4f09f8bb29146bb6fdb0113ef61c2275e | [
"self._guesses = []\nself._answer = get_random_number()\nself._win = False",
"guess = input('Guess a number between 1 and 20: ')\nif guess == '' or guess == 'None' or guess == None:\n print('Please enter a number')\n raise ValueError\nelif not isInt_try(guess):\n print('Should be a number')\n raise Va... | <|body_start_0|>
self._guesses = []
self._answer = get_random_number()
self._win = False
<|end_body_0|>
<|body_start_1|>
guess = input('Guess a number between 1 and 20: ')
if guess == '' or guess == 'None' or guess == None:
print('Please enter a number')
... | Number guess class, make it callable to initiate game | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Number guess class, make it callable to initiate game"""
def __init__(self):
"""Init _guesses, _answer, _win to set(), get_random_number(), False"""
<|body_0|>
def guess(self):
"""Ask user for input, convert to int, raise ValueError outputting the follow... | stack_v2_sparse_classes_75kplus_train_071923 | 4,215 | no_license | [
{
"docstring": "Init _guesses, _answer, _win to set(), get_random_number(), False",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Ask user for input, convert to int, raise ValueError outputting the following errors when applicable: 'Please enter a number' 'Should be a ... | 4 | null | Implement the Python class `Game` described below.
Class description:
Number guess class, make it callable to initiate game
Method signatures and docstrings:
- def __init__(self): Init _guesses, _answer, _win to set(), get_random_number(), False
- def guess(self): Ask user for input, convert to int, raise ValueError ... | Implement the Python class `Game` described below.
Class description:
Number guess class, make it callable to initiate game
Method signatures and docstrings:
- def __init__(self): Init _guesses, _answer, _win to set(), get_random_number(), False
- def guess(self): Ask user for input, convert to int, raise ValueError ... | c28aa88e1366ab65f031695959d7cd0b3d08be6b | <|skeleton|>
class Game:
"""Number guess class, make it callable to initiate game"""
def __init__(self):
"""Init _guesses, _answer, _win to set(), get_random_number(), False"""
<|body_0|>
def guess(self):
"""Ask user for input, convert to int, raise ValueError outputting the follow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Game:
"""Number guess class, make it callable to initiate game"""
def __init__(self):
"""Init _guesses, _answer, _win to set(), get_random_number(), False"""
self._guesses = []
self._answer = get_random_number()
self._win = False
def guess(self):
"""Ask user f... | the_stack_v2_python_sparse | 42/guess.py | nishanthegde/bitesofpy | train | 0 |
a5a4f5cfbaff00af750762c4ea13d060c1e2545e | [
"super().__init__(config_entry, client, info)\nself._attr_name = self.generate_name(include_value_name=True)\nself._attr_device_class = DEVICE_CLASS_BATTERY if self.info.primary_value.command_class == CommandClass.BATTERY else None\nself._attr_entity_registry_enabled_default = bool(self.info.primary_value.command_c... | <|body_start_0|>
super().__init__(config_entry, client, info)
self._attr_name = self.generate_name(include_value_name=True)
self._attr_device_class = DEVICE_CLASS_BATTERY if self.info.primary_value.command_class == CommandClass.BATTERY else None
self._attr_entity_registry_enabled_default... | Representation of a Z-Wave binary_sensor. | ZWaveBooleanBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZWaveBooleanBinarySensor:
"""Representation of a Z-Wave binary_sensor."""
def __init__(self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveBooleanBinarySensor entity."""
<|body_0|>
def is_on(self) -> bool | None:
... | stack_v2_sparse_classes_75kplus_train_071924 | 12,776 | permissive | [
{
"docstring": "Initialize a ZWaveBooleanBinarySensor entity.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo) -> None"
},
{
"docstring": "Return if the sensor is on or off.",
"name": "is_on",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_032581 | Implement the Python class `ZWaveBooleanBinarySensor` described below.
Class description:
Representation of a Z-Wave binary_sensor.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo) -> None: Initialize a ZWaveBooleanBinarySensor entity.
- ... | Implement the Python class `ZWaveBooleanBinarySensor` described below.
Class description:
Representation of a Z-Wave binary_sensor.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo) -> None: Initialize a ZWaveBooleanBinarySensor entity.
- ... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ZWaveBooleanBinarySensor:
"""Representation of a Z-Wave binary_sensor."""
def __init__(self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveBooleanBinarySensor entity."""
<|body_0|>
def is_on(self) -> bool | None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZWaveBooleanBinarySensor:
"""Representation of a Z-Wave binary_sensor."""
def __init__(self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo) -> None:
"""Initialize a ZWaveBooleanBinarySensor entity."""
super().__init__(config_entry, client, info)
self._at... | the_stack_v2_python_sparse | homeassistant/components/zwave_js/binary_sensor.py | BenWoodford/home-assistant | train | 11 |
fd78f303ce3eebf391f868c87b5a70aa8b8459a2 | [
"self.backup_run = backup_run\nself.copy_run = copy_run\nself.job_id = job_id\nself.job_name = job_name\nself.job_uid = job_uid\nself.protection_shell_info = protection_shell_info\nself.view_box_id = view_box_id",
"if dictionary is None:\n return None\nbackup_run = cohesity_management_sdk.models.backup_run.Bac... | <|body_start_0|>
self.backup_run = backup_run
self.copy_run = copy_run
self.job_id = job_id
self.job_name = job_name
self.job_uid = job_uid
self.protection_shell_info = protection_shell_info
self.view_box_id = view_box_id
<|end_body_0|>
<|body_start_1|>
i... | Implementation of the 'ProtectionRunInstance' model. Specifies the status of one Job Run. A Job Run can have one Backup Run and zero or more Copy Runs. Attributes: backup_run (BackupRun): Specifies details about the Backup task. A Backup task captures the original backup snapshots. copy_run (list of CopyRun): Array of ... | ProtectionRunInstance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionRunInstance:
"""Implementation of the 'ProtectionRunInstance' model. Specifies the status of one Job Run. A Job Run can have one Backup Run and zero or more Copy Runs. Attributes: backup_run (BackupRun): Specifies details about the Backup task. A Backup task captures the original backup... | stack_v2_sparse_classes_75kplus_train_071925 | 4,263 | permissive | [
{
"docstring": "Constructor for the ProtectionRunInstance class",
"name": "__init__",
"signature": "def __init__(self, backup_run=None, copy_run=None, job_id=None, job_name=None, job_uid=None, protection_shell_info=None, view_box_id=None)"
},
{
"docstring": "Creates an instance of this model fro... | 2 | stack_v2_sparse_classes_30k_val_001970 | Implement the Python class `ProtectionRunInstance` described below.
Class description:
Implementation of the 'ProtectionRunInstance' model. Specifies the status of one Job Run. A Job Run can have one Backup Run and zero or more Copy Runs. Attributes: backup_run (BackupRun): Specifies details about the Backup task. A B... | Implement the Python class `ProtectionRunInstance` described below.
Class description:
Implementation of the 'ProtectionRunInstance' model. Specifies the status of one Job Run. A Job Run can have one Backup Run and zero or more Copy Runs. Attributes: backup_run (BackupRun): Specifies details about the Backup task. A B... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionRunInstance:
"""Implementation of the 'ProtectionRunInstance' model. Specifies the status of one Job Run. A Job Run can have one Backup Run and zero or more Copy Runs. Attributes: backup_run (BackupRun): Specifies details about the Backup task. A Backup task captures the original backup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectionRunInstance:
"""Implementation of the 'ProtectionRunInstance' model. Specifies the status of one Job Run. A Job Run can have one Backup Run and zero or more Copy Runs. Attributes: backup_run (BackupRun): Specifies details about the Backup task. A Backup task captures the original backup snapshots. c... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_run_instance.py | cohesity/management-sdk-python | train | 24 |
942f7e2ac06f33815a91e6f04e0527deb23a6d66 | [
"expected_shape = (1, 5, 5)\nplugin = RecursiveFilter(iterations=self.iterations)\nresult = plugin(self.cube, smoothing_coefficients=self.smoothing_coefficients)\nself.assertIsInstance(result, Cube)\nself.assertEqual(result.shape, expected_shape)\nself.assertEqual(result.shape, expected_shape)",
"plugin = Recursi... | <|body_start_0|>
expected_shape = (1, 5, 5)
plugin = RecursiveFilter(iterations=self.iterations)
result = plugin(self.cube, smoothing_coefficients=self.smoothing_coefficients)
self.assertIsInstance(result, Cube)
self.assertEqual(result.shape, expected_shape)
self.assertEq... | Test the process method. | Test_process | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_process:
"""Test the process method."""
def test_return_type_and_shape(self):
"""Test that the RecursiveFilter plugin returns an iris.cube.Cube of the expected shape."""
<|body_0|>
def test_smoothing_coefficient_cubes(self):
"""Test that the RecursiveFilter ... | stack_v2_sparse_classes_75kplus_train_071926 | 22,857 | permissive | [
{
"docstring": "Test that the RecursiveFilter plugin returns an iris.cube.Cube of the expected shape.",
"name": "test_return_type_and_shape",
"signature": "def test_return_type_and_shape(self)"
},
{
"docstring": "Test that the RecursiveFilter plugin returns the correct data.",
"name": "test_... | 5 | stack_v2_sparse_classes_30k_train_012483 | Implement the Python class `Test_process` described below.
Class description:
Test the process method.
Method signatures and docstrings:
- def test_return_type_and_shape(self): Test that the RecursiveFilter plugin returns an iris.cube.Cube of the expected shape.
- def test_smoothing_coefficient_cubes(self): Test that... | Implement the Python class `Test_process` described below.
Class description:
Test the process method.
Method signatures and docstrings:
- def test_return_type_and_shape(self): Test that the RecursiveFilter plugin returns an iris.cube.Cube of the expected shape.
- def test_smoothing_coefficient_cubes(self): Test that... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_process:
"""Test the process method."""
def test_return_type_and_shape(self):
"""Test that the RecursiveFilter plugin returns an iris.cube.Cube of the expected shape."""
<|body_0|>
def test_smoothing_coefficient_cubes(self):
"""Test that the RecursiveFilter ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_process:
"""Test the process method."""
def test_return_type_and_shape(self):
"""Test that the RecursiveFilter plugin returns an iris.cube.Cube of the expected shape."""
expected_shape = (1, 5, 5)
plugin = RecursiveFilter(iterations=self.iterations)
result = plugin(se... | the_stack_v2_python_sparse | improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py | metoppv/improver | train | 101 |
c613557999b76ee32f1f6adeaa58ab22792cb7fc | [
"self.capacity = capacity\nself.size = 0\nself.cache = DoubleLinkedList()\nself.map = dict()",
"if key in self.map and self.map[key]:\n self.cache.remove(self.map[key])\n self.cache.addHead(self.map[key])\n return self.map[key].val\nelse:\n return -1",
"if key in self.map:\n self.cache.remove(sel... | <|body_start_0|>
self.capacity = capacity
self.size = 0
self.cache = DoubleLinkedList()
self.map = dict()
<|end_body_0|>
<|body_start_1|>
if key in self.map and self.map[key]:
self.cache.remove(self.map[key])
self.cache.addHead(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):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_071927 | 2,149 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 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): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | 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): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 08e791733824ddf82ba07d1666b1e5e07fb8189d | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.size = 0
self.cache = DoubleLinkedList()
self.map = dict()
def get(self, key):
""":rtype: int"""
if key in self.map and self.map[key]:
self.c... | the_stack_v2_python_sparse | LRUCache.py | mihaanali/coding_practice | train | 0 | |
88ea78055a55b657f15dedb6dc7dd94b5d6391f8 | [
"super().__init__()\n\ndef discriminator_block(in_filters, out_filters, bn=True):\n \"\"\"Returns layers of each discriminator block\"\"\"\n block = [torch.nn.Conv2d(in_filters, out_filters, 3, 2, 1), torch.nn.LeakyReLU(0.2, inplace=True), torch.nn.Dropout2d(0.25)]\n if bn:\n block.append(torch.nn.B... | <|body_start_0|>
super().__init__()
def discriminator_block(in_filters, out_filters, bn=True):
"""Returns layers of each discriminator block"""
block = [torch.nn.Conv2d(in_filters, out_filters, 3, 2, 1), torch.nn.LeakyReLU(0.2, inplace=True), torch.nn.Dropout2d(0.25)]
... | A simple discriminator network | Discriminator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Discriminator:
"""A simple discriminator network"""
def __init__(self, code_dim, n_classes, num_channels, img_size):
"""Parameters ---------- code_dim : int size of the code dimension n_classes : int number of image classes num_channels : int number of image channels img_size : int n... | stack_v2_sparse_classes_75kplus_train_071928 | 4,507 | permissive | [
{
"docstring": "Parameters ---------- code_dim : int size of the code dimension n_classes : int number of image classes num_channels : int number of image channels img_size : int number of pixels per side",
"name": "__init__",
"signature": "def __init__(self, code_dim, n_classes, num_channels, img_size)... | 2 | null | Implement the Python class `Discriminator` described below.
Class description:
A simple discriminator network
Method signatures and docstrings:
- def __init__(self, code_dim, n_classes, num_channels, img_size): Parameters ---------- code_dim : int size of the code dimension n_classes : int number of image classes num... | Implement the Python class `Discriminator` described below.
Class description:
A simple discriminator network
Method signatures and docstrings:
- def __init__(self, code_dim, n_classes, num_channels, img_size): Parameters ---------- code_dim : int size of the code dimension n_classes : int number of image classes num... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class Discriminator:
"""A simple discriminator network"""
def __init__(self, code_dim, n_classes, num_channels, img_size):
"""Parameters ---------- code_dim : int size of the code dimension n_classes : int number of image classes num_channels : int number of image channels img_size : int n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Discriminator:
"""A simple discriminator network"""
def __init__(self, code_dim, n_classes, num_channels, img_size):
"""Parameters ---------- code_dim : int size of the code dimension n_classes : int number of image classes num_channels : int number of image channels img_size : int number of pixe... | the_stack_v2_python_sparse | dlutils/models/gans/info/models.py | justusschock/dl-utils | train | 15 |
d623b02e7b2d98227866e3cfc49467a30e2cd2fc | [
"permissions = [IsAuthenticated]\nif self.action in ['update', 'partial_update']:\n permissions.append(IsCircleAdmin)\nreturn [p() for p in permissions]",
"queryset = Circle.objects.all()\nif self.action == 'list':\n queryset = Circle.objects.filter(is_public=True)\nreturn queryset",
"user = self.request.... | <|body_start_0|>
permissions = [IsAuthenticated]
if self.action in ['update', 'partial_update']:
permissions.append(IsCircleAdmin)
return [p() for p in permissions]
<|end_body_0|>
<|body_start_1|>
queryset = Circle.objects.all()
if self.action == 'list':
... | Circle viewset. | CircleViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CircleViewSet:
"""Circle viewset."""
def get_permissions(self):
"""Permissions based in actions."""
<|body_0|>
def get_queryset(self):
"""Specify and limit queryset in list action."""
<|body_1|>
def perform_create(self, serializer):
"""Create... | stack_v2_sparse_classes_75kplus_train_071929 | 1,656 | permissive | [
{
"docstring": "Permissions based in actions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Specify and limit queryset in list action.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Create the relation... | 3 | stack_v2_sparse_classes_30k_train_044341 | Implement the Python class `CircleViewSet` described below.
Class description:
Circle viewset.
Method signatures and docstrings:
- def get_permissions(self): Permissions based in actions.
- def get_queryset(self): Specify and limit queryset in list action.
- def perform_create(self, serializer): Create the relationsh... | Implement the Python class `CircleViewSet` described below.
Class description:
Circle viewset.
Method signatures and docstrings:
- def get_permissions(self): Permissions based in actions.
- def get_queryset(self): Specify and limit queryset in list action.
- def perform_create(self, serializer): Create the relationsh... | 5c3b7e97400170c20864ad74af7f524bccf87cf9 | <|skeleton|>
class CircleViewSet:
"""Circle viewset."""
def get_permissions(self):
"""Permissions based in actions."""
<|body_0|>
def get_queryset(self):
"""Specify and limit queryset in list action."""
<|body_1|>
def perform_create(self, serializer):
"""Create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CircleViewSet:
"""Circle viewset."""
def get_permissions(self):
"""Permissions based in actions."""
permissions = [IsAuthenticated]
if self.action in ['update', 'partial_update']:
permissions.append(IsCircleAdmin)
return [p() for p in permissions]
def get_... | the_stack_v2_python_sparse | bookshare/circles/views/circles.py | ezecavallo/bookshare | train | 0 |
156a77d9fbccb8b044b7b2a03b6d6aa97d4c02f6 | [
"self.connection = None\nself.method = method\nself.protocol = protocol\nself.servername = servername\nself.url = url\nself.params = params or {}\nself.location = None\nself.credentials = credentials\nself.proxy = proxy\nself.rdns = rdns\nself.proxy_auth = proxy_auth\nself.timeout = timeout\nself.headers = headers ... | <|body_start_0|>
self.connection = None
self.method = method
self.protocol = protocol
self.servername = servername
self.url = url
self.params = params or {}
self.location = None
self.credentials = credentials
self.proxy = proxy
self.rdns = ... | HTTP client with proxy support | HTTPClient | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPClient:
"""HTTP client with proxy support"""
def __init__(self, method, protocol, servername, url, params=None, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None):
"""Intialize HTTP connection"""
<|body_0|>
def get_response(self):
... | stack_v2_sparse_classes_75kplus_train_071930 | 4,683 | permissive | [
{
"docstring": "Intialize HTTP connection",
"name": "__init__",
"signature": "def __init__(self, method, protocol, servername, url, params=None, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None)"
},
{
"docstring": "Common HTTP request",
"name": "get_response",
... | 2 | stack_v2_sparse_classes_30k_train_029358 | Implement the Python class `HTTPClient` described below.
Class description:
HTTP client with proxy support
Method signatures and docstrings:
- def __init__(self, method, protocol, servername, url, params=None, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None): Intialize HTTP connection
-... | Implement the Python class `HTTPClient` described below.
Class description:
HTTP client with proxy support
Method signatures and docstrings:
- def __init__(self, method, protocol, servername, url, params=None, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None): Intialize HTTP connection
-... | 88253ca166c15a1eb7d9112a025b3a4e130a7db6 | <|skeleton|>
class HTTPClient:
"""HTTP client with proxy support"""
def __init__(self, method, protocol, servername, url, params=None, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None):
"""Intialize HTTP connection"""
<|body_0|>
def get_response(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTTPClient:
"""HTTP client with proxy support"""
def __init__(self, method, protocol, servername, url, params=None, credentials=(), proxy=(), rdns=True, proxy_auth=(), timeout=None, headers=None):
"""Intialize HTTP connection"""
self.connection = None
self.method = method
... | the_stack_v2_python_sparse | src/pyams_utils/protocol/http.py | Py-AMS/pyams-utils | train | 0 |
52a067d18f5bf6ddfcb6c2955a0251eda271e4ad | [
"compound_action_constructor = None\nif replay_schema is ReplaySchema.V2:\n compound_action_constructor = WhenAllAction\nsuper().__init__(task, compound_action_constructor)",
"if child.state is TaskState.SUCCEEDED:\n if len(self.pending_tasks) == 0:\n results = list(map(lambda x: x.result, self.child... | <|body_start_0|>
compound_action_constructor = None
if replay_schema is ReplaySchema.V2:
compound_action_constructor = WhenAllAction
super().__init__(task, compound_action_constructor)
<|end_body_0|>
<|body_start_1|>
if child.state is TaskState.SUCCEEDED:
if len(... | A Task representing `when_all` scenarios. | WhenAllTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhenAllTask:
"""A Task representing `when_all` scenarios."""
def __init__(self, task: List[TaskBase], replay_schema: ReplaySchema):
"""Initialize a WhenAllTask. Parameters ---------- task : List[Task] The list of child tasks replay_schema : ReplaySchema The ReplaySchema, which determ... | stack_v2_sparse_classes_75kplus_train_071931 | 14,773 | permissive | [
{
"docstring": "Initialize a WhenAllTask. Parameters ---------- task : List[Task] The list of child tasks replay_schema : ReplaySchema The ReplaySchema, which determines the inner action payload representation",
"name": "__init__",
"signature": "def __init__(self, task: List[TaskBase], replay_schema: Re... | 2 | null | Implement the Python class `WhenAllTask` described below.
Class description:
A Task representing `when_all` scenarios.
Method signatures and docstrings:
- def __init__(self, task: List[TaskBase], replay_schema: ReplaySchema): Initialize a WhenAllTask. Parameters ---------- task : List[Task] The list of child tasks re... | Implement the Python class `WhenAllTask` described below.
Class description:
A Task representing `when_all` scenarios.
Method signatures and docstrings:
- def __init__(self, task: List[TaskBase], replay_schema: ReplaySchema): Initialize a WhenAllTask. Parameters ---------- task : List[Task] The list of child tasks re... | 5d30ae3b6b1158b021eb848629c1399381d783a8 | <|skeleton|>
class WhenAllTask:
"""A Task representing `when_all` scenarios."""
def __init__(self, task: List[TaskBase], replay_schema: ReplaySchema):
"""Initialize a WhenAllTask. Parameters ---------- task : List[Task] The list of child tasks replay_schema : ReplaySchema The ReplaySchema, which determ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhenAllTask:
"""A Task representing `when_all` scenarios."""
def __init__(self, task: List[TaskBase], replay_schema: ReplaySchema):
"""Initialize a WhenAllTask. Parameters ---------- task : List[Task] The list of child tasks replay_schema : ReplaySchema The ReplaySchema, which determines the inne... | the_stack_v2_python_sparse | azure/durable_functions/models/Task.py | Azure/azure-functions-durable-python | train | 104 |
27e726f040976c24c57f1b6d78f0f106314de362 | [
"parser.usage = help_usage.format(parser.prog)\nparser.description = help_description.format(parser.prog, ' ' * len(parser.prog))\ng = parser.add_mutually_exclusive_group()\ng.add_argument('--total', '-t', default=False, action='store_true', help='assume a total order')\ng.add_argument('--smart', '-s', default=Fals... | <|body_start_0|>
parser.usage = help_usage.format(parser.prog)
parser.description = help_description.format(parser.prog, ' ' * len(parser.prog))
g = parser.add_mutually_exclusive_group()
g.add_argument('--total', '-t', default=False, action='store_true', help='assume a total order')
... | Command line helper for Ordering principle formulas | OPCmdHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OPCmdHelper:
"""Command line helper for Ordering principle formulas"""
def setup_command_line(parser):
"""Setup the command line options for Ordering principle formula Arguments: - `parser`: parser to load with options."""
<|body_0|>
def build_cnf(args):
"""Build... | stack_v2_sparse_classes_75kplus_train_071932 | 5,321 | no_license | [
{
"docstring": "Setup the command line options for Ordering principle formula Arguments: - `parser`: parser to load with options.",
"name": "setup_command_line",
"signature": "def setup_command_line(parser)"
},
{
"docstring": "Build an Ordering principle formula according to the arguments Argume... | 2 | null | Implement the Python class `OPCmdHelper` described below.
Class description:
Command line helper for Ordering principle formulas
Method signatures and docstrings:
- def setup_command_line(parser): Setup the command line options for Ordering principle formula Arguments: - `parser`: parser to load with options.
- def b... | Implement the Python class `OPCmdHelper` described below.
Class description:
Command line helper for Ordering principle formulas
Method signatures and docstrings:
- def setup_command_line(parser): Setup the command line options for Ordering principle formula Arguments: - `parser`: parser to load with options.
- def b... | f4dbc89eddaaf7fac1730685bc97d646cec06a1e | <|skeleton|>
class OPCmdHelper:
"""Command line helper for Ordering principle formulas"""
def setup_command_line(parser):
"""Setup the command line options for Ordering principle formula Arguments: - `parser`: parser to load with options."""
<|body_0|>
def build_cnf(args):
"""Build... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OPCmdHelper:
"""Command line helper for Ordering principle formulas"""
def setup_command_line(parser):
"""Setup the command line options for Ordering principle formula Arguments: - `parser`: parser to load with options."""
parser.usage = help_usage.format(parser.prog)
parser.descr... | the_stack_v2_python_sparse | Experiments/venv/lib/python3.7/site-packages/cnfgen/clihelpers/ordering_helpers.py | souravskr/MS-Project | train | 0 |
eb67b974f9a01731dc22996004c6ae264c83dc99 | [
"if hasattr(self, '_ext'):\n return None\ndct = self._base_map(no_owner, no_privs)\nif 'functions' in dct:\n del dct['functions']\nreturn dct",
"stmts = []\nif not hasattr(self, '_ext'):\n stmts.append('CREATE LANGUAGE %s' % quote_id(self.name))\n if self.owner is not None:\n stmts.append(self.... | <|body_start_0|>
if hasattr(self, '_ext'):
return None
dct = self._base_map(no_owner, no_privs)
if 'functions' in dct:
del dct['functions']
return dct
<|end_body_0|>
<|body_start_1|>
stmts = []
if not hasattr(self, '_ext'):
stmts.appen... | A procedural language definition | Language | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Language:
"""A procedural language definition"""
def to_map(self, no_owner, no_privs):
"""Convert language to a YAML-suitable format :param no_owner: exclude language owner information :return: dictionary"""
<|body_0|>
def create(self):
"""Return SQL statements t... | stack_v2_sparse_classes_75kplus_train_071933 | 6,116 | permissive | [
{
"docstring": "Convert language to a YAML-suitable format :param no_owner: exclude language owner information :return: dictionary",
"name": "to_map",
"signature": "def to_map(self, no_owner, no_privs)"
},
{
"docstring": "Return SQL statements to CREATE the language :return: SQL statements",
... | 2 | stack_v2_sparse_classes_30k_train_041187 | Implement the Python class `Language` described below.
Class description:
A procedural language definition
Method signatures and docstrings:
- def to_map(self, no_owner, no_privs): Convert language to a YAML-suitable format :param no_owner: exclude language owner information :return: dictionary
- def create(self): Re... | Implement the Python class `Language` described below.
Class description:
A procedural language definition
Method signatures and docstrings:
- def to_map(self, no_owner, no_privs): Convert language to a YAML-suitable format :param no_owner: exclude language owner information :return: dictionary
- def create(self): Re... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class Language:
"""A procedural language definition"""
def to_map(self, no_owner, no_privs):
"""Convert language to a YAML-suitable format :param no_owner: exclude language owner information :return: dictionary"""
<|body_0|>
def create(self):
"""Return SQL statements t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Language:
"""A procedural language definition"""
def to_map(self, no_owner, no_privs):
"""Convert language to a YAML-suitable format :param no_owner: exclude language owner information :return: dictionary"""
if hasattr(self, '_ext'):
return None
dct = self._base_map(no... | the_stack_v2_python_sparse | pyrseas/dbobject/language.py | vayerx/Pyrseas | train | 1 |
300026554d56b5c8db50d4aeb8214ac13f36d766 | [
"args = get_checkin_parser.parse_args()\nlimit = min(args['limit'], 10)\nres = Checkins.get_all(g.user.id, limit)\nreturn (res, 200)",
"args = post_checkin_parser.parse_args()\nres = Checkins.add(g.user.id, args['slot_id'])\nif not res:\n api.abort(404, 'No slot existing with this id')\nreturn (res, 201)"
] | <|body_start_0|>
args = get_checkin_parser.parse_args()
limit = min(args['limit'], 10)
res = Checkins.get_all(g.user.id, limit)
return (res, 200)
<|end_body_0|>
<|body_start_1|>
args = post_checkin_parser.parse_args()
res = Checkins.add(g.user.id, args['slot_id'])
... | CheckinList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckinList:
def get(self):
"""Get the list of last checkins. List has a max length of 10 checkins."""
<|body_0|>
def post(self):
"""Add a new checkin"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = get_checkin_parser.parse_args()
lim... | stack_v2_sparse_classes_75kplus_train_071934 | 36,924 | permissive | [
{
"docstring": "Get the list of last checkins. List has a max length of 10 checkins.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a new checkin",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034290 | Implement the Python class `CheckinList` described below.
Class description:
Implement the CheckinList class.
Method signatures and docstrings:
- def get(self): Get the list of last checkins. List has a max length of 10 checkins.
- def post(self): Add a new checkin | Implement the Python class `CheckinList` described below.
Class description:
Implement the CheckinList class.
Method signatures and docstrings:
- def get(self): Get the list of last checkins. List has a max length of 10 checkins.
- def post(self): Add a new checkin
<|skeleton|>
class CheckinList:
def get(self):... | aa8110de839233dd9b0905f010ca9994c6f3ffb7 | <|skeleton|>
class CheckinList:
def get(self):
"""Get the list of last checkins. List has a max length of 10 checkins."""
<|body_0|>
def post(self):
"""Add a new checkin"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckinList:
def get(self):
"""Get the list of last checkins. List has a max length of 10 checkins."""
args = get_checkin_parser.parse_args()
limit = min(args['limit'], 10)
res = Checkins.get_all(g.user.id, limit)
return (res, 200)
def post(self):
"""Add a ... | the_stack_v2_python_sparse | prkng/api/public/v1.py | OmniaProbitate/api | train | 0 | |
5bd16de76f20cc5722bda3757549d88fdef34848 | [
"with self.schema.table('drinkers') as table:\n table.drop_column('profile_photo')\n table.string('profile_photos')\n table.integer('profile_pivot_increment')\n table.integer('profile_pivot_type').unsigned()\n table.foreign('profile_pivot_type').references('id').on('event_types').on_delete('cascade')... | <|body_start_0|>
with self.schema.table('drinkers') as table:
table.drop_column('profile_photo')
table.string('profile_photos')
table.integer('profile_pivot_increment')
table.integer('profile_pivot_type').unsigned()
table.foreign('profile_pivot_type').... | UpdateProfilePhotos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateProfilePhotos:
def up(self):
"""Run the migrations."""
<|body_0|>
def down(self):
"""Revert the migrations."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with self.schema.table('drinkers') as table:
table.drop_column('profile_pho... | stack_v2_sparse_classes_75kplus_train_071935 | 850 | no_license | [
{
"docstring": "Run the migrations.",
"name": "up",
"signature": "def up(self)"
},
{
"docstring": "Revert the migrations.",
"name": "down",
"signature": "def down(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008301 | Implement the Python class `UpdateProfilePhotos` described below.
Class description:
Implement the UpdateProfilePhotos class.
Method signatures and docstrings:
- def up(self): Run the migrations.
- def down(self): Revert the migrations. | Implement the Python class `UpdateProfilePhotos` described below.
Class description:
Implement the UpdateProfilePhotos class.
Method signatures and docstrings:
- def up(self): Run the migrations.
- def down(self): Revert the migrations.
<|skeleton|>
class UpdateProfilePhotos:
def up(self):
"""Run the mi... | 280e678d8f63ba219a61e658ea2215281561b4bf | <|skeleton|>
class UpdateProfilePhotos:
def up(self):
"""Run the migrations."""
<|body_0|>
def down(self):
"""Revert the migrations."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateProfilePhotos:
def up(self):
"""Run the migrations."""
with self.schema.table('drinkers') as table:
table.drop_column('profile_photo')
table.string('profile_photos')
table.integer('profile_pivot_increment')
table.integer('profile_pivot_type... | the_stack_v2_python_sparse | migrations/2018_05_10_192004_update_profile_photos.py | ChiSigma/chi-swig-tracker | train | 0 | |
5da4494b1b1818424d71ccbb1b66db0bb9dc17b7 | [
"for project_id, instances in resource_from_api.iteritems():\n for instance in instances:\n yield {'project_id': project_id, 'id': instance.get('id'), 'creation_timestamp': parser.format_timestamp(instance.get('creationTimestamp'), self.MYSQL_DATETIME_FORMAT), 'name': instance.get('name'), 'description': ... | <|body_start_0|>
for project_id, instances in resource_from_api.iteritems():
for instance in instances:
yield {'project_id': project_id, 'id': instance.get('id'), 'creation_timestamp': parser.format_timestamp(instance.get('creationTimestamp'), self.MYSQL_DATETIME_FORMAT), 'name': ins... | Load compute instances for all projects. | LoadInstancesPipeline | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadInstancesPipeline:
"""Load compute instances for all projects."""
def _transform(self, resource_from_api):
"""Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance prop... | stack_v2_sparse_classes_75kplus_train_071936 | 4,162 | permissive | [
{
"docstring": "Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance properties.",
"name": "_transform",
"signature": "def _transform(self, resource_from_api)"
},
{
"docstring": "Retr... | 3 | stack_v2_sparse_classes_30k_train_006025 | Implement the Python class `LoadInstancesPipeline` described below.
Class description:
Load compute instances for all projects.
Method signatures and docstrings:
- def _transform(self, resource_from_api): Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed... | Implement the Python class `LoadInstancesPipeline` described below.
Class description:
Load compute instances for all projects.
Method signatures and docstrings:
- def _transform(self, resource_from_api): Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed... | a6a1aa7464cda2ad5948e3e8876eb8dded5e2514 | <|skeleton|>
class LoadInstancesPipeline:
"""Load compute instances for all projects."""
def _transform(self, resource_from_api):
"""Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance prop... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadInstancesPipeline:
"""Load compute instances for all projects."""
def _transform(self, resource_from_api):
"""Create an iterator of instances to load into database. Args: resource_from_api (dict): A dict of instances, keyed by project id, from GCP API. Yields: dict: Instance properties."""
... | the_stack_v2_python_sparse | google/cloud/security/inventory/pipelines/load_instances_pipeline.py | shimizu19691210/forseti-security | train | 1 |
0efe5d502ffa1cb9a3ed2551e6d24b833f646ec0 | [
"dp = [float('inf')] * (T + 1)\ndp[0] = 0\npre = [float('inf')] * (100 + 1)\nfor l, r in clips:\n for j in range(l, r + 1):\n pre[j] = min(pre[j], l)\nfor i in range(1, T + 1):\n if pre[i] != float('inf'):\n dp[i] = min(dp[i], dp[pre[i]] + 1)\nreturn dp[-1] if dp[-1] != float('inf') else -1",
... | <|body_start_0|>
dp = [float('inf')] * (T + 1)
dp[0] = 0
pre = [float('inf')] * (100 + 1)
for l, r in clips:
for j in range(l, r + 1):
pre[j] = min(pre[j], l)
for i in range(1, T + 1):
if pre[i] != float('inf'):
dp[i] = min(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def videoStitching1(self, clips: List[List[int]], T: int) -> int:
"""思路:动态规划法 1. 获取每个位置对应的左边可以到达的最小位置,动态规划时从最小的位置转移 @param clips: @param T: @return:"""
<|body_0|>
def videoStitching2(self, clips: List[List[int]], T: int) -> int:
"""思路:贪心算法 @param clips: @pa... | stack_v2_sparse_classes_75kplus_train_071937 | 3,323 | no_license | [
{
"docstring": "思路:动态规划法 1. 获取每个位置对应的左边可以到达的最小位置,动态规划时从最小的位置转移 @param clips: @param T: @return:",
"name": "videoStitching1",
"signature": "def videoStitching1(self, clips: List[List[int]], T: int) -> int"
},
{
"docstring": "思路:贪心算法 @param clips: @param T: @return:",
"name": "videoStitching2"... | 2 | stack_v2_sparse_classes_30k_val_002997 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def videoStitching1(self, clips: List[List[int]], T: int) -> int: 思路:动态规划法 1. 获取每个位置对应的左边可以到达的最小位置,动态规划时从最小的位置转移 @param clips: @param T: @return:
- def videoStitching2(self, clip... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def videoStitching1(self, clips: List[List[int]], T: int) -> int: 思路:动态规划法 1. 获取每个位置对应的左边可以到达的最小位置,动态规划时从最小的位置转移 @param clips: @param T: @return:
- def videoStitching2(self, clip... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def videoStitching1(self, clips: List[List[int]], T: int) -> int:
"""思路:动态规划法 1. 获取每个位置对应的左边可以到达的最小位置,动态规划时从最小的位置转移 @param clips: @param T: @return:"""
<|body_0|>
def videoStitching2(self, clips: List[List[int]], T: int) -> int:
"""思路:贪心算法 @param clips: @pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def videoStitching1(self, clips: List[List[int]], T: int) -> int:
"""思路:动态规划法 1. 获取每个位置对应的左边可以到达的最小位置,动态规划时从最小的位置转移 @param clips: @param T: @return:"""
dp = [float('inf')] * (T + 1)
dp[0] = 0
pre = [float('inf')] * (100 + 1)
for l, r in clips:
for ... | the_stack_v2_python_sparse | LeetCode/动态规划法(dp)/1024. 视频拼接.py | yiming1012/MyLeetCode | train | 2 | |
a7db6285fac2f35c47ebf93afa71881395aa1695 | [
"super(ContentEnc, self).__init__()\nself.cont_conv1 = nn.Sequential(nn.Conv2d(c_dim, gf_dim, 3, padding=1), nn.ReLU(), nn.Conv2d(gf_dim, gf_dim, 3, padding=1), nn.ReLU())\nself.cont_conv2 = nn.Sequential(nn.MaxPool2d(2), nn.Conv2d(gf_dim, gf_dim * 2, 3, padding=1), nn.ReLU(), nn.Conv2d(gf_dim * 2, gf_dim * 2, 3, p... | <|body_start_0|>
super(ContentEnc, self).__init__()
self.cont_conv1 = nn.Sequential(nn.Conv2d(c_dim, gf_dim, 3, padding=1), nn.ReLU(), nn.Conv2d(gf_dim, gf_dim, 3, padding=1), nn.ReLU())
self.cont_conv2 = nn.Sequential(nn.MaxPool2d(2), nn.Conv2d(gf_dim, gf_dim * 2, 3, padding=1), nn.ReLU(), nn.C... | The motion encoder as defined by Villegas et al. (https://arxiv.org/abs/1706.08033). This module takes a standard frame and produces an encoded representation with reduced resolution. It also produces the intermediate convolutional activations for use with residual layers. | ContentEnc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentEnc:
"""The motion encoder as defined by Villegas et al. (https://arxiv.org/abs/1706.08033). This module takes a standard frame and produces an encoded representation with reduced resolution. It also produces the intermediate convolutional activations for use with residual layers."""
... | stack_v2_sparse_classes_75kplus_train_071938 | 16,402 | no_license | [
{
"docstring": "Constructor :param c_dim: The number of image channels (e.g. 3 for RGB) :param gf_dim: The number of filters in the first layer",
"name": "__init__",
"signature": "def __init__(self, c_dim, gf_dim)"
},
{
"docstring": "Forward method :param raw: A raw image frame [batch_size, c_di... | 2 | stack_v2_sparse_classes_30k_train_053907 | Implement the Python class `ContentEnc` described below.
Class description:
The motion encoder as defined by Villegas et al. (https://arxiv.org/abs/1706.08033). This module takes a standard frame and produces an encoded representation with reduced resolution. It also produces the intermediate convolutional activations... | Implement the Python class `ContentEnc` described below.
Class description:
The motion encoder as defined by Villegas et al. (https://arxiv.org/abs/1706.08033). This module takes a standard frame and produces an encoded representation with reduced resolution. It also produces the intermediate convolutional activations... | da2872999c38c3aab0357cb6e7e0db9100638505 | <|skeleton|>
class ContentEnc:
"""The motion encoder as defined by Villegas et al. (https://arxiv.org/abs/1706.08033). This module takes a standard frame and produces an encoded representation with reduced resolution. It also produces the intermediate convolutional activations for use with residual layers."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContentEnc:
"""The motion encoder as defined by Villegas et al. (https://arxiv.org/abs/1706.08033). This module takes a standard frame and produces an encoded representation with reduced resolution. It also produces the intermediate convolutional activations for use with residual layers."""
def __init__(... | the_stack_v2_python_sparse | src/models/mcnet/mcnet.py | MichiganCOG/video-frame-inpainting | train | 9 |
48b50c0e2b96caf223f4991ae64ae86248aac133 | [
"for _ng in cls.WORD_LIST:\n m = re.search(_ng, text)\n if m:\n return True\nreturn False",
"for _ng_word in cls.WORD_LIST:\n text = re.sub('%s' % _ng_word, '', text)\nreturn text"
] | <|body_start_0|>
for _ng in cls.WORD_LIST:
m = re.search(_ng, text)
if m:
return True
return False
<|end_body_0|>
<|body_start_1|>
for _ng_word in cls.WORD_LIST:
text = re.sub('%s' % _ng_word, '', text)
return text
<|end_body_1|>
| NGBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NGBase:
def check(cls, text):
"""マッチしたらTrue"""
<|body_0|>
def remove(cls, text):
"""textからNGワードを除外して返却"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for _ng in cls.WORD_LIST:
m = re.search(_ng, text)
if m:
r... | stack_v2_sparse_classes_75kplus_train_071939 | 844 | no_license | [
{
"docstring": "マッチしたらTrue",
"name": "check",
"signature": "def check(cls, text)"
},
{
"docstring": "textからNGワードを除外して返却",
"name": "remove",
"signature": "def remove(cls, text)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014802 | Implement the Python class `NGBase` described below.
Class description:
Implement the NGBase class.
Method signatures and docstrings:
- def check(cls, text): マッチしたらTrue
- def remove(cls, text): textからNGワードを除外して返却 | Implement the Python class `NGBase` described below.
Class description:
Implement the NGBase class.
Method signatures and docstrings:
- def check(cls, text): マッチしたらTrue
- def remove(cls, text): textからNGワードを除外して返却
<|skeleton|>
class NGBase:
def check(cls, text):
"""マッチしたらTrue"""
<|body_0|>
d... | eefd311c6f1edad483b89f9a513bcc2f9dfabe14 | <|skeleton|>
class NGBase:
def check(cls, text):
"""マッチしたらTrue"""
<|body_0|>
def remove(cls, text):
"""textからNGワードを除外して返却"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NGBase:
def check(cls, text):
"""マッチしたらTrue"""
for _ng in cls.WORD_LIST:
m = re.search(_ng, text)
if m:
return True
return False
def remove(cls, text):
"""textからNGワードを除外して返却"""
for _ng_word in cls.WORD_LIST:
text ... | the_stack_v2_python_sparse | anchovy/module/mecab/ng_word.py | arpsabbir/anchovy | train | 0 | |
88dbadd15ab71c8a101724777572d76dfd810e4e | [
"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. | RoleAppServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def role_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def role_by_id(self, request, context):
"""Missing associate... | stack_v2_sparse_classes_75kplus_train_071940 | 11,553 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "role_by_name",
"signature": "def role_by_name(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "role_by_id",
"signature": "def role_by_id(self... | 6 | null | Implement the Python class `RoleAppServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def role_by_name(self, request, context): Missing associated documentation comment in .proto file.
- def role_by_id(self, request, contex... | Implement the Python class `RoleAppServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def role_by_name(self, request, context): Missing associated documentation comment in .proto file.
- def role_by_id(self, request, contex... | 55d36c068e26e13ee5bae5c033e2e17784c63feb | <|skeleton|>
class RoleAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def role_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def role_by_id(self, request, context):
"""Missing associate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoleAppServiceServicer:
"""Missing associated documentation comment in .proto file."""
def role_by_name(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implement... | the_stack_v2_python_sparse | src/resource/proto/_generated/identity/role_app_service_pb2_grpc.py | arkanmgerges/cafm.identity | train | 0 |
eec2491ad6aacfba55affcb39edb0e4071cac320 | [
"indptr, indices = self.delaunay.vertex_neighbor_vertices\nsizes = indptr[1:] - indptr[:-1]\nneighbors = -1 * np.ones(shape=(self.parameters, int(np.max(sizes))), dtype='int')\nfor k in range(self.parameters):\n neighbors[k][0:sizes[k]] = indices[indptr[k]:indptr[k + 1]]\nreturn Neighbors(arr=neighbors.astype('i... | <|body_start_0|>
indptr, indices = self.delaunay.vertex_neighbor_vertices
sizes = indptr[1:] - indptr[:-1]
neighbors = -1 * np.ones(shape=(self.parameters, int(np.max(sizes))), dtype='int')
for k in range(self.parameters):
neighbors[k][0:sizes[k]] = indices[indptr[k]:indptr[k... | Mesh2DDelaunay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mesh2DDelaunay:
def neighbors(self) -> Neighbors:
"""Returns a ndarray describing the neighbors of every pixel in a Delaunay triangulation, where a neighbor is defined as two Delaunay triangles which are directly connected to one another in the triangulation. see `Neighbors` for a comple... | stack_v2_sparse_classes_75kplus_train_071941 | 3,544 | permissive | [
{
"docstring": "Returns a ndarray describing the neighbors of every pixel in a Delaunay triangulation, where a neighbor is defined as two Delaunay triangles which are directly connected to one another in the triangulation. see `Neighbors` for a complete description of the neighboring scheme. The neighbors of a ... | 2 | null | Implement the Python class `Mesh2DDelaunay` described below.
Class description:
Implement the Mesh2DDelaunay class.
Method signatures and docstrings:
- def neighbors(self) -> Neighbors: Returns a ndarray describing the neighbors of every pixel in a Delaunay triangulation, where a neighbor is defined as two Delaunay t... | Implement the Python class `Mesh2DDelaunay` described below.
Class description:
Implement the Mesh2DDelaunay class.
Method signatures and docstrings:
- def neighbors(self) -> Neighbors: Returns a ndarray describing the neighbors of every pixel in a Delaunay triangulation, where a neighbor is defined as two Delaunay t... | 6639dd86d21ea28e942155753ec556752735b4e4 | <|skeleton|>
class Mesh2DDelaunay:
def neighbors(self) -> Neighbors:
"""Returns a ndarray describing the neighbors of every pixel in a Delaunay triangulation, where a neighbor is defined as two Delaunay triangles which are directly connected to one another in the triangulation. see `Neighbors` for a comple... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mesh2DDelaunay:
def neighbors(self) -> Neighbors:
"""Returns a ndarray describing the neighbors of every pixel in a Delaunay triangulation, where a neighbor is defined as two Delaunay triangles which are directly connected to one another in the triangulation. see `Neighbors` for a complete description... | the_stack_v2_python_sparse | autoarray/structures/mesh/delaunay_2d.py | Jammy2211/PyAutoArray | train | 6 | |
aee26f8d7271f9cfda249722ecb7f1362db4e1bb | [
"user_login_obj = UserLoginSchemaBase().load({'login': login})\nif user_login_obj.errors:\n return ({'errors': user_login_obj.errors}, 400)\nuser = db.session.query(User).filter(User.login == login, User.pending == true()).first()\nuser.pending = False\nuser.registered_on = datetime.datetime.now()\nuser.register... | <|body_start_0|>
user_login_obj = UserLoginSchemaBase().load({'login': login})
if user_login_obj.errors:
return ({'errors': user_login_obj.errors}, 400)
user = db.session.query(User).filter(User.login == login, User.pending == true()).first()
user.pending = False
user... | UserPendingResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPendingResource:
def post(self, login):
"""--- summary: Accept a pending registration description: | Accepts pending user registration. Requires `manage_users` capability. security: - bearerAuth: [] tags: - user parameters: - in: path name: login schema: type: string description: Log... | stack_v2_sparse_classes_75kplus_train_071942 | 13,862 | no_license | [
{
"docstring": "--- summary: Accept a pending registration description: | Accepts pending user registration. Requires `manage_users` capability. security: - bearerAuth: [] tags: - user parameters: - in: path name: login schema: type: string description: Login of pending account responses: 200: description: When... | 2 | stack_v2_sparse_classes_30k_train_017125 | Implement the Python class `UserPendingResource` described below.
Class description:
Implement the UserPendingResource class.
Method signatures and docstrings:
- def post(self, login): --- summary: Accept a pending registration description: | Accepts pending user registration. Requires `manage_users` capability. secu... | Implement the Python class `UserPendingResource` described below.
Class description:
Implement the UserPendingResource class.
Method signatures and docstrings:
- def post(self, login): --- summary: Accept a pending registration description: | Accepts pending user registration. Requires `manage_users` capability. secu... | f18f56789d2b7db8fdb7e172113a9918b4b72658 | <|skeleton|>
class UserPendingResource:
def post(self, login):
"""--- summary: Accept a pending registration description: | Accepts pending user registration. Requires `manage_users` capability. security: - bearerAuth: [] tags: - user parameters: - in: path name: login schema: type: string description: Log... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserPendingResource:
def post(self, login):
"""--- summary: Accept a pending registration description: | Accepts pending user registration. Requires `manage_users` capability. security: - bearerAuth: [] tags: - user parameters: - in: path name: login schema: type: string description: Login of pending ... | the_stack_v2_python_sparse | resources/user.py | dskwhitehat/malwarecage | train | 0 | |
73002fff89b9e51474aa192cf7800d20e6af9147 | [
"self.wait_for_ajax()\nself.locator_finder_by_id(self.navbar_id)\nitem = self.locator_finder_by_id(tag)\nitem.click()\nself.wait_for_ajax()",
"click_twitter_link_sitem = self.locator_finder_by_xpath(self.click_twitter_link_id)\ntitle = self.switch_tab(click_twitter_link_sitem)\nexpected_title = 'ArangoDB (@arango... | <|body_start_0|>
self.wait_for_ajax()
self.locator_finder_by_id(self.navbar_id)
item = self.locator_finder_by_id(tag)
item.click()
self.wait_for_ajax()
<|end_body_0|>
<|body_start_1|>
click_twitter_link_sitem = self.locator_finder_by_xpath(self.click_twitter_link_id)
... | Page object representing the navigation bar | NavigationBarPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NavigationBarPage:
"""Page object representing the navigation bar"""
def navbar_goto(self, tag):
"""click on any of the items in the 'navbar'"""
<|body_0|>
def click_twitter_link(self):
"""Clicking on twitter link on dashboard"""
<|body_1|>
def click... | stack_v2_sparse_classes_75kplus_train_071943 | 3,510 | no_license | [
{
"docstring": "click on any of the items in the 'navbar'",
"name": "navbar_goto",
"signature": "def navbar_goto(self, tag)"
},
{
"docstring": "Clicking on twitter link on dashboard",
"name": "click_twitter_link",
"signature": "def click_twitter_link(self)"
},
{
"docstring": "Cli... | 6 | stack_v2_sparse_classes_30k_train_003777 | Implement the Python class `NavigationBarPage` described below.
Class description:
Page object representing the navigation bar
Method signatures and docstrings:
- def navbar_goto(self, tag): click on any of the items in the 'navbar'
- def click_twitter_link(self): Clicking on twitter link on dashboard
- def click_sla... | Implement the Python class `NavigationBarPage` described below.
Class description:
Page object representing the navigation bar
Method signatures and docstrings:
- def navbar_goto(self, tag): click on any of the items in the 'navbar'
- def click_twitter_link(self): Clicking on twitter link on dashboard
- def click_sla... | 4d4a0b049eb83625df41d86f2066ddb0c6c9c85b | <|skeleton|>
class NavigationBarPage:
"""Page object representing the navigation bar"""
def navbar_goto(self, tag):
"""click on any of the items in the 'navbar'"""
<|body_0|>
def click_twitter_link(self):
"""Clicking on twitter link on dashboard"""
<|body_1|>
def click... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NavigationBarPage:
"""Page object representing the navigation bar"""
def navbar_goto(self, tag):
"""click on any of the items in the 'navbar'"""
self.wait_for_ajax()
self.locator_finder_by_id(self.navbar_id)
item = self.locator_finder_by_id(tag)
item.click()
... | the_stack_v2_python_sparse | release_tester/selenium_ui_test/pages/navbar.py | arangodb/release-test-automation | train | 14 |
b71fa2e4acb765312be3f4ed55455f551f304ec4 | [
"params = get_params(locals())\nraw_result = await self.api_request('getComments', params)\nif return_raw_response:\n return raw_result\nresult = WidgetsGetCommentsResponse(**raw_result)\nreturn result",
"params = get_params(locals())\nraw_result = await self.api_request('getPages', params)\nif return_raw_resp... | <|body_start_0|>
params = get_params(locals())
raw_result = await self.api_request('getComments', params)
if return_raw_response:
return raw_result
result = WidgetsGetCommentsResponse(**raw_result)
return result
<|end_body_0|>
<|body_start_1|>
params = get_pa... | Widgets | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Widgets:
async def get_comments(self, return_raw_response: bool=False, widget_api_id: typing.Optional[int]=None, url: typing.Optional[str]=None, page_id: typing.Optional[str]=None, order: typing.Optional[str]=None, fields: typing.Optional[typing.List[UsersFields]]=None, offset: typing.Optional[i... | stack_v2_sparse_classes_75kplus_train_071944 | 1,955 | permissive | [
{
"docstring": ":param widget_api_id: :param url: :param page_id: :param order: :param fields: :param offset: :param count: :param return_raw_response: - return result at dict :return:",
"name": "get_comments",
"signature": "async def get_comments(self, return_raw_response: bool=False, widget_api_id: ty... | 2 | stack_v2_sparse_classes_30k_train_047002 | Implement the Python class `Widgets` described below.
Class description:
Implement the Widgets class.
Method signatures and docstrings:
- async def get_comments(self, return_raw_response: bool=False, widget_api_id: typing.Optional[int]=None, url: typing.Optional[str]=None, page_id: typing.Optional[str]=None, order: t... | Implement the Python class `Widgets` described below.
Class description:
Implement the Widgets class.
Method signatures and docstrings:
- async def get_comments(self, return_raw_response: bool=False, widget_api_id: typing.Optional[int]=None, url: typing.Optional[str]=None, page_id: typing.Optional[str]=None, order: t... | d88311a680e52faf04f3a18f9c5b381ee9e94a8f | <|skeleton|>
class Widgets:
async def get_comments(self, return_raw_response: bool=False, widget_api_id: typing.Optional[int]=None, url: typing.Optional[str]=None, page_id: typing.Optional[str]=None, order: typing.Optional[str]=None, fields: typing.Optional[typing.List[UsersFields]]=None, offset: typing.Optional[i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Widgets:
async def get_comments(self, return_raw_response: bool=False, widget_api_id: typing.Optional[int]=None, url: typing.Optional[str]=None, page_id: typing.Optional[str]=None, order: typing.Optional[str]=None, fields: typing.Optional[typing.List[UsersFields]]=None, offset: typing.Optional[int]=None, coun... | the_stack_v2_python_sparse | vkwave/api/methods/widgets.py | prog1ckg/vkwave | train | 0 | |
dcad37a8101e1054ceb0404e5dcec42041a1f2a3 | [
"BaseController.__init__(self, veh_id, car_following_params, delay=delay, fail_safe=fail_safe, noise=noise)\nself.v_desired = v0\nself.acc = acc\nself.b = b\nself.b_l = b_l\nself.s0 = s0\nself.tau = tau",
"v = env.k.vehicle.get_speed(self.veh_id)\nh = env.k.vehicle.get_headway(self.veh_id)\nv_l = env.k.vehicle.ge... | <|body_start_0|>
BaseController.__init__(self, veh_id, car_following_params, delay=delay, fail_safe=fail_safe, noise=noise)
self.v_desired = v0
self.acc = acc
self.b = b
self.b_l = b_l
self.s0 = s0
self.tau = tau
<|end_body_0|>
<|body_start_1|>
v = env.k.... | Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseController for usage example. Attributes ---------- ... | GippsController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GippsController:
"""Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseControlle... | stack_v2_sparse_classes_75kplus_train_071945 | 17,548 | permissive | [
{
"docstring": "Instantiate a Gipps' controller.",
"name": "__init__",
"signature": "def __init__(self, veh_id, car_following_params=None, v0=30, acc=1.5, b=-1, b_l=-1, s0=2, tau=1, delay=0, noise=0, fail_safe=None)"
},
{
"docstring": "See parent class.",
"name": "get_accel",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_049774 | Implement the Python class `GippsController` described below.
Class description:
Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChap... | Implement the Python class `GippsController` described below.
Class description:
Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChap... | badac3da17f04d8d8ae5691ee8ba2af9d56fac35 | <|skeleton|>
class GippsController:
"""Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseControlle... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GippsController:
"""Gipps' Model controller. For more information on this controller, see: Traffic Flow Dynamics written by M.Treiber and A.Kesting By courtesy of Springer publisher, http://www.springer.com http://www.traffic-flow-dynamics.org/res/SampleChapter11.pdf Usage ----- See BaseController for usage e... | the_stack_v2_python_sparse | flow/controllers/car_following_models.py | parthjaggi/flow | train | 6 |
35b28acc7c552cf47a2b605c156dc1a5e51e3fda | [
"ancestor = None\n\ndef find_nodes(node) -> int:\n nonlocal ancestor\n if not node:\n return 0\n found_from_left = find_nodes(node.left)\n if found_from_left == 2:\n return 2\n if found_from_left == 1 and node.val in {p.val, q.val}:\n ancestor = node\n return 2\n found_... | <|body_start_0|>
ancestor = None
def find_nodes(node) -> int:
nonlocal ancestor
if not node:
return 0
found_from_left = find_nodes(node.left)
if found_from_left == 2:
return 2
if found_from_left == 1 and node.va... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/25/2019 19:40"""
<|body_0|>
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/21/2021 16:57"""
<|bo... | stack_v2_sparse_classes_75kplus_train_071946 | 4,875 | no_license | [
{
"docstring": "08/25/2019 19:40",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "08/21/2021 16:57",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self... | 3 | stack_v2_sparse_classes_30k_train_023758 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 08/25/2019 19:40
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 08/25/2019 19:40
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/25/2019 19:40"""
<|body_0|>
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/21/2021 16:57"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/25/2019 19:40"""
ancestor = None
def find_nodes(node) -> int:
nonlocal ancestor
if not node:
return 0
found_from_left = fin... | the_stack_v2_python_sparse | leetcode/solved/236_Lowest_Common_Ancestor_of_a_Binary_Tree/solution.py | sungminoh/algorithms | train | 0 | |
164b829f6a71ed8f0b9142db81ded0dc26b05b46 | [
"if item_id:\n item = Item.get_by_id(item_id)\n if not item:\n return RESPONSE_404_OBJECT_NOT_FOUND\n item = item.to_dict()\n return JsonResponse(item, status=200)\nif topic_id:\n topic = Topic.get_by_id(topic_id)\n if not topic:\n return RESPONSE_404_OBJECT_NOT_FOUND\n items_supe... | <|body_start_0|>
if item_id:
item = Item.get_by_id(item_id)
if not item:
return RESPONSE_404_OBJECT_NOT_FOUND
item = item.to_dict()
return JsonResponse(item, status=200)
if topic_id:
topic = Topic.get_by_id(topic_id)
... | Item view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with item model. | ItemView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemView:
"""Item view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with item model."""
def get(self, request, curriculum_id, item_id=None, topic_id=None):
"""Method that handles GET request. :param request: the accepted HTTP request. :type request... | stack_v2_sparse_classes_75kplus_train_071947 | 7,094 | no_license | [
{
"docstring": "Method that handles GET request. :param request: the accepted HTTP request. :type request: `HttpRequest object` :param item_id: ID of the certain item. :type item_id: `int` :param topic_id: ID of the certain topic. :type topic_id: `int` :return: the response with the certain item information whe... | 4 | stack_v2_sparse_classes_30k_val_002666 | Implement the Python class `ItemView` described below.
Class description:
Item view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with item model.
Method signatures and docstrings:
- def get(self, request, curriculum_id, item_id=None, topic_id=None): Method that handles GET request.... | Implement the Python class `ItemView` described below.
Class description:
Item view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with item model.
Method signatures and docstrings:
- def get(self, request, curriculum_id, item_id=None, topic_id=None): Method that handles GET request.... | 541ee6ae488c4be7e10d001f7d05c9f9cf269821 | <|skeleton|>
class ItemView:
"""Item view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with item model."""
def get(self, request, curriculum_id, item_id=None, topic_id=None):
"""Method that handles GET request. :param request: the accepted HTTP request. :type request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemView:
"""Item view that handles GET, POST, PUT, DELETE requests and provides appropriate operations with item model."""
def get(self, request, curriculum_id, item_id=None, topic_id=None):
"""Method that handles GET request. :param request: the accepted HTTP request. :type request: `HttpReques... | the_stack_v2_python_sparse | eventually/item/views.py | lv275python/eventually.api | train | 12 |
61bc8178bf823b32e379b60f6e52d3518e6088c2 | [
"self.terms = []\nfor t in make_iterable(terms):\n self.add_term(t)",
"if isinstance(term, lbann.core.layer.Layer):\n term = LayerTerm(term)\nself.terms.append(term)",
"proto = objective_functions_pb2.ObjectiveFunction()\nfor term in self.terms:\n term_message = term.export_proto()\n if type(term) i... | <|body_start_0|>
self.terms = []
for t in make_iterable(terms):
self.add_term(t)
<|end_body_0|>
<|body_start_1|>
if isinstance(term, lbann.core.layer.Layer):
term = LayerTerm(term)
self.terms.append(term)
<|end_body_1|>
<|body_start_2|>
proto = objective... | Objective function for optimization algorithm. | ObjectiveFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectiveFunction:
"""Objective function for optimization algorithm."""
def __init__(self, terms=[]):
"""Create an objective function with layer terms and regularization. `terms` should be a sequence of `ObjectiveFunctionTerm`s and `Layer`s."""
<|body_0|>
def add_term(se... | stack_v2_sparse_classes_75kplus_train_071948 | 2,565 | permissive | [
{
"docstring": "Create an objective function with layer terms and regularization. `terms` should be a sequence of `ObjectiveFunctionTerm`s and `Layer`s.",
"name": "__init__",
"signature": "def __init__(self, terms=[])"
},
{
"docstring": "Add a term to the objective function. `term` may be a `Lay... | 3 | null | Implement the Python class `ObjectiveFunction` described below.
Class description:
Objective function for optimization algorithm.
Method signatures and docstrings:
- def __init__(self, terms=[]): Create an objective function with layer terms and regularization. `terms` should be a sequence of `ObjectiveFunctionTerm`s... | Implement the Python class `ObjectiveFunction` described below.
Class description:
Objective function for optimization algorithm.
Method signatures and docstrings:
- def __init__(self, terms=[]): Create an objective function with layer terms and regularization. `terms` should be a sequence of `ObjectiveFunctionTerm`s... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class ObjectiveFunction:
"""Objective function for optimization algorithm."""
def __init__(self, terms=[]):
"""Create an objective function with layer terms and regularization. `terms` should be a sequence of `ObjectiveFunctionTerm`s and `Layer`s."""
<|body_0|>
def add_term(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObjectiveFunction:
"""Objective function for optimization algorithm."""
def __init__(self, terms=[]):
"""Create an objective function with layer terms and regularization. `terms` should be a sequence of `ObjectiveFunctionTerm`s and `Layer`s."""
self.terms = []
for t in make_iterab... | the_stack_v2_python_sparse | python/lbann/core/objective_function.py | LLNL/lbann | train | 225 |
40b3ef854f76eb9f8f06d629f60acf07286e1e0d | [
"def dfs(cur: int, pre: int, v1: int, v2: int, d: int) -> int:\n count = 1\n for next in adjList[cur]:\n if next != pre:\n if (dist[v1][next] < d or (dist[v1][next] == d and next > v2)) and (dist[v2][next] < d or (dist[v2][next] == d and next > v1)):\n count *= dfs(next, cur, ... | <|body_start_0|>
def dfs(cur: int, pre: int, v1: int, v2: int, d: int) -> int:
count = 1
for next in adjList[cur]:
if next != pre:
if (dist[v1][next] < d or (dist[v1][next] == d and next > v2)) and (dist[v2][next] < d or (dist[v2][next] == d and next >... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
"""O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-sub... | stack_v2_sparse_classes_75kplus_train_071949 | 7,378 | no_license | [
{
"docstring": "O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/shi-xian-hen-jian-dan-yuan-li-lue-you-xie-fu-za-de/",
"... | 2 | stack_v2_sparse_classes_30k_train_054529 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-citi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-citi... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
"""O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-sub... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
"""O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-subtrees-with-max... | the_stack_v2_python_sparse | 7_graph/带权图最短路和最小生成树/floyd多源/1617. 统计子树中城市之间最大距离.py | 981377660LMT/algorithm-study | train | 225 | |
060183205cf655b435536811db87cf2fb50c64e6 | [
"self.gameObject = gameObject\nself.winX = windowConfig['width']\nself.winY = windowConfig['height']\npygame.display.set_caption(windowConfig['name'])\nself.pygameScreen = pygame.display.set_mode((self.winX, self.winY))\nself.mapSize = self.calculateMapDimensions()\nself.mapCoord = math.floor((self.winX - self.mapS... | <|body_start_0|>
self.gameObject = gameObject
self.winX = windowConfig['width']
self.winY = windowConfig['height']
pygame.display.set_caption(windowConfig['name'])
self.pygameScreen = pygame.display.set_mode((self.winX, self.winY))
self.mapSize = self.calculateMapDimensio... | Screen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Screen:
def __init__(self, gameObject, windowConfig):
"""Create a signleton screen object. :param gameObject: Game object :param windowConfig: A dictionary with window settings. :raises KeyError"""
<|body_0|>
def calculateMapDimensions(self):
"""Determines the map's ... | stack_v2_sparse_classes_75kplus_train_071950 | 3,808 | no_license | [
{
"docstring": "Create a signleton screen object. :param gameObject: Game object :param windowConfig: A dictionary with window settings. :raises KeyError",
"name": "__init__",
"signature": "def __init__(self, gameObject, windowConfig)"
},
{
"docstring": "Determines the map's dimmension based on ... | 5 | stack_v2_sparse_classes_30k_train_013593 | Implement the Python class `Screen` described below.
Class description:
Implement the Screen class.
Method signatures and docstrings:
- def __init__(self, gameObject, windowConfig): Create a signleton screen object. :param gameObject: Game object :param windowConfig: A dictionary with window settings. :raises KeyErro... | Implement the Python class `Screen` described below.
Class description:
Implement the Screen class.
Method signatures and docstrings:
- def __init__(self, gameObject, windowConfig): Create a signleton screen object. :param gameObject: Game object :param windowConfig: A dictionary with window settings. :raises KeyErro... | c42a1038bc63e3c4c7a4e6618415ae9a8fe1585e | <|skeleton|>
class Screen:
def __init__(self, gameObject, windowConfig):
"""Create a signleton screen object. :param gameObject: Game object :param windowConfig: A dictionary with window settings. :raises KeyError"""
<|body_0|>
def calculateMapDimensions(self):
"""Determines the map's ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Screen:
def __init__(self, gameObject, windowConfig):
"""Create a signleton screen object. :param gameObject: Game object :param windowConfig: A dictionary with window settings. :raises KeyError"""
self.gameObject = gameObject
self.winX = windowConfig['width']
self.winY = windo... | the_stack_v2_python_sparse | src/game/Screen.py | emkarcinos/DSZI_Survival | train | 0 | |
e8df151a2ee23dee3e567e2be58f85352d6ffcc7 | [
"if opt_options is None:\n opt_options = {'maxiter': 100, 'disp': True, 'iprint': 2, 'ftol': 1e-12, 'eps': 0.1}\nsuper().__init__(fi=fi, minimum_yaw_angle=minimum_yaw_angle, maximum_yaw_angle=maximum_yaw_angle, yaw_angles_baseline=yaw_angles_baseline, x0=x0, turbine_weights=turbine_weights, normalize_control_var... | <|body_start_0|>
if opt_options is None:
opt_options = {'maxiter': 100, 'disp': True, 'iprint': 2, 'ftol': 1e-12, 'eps': 0.1}
super().__init__(fi=fi, minimum_yaw_angle=minimum_yaw_angle, maximum_yaw_angle=maximum_yaw_angle, yaw_angles_baseline=yaw_angles_baseline, x0=x0, turbine_weights=turb... | YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package. | YawOptimizationScipy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YawOptimizationScipy:
"""YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package."""
def __init_... | stack_v2_sparse_classes_75kplus_train_071951 | 5,455 | permissive | [
{
"docstring": "Instantiate YawOptimizationScipy object with a FlorisInterface object and assign parameter values.",
"name": "__init__",
"signature": "def __init__(self, fi, minimum_yaw_angle=0.0, maximum_yaw_angle=25.0, yaw_angles_baseline=None, x0=None, opt_method='SLSQP', opt_options=None, turbine_we... | 2 | stack_v2_sparse_classes_30k_train_020892 | Implement the Python class `YawOptimizationScipy` described below.
Class description:
YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciP... | Implement the Python class `YawOptimizationScipy` described below.
Class description:
YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciP... | 59e53a66aef134a3c9e912f9468ca667b599d4e5 | <|skeleton|>
class YawOptimizationScipy:
"""YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package."""
def __init_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YawOptimizationScipy:
"""YawOptimizationScipy is a subclass of :py:class:`floris.tools.optimization.general_library.YawOptimization` that is used to optimize the yaw angles of all turbines in a Floris Farm for a single set of inflow conditions using the SciPy optimize package."""
def __init__(self, fi, m... | the_stack_v2_python_sparse | floris/tools/optimization/yaw_optimization/yaw_optimizer_scipy.py | NREL/floris | train | 151 |
a3ae854dc152198db5c728f6b1403f6c0c3b9b7b | [
"if form_class is None:\n form_class = self.get_form_class()\nform_class.__dict__['base_fields']['latitude_point'].widget = forms.TextInput()\nform_class.__dict__['base_fields']['longitude_point'].widget = forms.TextInput()\nreturn form_class(**self.get_form_kwargs())",
"self.object = form.save(commit=False)\n... | <|body_start_0|>
if form_class is None:
form_class = self.get_form_class()
form_class.__dict__['base_fields']['latitude_point'].widget = forms.TextInput()
form_class.__dict__['base_fields']['longitude_point'].widget = forms.TextInput()
return form_class(**self.get_form_kwargs... | Renderiza el template y formulario para creación de :model:`ecopoints.RecyclingPoint`. Requiere que el usuario esté logeado y sea persona. ***Context:*** ``model`` Instancia de :model:`ecopoints.RecyclingPoint`. ``fields`` Filtro de campos a mostrar en el formulario. ``success_url`` URL de redirección si el formulario ... | RecyclingPointCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecyclingPointCreateView:
"""Renderiza el template y formulario para creación de :model:`ecopoints.RecyclingPoint`. Requiere que el usuario esté logeado y sea persona. ***Context:*** ``model`` Instancia de :model:`ecopoints.RecyclingPoint`. ``fields`` Filtro de campos a mostrar en el formulario. ... | stack_v2_sparse_classes_75kplus_train_071952 | 11,031 | no_license | [
{
"docstring": "Obtiene la instancia del formulario actual para cambiar el tipo de input para los campos de",
"name": "get_form",
"signature": "def get_form(self, form_class=None)"
},
{
"docstring": "Si el formulario es valido, añade la Comuna y Ciudad del :model:`registration.Person` logeado, l... | 2 | stack_v2_sparse_classes_30k_train_007686 | Implement the Python class `RecyclingPointCreateView` described below.
Class description:
Renderiza el template y formulario para creación de :model:`ecopoints.RecyclingPoint`. Requiere que el usuario esté logeado y sea persona. ***Context:*** ``model`` Instancia de :model:`ecopoints.RecyclingPoint`. ``fields`` Filtro... | Implement the Python class `RecyclingPointCreateView` described below.
Class description:
Renderiza el template y formulario para creación de :model:`ecopoints.RecyclingPoint`. Requiere que el usuario esté logeado y sea persona. ***Context:*** ``model`` Instancia de :model:`ecopoints.RecyclingPoint`. ``fields`` Filtro... | cac61a567f2bdc57191b7cb42c43389a8c8e9b1e | <|skeleton|>
class RecyclingPointCreateView:
"""Renderiza el template y formulario para creación de :model:`ecopoints.RecyclingPoint`. Requiere que el usuario esté logeado y sea persona. ***Context:*** ``model`` Instancia de :model:`ecopoints.RecyclingPoint`. ``fields`` Filtro de campos a mostrar en el formulario. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecyclingPointCreateView:
"""Renderiza el template y formulario para creación de :model:`ecopoints.RecyclingPoint`. Requiere que el usuario esté logeado y sea persona. ***Context:*** ``model`` Instancia de :model:`ecopoints.RecyclingPoint`. ``fields`` Filtro de campos a mostrar en el formulario. ``success_url... | the_stack_v2_python_sparse | ecopoints/views.py | pmunozroa/trabajo_taller_software | train | 0 |
cce283188614738967871d513ab55c75d177642f | [
"shim_format_util.replace_autoclass_value_with_prefixed_time(bucket_resource, use_gsutil_time_style=True)\nshim_format_util.replace_time_values_with_gsutil_style_strings(bucket_resource)\nshim_format_util.replace_bucket_values_with_present_string(bucket_resource)\nreturn base.get_formatted_string(bucket_resource, _... | <|body_start_0|>
shim_format_util.replace_autoclass_value_with_prefixed_time(bucket_resource, use_gsutil_time_style=True)
shim_format_util.replace_time_values_with_gsutil_style_strings(bucket_resource)
shim_format_util.replace_bucket_values_with_present_string(bucket_resource)
return bas... | Format a resource as per gsutil Storage style for ls -L output. | GsutilFullResourceFormatter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GsutilFullResourceFormatter:
"""Format a resource as per gsutil Storage style for ls -L output."""
def format_bucket(self, bucket_resource):
"""See super class."""
<|body_0|>
def format_object(self, object_resource, show_acl=True, show_version_in_url=False, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_071953 | 8,524 | permissive | [
{
"docstring": "See super class.",
"name": "format_bucket",
"signature": "def format_bucket(self, bucket_resource)"
},
{
"docstring": "See super class.",
"name": "format_object",
"signature": "def format_object(self, object_resource, show_acl=True, show_version_in_url=False, **kwargs)"
... | 2 | stack_v2_sparse_classes_30k_train_017368 | Implement the Python class `GsutilFullResourceFormatter` described below.
Class description:
Format a resource as per gsutil Storage style for ls -L output.
Method signatures and docstrings:
- def format_bucket(self, bucket_resource): See super class.
- def format_object(self, object_resource, show_acl=True, show_ver... | Implement the Python class `GsutilFullResourceFormatter` described below.
Class description:
Format a resource as per gsutil Storage style for ls -L output.
Method signatures and docstrings:
- def format_bucket(self, bucket_resource): See super class.
- def format_object(self, object_resource, show_acl=True, show_ver... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class GsutilFullResourceFormatter:
"""Format a resource as per gsutil Storage style for ls -L output."""
def format_bucket(self, bucket_resource):
"""See super class."""
<|body_0|>
def format_object(self, object_resource, show_acl=True, show_version_in_url=False, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GsutilFullResourceFormatter:
"""Format a resource as per gsutil Storage style for ls -L output."""
def format_bucket(self, bucket_resource):
"""See super class."""
shim_format_util.replace_autoclass_value_with_prefixed_time(bucket_resource, use_gsutil_time_style=True)
shim_format_... | the_stack_v2_python_sparse | lib/googlecloudsdk/command_lib/storage/resources/gsutil_full_resource_formatter.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
86e0560882f7933938c26ac1f230b8b5e129a8c9 | [
"MProVictor.quick_renanimation = True\nvictor = MProVictor.from_hit_codes(hit_codes=['x0692', 'x0305', 'x1249'])\nvictor.place(smiles='CCNc1ncc(C#N)cc1CN1CCN(C(=O)C*)CC1', long_name='2_ACL')\nself.assertEqual(victor.error_msg, '', victor.error_msg)\nself.assertIsNotNone(victor.minimised_mol, 'Failed minimisation')\... | <|body_start_0|>
MProVictor.quick_renanimation = True
victor = MProVictor.from_hit_codes(hit_codes=['x0692', 'x0305', 'x1249'])
victor.place(smiles='CCNc1ncc(C#N)cc1CN1CCN(C(=O)C*)CC1', long_name='2_ACL')
self.assertEqual(victor.error_msg, '', victor.error_msg)
self.assertIsNotNo... | MProPlaceTester | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MProPlaceTester:
def test_easy(self):
"""To a **human** this looks easy. x0692 is a red herring and the other two make the molecule. As currently written this will fail. :return:"""
<|body_0|>
def test_nasty(self):
"""The human suggested a lot of novel groups. 'x0540... | stack_v2_sparse_classes_75kplus_train_071954 | 15,388 | permissive | [
{
"docstring": "To a **human** this looks easy. x0692 is a red herring and the other two make the molecule. As currently written this will fail. :return:",
"name": "test_easy",
"signature": "def test_easy(self)"
},
{
"docstring": "The human suggested a lot of novel groups. 'x0540' is a really od... | 4 | stack_v2_sparse_classes_30k_train_014818 | Implement the Python class `MProPlaceTester` described below.
Class description:
Implement the MProPlaceTester class.
Method signatures and docstrings:
- def test_easy(self): To a **human** this looks easy. x0692 is a red herring and the other two make the molecule. As currently written this will fail. :return:
- def... | Implement the Python class `MProPlaceTester` described below.
Class description:
Implement the MProPlaceTester class.
Method signatures and docstrings:
- def test_easy(self): To a **human** this looks easy. x0692 is a red herring and the other two make the molecule. As currently written this will fail. :return:
- def... | 151bde01f4ebd930880cb7ad234bab68ac4a3e76 | <|skeleton|>
class MProPlaceTester:
def test_easy(self):
"""To a **human** this looks easy. x0692 is a red herring and the other two make the molecule. As currently written this will fail. :return:"""
<|body_0|>
def test_nasty(self):
"""The human suggested a lot of novel groups. 'x0540... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MProPlaceTester:
def test_easy(self):
"""To a **human** this looks easy. x0692 is a red herring and the other two make the molecule. As currently written this will fail. :return:"""
MProVictor.quick_renanimation = True
victor = MProVictor.from_hit_codes(hit_codes=['x0692', 'x0305', 'x1... | the_stack_v2_python_sparse | test.py | Kaziaa/Fragmenstein | train | 0 | |
1352f5017b7175cb90a571b3bcd01a7480498a5a | [
"self.obj_encoders = []\nif obj_encoders:\n self.obj_encoders = list(obj_encoders)\nself.silence_typeerror = silence_typeerror\nself.primitives = primitives\nsuper(TricksEncoder, self).__init__(**json_kwargs)",
"prev_id = id(obj)\nfor encoder in self.obj_encoders:\n if hasattr(encoder, 'default'):\n ... | <|body_start_0|>
self.obj_encoders = []
if obj_encoders:
self.obj_encoders = list(obj_encoders)
self.silence_typeerror = silence_typeerror
self.primitives = primitives
super(TricksEncoder, self).__init__(**json_kwargs)
<|end_body_0|>
<|body_start_1|>
prev_id ... | Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders. | TricksEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TricksEncoder:
"""Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders."""
def __init__(self, obj_encoders=None, s... | stack_v2_sparse_classes_75kplus_train_071955 | 10,822 | permissive | [
{
"docstring": ":param obj_encoders: An iterable of functions or encoder instances to try. :param silence_typeerror: If set to True, ignore the TypeErrors that Encoder instances throw (default False).",
"name": "__init__",
"signature": "def __init__(self, obj_encoders=None, silence_typeerror=False, prim... | 2 | stack_v2_sparse_classes_30k_train_021860 | Implement the Python class `TricksEncoder` described below.
Class description:
Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders.
Method ... | Implement the Python class `TricksEncoder` described below.
Class description:
Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders.
Method ... | 4ced7d8c8f9f5fb47d12410f87fa33d782e9f0f4 | <|skeleton|>
class TricksEncoder:
"""Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders."""
def __init__(self, obj_encoders=None, s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TricksEncoder:
"""Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders."""
def __init__(self, obj_encoders=None, silence_typeer... | the_stack_v2_python_sparse | Contents/Libraries/Shared/json_tricks/encoders.py | pannal/Sub-Zero.bundle | train | 1,820 |
1d3585de4df8a057b0e453aa89670e3fa937d938 | [
"FeatureExtractor.__init__(self)\nself.width = 40\nself.height = 40\nself.channels = 3\nself.load_model(model_path)",
"with tf.variable_scope('placeholder'):\n Img = tf.placeholder('float', [None, self.width, self.height, self.channels])\n Dropout = tf.placeholder(tf.float32)\n Is_Training = tf.placehold... | <|body_start_0|>
FeatureExtractor.__init__(self)
self.width = 40
self.height = 40
self.channels = 3
self.load_model(model_path)
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope('placeholder'):
Img = tf.placeholder('float', [None, self.width, self.height... | MiniFacenet特征提取器 es 2018-11-06 | MiniFacenetFeatureExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MiniFacenetFeatureExtractor:
"""MiniFacenet特征提取器 es 2018-11-06"""
def __init__(self, model_path):
"""初始化"""
<|body_0|>
def load_model(self, model_path):
"""加载预先已训练的模型"""
<|body_1|>
def preprocess(self, imgs):
"""图像预处理"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_071956 | 3,122 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, model_path)"
},
{
"docstring": "加载预先已训练的模型",
"name": "load_model",
"signature": "def load_model(self, model_path)"
},
{
"docstring": "图像预处理",
"name": "preprocess",
"signature": "def preprocess(self... | 4 | stack_v2_sparse_classes_30k_val_000514 | Implement the Python class `MiniFacenetFeatureExtractor` described below.
Class description:
MiniFacenet特征提取器 es 2018-11-06
Method signatures and docstrings:
- def __init__(self, model_path): 初始化
- def load_model(self, model_path): 加载预先已训练的模型
- def preprocess(self, imgs): 图像预处理
- def extract_features(self, imgs, batc... | Implement the Python class `MiniFacenetFeatureExtractor` described below.
Class description:
MiniFacenet特征提取器 es 2018-11-06
Method signatures and docstrings:
- def __init__(self, model_path): 初始化
- def load_model(self, model_path): 加载预先已训练的模型
- def preprocess(self, imgs): 图像预处理
- def extract_features(self, imgs, batc... | 3c756d00c83cd0a8dd745fd32a074c9121977ab8 | <|skeleton|>
class MiniFacenetFeatureExtractor:
"""MiniFacenet特征提取器 es 2018-11-06"""
def __init__(self, model_path):
"""初始化"""
<|body_0|>
def load_model(self, model_path):
"""加载预先已训练的模型"""
<|body_1|>
def preprocess(self, imgs):
"""图像预处理"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MiniFacenetFeatureExtractor:
"""MiniFacenet特征提取器 es 2018-11-06"""
def __init__(self, model_path):
"""初始化"""
FeatureExtractor.__init__(self)
self.width = 40
self.height = 40
self.channels = 3
self.load_model(model_path)
def load_model(self, model_path):... | the_stack_v2_python_sparse | feature/mini_facenet_feature_extractor.py | esfamely/es_face_server | train | 0 |
a2bc12321e5148fbc36ff0b5038bf657180e1f50 | [
"super(Cell, self).__init__()\nself.genotype = genotype\nself.steps = steps\nself.concat = concat\nself.reduction = reduction\nself.reduction_prev = reduction_prev\nself.C_prev_prev = C_prev_prev\nself.C_prev = C_prev\nself.C = C\nself.concat_size = 0\nself.build()",
"affine = True\nif isinstance(self.genotype[0]... | <|body_start_0|>
super(Cell, self).__init__()
self.genotype = genotype
self.steps = steps
self.concat = concat
self.reduction = reduction
self.reduction_prev = reduction_prev
self.C_prev_prev = C_prev_prev
self.C_prev = C_prev
self.C = C
se... | Cell structure according to desc. | Cell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cell:
"""Cell structure according to desc."""
def __init__(self, genotype, steps, concat, reduction, reduction_prev=None, C_prev_prev=None, C_prev=None, C=None):
"""Init Cell."""
<|body_0|>
def build(self):
"""Build Cell."""
<|body_1|>
def build_ops(... | stack_v2_sparse_classes_75kplus_train_071957 | 10,880 | permissive | [
{
"docstring": "Init Cell.",
"name": "__init__",
"signature": "def __init__(self, genotype, steps, concat, reduction, reduction_prev=None, C_prev_prev=None, C_prev=None, C=None)"
},
{
"docstring": "Build Cell.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "C... | 4 | null | Implement the Python class `Cell` described below.
Class description:
Cell structure according to desc.
Method signatures and docstrings:
- def __init__(self, genotype, steps, concat, reduction, reduction_prev=None, C_prev_prev=None, C_prev=None, C=None): Init Cell.
- def build(self): Build Cell.
- def build_ops(self... | Implement the Python class `Cell` described below.
Class description:
Cell structure according to desc.
Method signatures and docstrings:
- def __init__(self, genotype, steps, concat, reduction, reduction_prev=None, C_prev_prev=None, C_prev=None, C=None): Init Cell.
- def build(self): Build Cell.
- def build_ops(self... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Cell:
"""Cell structure according to desc."""
def __init__(self, genotype, steps, concat, reduction, reduction_prev=None, C_prev_prev=None, C_prev=None, C=None):
"""Init Cell."""
<|body_0|>
def build(self):
"""Build Cell."""
<|body_1|>
def build_ops(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cell:
"""Cell structure according to desc."""
def __init__(self, genotype, steps, concat, reduction, reduction_prev=None, C_prev_prev=None, C_prev=None, C=None):
"""Init Cell."""
super(Cell, self).__init__()
self.genotype = genotype
self.steps = steps
self.concat =... | the_stack_v2_python_sparse | zeus/modules/operators/cell.py | huawei-noah/xingtian | train | 308 |
626ae5019c06c8ca48070f2a32bb5a7f03789244 | [
"self.n_fft = frontend_conf.get('n_fft', 512)\nself.hop_sz = frontend_conf.get('hop_length', 128)\nself.win_sz = frontend_conf.get('win_sz', self.n_fft)\nself.win_hop_sz = self.win_sz - self.hop_sz\nself.trim_val = self.win_sz // -self.hop_sz // -2\nself.decoding_samples = round(decoding_window * audio_sampling_rat... | <|body_start_0|>
self.n_fft = frontend_conf.get('n_fft', 512)
self.hop_sz = frontend_conf.get('hop_length', 128)
self.win_sz = frontend_conf.get('win_sz', self.n_fft)
self.win_hop_sz = self.win_sz - self.hop_sz
self.trim_val = self.win_sz // -self.hop_sz // -2
self.decodi... | OnlineProcessor module definition. Args: feature_extractor: Feature extractor module. normalization_module: Normalization module. decoding_window: Size of the decoding window (in ms). encoder_sub_factor: Encoder subsampling factor. frontend_conf: Frontend configuration. device: Device to pin module tensors on. audio_sa... | OnlineAudioProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnlineAudioProcessor:
"""OnlineProcessor module definition. Args: feature_extractor: Feature extractor module. normalization_module: Normalization module. decoding_window: Size of the decoding window (in ms). encoder_sub_factor: Encoder subsampling factor. frontend_conf: Frontend configuration. d... | stack_v2_sparse_classes_75kplus_train_071958 | 5,265 | permissive | [
{
"docstring": "Construct an OnlineAudioProcessor.",
"name": "__init__",
"signature": "def __init__(self, feature_extractor: torch.nn.Module, normalization_module: torch.nn.Module, decoding_window: int, encoder_sub_factor: int, frontend_conf: Dict, device: torch.device, audio_sampling_rate: int=16000) -... | 5 | stack_v2_sparse_classes_30k_train_050556 | Implement the Python class `OnlineAudioProcessor` described below.
Class description:
OnlineProcessor module definition. Args: feature_extractor: Feature extractor module. normalization_module: Normalization module. decoding_window: Size of the decoding window (in ms). encoder_sub_factor: Encoder subsampling factor. f... | Implement the Python class `OnlineAudioProcessor` described below.
Class description:
OnlineProcessor module definition. Args: feature_extractor: Feature extractor module. normalization_module: Normalization module. decoding_window: Size of the decoding window (in ms). encoder_sub_factor: Encoder subsampling factor. f... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class OnlineAudioProcessor:
"""OnlineProcessor module definition. Args: feature_extractor: Feature extractor module. normalization_module: Normalization module. decoding_window: Size of the decoding window (in ms). encoder_sub_factor: Encoder subsampling factor. frontend_conf: Frontend configuration. d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OnlineAudioProcessor:
"""OnlineProcessor module definition. Args: feature_extractor: Feature extractor module. normalization_module: Normalization module. decoding_window: Size of the decoding window (in ms). encoder_sub_factor: Encoder subsampling factor. frontend_conf: Frontend configuration. device: Device... | the_stack_v2_python_sparse | espnet2/asr_transducer/frontend/online_audio_processor.py | espnet/espnet | train | 7,242 |
ea8c0a32e2a0ba36ea9e29e1bbea77e68f5fb8b6 | [
"start = 0\ntotal = 0\ntank = 0\nfor i in range(len(gas)):\n tank += gas[i] - cost[i]\n if tank < 0:\n start = i + 1\n total += tank\n tank = 0\nif total + tank < 0:\n start = -1\nreturn start",
"start = len(gas) - 1\nend = 0\ntotal = gas[start] - cost[start]\nwhile end < start:\n ... | <|body_start_0|>
start = 0
total = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
total += tank
tank = 0
if total + tank < 0:
start = -1
return st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_071959 | 1,455 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit2",
"signature": "def canCo... | 2 | stack_v2_sparse_classes_30k_train_035629 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit2(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
start = 0
total = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
... | the_stack_v2_python_sparse | prob134_gas_station.py | Hu-Wenchao/leetcode | train | 0 | |
baf8338eddf4621f2f8e0ab2efc93c014e15355f | [
"self._name = name\nself._version = version\nself._release = release\nself._override = override",
"full_version = None\nif self.version:\n full_version = self.version\n if self.release:\n full_version = '{}-{}'.format(self.version, self.release)\nreturn full_version",
"if self.full_version:\n re... | <|body_start_0|>
self._name = name
self._version = version
self._release = release
self._override = override
<|end_body_0|>
<|body_start_1|>
full_version = None
if self.version:
full_version = self.version
if self.release:
full_ver... | A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families. | PackageVersion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageVersion:
"""A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families."""
def __init__(self, name: str, ve... | stack_v2_sparse_classes_75kplus_train_071960 | 14,999 | permissive | [
{
"docstring": "Initializes a package version. Arguments: name: the name of the package version: the version of the package release: the release of the package",
"name": "__init__",
"signature": "def __init__(self, name: str, version: Optional[str]=None, release: Optional[str]=None, override: Optional[s... | 3 | stack_v2_sparse_classes_30k_test_002033 | Implement the Python class `PackageVersion` described below.
Class description:
A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families.
... | Implement the Python class `PackageVersion` described below.
Class description:
A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families.
... | 6854d582f58592675afb3759585ce614b3db08f3 | <|skeleton|>
class PackageVersion:
"""A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families."""
def __init__(self, name: str, ve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PackageVersion:
"""A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families."""
def __init__(self, name: str, version: Option... | the_stack_v2_python_sparse | buildchain/buildchain/versions.py | scality/metalk8s | train | 321 |
844039f1b19601baeb8cba086dfc36abf999429a | [
"if not page_url or not html_cont:\n return\nsoup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')\nnew_urls = self._get_new_urls(page_url, soup)\nnew_data = self._get_new_data(page_url, soup)\nreturn (new_urls, new_data)",
"new_urls = set()\nlinks = soup.find_all('a', href=re.compile('/view/\\... | <|body_start_0|>
if not page_url or not html_cont:
return
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return (new_urls, new_data)
<|end_body_0|>
<|bo... | html 解析器 | HtmlParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParser:
"""html 解析器"""
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取 URL 和数据 :param page_url: 下载页面的 URL :param html_cont: 下载的网页内容 :return:"""
<|body_0|>
def _get_new_urls(self, page_url, soup: BeautifulSoup):
"""抽取新的 url 集合 :param page_url: 下载页面的 URL ... | stack_v2_sparse_classes_75kplus_train_071961 | 1,975 | no_license | [
{
"docstring": "用于解析网页内容,抽取 URL 和数据 :param page_url: 下载页面的 URL :param html_cont: 下载的网页内容 :return:",
"name": "parser",
"signature": "def parser(self, page_url, html_cont)"
},
{
"docstring": "抽取新的 url 集合 :param page_url: 下载页面的 URL :param soup: soup :return: 返回新的 URL 集合",
"name": "_get_new_urls... | 3 | stack_v2_sparse_classes_30k_train_052461 | Implement the Python class `HtmlParser` described below.
Class description:
html 解析器
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取 URL 和数据 :param page_url: 下载页面的 URL :param html_cont: 下载的网页内容 :return:
- def _get_new_urls(self, page_url, soup: BeautifulSoup): 抽取新的 url 集合 :param... | Implement the Python class `HtmlParser` described below.
Class description:
html 解析器
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取 URL 和数据 :param page_url: 下载页面的 URL :param html_cont: 下载的网页内容 :return:
- def _get_new_urls(self, page_url, soup: BeautifulSoup): 抽取新的 url 集合 :param... | 21c3b190329e4f3571747c2feba8fad268592c0d | <|skeleton|>
class HtmlParser:
"""html 解析器"""
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取 URL 和数据 :param page_url: 下载页面的 URL :param html_cont: 下载的网页内容 :return:"""
<|body_0|>
def _get_new_urls(self, page_url, soup: BeautifulSoup):
"""抽取新的 url 集合 :param page_url: 下载页面的 URL ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HtmlParser:
"""html 解析器"""
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取 URL 和数据 :param page_url: 下载页面的 URL :param html_cont: 下载的网页内容 :return:"""
if not page_url or not html_cont:
return
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
... | the_stack_v2_python_sparse | day03_base_spider/HtmlParser.py | zhayangtao/python-reptile | train | 0 |
39d20ba1c25a0cb11ca669b6918e1194984659cb | [
"while 1:\n s = '/acquire/%s/%s/%d' % (ttype, tpid, tsize)\n result = self.request(s, '')\n if result == None:\n time.sleep(0.1 + random.random() / 20.0)\n logging.critical('*** Error *** acquire1')\n continue\n if len(result) >= 2:\n if result[:2] == 'OK':\n break... | <|body_start_0|>
while 1:
s = '/acquire/%s/%s/%d' % (ttype, tpid, tsize)
result = self.request(s, '')
if result == None:
time.sleep(0.1 + random.random() / 20.0)
logging.critical('*** Error *** acquire1')
continue
if... | GateKeeperClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GateKeeperClient:
def acquire(self, ttype, tpid, tsize):
"""acquire a token"""
<|body_0|>
def release(self, ttype, tpid):
"""release a token"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while 1:
s = '/acquire/%s/%s/%d' % (ttype, tpid,... | stack_v2_sparse_classes_75kplus_train_071962 | 1,777 | no_license | [
{
"docstring": "acquire a token",
"name": "acquire",
"signature": "def acquire(self, ttype, tpid, tsize)"
},
{
"docstring": "release a token",
"name": "release",
"signature": "def release(self, ttype, tpid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052530 | Implement the Python class `GateKeeperClient` described below.
Class description:
Implement the GateKeeperClient class.
Method signatures and docstrings:
- def acquire(self, ttype, tpid, tsize): acquire a token
- def release(self, ttype, tpid): release a token | Implement the Python class `GateKeeperClient` described below.
Class description:
Implement the GateKeeperClient class.
Method signatures and docstrings:
- def acquire(self, ttype, tpid, tsize): acquire a token
- def release(self, ttype, tpid): release a token
<|skeleton|>
class GateKeeperClient:
def acquire(se... | 37c5645e3876a7c35dc203b0324535b1a8b225ab | <|skeleton|>
class GateKeeperClient:
def acquire(self, ttype, tpid, tsize):
"""acquire a token"""
<|body_0|>
def release(self, ttype, tpid):
"""release a token"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GateKeeperClient:
def acquire(self, ttype, tpid, tsize):
"""acquire a token"""
while 1:
s = '/acquire/%s/%s/%d' % (ttype, tpid, tsize)
result = self.request(s, '')
if result == None:
time.sleep(0.1 + random.random() / 20.0)
lo... | the_stack_v2_python_sparse | python/gatekeeperlib.py | vishalbelsare/snapworld | train | 0 | |
3ee9f335dbec1737b955cadc5f401c5eabbfa393 | [
"nn.Module.__init__(self)\nself.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\nself.bn1 = nn.BatchNorm2d(64, affine=False)\nself.relu = nn.ReLU(inplace=True)\nself.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\nself.layer1 = nn.Sequential(DownResBlock(64, 64, downsample=False... | <|body_start_0|>
nn.Module.__init__(self)
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64, affine=False)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer... | ResNet18_binary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet18_binary:
def __init__(self, pretrained=False):
"""Build ResNet18 binary classifer. The encoder is composed of an initial 7x7 convolution that halves the input dimension (h and w) followed by several layers of residual blocks. Each layer is composed of k Residual blocks. The first... | stack_v2_sparse_classes_75kplus_train_071963 | 3,981 | permissive | [
{
"docstring": "Build ResNet18 binary classifer. The encoder is composed of an initial 7x7 convolution that halves the input dimension (h and w) followed by several layers of residual blocks. Each layer is composed of k Residual blocks. The first one reduce the input height and width by a factor 2 while the num... | 3 | stack_v2_sparse_classes_30k_train_014920 | Implement the Python class `ResNet18_binary` described below.
Class description:
Implement the ResNet18_binary class.
Method signatures and docstrings:
- def __init__(self, pretrained=False): Build ResNet18 binary classifer. The encoder is composed of an initial 7x7 convolution that halves the input dimension (h and ... | Implement the Python class `ResNet18_binary` described below.
Class description:
Implement the ResNet18_binary class.
Method signatures and docstrings:
- def __init__(self, pretrained=False): Build ResNet18 binary classifer. The encoder is composed of an initial 7x7 convolution that halves the input dimension (h and ... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class ResNet18_binary:
def __init__(self, pretrained=False):
"""Build ResNet18 binary classifer. The encoder is composed of an initial 7x7 convolution that halves the input dimension (h and w) followed by several layers of residual blocks. Each layer is composed of k Residual blocks. The first... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet18_binary:
def __init__(self, pretrained=False):
"""Build ResNet18 binary classifer. The encoder is composed of an initial 7x7 convolution that halves the input dimension (h and w) followed by several layers of residual blocks. Each layer is composed of k Residual blocks. The first one reduce th... | the_stack_v2_python_sparse | Code/src/models/networks/ResNet18_binary.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 | |
18a986925e2e8bf1b4f45ec1f4cdc3312485112d | [
"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!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | The greeting service definition. | GreeterServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreeterServicer:
"""The greeting service definition."""
def SayHello(self, request, context):
"""Sends a greeting"""
<|body_0|>
def SayHelloAgain(self, request, context):
"""Sends another greeting"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_071964 | 2,740 | permissive | [
{
"docstring": "Sends a greeting",
"name": "SayHello",
"signature": "def SayHello(self, request, context)"
},
{
"docstring": "Sends another greeting",
"name": "SayHelloAgain",
"signature": "def SayHelloAgain(self, request, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023969 | Implement the Python class `GreeterServicer` described below.
Class description:
The greeting service definition.
Method signatures and docstrings:
- def SayHello(self, request, context): Sends a greeting
- def SayHelloAgain(self, request, context): Sends another greeting | Implement the Python class `GreeterServicer` described below.
Class description:
The greeting service definition.
Method signatures and docstrings:
- def SayHello(self, request, context): Sends a greeting
- def SayHelloAgain(self, request, context): Sends another greeting
<|skeleton|>
class GreeterServicer:
"""T... | 44e819e713c3885e38c99c16dc73b7d7478acfe8 | <|skeleton|>
class GreeterServicer:
"""The greeting service definition."""
def SayHello(self, request, context):
"""Sends a greeting"""
<|body_0|>
def SayHelloAgain(self, request, context):
"""Sends another greeting"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GreeterServicer:
"""The greeting service definition."""
def SayHello(self, request, context):
"""Sends a greeting"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def... | the_stack_v2_python_sparse | endpoints/getting-started-grpc/helloworld_pb2_grpc.py | GoogleCloudPlatform/python-docs-samples | train | 7,035 |
cf06d4c271acece9e23a2de1b3090a1d352d3749 | [
"Expr.__init__(self, template, line)\nself._var = var\nself._nodes = nodes",
"try:\n var = self._env.get(self._var)\n params = [node.eval() for node in self._nodes]\nexcept KeyError:\n raise UnknownVariableError('.'.join(self._var), self._template._filename, self._line)\ntry:\n for param in params:\n ... | <|body_start_0|>
Expr.__init__(self, template, line)
self._var = var
self._nodes = nodes
<|end_body_0|>
<|body_start_1|>
try:
var = self._env.get(self._var)
params = [node.eval() for node in self._nodes]
except KeyError:
raise UnknownVariableE... | An array index expression node. | IndexExpr | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexExpr:
"""An array index expression node."""
def __init__(self, template, line, var, nodes):
"""Initialize the node."""
<|body_0|>
def eval(self):
"""Evaluate the expression."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Expr.__init__(self... | stack_v2_sparse_classes_75kplus_train_071965 | 3,521 | permissive | [
{
"docstring": "Initialize the node.",
"name": "__init__",
"signature": "def __init__(self, template, line, var, nodes)"
},
{
"docstring": "Evaluate the expression.",
"name": "eval",
"signature": "def eval(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044921 | Implement the Python class `IndexExpr` described below.
Class description:
An array index expression node.
Method signatures and docstrings:
- def __init__(self, template, line, var, nodes): Initialize the node.
- def eval(self): Evaluate the expression. | Implement the Python class `IndexExpr` described below.
Class description:
An array index expression node.
Method signatures and docstrings:
- def __init__(self, template, line, var, nodes): Initialize the node.
- def eval(self): Evaluate the expression.
<|skeleton|>
class IndexExpr:
"""An array index expression... | 6aeee9b229d3f62aace98a51d9014781bbe6cb52 | <|skeleton|>
class IndexExpr:
"""An array index expression node."""
def __init__(self, template, line, var, nodes):
"""Initialize the node."""
<|body_0|>
def eval(self):
"""Evaluate the expression."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IndexExpr:
"""An array index expression node."""
def __init__(self, template, line, var, nodes):
"""Initialize the node."""
Expr.__init__(self, template, line)
self._var = var
self._nodes = nodes
def eval(self):
"""Evaluate the expression."""
try:
... | the_stack_v2_python_sparse | mrbaviirc/template/expr.py | brianvanderburg2/mrbaviirc | train | 0 |
61013f5d18ffd68ac791127bbbc4978d735ced4a | [
"ins_col = 0\nfor point in self.points:\n time.sleep(2)\n ins_col = ins_col + 1\n self.cut(point)\n trans_img = img_to_str(self.cut_img_name)\n row_content, col_content = trans_img.basicAccurate()\n excel_obj = excel_class(row_content, col_content, ins_col, self.start_row, excel_name=self.excel_na... | <|body_start_0|>
ins_col = 0
for point in self.points:
time.sleep(2)
ins_col = ins_col + 1
self.cut(point)
trans_img = img_to_str(self.cut_img_name)
row_content, col_content = trans_img.basicAccurate()
excel_obj = excel_class(row_co... | handler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class handler:
def pre_cut(self):
"""根据point来将图片截取为多张图片,并识别生成excel"""
<|body_0|>
def handler_img(self):
"""读取文件夹里面的图片,并交给pre_cut()处理"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ins_col = 0
for point in self.points:
time.sleep(2)
... | stack_v2_sparse_classes_75kplus_train_071966 | 8,802 | no_license | [
{
"docstring": "根据point来将图片截取为多张图片,并识别生成excel",
"name": "pre_cut",
"signature": "def pre_cut(self)"
},
{
"docstring": "读取文件夹里面的图片,并交给pre_cut()处理",
"name": "handler_img",
"signature": "def handler_img(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048840 | Implement the Python class `handler` described below.
Class description:
Implement the handler class.
Method signatures and docstrings:
- def pre_cut(self): 根据point来将图片截取为多张图片,并识别生成excel
- def handler_img(self): 读取文件夹里面的图片,并交给pre_cut()处理 | Implement the Python class `handler` described below.
Class description:
Implement the handler class.
Method signatures and docstrings:
- def pre_cut(self): 根据point来将图片截取为多张图片,并识别生成excel
- def handler_img(self): 读取文件夹里面的图片,并交给pre_cut()处理
<|skeleton|>
class handler:
def pre_cut(self):
"""根据point来将图片截取为多张... | 3c02098163611eaa4a21994cded89912794b9338 | <|skeleton|>
class handler:
def pre_cut(self):
"""根据point来将图片截取为多张图片,并识别生成excel"""
<|body_0|>
def handler_img(self):
"""读取文件夹里面的图片,并交给pre_cut()处理"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class handler:
def pre_cut(self):
"""根据point来将图片截取为多张图片,并识别生成excel"""
ins_col = 0
for point in self.points:
time.sleep(2)
ins_col = ins_col + 1
self.cut(point)
trans_img = img_to_str(self.cut_img_name)
row_content, col_content = tra... | the_stack_v2_python_sparse | other/ocr.py | sunjiebin/s12 | train | 0 | |
0841afd1c38e0a802938bf18fc0017cd1df4403c | [
"for i in range(1, 32):\n bit = DiscreteBit.Field(bitIndex=i, bitName='testBit', meaningWhenSet='happy', meaningWhenNotSet='unhappy')\n bit.setData(True)\n self.assertEqual(bit.pack(), 1 << i - 1, 'Label Not Packed Properly')",
"for i in range(1, 32):\n bit = DiscreteBit.Field(bitIndex=i, bitName='tes... | <|body_start_0|>
for i in range(1, 32):
bit = DiscreteBit.Field(bitIndex=i, bitName='testBit', meaningWhenSet='happy', meaningWhenNotSet='unhappy')
bit.setData(True)
self.assertEqual(bit.pack(), 1 << i - 1, 'Label Not Packed Properly')
<|end_body_0|>
<|body_start_1|>
... | Verify that bits are packed and unpacked properly | testBitPackandUnpack | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testBitPackandUnpack:
"""Verify that bits are packed and unpacked properly"""
def testBitPackingSet(self):
"""Move a bit from 1 to 32, check only this bit is set"""
<|body_0|>
def testBitPackingUnset(self):
"""Move a bit from 1 to 32, check only this bit is not s... | stack_v2_sparse_classes_75kplus_train_071967 | 7,060 | permissive | [
{
"docstring": "Move a bit from 1 to 32, check only this bit is set",
"name": "testBitPackingSet",
"signature": "def testBitPackingSet(self)"
},
{
"docstring": "Move a bit from 1 to 32, check only this bit is not set",
"name": "testBitPackingUnset",
"signature": "def testBitPackingUnset(... | 3 | stack_v2_sparse_classes_30k_train_012183 | Implement the Python class `testBitPackandUnpack` described below.
Class description:
Verify that bits are packed and unpacked properly
Method signatures and docstrings:
- def testBitPackingSet(self): Move a bit from 1 to 32, check only this bit is set
- def testBitPackingUnset(self): Move a bit from 1 to 32, check o... | Implement the Python class `testBitPackandUnpack` described below.
Class description:
Verify that bits are packed and unpacked properly
Method signatures and docstrings:
- def testBitPackingSet(self): Move a bit from 1 to 32, check only this bit is set
- def testBitPackingUnset(self): Move a bit from 1 to 32, check o... | 077c979c7eb2aae206f6052c2a67e68ecc5b35a8 | <|skeleton|>
class testBitPackandUnpack:
"""Verify that bits are packed and unpacked properly"""
def testBitPackingSet(self):
"""Move a bit from 1 to 32, check only this bit is set"""
<|body_0|>
def testBitPackingUnset(self):
"""Move a bit from 1 to 32, check only this bit is not s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class testBitPackandUnpack:
"""Verify that bits are packed and unpacked properly"""
def testBitPackingSet(self):
"""Move a bit from 1 to 32, check only this bit is set"""
for i in range(1, 32):
bit = DiscreteBit.Field(bitIndex=i, bitName='testBit', meaningWhenSet='happy', meaningWhe... | the_stack_v2_python_sparse | ARINC429/UnitTests/DiscreteBitTest.py | superliujian/Py429 | train | 1 |
307d9e22169d8470c4c8a3b1724dcb4c53f4ad14 | [
"self.e = self.double(dos.e, -1.0)\nself.g = self.double(dos.g)\nself.gz = self.double(dos.gz)\nself.cutoffInd = dos.cutoffInd\nself.cutoff = dos.cutoff\nself.de = dos.de",
"res = (multi * array).tolist()\nres.reverse()\nreturn numpy.array(res + array[1:].tolist())"
] | <|body_start_0|>
self.e = self.double(dos.e, -1.0)
self.g = self.double(dos.g)
self.gz = self.double(dos.gz)
self.cutoffInd = dos.cutoffInd
self.cutoff = dos.cutoff
self.de = dos.de
<|end_body_0|>
<|body_start_1|>
res = (multi * array).tolist()
res.revers... | Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with zeros after cutoff } cutoff = energy... | doubleDos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class doubleDos:
"""Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with... | stack_v2_sparse_classes_75kplus_train_071968 | 1,265 | no_license | [
{
"docstring": "Initinitializes from an instance of class densityOfStates",
"name": "__init__",
"signature": "def __init__(self, dos)"
},
{
"docstring": "Takes an array and returns that array reflected about array[0]. If multi = 1.0, even reflection, if multi = -1.0, odd.",
"name": "double",... | 2 | stack_v2_sparse_classes_30k_train_035167 | Implement the Python class `doubleDos` described below.
Class description:
Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz... | Implement the Python class `doubleDos` described below.
Class description:
Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz... | c35814533fa1ebc410f1f11b0664b7bb95a89ecb | <|skeleton|>
class doubleDos:
"""Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class doubleDos:
"""Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with zeros after ... | the_stack_v2_python_sparse | src/multiphonon2/doubleDos.py | danse-inelastic/multiphonon | train | 1 |
fbe855af2c1ba4df177f09df1d7de8e93c5376b8 | [
"if hasattr(self, '_x'):\n return\nself._x = Int(0)",
"from apysc.type import value_util\nself._initialize_x_if_not_initialized()\nreturn value_util.get_copy(value=self._x)",
"from apysc.type.number_value_interface import NumberValueInterface\nfrom apysc.validation import number_validation\nif not isinstance... | <|body_start_0|>
if hasattr(self, '_x'):
return
self._x = Int(0)
<|end_body_0|>
<|body_start_1|>
from apysc.type import value_util
self._initialize_x_if_not_initialized()
return value_util.get_copy(value=self._x)
<|end_body_1|>
<|body_start_2|>
from apysc.ty... | XInterface | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XInterface:
def _initialize_x_if_not_initialized(self) -> None:
"""Initialize _x attribute if it is not initialized yet."""
<|body_0|>
def x(self) -> Int:
"""Get a x-coordinate. Returns ------- x : Int X-coordinate."""
<|body_1|>
def x(self, value: Int) ... | stack_v2_sparse_classes_75kplus_train_071969 | 2,964 | permissive | [
{
"docstring": "Initialize _x attribute if it is not initialized yet.",
"name": "_initialize_x_if_not_initialized",
"signature": "def _initialize_x_if_not_initialized(self) -> None"
},
{
"docstring": "Get a x-coordinate. Returns ------- x : Int X-coordinate.",
"name": "x",
"signature": "... | 6 | stack_v2_sparse_classes_30k_val_002608 | Implement the Python class `XInterface` described below.
Class description:
Implement the XInterface class.
Method signatures and docstrings:
- def _initialize_x_if_not_initialized(self) -> None: Initialize _x attribute if it is not initialized yet.
- def x(self) -> Int: Get a x-coordinate. Returns ------- x : Int X-... | Implement the Python class `XInterface` described below.
Class description:
Implement the XInterface class.
Method signatures and docstrings:
- def _initialize_x_if_not_initialized(self) -> None: Initialize _x attribute if it is not initialized yet.
- def x(self) -> Int: Get a x-coordinate. Returns ------- x : Int X-... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class XInterface:
def _initialize_x_if_not_initialized(self) -> None:
"""Initialize _x attribute if it is not initialized yet."""
<|body_0|>
def x(self) -> Int:
"""Get a x-coordinate. Returns ------- x : Int X-coordinate."""
<|body_1|>
def x(self, value: Int) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XInterface:
def _initialize_x_if_not_initialized(self) -> None:
"""Initialize _x attribute if it is not initialized yet."""
if hasattr(self, '_x'):
return
self._x = Int(0)
def x(self) -> Int:
"""Get a x-coordinate. Returns ------- x : Int X-coordinate."""
... | the_stack_v2_python_sparse | apysc/display/x_interface.py | TrendingTechnology/apysc | train | 0 | |
c7245f2d1887a982782877f740e12a1dfac3a3d3 | [
"user_auth = TokenAuthentication()\naccess = user_auth.get(request)\ntry:\n user_email = access['email']\nexcept KeyError:\n return Response('You are logged out.', status=200)\nuser = User.objects.get(email_address=user_email)\nuser_id = user.id\naudio_path = request.data['audio_path']\ndata = {'user_id': use... | <|body_start_0|>
user_auth = TokenAuthentication()
access = user_auth.get(request)
try:
user_email = access['email']
except KeyError:
return Response('You are logged out.', status=200)
user = User.objects.get(email_address=user_email)
user_id = use... | MakeDeletePitt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakeDeletePitt:
def post(cls, request) -> Response:
"""Makes a pitt :return: Response with audio's name"""
<|body_0|>
def delete(cls, request) -> Response:
"""Deletes a pitt :param request: :return: Response dict"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_071970 | 2,078 | no_license | [
{
"docstring": "Makes a pitt :return: Response with audio's name",
"name": "post",
"signature": "def post(cls, request) -> Response"
},
{
"docstring": "Deletes a pitt :param request: :return: Response dict",
"name": "delete",
"signature": "def delete(cls, request) -> Response"
}
] | 2 | stack_v2_sparse_classes_30k_train_046861 | Implement the Python class `MakeDeletePitt` described below.
Class description:
Implement the MakeDeletePitt class.
Method signatures and docstrings:
- def post(cls, request) -> Response: Makes a pitt :return: Response with audio's name
- def delete(cls, request) -> Response: Deletes a pitt :param request: :return: R... | Implement the Python class `MakeDeletePitt` described below.
Class description:
Implement the MakeDeletePitt class.
Method signatures and docstrings:
- def post(cls, request) -> Response: Makes a pitt :return: Response with audio's name
- def delete(cls, request) -> Response: Deletes a pitt :param request: :return: R... | 4ae72142e792c3295781e5e6a95caf3854d18c6f | <|skeleton|>
class MakeDeletePitt:
def post(cls, request) -> Response:
"""Makes a pitt :return: Response with audio's name"""
<|body_0|>
def delete(cls, request) -> Response:
"""Deletes a pitt :param request: :return: Response dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MakeDeletePitt:
def post(cls, request) -> Response:
"""Makes a pitt :return: Response with audio's name"""
user_auth = TokenAuthentication()
access = user_auth.get(request)
try:
user_email = access['email']
except KeyError:
return Response('You a... | the_stack_v2_python_sparse | src/api_client/views/make_delete_pitt_view.py | alexfurmenkov/backend-2019-trainee-sync | train | 0 | |
bd8d2fe72df8f665cf2edcf5e908d5b965109368 | [
"AbstractLayer.__init__(self)\nself.input = InputPort(inputSize)\nself.outputPorts = []\nfor size in outputSizes:\n self.outputPorts.append(OutputPort(size))",
"idx = 0\nfor port in self.outputPorts:\n port.setOutput(self.input.getNetInput()[:, idx:idx + port.size])\n idx += port.size",
"deltas = np.ze... | <|body_start_0|>
AbstractLayer.__init__(self)
self.input = InputPort(inputSize)
self.outputPorts = []
for size in outputSizes:
self.outputPorts.append(OutputPort(size))
<|end_body_0|>
<|body_start_1|>
idx = 0
for port in self.outputPorts:
port.set... | A layer which splits an input port into multiple output ports | SplitLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitLayer:
"""A layer which splits an input port into multiple output ports"""
def __init__(self, inputSize, outputSizes):
"""Create a layer which splits the input into the provided output sizes"""
<|body_0|>
def forward(self):
"""Perform a forward step - split ... | stack_v2_sparse_classes_75kplus_train_071971 | 1,664 | no_license | [
{
"docstring": "Create a layer which splits the input into the provided output sizes",
"name": "__init__",
"signature": "def __init__(self, inputSize, outputSizes)"
},
{
"docstring": "Perform a forward step - split the input to the various outputs",
"name": "forward",
"signature": "def f... | 3 | stack_v2_sparse_classes_30k_train_043078 | Implement the Python class `SplitLayer` described below.
Class description:
A layer which splits an input port into multiple output ports
Method signatures and docstrings:
- def __init__(self, inputSize, outputSizes): Create a layer which splits the input into the provided output sizes
- def forward(self): Perform a ... | Implement the Python class `SplitLayer` described below.
Class description:
A layer which splits an input port into multiple output ports
Method signatures and docstrings:
- def __init__(self, inputSize, outputSizes): Create a layer which splits the input into the provided output sizes
- def forward(self): Perform a ... | dbe2090e50434f33ac7a46845ad67eb5dc7dea87 | <|skeleton|>
class SplitLayer:
"""A layer which splits an input port into multiple output ports"""
def __init__(self, inputSize, outputSizes):
"""Create a layer which splits the input into the provided output sizes"""
<|body_0|>
def forward(self):
"""Perform a forward step - split ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SplitLayer:
"""A layer which splits an input port into multiple output ports"""
def __init__(self, inputSize, outputSizes):
"""Create a layer which splits the input into the provided output sizes"""
AbstractLayer.__init__(self)
self.input = InputPort(inputSize)
self.output... | the_stack_v2_python_sparse | nn/components/layers/SplitLayer.py | danathughes/pyNeuralNetwork | train | 0 |
94e556b45322c452143c97402f4154b34eb28e84 | [
"assert criterion in ['loss', 'accuracy']\nself.best_accuracy = 0\nself.best_loss = np.inf\nself.best_epoch = 0\nself.delta = delta\nself.filename = filename\nself.criterion = criterion",
"is_better = False\nif self.criterion == 'loss' and loss < self.best_loss - self.delta:\n is_better = True\nif self.criteri... | <|body_start_0|>
assert criterion in ['loss', 'accuracy']
self.best_accuracy = 0
self.best_loss = np.inf
self.best_epoch = 0
self.delta = delta
self.filename = filename
self.criterion = criterion
<|end_body_0|>
<|body_start_1|>
is_better = False
i... | Implementation for Early Stopping Always stores the best model in a file, which can be accessed at the end of all epochs. Invoke self.checkpoint() after every training step | EarlyStopping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
"""Implementation for Early Stopping Always stores the best model in a file, which can be accessed at the end of all epochs. Invoke self.checkpoint() after every training step"""
def __init__(self, filename='.checkpoint.params', delta=0, criterion='loss'):
"""Construct... | stack_v2_sparse_classes_75kplus_train_071972 | 2,315 | permissive | [
{
"docstring": "Constructor Parameters: - filename: string for the filename (can also be an absolute path) - delta: minimum change needed for the model to update on the disk - criterion: 'loss' or 'accuracy', which should be the indicator for the best model",
"name": "__init__",
"signature": "def __init... | 3 | null | Implement the Python class `EarlyStopping` described below.
Class description:
Implementation for Early Stopping Always stores the best model in a file, which can be accessed at the end of all epochs. Invoke self.checkpoint() after every training step
Method signatures and docstrings:
- def __init__(self, filename='.... | Implement the Python class `EarlyStopping` described below.
Class description:
Implementation for Early Stopping Always stores the best model in a file, which can be accessed at the end of all epochs. Invoke self.checkpoint() after every training step
Method signatures and docstrings:
- def __init__(self, filename='.... | 0f467e7f0d9e56d606d8f957773067bc89c2b42c | <|skeleton|>
class EarlyStopping:
"""Implementation for Early Stopping Always stores the best model in a file, which can be accessed at the end of all epochs. Invoke self.checkpoint() after every training step"""
def __init__(self, filename='.checkpoint.params', delta=0, criterion='loss'):
"""Construct... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EarlyStopping:
"""Implementation for Early Stopping Always stores the best model in a file, which can be accessed at the end of all epochs. Invoke self.checkpoint() after every training step"""
def __init__(self, filename='.checkpoint.params', delta=0, criterion='loss'):
"""Constructor Parameters... | the_stack_v2_python_sparse | utils/early_stopping.py | path-env/q-eegnet_torch | train | 0 |
5d70d3035717d2baf5b39fdd614d8512f2d1e2bd | [
"data = np.array([[0, 10, 20, 5, 0], [0, 50, 20, 5, 0], [0, 80, 90, 0, 0], [0, 20, 5, 10, 0], [0, 5, 10, 10, 0]])\nself.cube = set_up_variable_cube(data, name='orographic_height', units='m', spatial_grid='equalarea', grid_spacing=2000.0)\nself.expected_data = [[50, 50, 50, 20, 5], [80, 90, 90, 90, 5], [80, 90, 90, ... | <|body_start_0|>
data = np.array([[0, 10, 20, 5, 0], [0, 50, 20, 5, 0], [0, 80, 90, 0, 0], [0, 20, 5, 10, 0], [0, 5, 10, 10, 0]])
self.cube = set_up_variable_cube(data, name='orographic_height', units='m', spatial_grid='equalarea', grid_spacing=2000.0)
self.expected_data = [[50, 50, 50, 20, 5], ... | Test the find_max_in_nbhood_orography method | Test_find_max_in_nbhood_orography | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_find_max_in_nbhood_orography:
"""Test the find_max_in_nbhood_orography method"""
def setUp(self):
"""Set up a cube with x and y coordinates"""
<|body_0|>
def test_basic(self):
"""Test the function does what it's meant to in a simple case."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_071973 | 37,344 | permissive | [
{
"docstring": "Set up a cube with x and y coordinates",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the function does what it's meant to in a simple case.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test the function... | 4 | stack_v2_sparse_classes_30k_train_018139 | Implement the Python class `Test_find_max_in_nbhood_orography` described below.
Class description:
Test the find_max_in_nbhood_orography method
Method signatures and docstrings:
- def setUp(self): Set up a cube with x and y coordinates
- def test_basic(self): Test the function does what it's meant to in a simple case... | Implement the Python class `Test_find_max_in_nbhood_orography` described below.
Class description:
Test the find_max_in_nbhood_orography method
Method signatures and docstrings:
- def setUp(self): Set up a cube with x and y coordinates
- def test_basic(self): Test the function does what it's meant to in a simple case... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_find_max_in_nbhood_orography:
"""Test the find_max_in_nbhood_orography method"""
def setUp(self):
"""Set up a cube with x and y coordinates"""
<|body_0|>
def test_basic(self):
"""Test the function does what it's meant to in a simple case."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_find_max_in_nbhood_orography:
"""Test the find_max_in_nbhood_orography method"""
def setUp(self):
"""Set up a cube with x and y coordinates"""
data = np.array([[0, 10, 20, 5, 0], [0, 50, 20, 5, 0], [0, 80, 90, 0, 0], [0, 20, 5, 10, 0], [0, 5, 10, 10, 0]])
self.cube = set_up_v... | the_stack_v2_python_sparse | improver_tests/psychrometric_calculations/test_PhaseChangeLevel.py | metoppv/improver | train | 101 |
cc6ba8a90e3be82dca6298bf20b8533de9e9d77a | [
"self.width = width\nself.height = height\nself.food = food\nself.x_pos = 0\nself.y_pos = 0\nself.score = 0\nself.path = [[0, 0]]",
"x, y = self.path[0]\nif direction == 'R':\n self.y_pos += 1\nelif direction == 'L':\n self.y_pos -= 1\nelif direction == 'U':\n self.x_pos -= 1\nelif direction == 'D':\n ... | <|body_start_0|>
self.width = width
self.height = height
self.food = food
self.x_pos = 0
self.y_pos = 0
self.score = 0
self.path = [[0, 0]]
<|end_body_0|>
<|body_start_1|>
x, y = self.path[0]
if direction == 'R':
self.y_pos += 1
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]."""
... | stack_v2_sparse_classes_75kplus_train_071974 | 3,176 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 1d5628f51adce49b295efc514325eeb0489e2602 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]."""
self.wi... | the_stack_v2_python_sparse | snakeGame.py | ebegeti/LeetCode-problems | train | 0 | |
c25cb8e395a20cd0760a9a4a5cf81bff503a3c6f | [
"self.storages = []\nself.main_storage = None\nself.stores = {}\nif storages is not None:\n map(self.add, storages)",
"if type(storage) is list:\n [self.add(st) for st in storage]\n return\nif not hasattr(storage, 'use_uuid'):\n raise RuntimeError('The storage to be added does not use UUIDs!')\nfor st... | <|body_start_0|>
self.storages = []
self.main_storage = None
self.stores = {}
if storages is not None:
map(self.add, storages)
<|end_body_0|>
<|body_start_1|>
if type(storage) is list:
[self.add(st) for st in storage]
return
if not has... | A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines. | DistributedUUIDStorage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistributedUUIDStorage:
"""A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines."""
def __init__(self, storages=None):
"""Parameters ---------- storages : list of :class:`openpathsa... | stack_v2_sparse_classes_75kplus_train_071975 | 3,665 | permissive | [
{
"docstring": "Parameters ---------- storages : list of :class:`openpathsampling.storage.Storage` The storages to be used",
"name": "__init__",
"signature": "def __init__(self, storages=None)"
},
{
"docstring": "Add a (read-only) file to the set of storages Parameters ---------- storage",
"... | 2 | stack_v2_sparse_classes_30k_train_006014 | Implement the Python class `DistributedUUIDStorage` described below.
Class description:
A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines.
Method signatures and docstrings:
- def __init__(self, storages=None): Pa... | Implement the Python class `DistributedUUIDStorage` described below.
Class description:
A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines.
Method signatures and docstrings:
- def __init__(self, storages=None): Pa... | 3d02df4ccdeb6d62030a28e371a6b4ea9aaee5fe | <|skeleton|>
class DistributedUUIDStorage:
"""A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines."""
def __init__(self, storages=None):
"""Parameters ---------- storages : list of :class:`openpathsa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DistributedUUIDStorage:
"""A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines."""
def __init__(self, storages=None):
"""Parameters ---------- storages : list of :class:`openpathsampling.storag... | the_stack_v2_python_sparse | openpathsampling/storage/distributed.py | dwhswenson/openpathsampling | train | 3 |
69f86ffd9038b134738c76594792cf6fcb8557e9 | [
"test_inventory = Furniture(123, 'chair', 100, 50, 'wood', 'm')\nself.assertEqual(test_inventory.material, 'wood')\nself.assertEqual(test_inventory.size, 'm')",
"test_inventory = Furniture(123, 'chair', 100, 50, 'wood', 'm').return_as_dictionary()\nself.assertEqual(test_inventory['material'], 'wood')\nself.assert... | <|body_start_0|>
test_inventory = Furniture(123, 'chair', 100, 50, 'wood', 'm')
self.assertEqual(test_inventory.material, 'wood')
self.assertEqual(test_inventory.size, 'm')
<|end_body_0|>
<|body_start_1|>
test_inventory = Furniture(123, 'chair', 100, 50, 'wood', 'm').return_as_dictionar... | Test the Furniture class | FurnitureTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FurnitureTest:
"""Test the Furniture class"""
def test_init(self):
"""Test init"""
<|body_0|>
def test_return_as_dictionary(self):
"""Test the return as dictionary method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_inventory = Furniture... | stack_v2_sparse_classes_75kplus_train_071976 | 3,232 | no_license | [
{
"docstring": "Test init",
"name": "test_init",
"signature": "def test_init(self)"
},
{
"docstring": "Test the return as dictionary method",
"name": "test_return_as_dictionary",
"signature": "def test_return_as_dictionary(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012451 | Implement the Python class `FurnitureTest` described below.
Class description:
Test the Furniture class
Method signatures and docstrings:
- def test_init(self): Test init
- def test_return_as_dictionary(self): Test the return as dictionary method | Implement the Python class `FurnitureTest` described below.
Class description:
Test the Furniture class
Method signatures and docstrings:
- def test_init(self): Test init
- def test_return_as_dictionary(self): Test the return as dictionary method
<|skeleton|>
class FurnitureTest:
"""Test the Furniture class"""
... | 6ffd7b4ab8346076d3b6cc02ca1ebca3bf028697 | <|skeleton|>
class FurnitureTest:
"""Test the Furniture class"""
def test_init(self):
"""Test init"""
<|body_0|>
def test_return_as_dictionary(self):
"""Test the return as dictionary method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FurnitureTest:
"""Test the Furniture class"""
def test_init(self):
"""Test init"""
test_inventory = Furniture(123, 'chair', 100, 50, 'wood', 'm')
self.assertEqual(test_inventory.material, 'wood')
self.assertEqual(test_inventory.size, 'm')
def test_return_as_dictionary... | the_stack_v2_python_sparse | students/AndrewMiotke/lesson01/assignment/test_unit.py | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | train | 4 |
442a09f7b33159f46fd0c3d1279fe5267960d7de | [
"if not isinstance(subsection, yc.ConfigElement):\n raise ValueError(\"Tried to add a subsection to the config, but it wasn't a yaml_config ConfigElement instance (or an instance of a ConfigElement child class).\")\nname = subsection.name\nnames = [el.name for el in cls.ELEMENTS]\nif name in names:\n raise Va... | <|body_start_0|>
if not isinstance(subsection, yc.ConfigElement):
raise ValueError("Tried to add a subsection to the config, but it wasn't a yaml_config ConfigElement instance (or an instance of a ConfigElement child class).")
name = subsection.name
names = [el.name for el in cls.ELE... | This class describes a test section in a Pavilion config file. It is expected to be added to by various plugins. | TestConfigLoader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConfigLoader:
"""This class describes a test section in a Pavilion config file. It is expected to be added to by various plugins."""
def add_subsection(cls, subsection):
"""Use this method to add additional sub-sections to the config. :param yc.ConfigElem subsection: A yaml confi... | stack_v2_sparse_classes_75kplus_train_071977 | 13,219 | permissive | [
{
"docstring": "Use this method to add additional sub-sections to the config. :param yc.ConfigElem subsection: A yaml config element to add. Keyed elements are expected, though any ConfigElem based instance (whose leave elements are StrElems) should work.",
"name": "add_subsection",
"signature": "def ad... | 5 | stack_v2_sparse_classes_30k_train_015191 | Implement the Python class `TestConfigLoader` described below.
Class description:
This class describes a test section in a Pavilion config file. It is expected to be added to by various plugins.
Method signatures and docstrings:
- def add_subsection(cls, subsection): Use this method to add additional sub-sections to ... | Implement the Python class `TestConfigLoader` described below.
Class description:
This class describes a test section in a Pavilion config file. It is expected to be added to by various plugins.
Method signatures and docstrings:
- def add_subsection(cls, subsection): Use this method to add additional sub-sections to ... | fd846b0508e2a3d60d4f2f538aa8fb5ff2ae9c8f | <|skeleton|>
class TestConfigLoader:
"""This class describes a test section in a Pavilion config file. It is expected to be added to by various plugins."""
def add_subsection(cls, subsection):
"""Use this method to add additional sub-sections to the config. :param yc.ConfigElem subsection: A yaml confi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestConfigLoader:
"""This class describes a test section in a Pavilion config file. It is expected to be added to by various plugins."""
def add_subsection(cls, subsection):
"""Use this method to add additional sub-sections to the config. :param yc.ConfigElem subsection: A yaml config element to ... | the_stack_v2_python_sparse | lib/pavilion/test_config/file_format.py | lanl-preteam/pavilion2-tmp | train | 1 |
1940b8823b8ef71298e3b0ce52df990fa0219941 | [
"try:\n contactData = {'firstName': input('First name:'), 'lastName': input('last name:'), 'address': input('address:'), 'city': input('city:'), 'state': input('state:'), 'zip': input('zip:'), 'phoneNumber': input('phoneNumber:'), 'email': input('email:')}\n contact = Contacts(contactData)\n contactList.ap... | <|body_start_0|>
try:
contactData = {'firstName': input('First name:'), 'lastName': input('last name:'), 'address': input('address:'), 'city': input('city:'), 'state': input('state:'), 'zip': input('zip:'), 'phoneNumber': input('phoneNumber:'), 'email': input('email:')}
contact = Contact... | AddressBook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressBook:
def addContact(self, addressBookName, contactList):
"""Desciption: this function add contact Parameter: addressBookName: string contactList: list"""
<|body_0|>
def updateContact(self, addressBookName, contactList):
"""Desciption: this function update con... | stack_v2_sparse_classes_75kplus_train_071978 | 8,712 | no_license | [
{
"docstring": "Desciption: this function add contact Parameter: addressBookName: string contactList: list",
"name": "addContact",
"signature": "def addContact(self, addressBookName, contactList)"
},
{
"docstring": "Desciption: this function update contact Parameter: contactList: list",
"nam... | 6 | stack_v2_sparse_classes_30k_val_001072 | Implement the Python class `AddressBook` described below.
Class description:
Implement the AddressBook class.
Method signatures and docstrings:
- def addContact(self, addressBookName, contactList): Desciption: this function add contact Parameter: addressBookName: string contactList: list
- def updateContact(self, add... | Implement the Python class `AddressBook` described below.
Class description:
Implement the AddressBook class.
Method signatures and docstrings:
- def addContact(self, addressBookName, contactList): Desciption: this function add contact Parameter: addressBookName: string contactList: list
- def updateContact(self, add... | 8150a07944d1885d15e7f9bbe21b6223fd91a657 | <|skeleton|>
class AddressBook:
def addContact(self, addressBookName, contactList):
"""Desciption: this function add contact Parameter: addressBookName: string contactList: list"""
<|body_0|>
def updateContact(self, addressBookName, contactList):
"""Desciption: this function update con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddressBook:
def addContact(self, addressBookName, contactList):
"""Desciption: this function add contact Parameter: addressBookName: string contactList: list"""
try:
contactData = {'firstName': input('First name:'), 'lastName': input('last name:'), 'address': input('address:'), 'c... | the_stack_v2_python_sparse | ObjectOrientedPrograms/AddressBookProgram/AddressBook.py | SwapnilBhoyar/PythonPrograms | train | 0 | |
648a893dcfdbe9916b99b3c2a7de457799884d71 | [
"meta = dict()\nfor k, v in self.__dict__.items():\n if isinstance(v, np.ndarray):\n meta[k] = v.tolist()\n else:\n meta[k] = v\nreturn meta",
"meta = dict()\nfor k, v in doc.items():\n if k == 'classes_':\n self.classes_ = np.array(v)\n continue\n meta[k] = v\nself.__dict_... | <|body_start_0|>
meta = dict()
for k, v in self.__dict__.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
else:
meta[k] = v
return meta
<|end_body_0|>
<|body_start_1|>
meta = dict()
for k, v in doc.items():
... | Label encoder with JSON serialization methods. | XGBoostLabelEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self):
"""Returns a JSON compatible dictionary"""
<|body_0|>
def from_json(self, doc):
"""Load the encoder back from a JSON compatible dict."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_071979 | 5,242 | permissive | [
{
"docstring": "Returns a JSON compatible dictionary",
"name": "to_json",
"signature": "def to_json(self)"
},
{
"docstring": "Load the encoder back from a JSON compatible dict.",
"name": "from_json",
"signature": "def from_json(self, doc)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040987 | Implement the Python class `XGBoostLabelEncoder` described below.
Class description:
Label encoder with JSON serialization methods.
Method signatures and docstrings:
- def to_json(self): Returns a JSON compatible dictionary
- def from_json(self, doc): Load the encoder back from a JSON compatible dict. | Implement the Python class `XGBoostLabelEncoder` described below.
Class description:
Label encoder with JSON serialization methods.
Method signatures and docstrings:
- def to_json(self): Returns a JSON compatible dictionary
- def from_json(self, doc): Load the encoder back from a JSON compatible dict.
<|skeleton|>
c... | a79c7e4a1e411b6a6221d193007a2328312714c3 | <|skeleton|>
class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self):
"""Returns a JSON compatible dictionary"""
<|body_0|>
def from_json(self, doc):
"""Load the encoder back from a JSON compatible dict."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XGBoostLabelEncoder:
"""Label encoder with JSON serialization methods."""
def to_json(self):
"""Returns a JSON compatible dictionary"""
meta = dict()
for k, v in self.__dict__.items():
if isinstance(v, np.ndarray):
meta[k] = v.tolist()
else:... | the_stack_v2_python_sparse | python-package/xgboost/compat.py | NVIDIA/spark-xgboost | train | 22 |
9440a22de05cdf99b8b67acd097a981285ac900e | [
"self.save_id = save_id\nself.nickname = nickname\nself.progress = progress\nself.created_at = created_at",
"progress = {}\nlevels_completed = self.progress // 100\nprogress['levels_completed'] = levels_completed\nlevel = 1\nwhile level <= levels_completed:\n progress[f'level{level}'] = 100\n progress[f'unl... | <|body_start_0|>
self.save_id = save_id
self.nickname = nickname
self.progress = progress
self.created_at = created_at
<|end_body_0|>
<|body_start_1|>
progress = {}
levels_completed = self.progress // 100
progress['levels_completed'] = levels_completed
le... | A class to represent save object and hold the information. Attributes: save_id: Unique id number. nickname: Name of the save object. progress: Corresponds progress level of the game. created_at: Timestamp when save has been created. | Save | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Save:
"""A class to represent save object and hold the information. Attributes: save_id: Unique id number. nickname: Name of the save object. progress: Corresponds progress level of the game. created_at: Timestamp when save has been created."""
def __init__(self, save_id, nickname, progress,... | stack_v2_sparse_classes_75kplus_train_071980 | 2,358 | no_license | [
{
"docstring": "Constructs all the necessary attributes for the save object. Args: save_id (int): Unique id number. nickname (str): Name of the save object. progress (int): Corresponds progress level of the game. created_at (date): Timestamp when save has been created.",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_047214 | Implement the Python class `Save` described below.
Class description:
A class to represent save object and hold the information. Attributes: save_id: Unique id number. nickname: Name of the save object. progress: Corresponds progress level of the game. created_at: Timestamp when save has been created.
Method signatur... | Implement the Python class `Save` described below.
Class description:
A class to represent save object and hold the information. Attributes: save_id: Unique id number. nickname: Name of the save object. progress: Corresponds progress level of the game. created_at: Timestamp when save has been created.
Method signatur... | 29cd15dddff620de068a479595a5cb9aba855343 | <|skeleton|>
class Save:
"""A class to represent save object and hold the information. Attributes: save_id: Unique id number. nickname: Name of the save object. progress: Corresponds progress level of the game. created_at: Timestamp when save has been created."""
def __init__(self, save_id, nickname, progress,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Save:
"""A class to represent save object and hold the information. Attributes: save_id: Unique id number. nickname: Name of the save object. progress: Corresponds progress level of the game. created_at: Timestamp when save has been created."""
def __init__(self, save_id, nickname, progress, created_at):... | the_stack_v2_python_sparse | src/entities/save.py | TopiasHarjunpaa/ot-harjoitustyo | train | 0 |
3351eaff490b820d6661fb2c9cc5212c892d478b | [
"self.items = items\nself.max_weight = max_weight\nself.dp_dict = {}\nself.iterations = 0",
"self.iterations = 0\nprint('Method: ' + method)\nif method == 'brute_force':\n sol = self.brute_force()\nelif method == 'recursive':\n sol = self.recursive(len(self.items), self.max_weight)\n print('Iterations:' ... | <|body_start_0|>
self.items = items
self.max_weight = max_weight
self.dp_dict = {}
self.iterations = 0
<|end_body_0|>
<|body_start_1|>
self.iterations = 0
print('Method: ' + method)
if method == 'brute_force':
sol = self.brute_force()
elif met... | Knapsack | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Knapsack:
def __init__(self, max_weight=7, items=[]):
"""Constructor :param max_weight: Max weight allowed in the knapsack :param items: List of items. Each item has a weight w, and a value v."""
<|body_0|>
def solver(self, method='brute_force'):
"""Input method to s... | stack_v2_sparse_classes_75kplus_train_071981 | 6,758 | permissive | [
{
"docstring": "Constructor :param max_weight: Max weight allowed in the knapsack :param items: List of items. Each item has a weight w, and a value v.",
"name": "__init__",
"signature": "def __init__(self, max_weight=7, items=[])"
},
{
"docstring": "Input method to solve the knapsack problem :r... | 6 | stack_v2_sparse_classes_30k_train_038085 | Implement the Python class `Knapsack` described below.
Class description:
Implement the Knapsack class.
Method signatures and docstrings:
- def __init__(self, max_weight=7, items=[]): Constructor :param max_weight: Max weight allowed in the knapsack :param items: List of items. Each item has a weight w, and a value v... | Implement the Python class `Knapsack` described below.
Class description:
Implement the Knapsack class.
Method signatures and docstrings:
- def __init__(self, max_weight=7, items=[]): Constructor :param max_weight: Max weight allowed in the knapsack :param items: List of items. Each item has a weight w, and a value v... | 517cc41d92abaa5b8263c821d54f968a2c31cc8d | <|skeleton|>
class Knapsack:
def __init__(self, max_weight=7, items=[]):
"""Constructor :param max_weight: Max weight allowed in the knapsack :param items: List of items. Each item has a weight w, and a value v."""
<|body_0|>
def solver(self, method='brute_force'):
"""Input method to s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Knapsack:
def __init__(self, max_weight=7, items=[]):
"""Constructor :param max_weight: Max weight allowed in the knapsack :param items: List of items. Each item has a weight w, and a value v."""
self.items = items
self.max_weight = max_weight
self.dp_dict = {}
self.ite... | the_stack_v2_python_sparse | Project5-knapsack.py | piyush69/Python_Projects | train | 0 | |
8b19f67aa364493be640e790b0298c3a8217e16a | [
"self.section = section_number\nself.name = course_name\nself.enrolled_students = []",
"if (names, ucid) not in self.enrolled_students:\n self.enrolled_students.append((names, ucid))\n print(names, 'with ucid', str(ucid), 'has successfully enrolled in section 1 of CS100')\nelse:\n print('Already Enrolled... | <|body_start_0|>
self.section = section_number
self.name = course_name
self.enrolled_students = []
<|end_body_0|>
<|body_start_1|>
if (names, ucid) not in self.enrolled_students:
self.enrolled_students.append((names, ucid))
print(names, 'with ucid', str(ucid), 'h... | this is class represent course section | Course_Section | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Course_Section:
"""this is class represent course section"""
def __init__(self, section_number, course_name):
"""this is class"""
<|body_0|>
def enroll(self, names, ucid):
"""this method enrolls student in the course section"""
<|body_1|>
def drop(se... | stack_v2_sparse_classes_75kplus_train_071982 | 2,447 | no_license | [
{
"docstring": "this is class",
"name": "__init__",
"signature": "def __init__(self, section_number, course_name)"
},
{
"docstring": "this method enrolls student in the course section",
"name": "enroll",
"signature": "def enroll(self, names, ucid)"
},
{
"docstring": "this method ... | 3 | stack_v2_sparse_classes_30k_train_005170 | Implement the Python class `Course_Section` described below.
Class description:
this is class represent course section
Method signatures and docstrings:
- def __init__(self, section_number, course_name): this is class
- def enroll(self, names, ucid): this method enrolls student in the course section
- def drop(self, ... | Implement the Python class `Course_Section` described below.
Class description:
this is class represent course section
Method signatures and docstrings:
- def __init__(self, section_number, course_name): this is class
- def enroll(self, names, ucid): this method enrolls student in the course section
- def drop(self, ... | 2f6e368ecf670b6690ca83902bf8f0701971661d | <|skeleton|>
class Course_Section:
"""this is class represent course section"""
def __init__(self, section_number, course_name):
"""this is class"""
<|body_0|>
def enroll(self, names, ucid):
"""this method enrolls student in the course section"""
<|body_1|>
def drop(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Course_Section:
"""this is class represent course section"""
def __init__(self, section_number, course_name):
"""this is class"""
self.section = section_number
self.name = course_name
self.enrolled_students = []
def enroll(self, names, ucid):
"""this method en... | the_stack_v2_python_sparse | Python & C++/HW12_Sk_ Adib_Asker.py | adib-asker/Projects | train | 0 |
6b7287968f1b3cc7ab61b125dfc6c1052bcf5fb9 | [
"self.sample = random.sample(self.get_app_id_list(), size)\nself.s = requests.Session()\nsuper().__init__('steam.txt')",
"descriptions = []\nfor appid in self.sample:\n description = self.get_app_description(appid)\n if description:\n description = self.filter_description(description)\n descri... | <|body_start_0|>
self.sample = random.sample(self.get_app_id_list(), size)
self.s = requests.Session()
super().__init__('steam.txt')
<|end_body_0|>
<|body_start_1|>
descriptions = []
for appid in self.sample:
description = self.get_app_description(appid)
... | Parse game descriptions from the Steam storefront. | SteamParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteamParser:
"""Parse game descriptions from the Steam storefront."""
def __init__(self, size=200):
"""Initialize parser with number of games whose description to read."""
<|body_0|>
def parse(self):
"""Parses the sample of appids for game descriptions and store ... | stack_v2_sparse_classes_75kplus_train_071983 | 4,061 | no_license | [
{
"docstring": "Initialize parser with number of games whose description to read.",
"name": "__init__",
"signature": "def __init__(self, size=200)"
},
{
"docstring": "Parses the sample of appids for game descriptions and store as self.content attribute. Note that not all apps in self.sample are ... | 6 | stack_v2_sparse_classes_30k_train_022898 | Implement the Python class `SteamParser` described below.
Class description:
Parse game descriptions from the Steam storefront.
Method signatures and docstrings:
- def __init__(self, size=200): Initialize parser with number of games whose description to read.
- def parse(self): Parses the sample of appids for game de... | Implement the Python class `SteamParser` described below.
Class description:
Parse game descriptions from the Steam storefront.
Method signatures and docstrings:
- def __init__(self, size=200): Initialize parser with number of games whose description to read.
- def parse(self): Parses the sample of appids for game de... | dcbf8130cf6b0bb132509547bf640396029ef2eb | <|skeleton|>
class SteamParser:
"""Parse game descriptions from the Steam storefront."""
def __init__(self, size=200):
"""Initialize parser with number of games whose description to read."""
<|body_0|>
def parse(self):
"""Parses the sample of appids for game descriptions and store ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SteamParser:
"""Parse game descriptions from the Steam storefront."""
def __init__(self, size=200):
"""Initialize parser with number of games whose description to read."""
self.sample = random.sample(self.get_app_id_list(), size)
self.s = requests.Session()
super().__init_... | the_stack_v2_python_sparse | src/parsers/steam_parser.py | lajanki/markov_text_generator | train | 1 |
a3c2508b492d98861d4d1f11420a15b0f3b293fe | [
"self.params = {}\nself.reg = reg\nself.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim)\nself.params['b1'] = np.zeros(hidden_dim)\nself.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes)\nself.params['b2'] = np.zeros(num_classes)",
"out1, cache1 = layer_utilities.affine_re... | <|body_start_0|>
self.params = {}
self.reg = reg
self.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim)
self.params['b1'] = np.zeros(hidden_dim)
self.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes)
self.params['b2'] = np.zeros(num... | A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this class does not implement ... | TwoLayerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. N... | stack_v2_sparse_classes_75kplus_train_071984 | 3,643 | no_license | [
{
"docstring": "Initialize a new network. Inputs: - input_dim: An integer giving the size of the input - hidden_dim: An integer giving the size of the hidden layer - num_classes: An integer giving the number of classes to classify - weight_scale: Scalar giving the standard deviation for random initialization of... | 2 | stack_v2_sparse_classes_30k_train_013082 | Implement the Python class `TwoLayerNet` described below.
Class description:
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should... | Implement the Python class `TwoLayerNet` described below.
Class description:
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should... | 3326ca3a7950102dbcc1035ae6b99478a06f8696 | <|skeleton|>
class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoLayerNet:
"""A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this... | the_stack_v2_python_sparse | assignment2/Q1/classifier_fc_net.py | dz-chen/cs231n-homework | train | 0 |
030ae291e5a2982c43503a714bfd6d9695a45101 | [
"n = len(senate)\nq1, q2 = (deque(), deque())\nfor i, s in enumerate(senate):\n if s == 'R':\n q1.append(i)\n else:\n q2.append(i)\nwhile q1 and q2:\n s1, s2 = (q1.popleft(), q2.popleft())\n if s1 < s2:\n q1.append(s1 + n)\n else:\n q2.append(s2 + n)\nreturn 'Radiant' if q... | <|body_start_0|>
n = len(senate)
q1, q2 = (deque(), deque())
for i, s in enumerate(senate):
if s == 'R':
q1.append(i)
else:
q2.append(i)
while q1 and q2:
s1, s2 = (q1.popleft(), q2.popleft())
if s1 < s2:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def predictPartyVictory(self, senate):
""":type senate: str :rtype: str"""
<|body_0|>
def predictPartyVictory_trial(self, senate):
""":type senate: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(senate)
q1,... | stack_v2_sparse_classes_75kplus_train_071985 | 3,826 | no_license | [
{
"docstring": ":type senate: str :rtype: str",
"name": "predictPartyVictory",
"signature": "def predictPartyVictory(self, senate)"
},
{
"docstring": ":type senate: str :rtype: str",
"name": "predictPartyVictory_trial",
"signature": "def predictPartyVictory_trial(self, senate)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006564 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def predictPartyVictory(self, senate): :type senate: str :rtype: str
- def predictPartyVictory_trial(self, senate): :type senate: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def predictPartyVictory(self, senate): :type senate: str :rtype: str
- def predictPartyVictory_trial(self, senate): :type senate: str :rtype: str
<|skeleton|>
class Solution:
... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def predictPartyVictory(self, senate):
""":type senate: str :rtype: str"""
<|body_0|>
def predictPartyVictory_trial(self, senate):
""":type senate: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def predictPartyVictory(self, senate):
""":type senate: str :rtype: str"""
n = len(senate)
q1, q2 = (deque(), deque())
for i, s in enumerate(senate):
if s == 'R':
q1.append(i)
else:
q2.append(i)
while q1 ... | the_stack_v2_python_sparse | code649Dota2Senate.py | cybelewang/leetcode-python | train | 0 | |
a4a55682a2ed200529de99d3daa320712e68d3ef | [
"super(DQN, self).__init__()\nself.layer1 = torch.nn.Sequential(torch.nn.Linear(input_dim, hidden_dim), torch.nn.BatchNorm1d(hidden_dim), torch.nn.PReLU())\nself.layer2 = torch.nn.Sequential(torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.BatchNorm1d(hidden_dim), torch.nn.PReLU())\nself.final = torch.nn.Linear(hi... | <|body_start_0|>
super(DQN, self).__init__()
self.layer1 = torch.nn.Sequential(torch.nn.Linear(input_dim, hidden_dim), torch.nn.BatchNorm1d(hidden_dim), torch.nn.PReLU())
self.layer2 = torch.nn.Sequential(torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.BatchNorm1d(hidden_dim), torch.nn.PReLU()... | DQN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DQN:
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None:
"""DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int): ... | stack_v2_sparse_classes_75kplus_train_071986 | 10,713 | permissive | [
{
"docstring": "DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int): Hidden dimension in fc layer",
"name": "__init__",
"signature": "def __init__(self, in... | 2 | null | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim... | Implement the Python class `DQN` described below.
Class description:
Implement the DQN class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim... | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | <|skeleton|>
class DQN:
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None:
"""DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int): ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DQN:
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None:
"""DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int): Hidden dimensi... | the_stack_v2_python_sparse | all-gists/52ea1e118101eb574b2a83b933851379/snippet.py | gistable/gistable | train | 76 | |
1da137d60458ecfa4b85c5a2abb132204c701727 | [
"super(DisplaceAtoms, self).__init__(**kwargs)\nself.atoms = []\n' Atomic displacements. '",
"from ..crystal import Atom\nself.atoms.append(Atom(*args, **kwargs))\nreturn self",
"result = super(DisplaceAtoms, self).__repr__()\nindent = ' '.join(('' for i in xrange(result.find('('))))\nfor o in self.atoms:\n ... | <|body_start_0|>
super(DisplaceAtoms, self).__init__(**kwargs)
self.atoms = []
' Atomic displacements. '
<|end_body_0|>
<|body_start_1|>
from ..crystal import Atom
self.atoms.append(Atom(*args, **kwargs))
return self
<|end_body_1|>
<|body_start_2|>
result = supe... | Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The above creates a displacement operations f... | DisplaceAtoms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisplaceAtoms:
"""Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The ... | stack_v2_sparse_classes_75kplus_train_071987 | 24,102 | no_license | [
{
"docstring": "Creates a displacement field.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Adds a displacement to a given atom. At present, atom.type should be an index to an atom in the structure.",
"name": "add_atom",
"signature": "def add_atom(s... | 5 | stack_v2_sparse_classes_30k_train_034619 | Implement the Python class `DisplaceAtoms` described below.
Class description:
Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0... | Implement the Python class `DisplaceAtoms` described below.
Class description:
Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class DisplaceAtoms:
"""Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisplaceAtoms:
"""Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The above creates... | the_stack_v2_python_sparse | dftcrystal/geometry.py | Shibu778/LaDa | train | 0 |
4d542d06223e08a24c96a31d4d834483f1bf64da | [
"def preorder(root):\n if not root:\n return '#,'\n return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right)\nreturn preorder(root)",
"if not data or data == '#':\n return\nnodes = data.split(',')\n\ndef preorder(i):\n if i >= len(nodes) or nodes[i] == '#':\n r... | <|body_start_0|>
def preorder(root):
if not root:
return '#,'
return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right)
return preorder(root)
<|end_body_0|>
<|body_start_1|>
if not data or data == '#':
return
... | CodecDFS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodecDFS:
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|>
<|bo... | stack_v2_sparse_classes_75kplus_train_071988 | 2,652 | 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_038800 | Implement the Python class `CodecDFS` described below.
Class description:
Implement the CodecDFS 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 :... | Implement the Python class `CodecDFS` described below.
Class description:
Implement the CodecDFS 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 :... | 3a5649357e0f21cbbc5e238351300cd706d533b3 | <|skeleton|>
class CodecDFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CodecDFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preorder(root):
if not root:
return '#,'
return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right)
return... | the_stack_v2_python_sparse | leetcode-py/leetcode297.py | cicihou/LearningProject | train | 0 | |
eb1c503a7eead0486a484d7154f9998f7cf70a50 | [
"L = []\nk = 0\na1.swap_k(L, k)\nexpected = []\nself.assertEqual(L, expected)",
"L = [1]\nk = 0\na1.swap_k(L, k)\nexpected = [1]\nself.assertEqual(L, expected)",
"L = [1, 2, 3, 4, 5, 6]\nk = 1\na1.swap_k(L, k)\nexpected = [6, 2, 3, 4, 5, 1]\nself.assertEqual(L, expected)",
"L = [1, 2, 3, 4, 5, 6]\nk = 2\na1.s... | <|body_start_0|>
L = []
k = 0
a1.swap_k(L, k)
expected = []
self.assertEqual(L, expected)
<|end_body_0|>
<|body_start_1|>
L = [1]
k = 0
a1.swap_k(L, k)
expected = [1]
self.assertEqual(L, expected)
<|end_body_1|>
<|body_start_2|>
L... | Test class for function a1.swap_k. | TestSwapK | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSwapK:
"""Test class for function a1.swap_k."""
def test_swap_k_1(self):
"""Test empty list"""
<|body_0|>
def test_swap_k_2(self):
"""Test single element case and k = 0 case"""
<|body_1|>
def test_swap_k_3(self):
"""Test k = 1"""
... | stack_v2_sparse_classes_75kplus_train_071989 | 1,144 | no_license | [
{
"docstring": "Test empty list",
"name": "test_swap_k_1",
"signature": "def test_swap_k_1(self)"
},
{
"docstring": "Test single element case and k = 0 case",
"name": "test_swap_k_2",
"signature": "def test_swap_k_2(self)"
},
{
"docstring": "Test k = 1",
"name": "test_swap_k_... | 5 | stack_v2_sparse_classes_30k_test_002061 | Implement the Python class `TestSwapK` described below.
Class description:
Test class for function a1.swap_k.
Method signatures and docstrings:
- def test_swap_k_1(self): Test empty list
- def test_swap_k_2(self): Test single element case and k = 0 case
- def test_swap_k_3(self): Test k = 1
- def test_swap_k_4(self):... | Implement the Python class `TestSwapK` described below.
Class description:
Test class for function a1.swap_k.
Method signatures and docstrings:
- def test_swap_k_1(self): Test empty list
- def test_swap_k_2(self): Test single element case and k = 0 case
- def test_swap_k_3(self): Test k = 1
- def test_swap_k_4(self):... | 8323476f5665f9495350092ec77ebca8698993ab | <|skeleton|>
class TestSwapK:
"""Test class for function a1.swap_k."""
def test_swap_k_1(self):
"""Test empty list"""
<|body_0|>
def test_swap_k_2(self):
"""Test single element case and k = 0 case"""
<|body_1|>
def test_swap_k_3(self):
"""Test k = 1"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSwapK:
"""Test class for function a1.swap_k."""
def test_swap_k_1(self):
"""Test empty list"""
L = []
k = 0
a1.swap_k(L, k)
expected = []
self.assertEqual(L, expected)
def test_swap_k_2(self):
"""Test single element case and k = 0 case"""
... | the_stack_v2_python_sparse | nikeethr/crafting_quality_code/test_swap_k.py | nikeethr/rflexstudygroup | train | 0 |
7d4715f046ba76cd9f00469602f7f2bed4b20c67 | [
"parents = set([])\nfor child in children:\n parent = getattr(child, parent_name, None)\n if not parent:\n continue\n if parent and parent not in parents:\n if not by_len:\n setattr(parent, counter_name, getattr(parent, children_name).order_by(None).count())\n else:\n ... | <|body_start_0|>
parents = set([])
for child in children:
parent = getattr(child, parent_name, None)
if not parent:
continue
if parent and parent not in parents:
if not by_len:
setattr(parent, counter_name, getattr(p... | CommonEntityHook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonEntityHook:
def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False):
"""全量式更新统计表的count值,效率低,有一致性保证"""
<|body_0|>
def increase_children_count(self, children, parent_name, counter_name, sign):
"""增量式更新统计表的count值,效率高,缺乏一致性... | stack_v2_sparse_classes_75kplus_train_071990 | 6,540 | no_license | [
{
"docstring": "全量式更新统计表的count值,效率低,有一致性保证",
"name": "update_children_count",
"signature": "def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False)"
},
{
"docstring": "增量式更新统计表的count值,效率高,缺乏一致性",
"name": "increase_children_count",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_030298 | Implement the Python class `CommonEntityHook` described below.
Class description:
Implement the CommonEntityHook class.
Method signatures and docstrings:
- def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False): 全量式更新统计表的count值,效率低,有一致性保证
- def increase_children_count(self, ... | Implement the Python class `CommonEntityHook` described below.
Class description:
Implement the CommonEntityHook class.
Method signatures and docstrings:
- def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False): 全量式更新统计表的count值,效率低,有一致性保证
- def increase_children_count(self, ... | 44be892ed657f462fb441d785c8550fc144f8896 | <|skeleton|>
class CommonEntityHook:
def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False):
"""全量式更新统计表的count值,效率低,有一致性保证"""
<|body_0|>
def increase_children_count(self, children, parent_name, counter_name, sign):
"""增量式更新统计表的count值,效率高,缺乏一致性... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonEntityHook:
def update_children_count(self, children, parent_name, children_name, counter_name, by_len=False):
"""全量式更新统计表的count值,效率低,有一致性保证"""
parents = set([])
for child in children:
parent = getattr(child, parent_name, None)
if not parent:
... | the_stack_v2_python_sparse | oj/models/hook.py | zrq495/OnlineJudge | train | 1 | |
ed52191d60476f3660a9b64073296eb82a51dd4e | [
"xs = []\nqueue = deque([root])\nwhile queue:\n node = queue.popleft()\n if node:\n xs.append(node.val)\n queue.append(node.left)\n queue.append(node.right)\n else:\n xs.append(None)\nwhile xs and xs[-1] is None:\n xs.pop()\nreturn str(xs).replace('None', 'null')",
"data = ... | <|body_start_0|>
xs = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
xs.append(node.val)
queue.append(node.left)
queue.append(node.right)
else:
xs.append(None)
while... | CodecFirst | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodecFirst:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_071991 | 1,980 | 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_033540 | Implement the Python class `CodecFirst` described below.
Class description:
Implement the CodecFirst 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: s... | Implement the Python class `CodecFirst` described below.
Class description:
Implement the CodecFirst 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: s... | 700ebd442ee224b8b369d0c4b0e986ba8edbff90 | <|skeleton|>
class CodecFirst:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CodecFirst:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
xs = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
xs.append(node.val)
queue.append(n... | the_stack_v2_python_sparse | leetcode/pai/chapter14/q47_p297_serialize.py | jms7446/hackerrank | train | 3 | |
993b3e3652dc7eebbb9ce2ace77f83b1b4caed27 | [
"try:\n if not data['project_id'] or not data['api_id'] or (not data['requestType']) or (not data['requestAddress']) or (not data['httpCode']):\n return JsonResponse(code='999996', msg='参数有误!')\n if not isinstance(data['project_id'], int) or not isinstance(data['api_id'], int):\n return JsonResp... | <|body_start_0|>
try:
if not data['project_id'] or not data['api_id'] or (not data['requestType']) or (not data['requestAddress']) or (not data['httpCode']):
return JsonResponse(code='999996', msg='参数有误!')
if not isinstance(data['project_id'], int) or not isinstance(data[... | AddHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddHistory:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""添加接口请求历史 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
if not data['project_id'] or not ... | stack_v2_sparse_classes_75kplus_train_071992 | 47,841 | permissive | [
{
"docstring": "校验参数 :param data: :return:",
"name": "parameter_check",
"signature": "def parameter_check(self, data)"
},
{
"docstring": "添加接口请求历史 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013276 | Implement the Python class `AddHistory` described below.
Class description:
Implement the AddHistory class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 添加接口请求历史 :param request: :return: | Implement the Python class `AddHistory` described below.
Class description:
Implement the AddHistory class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 添加接口请求历史 :param request: :return:
<|skeleton|>
class AddHistory:
def parameter_ch... | 6d08f58fa6985415ef7beae733e6f8147026806e | <|skeleton|>
class AddHistory:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""添加接口请求历史 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddHistory:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
try:
if not data['project_id'] or not data['api_id'] or (not data['requestType']) or (not data['requestAddress']) or (not data['httpCode']):
return JsonResponse(code='999996', msg='参数有误!')... | the_stack_v2_python_sparse | api_test/api/ApiDoc.py | yourant/tapi | train | 0 | |
f49e7ea7cfa572c7a06deeb29569c7958eefdc68 | [
"if not nums:\n return 0\nprev = nums[0]\ncnt = 0\nfor i in range(1, len(nums)):\n if nums[i] == prev:\n cnt += 1\n else:\n prev = nums[i]\n nums[i - cnt], nums[i] = (nums[i], nums[i - cnt])\nreturn len(nums) - cnt",
"i = j = 1\nn = nums[0]\nwhile i < len(nums):\n m = nums[i]\n ... | <|body_start_0|>
if not nums:
return 0
prev = nums[0]
cnt = 0
for i in range(1, len(nums)):
if nums[i] == prev:
cnt += 1
else:
prev = nums[i]
nums[i - cnt], nums[i] = (nums[i], nums[i - cnt])
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""03/31/2020 13:48"""
<|body_0|>
def removeDuplicates(self, nums: List[int]) -> int:
"""11/13/2022 20:15"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0... | stack_v2_sparse_classes_75kplus_train_071993 | 3,394 | no_license | [
{
"docstring": "03/31/2020 13:48",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums: List[int]) -> int"
},
{
"docstring": "11/13/2022 20:15",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_009836 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums: List[int]) -> int: 03/31/2020 13:48
- def removeDuplicates(self, nums: List[int]) -> int: 11/13/2022 20:15 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums: List[int]) -> int: 03/31/2020 13:48
- def removeDuplicates(self, nums: List[int]) -> int: 11/13/2022 20:15
<|skeleton|>
class Solution:
def... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""03/31/2020 13:48"""
<|body_0|>
def removeDuplicates(self, nums: List[int]) -> int:
"""11/13/2022 20:15"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""03/31/2020 13:48"""
if not nums:
return 0
prev = nums[0]
cnt = 0
for i in range(1, len(nums)):
if nums[i] == prev:
cnt += 1
else:
prev = ... | the_stack_v2_python_sparse | leetcode/solved/26_Remove_Duplicates_from_Sorted_Array/solution.py | sungminoh/algorithms | train | 0 | |
1b530234685b976b631ad94e1e8f3f9ec04e4a98 | [
"num_matches = 0\nfor line in basket.all_lines():\n if self.range.contains_product(line.product) and line.quantity_without_discount > 0:\n num_matches += line.quantity_without_discount\n if num_matches >= self.value:\n return True\nreturn False",
"lines = lines or basket.all_lines()\nconsumed_... | <|body_start_0|>
num_matches = 0
for line in basket.all_lines():
if self.range.contains_product(line.product) and line.quantity_without_discount > 0:
num_matches += line.quantity_without_discount
if num_matches >= self.value:
return True
re... | An offer condition dependent on the NUMBER of matching items from the basket. | CountCondition | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountCondition:
"""An offer condition dependent on the NUMBER of matching items from the basket."""
def is_satisfied(self, basket):
"""Determines whether a given basket meets this condition"""
<|body_0|>
def consume_items(self, basket, lines=None, value=None):
""... | stack_v2_sparse_classes_75kplus_train_071994 | 23,501 | permissive | [
{
"docstring": "Determines whether a given basket meets this condition",
"name": "is_satisfied",
"signature": "def is_satisfied(self, basket)"
},
{
"docstring": "Marks items within the basket lines as consumed so they can't be reused in other offers.",
"name": "consume_items",
"signature... | 2 | null | Implement the Python class `CountCondition` described below.
Class description:
An offer condition dependent on the NUMBER of matching items from the basket.
Method signatures and docstrings:
- def is_satisfied(self, basket): Determines whether a given basket meets this condition
- def consume_items(self, basket, lin... | Implement the Python class `CountCondition` described below.
Class description:
An offer condition dependent on the NUMBER of matching items from the basket.
Method signatures and docstrings:
- def is_satisfied(self, basket): Determines whether a given basket meets this condition
- def consume_items(self, basket, lin... | 5f3f586bdf4f45de87667b88c3cf0836ed34d393 | <|skeleton|>
class CountCondition:
"""An offer condition dependent on the NUMBER of matching items from the basket."""
def is_satisfied(self, basket):
"""Determines whether a given basket meets this condition"""
<|body_0|>
def consume_items(self, basket, lines=None, value=None):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CountCondition:
"""An offer condition dependent on the NUMBER of matching items from the basket."""
def is_satisfied(self, basket):
"""Determines whether a given basket meets this condition"""
num_matches = 0
for line in basket.all_lines():
if self.range.contains_produ... | the_stack_v2_python_sparse | oscar/apps/offer/models.py | AndrewIngram/django-oscar | train | 1 |
88175e7adc1782edad571c8cae30a1ae8643a578 | [
"self.N = N\nself.step_range = step_range\nnA = 1\nnS = N\nisd = np.zeros(nS)\nisd[int(N / 2)] = 1\nP = {s: {0: []} for s in range(nS)}\nprob = 0.5 / step_range\nfor s in range(nS):\n if s == 0 or s == nS - 1:\n continue\n for step in range(1, step_range + 1):\n sleft = s - step\n sright ... | <|body_start_0|>
self.N = N
self.step_range = step_range
nA = 1
nS = N
isd = np.zeros(nS)
isd[int(N / 2)] = 1
P = {s: {0: []} for s in range(nS)}
prob = 0.5 / step_range
for s in range(nS):
if s == 0 or s == nS - 1:
cont... | Description: A 1d random walk. Terminal states are the left and right states. Non-terminal transitions give a reward of 0, the reward of terminal transitions can be specified. The start state is in the center. At each time step, the agent moves to the left or right with equal probability within a fixed range. This is a... | RandomWalkEnv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalkEnv:
"""Description: A 1d random walk. Terminal states are the left and right states. Non-terminal transitions give a reward of 0, the reward of terminal transitions can be specified. The start state is in the center. At each time step, the agent moves to the left or right with equal pr... | stack_v2_sparse_classes_75kplus_train_071995 | 2,472 | permissive | [
{
"docstring": "Args: N: Number of states step_range: Step range terminal_rewards: Rewards of the left and right terminal states",
"name": "__init__",
"signature": "def __init__(self, N=11, step_range=1, terminal_rewards=(-1, 1))"
},
{
"docstring": "Prints current state",
"name": "render",
... | 2 | stack_v2_sparse_classes_30k_train_011807 | Implement the Python class `RandomWalkEnv` described below.
Class description:
Description: A 1d random walk. Terminal states are the left and right states. Non-terminal transitions give a reward of 0, the reward of terminal transitions can be specified. The start state is in the center. At each time step, the agent m... | Implement the Python class `RandomWalkEnv` described below.
Class description:
Description: A 1d random walk. Terminal states are the left and right states. Non-terminal transitions give a reward of 0, the reward of terminal transitions can be specified. The start state is in the center. At each time step, the agent m... | 8b911b5d655288a60b12ffbacc123e3a3c78638c | <|skeleton|>
class RandomWalkEnv:
"""Description: A 1d random walk. Terminal states are the left and right states. Non-terminal transitions give a reward of 0, the reward of terminal transitions can be specified. The start state is in the center. At each time step, the agent moves to the left or right with equal pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalkEnv:
"""Description: A 1d random walk. Terminal states are the left and right states. Non-terminal transitions give a reward of 0, the reward of terminal transitions can be specified. The start state is in the center. At each time step, the agent moves to the left or right with equal probability wit... | the_stack_v2_python_sparse | environments/randomwalk/gym_randomwalk/envs/randomwalk_env.py | lschw/rl-experiments | train | 0 |
4610281468889f0ada077d37e22f6e866183565b | [
"territory_locales, territory_languages = ([], [])\nif not territory_id:\n return (territory_locales, territory_languages, '')\ntwo_char_country_code = COUNTRY_CODE_3to2_LETTERS.get(territory_id, '')\nif not two_char_country_code:\n return (territory_locales, territory_languages, '')\nterritory_locales = lang... | <|body_start_0|>
territory_locales, territory_languages = ([], [])
if not territory_id:
return (territory_locales, territory_languages, '')
two_char_country_code = COUNTRY_CODE_3to2_LETTERS.get(territory_id, '')
if not two_char_country_code:
return (territory_loca... | Geo Location Manager | GeoLocationManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoLocationManager:
"""Geo Location Manager"""
def get_locales_from_territory_id(self, territory_id):
"""Get list of locales associated with a Territory :param territory_id: three characters country code :return: list of locales, languages, country code"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_071996 | 35,271 | permissive | [
{
"docstring": "Get list of locales associated with a Territory :param territory_id: three characters country code :return: list of locales, languages, country code",
"name": "get_locales_from_territory_id",
"signature": "def get_locales_from_territory_id(self, territory_id)"
},
{
"docstring": "... | 6 | stack_v2_sparse_classes_30k_train_019548 | Implement the Python class `GeoLocationManager` described below.
Class description:
Geo Location Manager
Method signatures and docstrings:
- def get_locales_from_territory_id(self, territory_id): Get list of locales associated with a Territory :param territory_id: three characters country code :return: list of locale... | Implement the Python class `GeoLocationManager` described below.
Class description:
Geo Location Manager
Method signatures and docstrings:
- def get_locales_from_territory_id(self, territory_id): Get list of locales associated with a Territory :param territory_id: three characters country code :return: list of locale... | 1a1da6f3f92489429e20fcbbf33d01893975664b | <|skeleton|>
class GeoLocationManager:
"""Geo Location Manager"""
def get_locales_from_territory_id(self, territory_id):
"""Get list of locales associated with a Territory :param territory_id: three characters country code :return: list of locales, languages, country code"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeoLocationManager:
"""Geo Location Manager"""
def get_locales_from_territory_id(self, territory_id):
"""Get list of locales associated with a Territory :param territory_id: three characters country code :return: list of locales, languages, country code"""
territory_locales, territory_lan... | the_stack_v2_python_sparse | dashboard/managers/graphs.py | transtats/transtats | train | 39 |
ff6868c40b4bd30e0e3d2654f6f0ff7f5eb29cda | [
"try:\n dhcpController = DhcpController()\n json_data = json.dumps(dhcpController.get_dhcp_server_configuration_max_lease_time())\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, mimetype='... | <|body_start_0|>
try:
dhcpController = DhcpController()
json_data = json.dumps(dhcpController.get_dhcp_server_configuration_max_lease_time())
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as ve:
... | DhcpServer_Configuration_MaxLeaseTime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DhcpServer_Configuration_MaxLeaseTime:
def get(self):
"""Gets the max lease time parameter"""
<|body_0|>
def put(self):
"""Update the max lease time parameter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
dhcpController = DhcpCont... | stack_v2_sparse_classes_75kplus_train_071997 | 20,424 | no_license | [
{
"docstring": "Gets the max lease time parameter",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update the max lease time parameter",
"name": "put",
"signature": "def put(self)"
}
] | 2 | null | Implement the Python class `DhcpServer_Configuration_MaxLeaseTime` described below.
Class description:
Implement the DhcpServer_Configuration_MaxLeaseTime class.
Method signatures and docstrings:
- def get(self): Gets the max lease time parameter
- def put(self): Update the max lease time parameter | Implement the Python class `DhcpServer_Configuration_MaxLeaseTime` described below.
Class description:
Implement the DhcpServer_Configuration_MaxLeaseTime class.
Method signatures and docstrings:
- def get(self): Gets the max lease time parameter
- def put(self): Update the max lease time parameter
<|skeleton|>
clas... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class DhcpServer_Configuration_MaxLeaseTime:
def get(self):
"""Gets the max lease time parameter"""
<|body_0|>
def put(self):
"""Update the max lease time parameter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DhcpServer_Configuration_MaxLeaseTime:
def get(self):
"""Gets the max lease time parameter"""
try:
dhcpController = DhcpController()
json_data = json.dumps(dhcpController.get_dhcp_server_configuration_max_lease_time())
resp = Response(json_data, status=200, ... | the_stack_v2_python_sparse | configuration-agent/dhcp/rest_api/resources/dhcp_server.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
39ee2d764e15535a2c3d2686b8bf978760cb2943 | [
"from pages.regions.accordion import Accordion\nfrom pages.regions.treeaccordionitem import LegacyTreeAccordionItem\nreturn Accordion(self.testsetup, LegacyTreeAccordionItem)",
"self.accordion.current_content.find_node_by_name(service_name).click()\nself._wait_for_results_refresh()\nreturn self",
"if self.accor... | <|body_start_0|>
from pages.regions.accordion import Accordion
from pages.regions.treeaccordionitem import LegacyTreeAccordionItem
return Accordion(self.testsetup, LegacyTreeAccordionItem)
<|end_body_0|>
<|body_start_1|>
self.accordion.current_content.find_node_by_name(service_name).cli... | MyServices | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyServices:
def accordion(self):
"""accordion"""
<|body_0|>
def select_service_in_tree(self, service_name):
"""Select service"""
<|body_1|>
def is_service_present(self, service_name):
"""Select service"""
<|body_2|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_071998 | 10,539 | no_license | [
{
"docstring": "accordion",
"name": "accordion",
"signature": "def accordion(self)"
},
{
"docstring": "Select service",
"name": "select_service_in_tree",
"signature": "def select_service_in_tree(self, service_name)"
},
{
"docstring": "Select service",
"name": "is_service_pres... | 3 | stack_v2_sparse_classes_30k_train_014474 | Implement the Python class `MyServices` described below.
Class description:
Implement the MyServices class.
Method signatures and docstrings:
- def accordion(self): accordion
- def select_service_in_tree(self, service_name): Select service
- def is_service_present(self, service_name): Select service | Implement the Python class `MyServices` described below.
Class description:
Implement the MyServices class.
Method signatures and docstrings:
- def accordion(self): accordion
- def select_service_in_tree(self, service_name): Select service
- def is_service_present(self, service_name): Select service
<|skeleton|>
cla... | 51bb86fda7d897e90444a6a0380a5aa2c61be6ff | <|skeleton|>
class MyServices:
def accordion(self):
"""accordion"""
<|body_0|>
def select_service_in_tree(self, service_name):
"""Select service"""
<|body_1|>
def is_service_present(self, service_name):
"""Select service"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyServices:
def accordion(self):
"""accordion"""
from pages.regions.accordion import Accordion
from pages.regions.treeaccordionitem import LegacyTreeAccordionItem
return Accordion(self.testsetup, LegacyTreeAccordionItem)
def select_service_in_tree(self, service_name):
... | the_stack_v2_python_sparse | pages/services.py | sshveta/cfme_tests | train | 0 | |
92c77ec587f57751aa0ea4d615cf32175578fe70 | [
"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!')"
] | <|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... | Proto file describing the Ad Group service. Service to manage ad groups. | AdGroupServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdGroupServiceServicer:
"""Proto file describing the Ad Group service. Service to manage ad groups."""
def GetAdGroup(self, request, context):
"""Returns the requested ad group in full detail."""
<|body_0|>
def MutateAdGroups(self, request, context):
"""Creates, ... | stack_v2_sparse_classes_75kplus_train_071999 | 5,260 | permissive | [
{
"docstring": "Returns the requested ad group in full detail.",
"name": "GetAdGroup",
"signature": "def GetAdGroup(self, request, context)"
},
{
"docstring": "Creates, updates, or removes ad groups. Operation statuses are returned.",
"name": "MutateAdGroups",
"signature": "def MutateAdG... | 2 | stack_v2_sparse_classes_30k_train_011665 | Implement the Python class `AdGroupServiceServicer` described below.
Class description:
Proto file describing the Ad Group service. Service to manage ad groups.
Method signatures and docstrings:
- def GetAdGroup(self, request, context): Returns the requested ad group in full detail.
- def MutateAdGroups(self, request... | Implement the Python class `AdGroupServiceServicer` described below.
Class description:
Proto file describing the Ad Group service. Service to manage ad groups.
Method signatures and docstrings:
- def GetAdGroup(self, request, context): Returns the requested ad group in full detail.
- def MutateAdGroups(self, request... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class AdGroupServiceServicer:
"""Proto file describing the Ad Group service. Service to manage ad groups."""
def GetAdGroup(self, request, context):
"""Returns the requested ad group in full detail."""
<|body_0|>
def MutateAdGroups(self, request, context):
"""Creates, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdGroupServiceServicer:
"""Proto file describing the Ad Group service. Service to manage ad groups."""
def GetAdGroup(self, request, context):
"""Returns the requested ad group in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/ad_group_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.