blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7d37d5a6af269483d014f0d8198febdf1e2cc4c5 | [
"parser = argparse.ArgumentParser(description='Easy Infer for model benchmark')\ncls.base_arg_parse(parser)\ncls.model_arg_parse(parser)\ncls.task_arg_parse(parser)\nargs = parser.parse_args()\nreturn args",
"parser.add_argument('--task_type', type=int, default=0, help='benchmark task type:0 for framework accurac... | <|body_start_0|>
parser = argparse.ArgumentParser(description='Easy Infer for model benchmark')
cls.base_arg_parse(parser)
cls.model_arg_parse(parser)
cls.task_arg_parse(parser)
args = parser.parse_args()
return args
<|end_body_0|>
<|body_start_1|>
parser.add_arg... | input argument parser functions | ArgParser | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgParser:
"""input argument parser functions"""
def parse_arguments(cls):
"""parse input arguments for mslite bench"""
<|body_0|>
def task_arg_parse(cls, parser):
"""parse task related arguments"""
<|body_1|>
def model_arg_parse(cls, parser):
... | stack_v2_sparse_classes_36k_train_008200 | 8,814 | permissive | [
{
"docstring": "parse input arguments for mslite bench",
"name": "parse_arguments",
"signature": "def parse_arguments(cls)"
},
{
"docstring": "parse task related arguments",
"name": "task_arg_parse",
"signature": "def task_arg_parse(cls, parser)"
},
{
"docstring": "parse model an... | 4 | stack_v2_sparse_classes_30k_train_012406 | Implement the Python class `ArgParser` described below.
Class description:
input argument parser functions
Method signatures and docstrings:
- def parse_arguments(cls): parse input arguments for mslite bench
- def task_arg_parse(cls, parser): parse task related arguments
- def model_arg_parse(cls, parser): parse mode... | Implement the Python class `ArgParser` described below.
Class description:
input argument parser functions
Method signatures and docstrings:
- def parse_arguments(cls): parse input arguments for mslite bench
- def task_arg_parse(cls, parser): parse task related arguments
- def model_arg_parse(cls, parser): parse mode... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class ArgParser:
"""input argument parser functions"""
def parse_arguments(cls):
"""parse input arguments for mslite bench"""
<|body_0|>
def task_arg_parse(cls, parser):
"""parse task related arguments"""
<|body_1|>
def model_arg_parse(cls, parser):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgParser:
"""input argument parser functions"""
def parse_arguments(cls):
"""parse input arguments for mslite bench"""
parser = argparse.ArgumentParser(description='Easy Infer for model benchmark')
cls.base_arg_parse(parser)
cls.model_arg_parse(parser)
cls.task_ar... | the_stack_v2_python_sparse | mindspore/lite/tools/mslite_bench/mslite_bench/utils/arg_parser.py | mindspore-ai/mindspore | train | 4,178 |
62bc33ba740e2c96d5f6d5b8f1c41417bbf266cd | [
"self.find(By.ID, 'username').send_keys(username)\nself.find(By.ID, 'memberAdd_acctid').send_keys(account)\nself.find(By.ID, 'memberAdd_phone').send_keys(phonenum)\nself.find(By.CSS_SELECTOR, '.js_btn_save').click()\nreturn True",
"locator = (By.CSS_SELECTOR, '.member_colRight_memberTable_th_Checkbox')\nself.wait... | <|body_start_0|>
self.find(By.ID, 'username').send_keys(username)
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)
self.find(By.CSS_SELECTOR, '.js_btn_save').click()
return True
<|end_body_0|>
<|body_start_1|>
... | AddMemberPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.find(By.ID, 'username').send_keys(username)
... | stack_v2_sparse_classes_36k_train_008201 | 1,787 | no_license | [
{
"docstring": "添加联系人,详细信息 :return:",
"name": "add_member",
"signature": "def add_member(self, username, account, phonenum)"
},
{
"docstring": "获取所有的联系人姓名 :return:",
"name": "get_member",
"signature": "def get_member(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006907 | Implement the Python class `AddMemberPage` described below.
Class description:
Implement the AddMemberPage class.
Method signatures and docstrings:
- def add_member(self, username, account, phonenum): 添加联系人,详细信息 :return:
- def get_member(self): 获取所有的联系人姓名 :return: | Implement the Python class `AddMemberPage` described below.
Class description:
Implement the AddMemberPage class.
Method signatures and docstrings:
- def add_member(self, username, account, phonenum): 添加联系人,详细信息 :return:
- def get_member(self): 获取所有的联系人姓名 :return:
<|skeleton|>
class AddMemberPage:
def add_membe... | 7fcafbfed7b581c48a9effe9302661aa7250e1c4 | <|skeleton|>
class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
<|body_0|>
def get_member(self):
"""获取所有的联系人姓名 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
self.find(By.ID, 'username').send_keys(username)
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)
self.find(By.CSS_... | the_stack_v2_python_sparse | live_selenium_po/seleniumPO/page/add_member_page.py | GaoPangPang0318/SDET_Study | train | 0 | |
187750d23175ba056677fe98119b15717de949f9 | [
"self.relations_df = relations_df\nself.correspondence_dict = correspondence_dict\nself.fplx_lookup = _make_famplex_lookup()\nself.statements = []",
"for _, row in self.relations_df.iterrows():\n acsn_agent_a, stmt_types, acsn_agent_b, pmids = list(row)\n stmt_type = get_stmt_type(stmt_types)\n if stmt_t... | <|body_start_0|>
self.relations_df = relations_df
self.correspondence_dict = correspondence_dict
self.fplx_lookup = _make_famplex_lookup()
self.statements = []
<|end_body_0|>
<|body_start_1|>
for _, row in self.relations_df.iterrows():
acsn_agent_a, stmt_types, acsn_... | Processes Atlas of cancer signalling network (ACSN) relationships into INDRA statements Attributes ---------- relations_df : pandas.DataFrame A tab-separated data frame which consists of binary relationship between proteins with PMIDs. correspondence_dict : dict A dictionary with correspondences between ACSN entities a... | AcsnProcessor | [
"BSD-2-Clause",
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcsnProcessor:
"""Processes Atlas of cancer signalling network (ACSN) relationships into INDRA statements Attributes ---------- relations_df : pandas.DataFrame A tab-separated data frame which consists of binary relationship between proteins with PMIDs. correspondence_dict : dict A dictionary wit... | stack_v2_sparse_classes_36k_train_008202 | 4,184 | permissive | [
{
"docstring": "Constructor for AcsnProcessor class",
"name": "__init__",
"signature": "def __init__(self, relations_df, correspondence_dict)"
},
{
"docstring": "Return INDRA Statements Extracted from ACSN relations.",
"name": "extract_statements",
"signature": "def extract_statements(se... | 3 | stack_v2_sparse_classes_30k_train_020300 | Implement the Python class `AcsnProcessor` described below.
Class description:
Processes Atlas of cancer signalling network (ACSN) relationships into INDRA statements Attributes ---------- relations_df : pandas.DataFrame A tab-separated data frame which consists of binary relationship between proteins with PMIDs. corr... | Implement the Python class `AcsnProcessor` described below.
Class description:
Processes Atlas of cancer signalling network (ACSN) relationships into INDRA statements Attributes ---------- relations_df : pandas.DataFrame A tab-separated data frame which consists of binary relationship between proteins with PMIDs. corr... | 6d6ca1174792b6c5a05cbf3afcb9f138fabcec6a | <|skeleton|>
class AcsnProcessor:
"""Processes Atlas of cancer signalling network (ACSN) relationships into INDRA statements Attributes ---------- relations_df : pandas.DataFrame A tab-separated data frame which consists of binary relationship between proteins with PMIDs. correspondence_dict : dict A dictionary wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcsnProcessor:
"""Processes Atlas of cancer signalling network (ACSN) relationships into INDRA statements Attributes ---------- relations_df : pandas.DataFrame A tab-separated data frame which consists of binary relationship between proteins with PMIDs. correspondence_dict : dict A dictionary with corresponde... | the_stack_v2_python_sparse | indra/sources/acsn/processor.py | sorgerlab/indra | train | 158 |
acbb36b322b49d5fb1259171372827e9a9e19c11 | [
"max = self.max\nif max is None:\n return None\nreturn max.val",
"self._remove_max()\nif value is None:\n return\nself._add_max(val=value)",
"min = self.min\nif min is None:\n return None\nreturn min.val",
"self._remove_min()\nif value is None:\n return\nself._add_min(val=value)"
] | <|body_start_0|>
max = self.max
if max is None:
return None
return max.val
<|end_body_0|>
<|body_start_1|>
self._remove_max()
if value is None:
return
self._add_max(val=value)
<|end_body_1|>
<|body_start_2|>
min = self.min
if min ... | `c:scaling` element. Defines axis scale characteristics such as maximum value, log vs. linear, etc. | CT_Scaling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Scaling:
"""`c:scaling` element. Defines axis scale characteristics such as maximum value, log vs. linear, etc."""
def maximum(self):
"""The float value of the ``<c:max>`` child element, or |None| if no max element is present."""
<|body_0|>
def maximum(self, value):
... | stack_v2_sparse_classes_36k_train_008203 | 9,428 | permissive | [
{
"docstring": "The float value of the ``<c:max>`` child element, or |None| if no max element is present.",
"name": "maximum",
"signature": "def maximum(self)"
},
{
"docstring": "Set the value of the ``<c:max>`` child element to the float *value*, or remove the max element if *value* is |None|."... | 4 | null | Implement the Python class `CT_Scaling` described below.
Class description:
`c:scaling` element. Defines axis scale characteristics such as maximum value, log vs. linear, etc.
Method signatures and docstrings:
- def maximum(self): The float value of the ``<c:max>`` child element, or |None| if no max element is presen... | Implement the Python class `CT_Scaling` described below.
Class description:
`c:scaling` element. Defines axis scale characteristics such as maximum value, log vs. linear, etc.
Method signatures and docstrings:
- def maximum(self): The float value of the ``<c:max>`` child element, or |None| if no max element is presen... | 61257cdf1a3bc79534e88d1f50a0885a688f04c2 | <|skeleton|>
class CT_Scaling:
"""`c:scaling` element. Defines axis scale characteristics such as maximum value, log vs. linear, etc."""
def maximum(self):
"""The float value of the ``<c:max>`` child element, or |None| if no max element is present."""
<|body_0|>
def maximum(self, value):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_Scaling:
"""`c:scaling` element. Defines axis scale characteristics such as maximum value, log vs. linear, etc."""
def maximum(self):
"""The float value of the ``<c:max>`` child element, or |None| if no max element is present."""
max = self.max
if max is None:
retur... | the_stack_v2_python_sparse | pptx/oxml/chart/axis.py | AndreasSteiner/python-pptx | train | 2 |
f00defa699fd87c608a01f9856165bda5e4a0fc3 | [
"TrainerMixin.__init__(self)\nself.estimator = estimator\nself.IK = IK\nself.flag = flag\nself.file_path = file_path",
"mask_kgb = y != -1\nmask_igb = ~mask_kgb\nX_kgb, y_kgb, X_igb = (X[mask_kgb], y[mask_kgb], X[mask_igb])\nbad_rate_kgb = y_kgb.sum() / len(y_kgb)\nbad_rate_igb = bad_rate_kgb * self.IK\nbad_num_i... | <|body_start_0|>
TrainerMixin.__init__(self)
self.estimator = estimator
self.IK = IK
self.flag = flag
self.file_path = file_path
<|end_body_0|>
<|body_start_1|>
mask_kgb = y != -1
mask_igb = ~mask_kgb
X_kgb, y_kgb, X_igb = (X[mask_kgb], y[mask_kgb], X[mas... | 硬截断法(简单展开法) step 1. 构建KGB模型,并对全量样本打分,得到P(bad)。 step 2. 将拒绝样本按P(bad)降序排列,设置cutoff。根据业务经验,比如拒绝样本的bad rate是放贷样本的2~4倍,从而结合拒绝样本量计算出cutoff。 step 3. 高于cutoff的拒绝样本标记为bad,其余拒绝样本当作灰色样本,不予考虑。 step 4. 利用组合样本构建AGB模型。 | HardCutoff | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HardCutoff:
"""硬截断法(简单展开法) step 1. 构建KGB模型,并对全量样本打分,得到P(bad)。 step 2. 将拒绝样本按P(bad)降序排列,设置cutoff。根据业务经验,比如拒绝样本的bad rate是放贷样本的2~4倍,从而结合拒绝样本量计算出cutoff。 step 3. 高于cutoff的拒绝样本标记为bad,其余拒绝样本当作灰色样本,不予考虑。 step 4. 利用组合样本构建AGB模型。"""
def __init__(self, estimator, IK: float=2, flag: bool=True, file_path:... | stack_v2_sparse_classes_36k_train_008204 | 17,175 | no_license | [
{
"docstring": "初始化函数 :param estimator: 学习器 :param IK: 经验风险因子,业务实际bad rate/放贷样本bad rate :param flag: 是否抛弃拒绝样本中的灰样本 :param file_path: 最终建模使用样本输出路径",
"name": "__init__",
"signature": "def __init__(self, estimator, IK: float=2, flag: bool=True, file_path: str=None)"
},
{
"docstring": "拟合学习器 :param ... | 2 | stack_v2_sparse_classes_30k_train_018116 | Implement the Python class `HardCutoff` described below.
Class description:
硬截断法(简单展开法) step 1. 构建KGB模型,并对全量样本打分,得到P(bad)。 step 2. 将拒绝样本按P(bad)降序排列,设置cutoff。根据业务经验,比如拒绝样本的bad rate是放贷样本的2~4倍,从而结合拒绝样本量计算出cutoff。 step 3. 高于cutoff的拒绝样本标记为bad,其余拒绝样本当作灰色样本,不予考虑。 step 4. 利用组合样本构建AGB模型。
Method signatures and docstrings:
- de... | Implement the Python class `HardCutoff` described below.
Class description:
硬截断法(简单展开法) step 1. 构建KGB模型,并对全量样本打分,得到P(bad)。 step 2. 将拒绝样本按P(bad)降序排列,设置cutoff。根据业务经验,比如拒绝样本的bad rate是放贷样本的2~4倍,从而结合拒绝样本量计算出cutoff。 step 3. 高于cutoff的拒绝样本标记为bad,其余拒绝样本当作灰色样本,不予考虑。 step 4. 利用组合样本构建AGB模型。
Method signatures and docstrings:
- de... | 1634ac69e8616f85c4233039e2d40246149a1617 | <|skeleton|>
class HardCutoff:
"""硬截断法(简单展开法) step 1. 构建KGB模型,并对全量样本打分,得到P(bad)。 step 2. 将拒绝样本按P(bad)降序排列,设置cutoff。根据业务经验,比如拒绝样本的bad rate是放贷样本的2~4倍,从而结合拒绝样本量计算出cutoff。 step 3. 高于cutoff的拒绝样本标记为bad,其余拒绝样本当作灰色样本,不予考虑。 step 4. 利用组合样本构建AGB模型。"""
def __init__(self, estimator, IK: float=2, flag: bool=True, file_path:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HardCutoff:
"""硬截断法(简单展开法) step 1. 构建KGB模型,并对全量样本打分,得到P(bad)。 step 2. 将拒绝样本按P(bad)降序排列,设置cutoff。根据业务经验,比如拒绝样本的bad rate是放贷样本的2~4倍,从而结合拒绝样本量计算出cutoff。 step 3. 高于cutoff的拒绝样本标记为bad,其余拒绝样本当作灰色样本,不予考虑。 step 4. 利用组合样本构建AGB模型。"""
def __init__(self, estimator, IK: float=2, flag: bool=True, file_path: str=None):
... | the_stack_v2_python_sparse | model_training/RITrainer.py | pengliang1226/model_procedure | train | 0 |
7e6e86aa0afe34d7a3fc9231709df28462d124e0 | [
"taskCnt = len(tasks)\nmaxFreqTaskCnt = 0\nmaxFreq = 0\nfreqDic = {}\nfor task in tasks:\n freqDic.setdefault(task, 0)\n freqDic[task] += 1\n if freqDic[task] > maxFreq:\n maxFreq = freqDic[task]\n maxFreqTaskCnt = 1\n elif freqDic[task] == maxFreq:\n maxFreqTaskCnt += 1\nrltHasIdle... | <|body_start_0|>
taskCnt = len(tasks)
maxFreqTaskCnt = 0
maxFreq = 0
freqDic = {}
for task in tasks:
freqDic.setdefault(task, 0)
freqDic[task] += 1
if freqDic[task] > maxFreq:
maxFreq = freqDic[task]
maxFreqTaskC... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
"""填桶法任务调度 https://leetcode-cn.com/problems/task-scheduler/solution/tong-zi-by-popopop/ 有空闲(桶没填满) + 没空闲(总数)"""
<|body_0|>
def leastInterval1(self, tasks: List[str], n: int) -> int:
"""priotiry queue ... | stack_v2_sparse_classes_36k_train_008205 | 7,597 | no_license | [
{
"docstring": "填桶法任务调度 https://leetcode-cn.com/problems/task-scheduler/solution/tong-zi-by-popopop/ 有空闲(桶没填满) + 没空闲(总数)",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks: List[str], n: int) -> int"
},
{
"docstring": "priotiry queue - 超时",
"name": "leastInterval1",
"... | 2 | stack_v2_sparse_classes_30k_test_000329 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks: List[str], n: int) -> int: 填桶法任务调度 https://leetcode-cn.com/problems/task-scheduler/solution/tong-zi-by-popopop/ 有空闲(桶没填满) + 没空闲(总数)
- def leastInte... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks: List[str], n: int) -> int: 填桶法任务调度 https://leetcode-cn.com/problems/task-scheduler/solution/tong-zi-by-popopop/ 有空闲(桶没填满) + 没空闲(总数)
- def leastInte... | 29f1bd681ae823ec6fe755c8f91bfe1ca80b6367 | <|skeleton|>
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
"""填桶法任务调度 https://leetcode-cn.com/problems/task-scheduler/solution/tong-zi-by-popopop/ 有空闲(桶没填满) + 没空闲(总数)"""
<|body_0|>
def leastInterval1(self, tasks: List[str], n: int) -> int:
"""priotiry queue ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
"""填桶法任务调度 https://leetcode-cn.com/problems/task-scheduler/solution/tong-zi-by-popopop/ 有空闲(桶没填满) + 没空闲(总数)"""
taskCnt = len(tasks)
maxFreqTaskCnt = 0
maxFreq = 0
freqDic = {}
for task in tasks:... | the_stack_v2_python_sparse | 1. solvedProblems/621. Task Scheduler/621.py | tgaochn/leetcode | train | 1 | |
93f73f563485791ef4269056197d983f352f292c | [
"if tmp_base is None or tmp is None:\n method = 'hungarian'\nself.tmp_base = tmp_base\nself.tmp = tmp\nspt_base = clean_spike_train(spt_base)\nspt = clean_spike_train(spt)\nself.n_units = np.max(spt_base[:, 1]) + 1\nself.n_clusters = np.max(spt[:, 1]) + 1\nself.spt_base = spt_base\nself.spt = spt\nself.spike_cou... | <|body_start_0|>
if tmp_base is None or tmp is None:
method = 'hungarian'
self.tmp_base = tmp_base
self.tmp = tmp
spt_base = clean_spike_train(spt_base)
spt = clean_spike_train(spt)
self.n_units = np.max(spt_base[:, 1]) + 1
self.n_clusters = np.max(spt... | SpikeSortingEvaluation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpikeSortingEvaluation:
def __init__(self, spt_base, spt, tmp_base=None, tmp=None, method='hungarian'):
"""Sets up the evaluation object with two spike trains. Parameters ---------- spt_base: numpy.ndarray Shape [N, 2]. base line spike train. First column is spike times and second the cl... | stack_v2_sparse_classes_36k_train_008206 | 26,376 | permissive | [
{
"docstring": "Sets up the evaluation object with two spike trains. Parameters ---------- spt_base: numpy.ndarray Shape [N, 2]. base line spike train. First column is spike times and second the cluster identities. spt: numpy.ndarray Shape [M, 2]. tmp_base: numpy.ndarray or None Shape [T1, C, N]. Ground truth u... | 5 | stack_v2_sparse_classes_30k_train_019896 | Implement the Python class `SpikeSortingEvaluation` described below.
Class description:
Implement the SpikeSortingEvaluation class.
Method signatures and docstrings:
- def __init__(self, spt_base, spt, tmp_base=None, tmp=None, method='hungarian'): Sets up the evaluation object with two spike trains. Parameters ------... | Implement the Python class `SpikeSortingEvaluation` described below.
Class description:
Implement the SpikeSortingEvaluation class.
Method signatures and docstrings:
- def __init__(self, spt_base, spt, tmp_base=None, tmp=None, method='hungarian'): Sets up the evaluation object with two spike trains. Parameters ------... | b18d13a69946c1fee28fbc1f67215d3a89d892af | <|skeleton|>
class SpikeSortingEvaluation:
def __init__(self, spt_base, spt, tmp_base=None, tmp=None, method='hungarian'):
"""Sets up the evaluation object with two spike trains. Parameters ---------- spt_base: numpy.ndarray Shape [N, 2]. base line spike train. First column is spike times and second the cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpikeSortingEvaluation:
def __init__(self, spt_base, spt, tmp_base=None, tmp=None, method='hungarian'):
"""Sets up the evaluation object with two spike trains. Parameters ---------- spt_base: numpy.ndarray Shape [N, 2]. base line spike train. First column is spike times and second the cluster identiti... | the_stack_v2_python_sparse | src/yass/evaluate/stability.py | paninski-lab/yass | train | 68 | |
4508b4d4dcceaca1f5dad560b896a1a8369c5688 | [
"comp = self.get_component()\ncomp.clear()\ncomp.send_keys(keyVal)\nbt = ButtonPhonePage(self.driver)\nbt.click_button('保存')\nreturn self.get_msg()",
"try:\n WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[name=\"' + compname + '\"]')))\n return True\nexce... | <|body_start_0|>
comp = self.get_component()
comp.clear()
comp.send_keys(keyVal)
bt = ButtonPhonePage(self.driver)
bt.click_button('保存')
return self.get_msg()
<|end_body_0|>
<|body_start_1|>
try:
WebDriverWait(self.driver, timeout).until(EC.visibility... | TextPhonePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextPhonePage:
def set_val_save_get_msg(self, keyVal):
"""输入值、触发保存、获取提醒消息返回"""
<|body_0|>
def is_comp_hide(self, compname, timeout=3):
"""文本框控件是否隐藏判断元素是否可见,可见返回Ture ,不可见返回 False"""
<|body_1|>
def is_comp_readonly(self, compname):
"""判断控件是否只读, 只读则... | stack_v2_sparse_classes_36k_train_008207 | 4,541 | no_license | [
{
"docstring": "输入值、触发保存、获取提醒消息返回",
"name": "set_val_save_get_msg",
"signature": "def set_val_save_get_msg(self, keyVal)"
},
{
"docstring": "文本框控件是否隐藏判断元素是否可见,可见返回Ture ,不可见返回 False",
"name": "is_comp_hide",
"signature": "def is_comp_hide(self, compname, timeout=3)"
},
{
"docstrin... | 4 | null | Implement the Python class `TextPhonePage` described below.
Class description:
Implement the TextPhonePage class.
Method signatures and docstrings:
- def set_val_save_get_msg(self, keyVal): 输入值、触发保存、获取提醒消息返回
- def is_comp_hide(self, compname, timeout=3): 文本框控件是否隐藏判断元素是否可见,可见返回Ture ,不可见返回 False
- def is_comp_readonly(... | Implement the Python class `TextPhonePage` described below.
Class description:
Implement the TextPhonePage class.
Method signatures and docstrings:
- def set_val_save_get_msg(self, keyVal): 输入值、触发保存、获取提醒消息返回
- def is_comp_hide(self, compname, timeout=3): 文本框控件是否隐藏判断元素是否可见,可见返回Ture ,不可见返回 False
- def is_comp_readonly(... | 78768989a79a14013b983024cf6e4838d51ed595 | <|skeleton|>
class TextPhonePage:
def set_val_save_get_msg(self, keyVal):
"""输入值、触发保存、获取提醒消息返回"""
<|body_0|>
def is_comp_hide(self, compname, timeout=3):
"""文本框控件是否隐藏判断元素是否可见,可见返回Ture ,不可见返回 False"""
<|body_1|>
def is_comp_readonly(self, compname):
"""判断控件是否只读, 只读则... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextPhonePage:
def set_val_save_get_msg(self, keyVal):
"""输入值、触发保存、获取提醒消息返回"""
comp = self.get_component()
comp.clear()
comp.send_keys(keyVal)
bt = ButtonPhonePage(self.driver)
bt.click_button('保存')
return self.get_msg()
def is_comp_hide(self, compn... | the_stack_v2_python_sparse | test_case/page_obj/form/text_page.py | pylk/pythonSelenium | train | 0 | |
2a1170a5bacb7646ea8ca6ac788ba393c245eff1 | [
"Validation.check_param_empty(train_id=train_id, tag=tag)\njob_response = []\ntry:\n tensors = self._data_manager.list_tensors(train_id, tag)\nexcept ParamValueError as ex:\n raise ScalarNotExistError(ex.message)\nfor tensor in tensors:\n job_response.append({'wall_time': tensor.wall_time, 'step': tensor.s... | <|body_start_0|>
Validation.check_param_empty(train_id=train_id, tag=tag)
job_response = []
try:
tensors = self._data_manager.list_tensors(train_id, tag)
except ParamValueError as ex:
raise ScalarNotExistError(ex.message)
for tensor in tensors:
... | Scalar Processor. | ScalarsProcessor | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarsProcessor:
"""Scalar Processor."""
def get_metadata_list(self, train_id, tag):
"""Builds a JSON-serializable object with information about scalars. Args: train_id (str): The ID of the events data. tag (str): The name of the tag the scalars all belonging to. Returns: list[dict]... | stack_v2_sparse_classes_36k_train_008208 | 3,823 | permissive | [
{
"docstring": "Builds a JSON-serializable object with information about scalars. Args: train_id (str): The ID of the events data. tag (str): The name of the tag the scalars all belonging to. Returns: list[dict], a list of dictionaries containing the `wall_time`, `step`, `value` for each scalar.",
"name": "... | 3 | null | Implement the Python class `ScalarsProcessor` described below.
Class description:
Scalar Processor.
Method signatures and docstrings:
- def get_metadata_list(self, train_id, tag): Builds a JSON-serializable object with information about scalars. Args: train_id (str): The ID of the events data. tag (str): The name of ... | Implement the Python class `ScalarsProcessor` described below.
Class description:
Scalar Processor.
Method signatures and docstrings:
- def get_metadata_list(self, train_id, tag): Builds a JSON-serializable object with information about scalars. Args: train_id (str): The ID of the events data. tag (str): The name of ... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class ScalarsProcessor:
"""Scalar Processor."""
def get_metadata_list(self, train_id, tag):
"""Builds a JSON-serializable object with information about scalars. Args: train_id (str): The ID of the events data. tag (str): The name of the tag the scalars all belonging to. Returns: list[dict]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScalarsProcessor:
"""Scalar Processor."""
def get_metadata_list(self, train_id, tag):
"""Builds a JSON-serializable object with information about scalars. Args: train_id (str): The ID of the events data. tag (str): The name of the tag the scalars all belonging to. Returns: list[dict], a list of d... | the_stack_v2_python_sparse | mindinsight/datavisual/processors/scalars_processor.py | mindspore-ai/mindinsight | train | 224 |
cdd26fcae9b29bdd70101d3edd484c1dcee03993 | [
"super().__init__(params=RespMatParams(), target=self._run_respmat)\nsofb, tune, curr, rfgen = self._create_devices()\nself.devices['sofb'] = sofb\nself.devices['tune'] = tune\nself.devices['curr'] = curr\nself.devices['rfgen'] = rfgen\nself.confdb = ConfigDBClient(config_type='si_orbcorr_respm')",
"if self._stop... | <|body_start_0|>
super().__init__(params=RespMatParams(), target=self._run_respmat)
sofb, tune, curr, rfgen = self._create_devices()
self.devices['sofb'] = sofb
self.devices['tune'] = tune
self.devices['curr'] = curr
self.devices['rfgen'] = rfgen
self.confdb = Con... | . | MeasureRespMat | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasureRespMat:
"""."""
def __init__(self):
"""."""
<|body_0|>
def _run_respmat(self):
"""."""
<|body_1|>
def _measure_respm(self):
"""."""
<|body_2|>
def _get_loco_setup(self, orbmat_name):
"""."""
<|body_3|>
... | stack_v2_sparse_classes_36k_train_008209 | 5,185 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "_run_respmat",
"signature": "def _run_respmat(self)"
},
{
"docstring": ".",
"name": "_measure_respm",
"signature": "def _measure_respm(self)"
},
{
"docstring"... | 6 | null | Implement the Python class `MeasureRespMat` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def _run_respmat(self): .
- def _measure_respm(self): .
- def _get_loco_setup(self, orbmat_name): .
- def _get_bpm_variation(self, period=10): .
- def _create_devices(): . | Implement the Python class `MeasureRespMat` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def _run_respmat(self): .
- def _measure_respm(self): .
- def _get_loco_setup(self, orbmat_name): .
- def _get_bpm_variation(self, period=10): .
- def _create_devices(): .
<|s... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class MeasureRespMat:
"""."""
def __init__(self):
"""."""
<|body_0|>
def _run_respmat(self):
"""."""
<|body_1|>
def _measure_respm(self):
"""."""
<|body_2|>
def _get_loco_setup(self, orbmat_name):
"""."""
<|body_3|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasureRespMat:
"""."""
def __init__(self):
"""."""
super().__init__(params=RespMatParams(), target=self._run_respmat)
sofb, tune, curr, rfgen = self._create_devices()
self.devices['sofb'] = sofb
self.devices['tune'] = tune
self.devices['curr'] = curr
... | the_stack_v2_python_sparse | apsuite/commisslib/measure_respmat.py | lnls-fac/apsuite | train | 1 |
62dd1bcdee1483113dd60307e894f1d448283006 | [
"try:\n cls, kwargs = get_blockdeviceapi_args(ProviderType.aws)\nexcept InvalidConfig as e:\n raise SkipTest(str(e))\nec2_client = kwargs['ec2_client']\nrequested_volume = ec2_client.connection.create_volume(int(Byte(REALISTIC_BLOCKDEVICE_SIZE).to_GiB().value), ec2_client.zone)\nself.addCleanup(ec2_client.con... | <|body_start_0|>
try:
cls, kwargs = get_blockdeviceapi_args(ProviderType.aws)
except InvalidConfig as e:
raise SkipTest(str(e))
ec2_client = kwargs['ec2_client']
requested_volume = ec2_client.connection.create_volume(int(Byte(REALISTIC_BLOCKDEVICE_SIZE).to_GiB().v... | Interface adherence Tests for ``EBSBlockDeviceAPI``. | EBSBlockDeviceAPIInterfaceTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EBSBlockDeviceAPIInterfaceTests:
"""Interface adherence Tests for ``EBSBlockDeviceAPI``."""
def test_foreign_volume(self):
"""Test that ``list_volumes`` lists only those volumes belonging to the current Flocker cluster."""
<|body_0|>
def test_foreign_cluster_volume(self)... | stack_v2_sparse_classes_36k_train_008210 | 4,436 | permissive | [
{
"docstring": "Test that ``list_volumes`` lists only those volumes belonging to the current Flocker cluster.",
"name": "test_foreign_volume",
"signature": "def test_foreign_volume(self)"
},
{
"docstring": "Test that list_volumes() excludes volumes belonging to other Flocker clusters.",
"nam... | 3 | stack_v2_sparse_classes_30k_train_019210 | Implement the Python class `EBSBlockDeviceAPIInterfaceTests` described below.
Class description:
Interface adherence Tests for ``EBSBlockDeviceAPI``.
Method signatures and docstrings:
- def test_foreign_volume(self): Test that ``list_volumes`` lists only those volumes belonging to the current Flocker cluster.
- def t... | Implement the Python class `EBSBlockDeviceAPIInterfaceTests` described below.
Class description:
Interface adherence Tests for ``EBSBlockDeviceAPI``.
Method signatures and docstrings:
- def test_foreign_volume(self): Test that ``list_volumes`` lists only those volumes belonging to the current Flocker cluster.
- def t... | 10d55b4fd0305fa31f6fc33d0f01745e9d99eb8a | <|skeleton|>
class EBSBlockDeviceAPIInterfaceTests:
"""Interface adherence Tests for ``EBSBlockDeviceAPI``."""
def test_foreign_volume(self):
"""Test that ``list_volumes`` lists only those volumes belonging to the current Flocker cluster."""
<|body_0|>
def test_foreign_cluster_volume(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EBSBlockDeviceAPIInterfaceTests:
"""Interface adherence Tests for ``EBSBlockDeviceAPI``."""
def test_foreign_volume(self):
"""Test that ``list_volumes`` lists only those volumes belonging to the current Flocker cluster."""
try:
cls, kwargs = get_blockdeviceapi_args(ProviderTyp... | the_stack_v2_python_sparse | flocker/node/agents/functional/test_ebs.py | runcom/flocker | train | 1 |
9b47e728a7d3d53fe94ca8d616f41a45c4d59fd9 | [
"super(AutomaticWeightedLoss, self).__init__()\nself.mode = mode\nif self.mode not in ['cls', 'reg']:\n raise ValueError('mode argument must be cls or reg.')\nparams = torch.ones(num, requires_grad=True)\nself.params = torch.nn.Parameter(params)",
"loss_sum = 0\nloss_num = len(x)\nfor i, loss in enumerate(x):\... | <|body_start_0|>
super(AutomaticWeightedLoss, self).__init__()
self.mode = mode
if self.mode not in ['cls', 'reg']:
raise ValueError('mode argument must be cls or reg.')
params = torch.ones(num, requires_grad=True)
self.params = torch.nn.Parameter(params)
<|end_body_0... | automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2) | AutomaticWeightedLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutomaticWeightedLoss:
"""automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)"""
def __init__(self, num=2, mode='cls'):
"""Args: num (int, optional): the number of loss. Defaults to 2. mode ... | stack_v2_sparse_classes_36k_train_008211 | 1,891 | permissive | [
{
"docstring": "Args: num (int, optional): the number of loss. Defaults to 2. mode (str, optional): 'cls' for classification multi-task, 'reg' for regression multi-task. Defaults to 'cls'.",
"name": "__init__",
"signature": "def __init__(self, num=2, mode='cls')"
},
{
"docstring": "[summary] Arg... | 2 | stack_v2_sparse_classes_30k_train_006881 | Implement the Python class `AutomaticWeightedLoss` described below.
Class description:
automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)
Method signatures and docstrings:
- def __init__(self, num=2, mode='cls'): Args: num ... | Implement the Python class `AutomaticWeightedLoss` described below.
Class description:
automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)
Method signatures and docstrings:
- def __init__(self, num=2, mode='cls'): Args: num ... | b4c049fd30db39b67984edfadc49b4354d52be83 | <|skeleton|>
class AutomaticWeightedLoss:
"""automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)"""
def __init__(self, num=2, mode='cls'):
"""Args: num (int, optional): the number of loss. Defaults to 2. mode ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutomaticWeightedLoss:
"""automatically weighted multi-task(classification task) loss Examples: loss1=1 loss2=2 awl = AutomaticWeightedLoss(2) loss_sum = awl(loss1, loss2)"""
def __init__(self, num=2, mode='cls'):
"""Args: num (int, optional): the number of loss. Defaults to 2. mode (str, optiona... | the_stack_v2_python_sparse | pasaie/losses/autoweighted_loss.py | tracy-talent/AIPolicy | train | 0 |
28298f108b217566ee4ed25591171a147002d887 | [
"m, n = (len(grid), len(grid[0]))\nresult = [[0 for _ in xrange(n)] for _ in xrange(m)]\nresult[0][0] = grid[0][0]\nfor i in xrange(1, n):\n result[0][i] = result[0][i - 1] + grid[0][i]\nfor i in xrange(1, m):\n result[i][0] += result[i - 1][0] + grid[i][0]\nfor i in xrange(1, m):\n for j in xrange(1, n):\... | <|body_start_0|>
m, n = (len(grid), len(grid[0]))
result = [[0 for _ in xrange(n)] for _ in xrange(m)]
result[0][0] = grid[0][0]
for i in xrange(1, n):
result[0][i] = result[0][i - 1] + grid[0][i]
for i in xrange(1, m):
result[i][0] += result[i - 1][0] + g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m, n = (len(grid), len(grid[0]))
... | stack_v2_sparse_classes_36k_train_008212 | 1,504 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum2",
"signature": "def minPathSum2(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | 0ca8983505ef5f694b68198742aaf50fc0b80e6b | <|skeleton|>
class Solution:
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
m, n = (len(grid), len(grid[0]))
result = [[0 for _ in xrange(n)] for _ in xrange(m)]
result[0][0] = grid[0][0]
for i in xrange(1, n):
result[0][i] = result[0][i - 1] + grid... | the_stack_v2_python_sparse | leetcode 051-100/64. Minimum Path Sum.py | raxxar1024/code_snippet | train | 0 | |
0582fe1d0c3100afd8d4baa29f0fbca1dbf47097 | [
"super(SemGraphConv, self).__init__(activity_regularizer=activity_regularizer, **kwargs)\nself.units = int(units)\nself.affinity_matrix = tf.convert_to_tensor(affinity_matrix, dtype=tf.dtypes.float32) > 0.0\nself.activation = tf.keras.activations.get(activation)\nself.use_bias = use_bias\nself.kernel_initializer = ... | <|body_start_0|>
super(SemGraphConv, self).__init__(activity_regularizer=activity_regularizer, **kwargs)
self.units = int(units)
self.affinity_matrix = tf.convert_to_tensor(affinity_matrix, dtype=tf.dtypes.float32) > 0.0
self.activation = tf.keras.activations.get(activation)
self... | Implements Semantic Graph Convolution. Reference: Zhao et al. Semantic Graph Convolutional Networks for 3D Human Pose Regression. https://arxiv.org/pdf/1904.03345.pdf. | SemGraphConv | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemGraphConv:
"""Implements Semantic Graph Convolution. Reference: Zhao et al. Semantic Graph Convolutional Networks for 3D Human Pose Regression. https://arxiv.org/pdf/1904.03345.pdf."""
def __init__(self, units, affinity_matrix, activation=None, use_bias=True, kernel_initializer='glorot_un... | stack_v2_sparse_classes_36k_train_008213 | 30,548 | permissive | [
{
"docstring": "Initializer. Args: units: An integer for the output dimension of the layer. affinity_matrix: A tensor for the keypoint affinity matrix. activation: Activation function to use. use_bias: A boolean for whether the layer uses a bias vector. kernel_initializer: Initializer for the kernel weights mat... | 3 | null | Implement the Python class `SemGraphConv` described below.
Class description:
Implements Semantic Graph Convolution. Reference: Zhao et al. Semantic Graph Convolutional Networks for 3D Human Pose Regression. https://arxiv.org/pdf/1904.03345.pdf.
Method signatures and docstrings:
- def __init__(self, units, affinity_m... | Implement the Python class `SemGraphConv` described below.
Class description:
Implements Semantic Graph Convolution. Reference: Zhao et al. Semantic Graph Convolutional Networks for 3D Human Pose Regression. https://arxiv.org/pdf/1904.03345.pdf.
Method signatures and docstrings:
- def __init__(self, units, affinity_m... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SemGraphConv:
"""Implements Semantic Graph Convolution. Reference: Zhao et al. Semantic Graph Convolutional Networks for 3D Human Pose Regression. https://arxiv.org/pdf/1904.03345.pdf."""
def __init__(self, units, affinity_matrix, activation=None, use_bias=True, kernel_initializer='glorot_un... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemGraphConv:
"""Implements Semantic Graph Convolution. Reference: Zhao et al. Semantic Graph Convolutional Networks for 3D Human Pose Regression. https://arxiv.org/pdf/1904.03345.pdf."""
def __init__(self, units, affinity_matrix, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_... | the_stack_v2_python_sparse | poem/cv_mim/models.py | Jimmy-INL/google-research | train | 1 |
c762bfff5189176d65c3fbff3ce653647fc98a63 | [
"self._data_context = data_context\nself._gamma = gamma\nself._n = n",
"if _is_transition_like(value):\n value = _as_tfa_transition(value)\nelif _is_trajectory_like(value):\n _validate_trajectory(value, self._data_context.trajectory_spec, sequence_length=None if self._n is None else self._n + 1)\n value ... | <|body_start_0|>
self._data_context = data_context
self._gamma = gamma
self._n = n
<|end_body_0|>
<|body_start_1|>
if _is_transition_like(value):
value = _as_tfa_transition(value)
elif _is_trajectory_like(value):
_validate_trajectory(value, self._data_con... | Class that validates and converts other data types to N-step Transition. Note that validation and conversion allows values to contain dictionaries with extra keys as compared to the the specs in the data context. These additional entries / observations are ignored and dropped during conversion. This non-strict checking... | AsNStepTransition | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsNStepTransition:
"""Class that validates and converts other data types to N-step Transition. Note that validation and conversion allows values to contain dictionaries with extra keys as compared to the the specs in the data context. These additional entries / observations are ignored and droppe... | stack_v2_sparse_classes_36k_train_008214 | 24,336 | permissive | [
{
"docstring": "Create the AsNStepTransition converter. For more details on how `Trajectory` objects are converted to N-step `Transition` objects, see `tf_agents.trajectories.trajectory.to_n_step_transition`. Args: data_context: An instance of `DataContext`, typically accessed from the `TFAgent.data_context` pr... | 2 | null | Implement the Python class `AsNStepTransition` described below.
Class description:
Class that validates and converts other data types to N-step Transition. Note that validation and conversion allows values to contain dictionaries with extra keys as compared to the the specs in the data context. These additional entrie... | Implement the Python class `AsNStepTransition` described below.
Class description:
Class that validates and converts other data types to N-step Transition. Note that validation and conversion allows values to contain dictionaries with extra keys as compared to the the specs in the data context. These additional entrie... | eca1093d3a047e538f17f6ab92ab4d8144284f23 | <|skeleton|>
class AsNStepTransition:
"""Class that validates and converts other data types to N-step Transition. Note that validation and conversion allows values to contain dictionaries with extra keys as compared to the the specs in the data context. These additional entries / observations are ignored and droppe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsNStepTransition:
"""Class that validates and converts other data types to N-step Transition. Note that validation and conversion allows values to contain dictionaries with extra keys as compared to the the specs in the data context. These additional entries / observations are ignored and dropped during conv... | the_stack_v2_python_sparse | tf_agents/agents/data_converter.py | tensorflow/agents | train | 2,755 |
5d36b7a52eded29bd53e248c315d4d27729bb223 | [
"super().__init__(grid_proportion)\nself.level = level\nself.text = text\nself.id = 'heading_' + str(uuid.uuid4())",
"env = templates.environment\ntemplate = env.get_template('heading.html')\nreturn template.render(level=self.level, text=self.text, id=self.id)"
] | <|body_start_0|>
super().__init__(grid_proportion)
self.level = level
self.text = text
self.id = 'heading_' + str(uuid.uuid4())
<|end_body_0|>
<|body_start_1|>
env = templates.environment
template = env.get_template('heading.html')
return template.render(level=se... | HeadingElement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeadingElement:
def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight):
"""Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The te... | stack_v2_sparse_classes_36k_train_008215 | 1,875 | permissive | [
{
"docstring": "Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The text to display in the heading.",
"name": "__init__",
"signature": "def __init__(self, level: int, text: str, grid_pro... | 2 | null | Implement the Python class `HeadingElement` described below.
Class description:
Implement the HeadingElement class.
Method signatures and docstrings:
- def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): Represents an ordinary heading, usually used to start a new section i... | Implement the Python class `HeadingElement` described below.
Class description:
Implement the HeadingElement class.
Method signatures and docstrings:
- def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight): Represents an ordinary heading, usually used to start a new section i... | f707e51bc2ff45f6e46dcdd24d59d83ce7dc4f94 | <|skeleton|>
class HeadingElement:
def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight):
"""Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeadingElement:
def __init__(self, level: int, text: str, grid_proportion: GridProportion=GridProportion.Eight):
"""Represents an ordinary heading, usually used to start a new section in a document. Parameters ---------- level The level of this heading, must be in range 1..6. text The text to display ... | the_stack_v2_python_sparse | qf_lib/documents_utils/document_exporting/element/heading.py | quarkfin/qf-lib | train | 379 | |
370c4215eab7b5c428d5d3f9aff3f5f8190fb492 | [
"self._text = text or ''\nself._has_div = True\nm = self.p_header.search(self._text)\nif m:\n self.ql = int(m['ql'])\n self.user = m['user']\n self.header = m['header']\n if not m['has_div']:\n self._has_div = False\nelse:\n self.ql = ProofreadPage.NOT_PROOFREAD\n self.user = ''\n self.h... | <|body_start_0|>
self._text = text or ''
self._has_div = True
m = self.p_header.search(self._text)
if m:
self.ql = int(m['ql'])
self.user = m['user']
self.header = m['header']
if not m['has_div']:
self._has_div = False
... | Header of a ProofreadPage object. | FullHeader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullHeader:
"""Header of a ProofreadPage object."""
def __init__(self, text: Optional[str]=None) -> None:
"""Initializer."""
<|body_0|>
def __str__(self) -> str:
"""Return a string representation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008216 | 47,197 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, text: Optional[str]=None) -> None"
},
{
"docstring": "Return a string representation.",
"name": "__str__",
"signature": "def __str__(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_018744 | Implement the Python class `FullHeader` described below.
Class description:
Header of a ProofreadPage object.
Method signatures and docstrings:
- def __init__(self, text: Optional[str]=None) -> None: Initializer.
- def __str__(self) -> str: Return a string representation. | Implement the Python class `FullHeader` described below.
Class description:
Header of a ProofreadPage object.
Method signatures and docstrings:
- def __init__(self, text: Optional[str]=None) -> None: Initializer.
- def __str__(self) -> str: Return a string representation.
<|skeleton|>
class FullHeader:
"""Header... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class FullHeader:
"""Header of a ProofreadPage object."""
def __init__(self, text: Optional[str]=None) -> None:
"""Initializer."""
<|body_0|>
def __str__(self) -> str:
"""Return a string representation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullHeader:
"""Header of a ProofreadPage object."""
def __init__(self, text: Optional[str]=None) -> None:
"""Initializer."""
self._text = text or ''
self._has_div = True
m = self.p_header.search(self._text)
if m:
self.ql = int(m['ql'])
self.... | the_stack_v2_python_sparse | pywikibot/proofreadpage.py | wikimedia/pywikibot | train | 432 |
3a22897ae9fbf3a754be03343fbd247a0f715fc0 | [
"cube_name = 'air_temperature'\ncube_units = Unit('degreesC')\nresult = get_bounds_of_distribution(cube_name, cube_units)\nself.assertIsInstance(result, np.ndarray)",
"cube_name = 'air_temperature'\ncube_units = Unit('degreesC')\nbounds_pairing = (-100, 60)\nresult = get_bounds_of_distribution(cube_name, cube_uni... | <|body_start_0|>
cube_name = 'air_temperature'
cube_units = Unit('degreesC')
result = get_bounds_of_distribution(cube_name, cube_units)
self.assertIsInstance(result, np.ndarray)
<|end_body_0|>
<|body_start_1|>
cube_name = 'air_temperature'
cube_units = Unit('degreesC')
... | Test the get_bounds_of_distribution plugin. | Test_get_bounds_of_distribution | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_get_bounds_of_distribution:
"""Test the get_bounds_of_distribution plugin."""
def test_basic(self):
"""Test that the result is a numpy array."""
<|body_0|>
def test_check_data(self):
"""Test that the expected results are returned for the bounds_pairing."""
... | stack_v2_sparse_classes_36k_train_008217 | 28,421 | permissive | [
{
"docstring": "Test that the result is a numpy array.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test that the expected results are returned for the bounds_pairing.",
"name": "test_check_data",
"signature": "def test_check_data(self)"
},
{
"do... | 4 | null | Implement the Python class `Test_get_bounds_of_distribution` described below.
Class description:
Test the get_bounds_of_distribution plugin.
Method signatures and docstrings:
- def test_basic(self): Test that the result is a numpy array.
- def test_check_data(self): Test that the expected results are returned for the... | Implement the Python class `Test_get_bounds_of_distribution` described below.
Class description:
Test the get_bounds_of_distribution plugin.
Method signatures and docstrings:
- def test_basic(self): Test that the result is a numpy array.
- def test_check_data(self): Test that the expected results are returned for the... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_get_bounds_of_distribution:
"""Test the get_bounds_of_distribution plugin."""
def test_basic(self):
"""Test that the result is a numpy array."""
<|body_0|>
def test_check_data(self):
"""Test that the expected results are returned for the bounds_pairing."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_get_bounds_of_distribution:
"""Test the get_bounds_of_distribution plugin."""
def test_basic(self):
"""Test that the result is a numpy array."""
cube_name = 'air_temperature'
cube_units = Unit('degreesC')
result = get_bounds_of_distribution(cube_name, cube_units)
... | the_stack_v2_python_sparse | improver_tests/ensemble_copula_coupling/test_utilities.py | metoppv/improver | train | 101 |
2c1efdee1105c559f158e5bbcd006763beb94e7d | [
"super().__init__()\nself.normalize_feats = normalize_feats\nlayers = []\nlast_dim = dims[0]\nfor i, dim in enumerate(dims[1:]):\n layers.append(nn.Linear(last_dim, dim, bias=use_bias))\n if i == len(dims) - 2 and skip_last_bn:\n break\n if use_bn:\n layers.append(nn.BatchNorm1d(dim, eps=mode... | <|body_start_0|>
super().__init__()
self.normalize_feats = normalize_feats
layers = []
last_dim = dims[0]
for i, dim in enumerate(dims[1:]):
layers.append(nn.Linear(last_dim, dim, bias=use_bias))
if i == len(dims) - 2 and skip_last_bn:
brea... | SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering step. Input: 2D torch.tensor of shape (N x C) Ou... | SwAVPrototypesHead | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwAVPrototypesHead:
"""SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering st... | stack_v2_sparse_classes_36k_train_008218 | 6,370 | permissive | [
{
"docstring": "Args: model_config (AttrDict): dictionary config.MODEL in the config file dims (int): dimensions of the linear layer. Must have length at least 2. Example: [2048, 2048, 128] attaches linear layer Linear(2048, 2048) -> BN -> Relu -> Linear(2048, 128) use_bn (bool): whether to attach BatchNorm aft... | 2 | stack_v2_sparse_classes_30k_train_021582 | Implement the Python class `SwAVPrototypesHead` described below.
Class description:
SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features... | Implement the Python class `SwAVPrototypesHead` described below.
Class description:
SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features... | b647c256447af7ea66655811849be1f642377db8 | <|skeleton|>
class SwAVPrototypesHead:
"""SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwAVPrototypesHead:
"""SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering step. Input: 2D... | the_stack_v2_python_sparse | vissl/models/heads/swav_prototypes_head.py | pzharrington/vissl | train | 1 |
5c5da9096a9e78526c8ff90a83c817a0e231e03f | [
"super().__init__(restaurant_name, cuisine_type, number_served)\nself.flavors = []\nfor flavor in flavors:\n self.flavors.append(flavor)",
"print(self.restaurant_name, 'has icecream of these flavors:')\nfor flavor in self.flavors:\n print(flavor, end=' ')"
] | <|body_start_0|>
super().__init__(restaurant_name, cuisine_type, number_served)
self.flavors = []
for flavor in flavors:
self.flavors.append(flavor)
<|end_body_0|>
<|body_start_1|>
print(self.restaurant_name, 'has icecream of these flavors:')
for flavor in self.flavo... | IceCreamStand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IceCreamStand:
def __init__(self, restaurant_name, cuisine_type, number_served=0, *flavors):
"""IceCreamStand类构造函数"""
<|body_0|>
def describe_icecreamstand(self):
"""打印冰激凌店名字以及拥有的冰激凌口味"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__... | stack_v2_sparse_classes_36k_train_008219 | 2,030 | no_license | [
{
"docstring": "IceCreamStand类构造函数",
"name": "__init__",
"signature": "def __init__(self, restaurant_name, cuisine_type, number_served=0, *flavors)"
},
{
"docstring": "打印冰激凌店名字以及拥有的冰激凌口味",
"name": "describe_icecreamstand",
"signature": "def describe_icecreamstand(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000857 | Implement the Python class `IceCreamStand` described below.
Class description:
Implement the IceCreamStand class.
Method signatures and docstrings:
- def __init__(self, restaurant_name, cuisine_type, number_served=0, *flavors): IceCreamStand类构造函数
- def describe_icecreamstand(self): 打印冰激凌店名字以及拥有的冰激凌口味 | Implement the Python class `IceCreamStand` described below.
Class description:
Implement the IceCreamStand class.
Method signatures and docstrings:
- def __init__(self, restaurant_name, cuisine_type, number_served=0, *flavors): IceCreamStand类构造函数
- def describe_icecreamstand(self): 打印冰激凌店名字以及拥有的冰激凌口味
<|skeleton|>
cl... | 542e8781f26676a62538714b92fb0bccdf41b47b | <|skeleton|>
class IceCreamStand:
def __init__(self, restaurant_name, cuisine_type, number_served=0, *flavors):
"""IceCreamStand类构造函数"""
<|body_0|>
def describe_icecreamstand(self):
"""打印冰激凌店名字以及拥有的冰激凌口味"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IceCreamStand:
def __init__(self, restaurant_name, cuisine_type, number_served=0, *flavors):
"""IceCreamStand类构造函数"""
super().__init__(restaurant_name, cuisine_type, number_served)
self.flavors = []
for flavor in flavors:
self.flavors.append(flavor)
def describ... | the_stack_v2_python_sparse | 孙林轩/2017310392 孙林轩 第四次作业/class_restaurant.py | jingong171/jingong-homework | train | 8 | |
305fee1943e236aa1338f3a083890bf0053eaec6 | [
"if self.dialog is None:\n self.dialog = TextureBakerDlg()\nreturn self.dialog.Open(dlgtype=c4d.DLG_TYPE_ASYNC, pluginid=PLUGIN_ID, defaultw=250, defaulth=50)",
"if self.dialog is None:\n self.dialog = TextureBakerDlg()\nreturn self.dialog.Restore(pluginid=PLUGIN_ID, secret=sec_ref)"
] | <|body_start_0|>
if self.dialog is None:
self.dialog = TextureBakerDlg()
return self.dialog.Open(dlgtype=c4d.DLG_TYPE_ASYNC, pluginid=PLUGIN_ID, defaultw=250, defaulth=50)
<|end_body_0|>
<|body_start_1|>
if self.dialog is None:
self.dialog = TextureBakerDlg()
ret... | Command Data class that holds the TextureBakerDlg instance. | TextureBakerData | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextureBakerData:
"""Command Data class that holds the TextureBakerDlg instance."""
def Execute(self, doc):
"""Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu) Args: doc (c4d.documents.BaseDocument): the current active document Re... | stack_v2_sparse_classes_36k_train_008220 | 10,936 | permissive | [
{
"docstring": "Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu) Args: doc (c4d.documents.BaseDocument): the current active document Returns: bool: True if the command success",
"name": "Execute",
"signature": "def Execute(self, doc)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_test_000787 | Implement the Python class `TextureBakerData` described below.
Class description:
Command Data class that holds the TextureBakerDlg instance.
Method signatures and docstrings:
- def Execute(self, doc): Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu) Args: doc (c4... | Implement the Python class `TextureBakerData` described below.
Class description:
Command Data class that holds the TextureBakerDlg instance.
Method signatures and docstrings:
- def Execute(self, doc): Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu) Args: doc (c4... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class TextureBakerData:
"""Command Data class that holds the TextureBakerDlg instance."""
def Execute(self, doc):
"""Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu) Args: doc (c4d.documents.BaseDocument): the current active document Re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextureBakerData:
"""Command Data class that holds the TextureBakerDlg instance."""
def Execute(self, doc):
"""Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu) Args: doc (c4d.documents.BaseDocument): the current active document Returns: bool: ... | the_stack_v2_python_sparse | plugins/py-texture_baker_r18/py-texture_baker_r18.pyp | PluginCafe/cinema4d_py_sdk_extended | train | 112 |
335529c8b4543e96e2b21823a4eb6bb98e1394d8 | [
"BaseElement.__init__(self, cle)\nself.longueur = 8\nself.nb_lever = 1\nself._attributs = {'jetee': Attribut(lambda: False)}",
"longueur = presentation.ajouter_choix(\"longueur de l'ancre\", None, Entier, self, 'longueur')\nlongueur.apercu = '{valeur} brasse(s)'\nlongueur.prompt = \"Longueur de l'ancre : \"\nlong... | <|body_start_0|>
BaseElement.__init__(self, cle)
self.longueur = 8
self.nb_lever = 1
self._attributs = {'jetee': Attribut(lambda: False)}
<|end_body_0|>
<|body_start_1|>
longueur = presentation.ajouter_choix("longueur de l'ancre", None, Entier, self, 'longueur')
longueur... | Classe représentant une ancre. | Ancre | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ancre:
"""Classe représentant une ancre."""
def __init__(self, cle=''):
"""Constructeur d'un type"""
<|body_0|>
def editer(self, presentation):
"""Édition de l'ancre."""
<|body_1|>
def get_description_ligne(self, personnage):
"""Retourne une ... | stack_v2_sparse_classes_36k_train_008221 | 7,163 | permissive | [
{
"docstring": "Constructeur d'un type",
"name": "__init__",
"signature": "def __init__(self, cle='')"
},
{
"docstring": "Édition de l'ancre.",
"name": "editer",
"signature": "def editer(self, presentation)"
},
{
"docstring": "Retourne une description d'une ligne de l'élément.",
... | 6 | null | Implement the Python class `Ancre` described below.
Class description:
Classe représentant une ancre.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur d'un type
- def editer(self, presentation): Édition de l'ancre.
- def get_description_ligne(self, personnage): Retourne une description d'u... | Implement the Python class `Ancre` described below.
Class description:
Classe représentant une ancre.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur d'un type
- def editer(self, presentation): Édition de l'ancre.
- def get_description_ligne(self, personnage): Retourne une description d'u... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class Ancre:
"""Classe représentant une ancre."""
def __init__(self, cle=''):
"""Constructeur d'un type"""
<|body_0|>
def editer(self, presentation):
"""Édition de l'ancre."""
<|body_1|>
def get_description_ligne(self, personnage):
"""Retourne une ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ancre:
"""Classe représentant une ancre."""
def __init__(self, cle=''):
"""Constructeur d'un type"""
BaseElement.__init__(self, cle)
self.longueur = 8
self.nb_lever = 1
self._attributs = {'jetee': Attribut(lambda: False)}
def editer(self, presentation):
... | the_stack_v2_python_sparse | src/secondaires/navigation/elements/ancre.py | vincent-lg/tsunami | train | 5 |
753daf2d8da574874f5212b85659377b3435ca31 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ExtensionProperty()",
"from .directory_object import DirectoryObject\nfrom .directory_object import DirectoryObject\nfields: Dict[str, Callable[[Any], None]] = {'appDisplayName': lambda n: setattr(self, 'app_display_name', n.get_str_va... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ExtensionProperty()
<|end_body_0|>
<|body_start_1|>
from .directory_object import DirectoryObject
from .directory_object import DirectoryObject
fields: Dict[str, Callable[[Any], ... | ExtensionProperty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtensionProperty:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExtensionProperty:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_36k_train_008222 | 3,640 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ExtensionProperty",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_014765 | Implement the Python class `ExtensionProperty` described below.
Class description:
Implement the ExtensionProperty class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExtensionProperty: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `ExtensionProperty` described below.
Class description:
Implement the ExtensionProperty class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExtensionProperty: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ExtensionProperty:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExtensionProperty:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtensionProperty:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExtensionProperty:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Exte... | the_stack_v2_python_sparse | msgraph/generated/models/extension_property.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ae99ad175c99f95fdb10c9342cb983b20ff621f9 | [
"if not events:\n events = {}\nself.subscriptions = {}\nself.subscription_count = 0\nfor event_name in events.keys():\n self.subscribe(event_name, events.get(event_name))",
"self.subscription_count += 1\nif not self.subscriptions.get(event_name):\n self.subscriptions[event_name] = {}\nself.subscriptions[... | <|body_start_0|>
if not events:
events = {}
self.subscriptions = {}
self.subscription_count = 0
for event_name in events.keys():
self.subscribe(event_name, events.get(event_name))
<|end_body_0|>
<|body_start_1|>
self.subscription_count += 1
if not... | EventProvider | EventProvider | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventProvider:
"""EventProvider"""
def __init__(self, events=None):
""":param events: (dict.<str, callable>) An object with event name keys and callback function values, optional"""
<|body_0|>
def subscribe(self, event_name, callback_func):
"""Subscribe to events... | stack_v2_sparse_classes_36k_train_008223 | 2,752 | permissive | [
{
"docstring": ":param events: (dict.<str, callable>) An object with event name keys and callback function values, optional",
"name": "__init__",
"signature": "def __init__(self, events=None)"
},
{
"docstring": "Subscribe to events :param event_name: (str) Event name, required :param callback_fu... | 4 | stack_v2_sparse_classes_30k_train_014204 | Implement the Python class `EventProvider` described below.
Class description:
EventProvider
Method signatures and docstrings:
- def __init__(self, events=None): :param events: (dict.<str, callable>) An object with event name keys and callback function values, optional
- def subscribe(self, event_name, callback_func)... | Implement the Python class `EventProvider` described below.
Class description:
EventProvider
Method signatures and docstrings:
- def __init__(self, events=None): :param events: (dict.<str, callable>) An object with event name keys and callback function values, optional
- def subscribe(self, event_name, callback_func)... | f3e9b1bb6c8e1984e3d758ab1fe1a71225ade13e | <|skeleton|>
class EventProvider:
"""EventProvider"""
def __init__(self, events=None):
""":param events: (dict.<str, callable>) An object with event name keys and callback function values, optional"""
<|body_0|>
def subscribe(self, event_name, callback_func):
"""Subscribe to events... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventProvider:
"""EventProvider"""
def __init__(self, events=None):
""":param events: (dict.<str, callable>) An object with event name keys and callback function values, optional"""
if not events:
events = {}
self.subscriptions = {}
self.subscription_count = 0
... | the_stack_v2_python_sparse | target_tools/event_provider.py | 5amfung/target-python-sdk | train | 0 |
13ccc774972bd4d141b0d2bb571ff646bd1372f8 | [
"while left and right:\n if left.val <= right.val:\n tail.next = left\n left = left.next\n else:\n tail.next = right\n right = right.next\n tail = tail.next\nif left:\n tail.next = left\nelif right:\n tail.next = right\nwhile tail.next:\n tail = tail.next\nreturn tail",... | <|body_start_0|>
while left and right:
if left.val <= right.val:
tail.next = left
left = left.next
else:
tail.next = right
right = right.next
tail = tail.next
if left:
tail.next = left
... | SolutionIterative | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionIterative:
def merge(self, left, right, tail):
"""Merges two sorted linked lists. Returns the link to the last node of sorted merged list. input: left >> start of the left linked list right >> start of the right linked list tail >> last node of already original sorted linked list... | stack_v2_sparse_classes_36k_train_008224 | 5,124 | no_license | [
{
"docstring": "Merges two sorted linked lists. Returns the link to the last node of sorted merged list. input: left >> start of the left linked list right >> start of the right linked list tail >> last node of already original sorted linked list Time complexity: O(n + m). Space complexity: O(1), n, m are lengt... | 3 | null | Implement the Python class `SolutionIterative` described below.
Class description:
Implement the SolutionIterative class.
Method signatures and docstrings:
- def merge(self, left, right, tail): Merges two sorted linked lists. Returns the link to the last node of sorted merged list. input: left >> start of the left li... | Implement the Python class `SolutionIterative` described below.
Class description:
Implement the SolutionIterative class.
Method signatures and docstrings:
- def merge(self, left, right, tail): Merges two sorted linked lists. Returns the link to the last node of sorted merged list. input: left >> start of the left li... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionIterative:
def merge(self, left, right, tail):
"""Merges two sorted linked lists. Returns the link to the last node of sorted merged list. input: left >> start of the left linked list right >> start of the right linked list tail >> last node of already original sorted linked list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionIterative:
def merge(self, left, right, tail):
"""Merges two sorted linked lists. Returns the link to the last node of sorted merged list. input: left >> start of the left linked list right >> start of the right linked list tail >> last node of already original sorted linked list Time complexi... | the_stack_v2_python_sparse | Linked_Lists/sort_list.py | vladn90/Algorithms | train | 0 | |
bf9d890180b7c2e33e39c1e70ce88f5668a6c26b | [
"if not s or n < 0:\n return s\ns = list(s)\nself.swap(s, 0, n - 1)\nself.swap(s, n, len(s) - 1)\nself.swap(s, 0, len(s) - 1)\nreturn ''.join(s)",
"while l < r:\n s[l], s[r] = (s[r], s[l])\n l += 1\n r -= 1"
] | <|body_start_0|>
if not s or n < 0:
return s
s = list(s)
self.swap(s, 0, n - 1)
self.swap(s, n, len(s) - 1)
self.swap(s, 0, len(s) - 1)
return ''.join(s)
<|end_body_0|>
<|body_start_1|>
while l < r:
s[l], s[r] = (s[r], s[l])
l ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def LeftRotateString(self, s, n):
"""左旋转字符串"""
<|body_0|>
def swap(self, s, l, r):
"""旋转函数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s or n < 0:
return s
s = list(s)
self.swap(s, 0, n - 1)
s... | stack_v2_sparse_classes_36k_train_008225 | 1,081 | no_license | [
{
"docstring": "左旋转字符串",
"name": "LeftRotateString",
"signature": "def LeftRotateString(self, s, n)"
},
{
"docstring": "旋转函数",
"name": "swap",
"signature": "def swap(self, s, l, r)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LeftRotateString(self, s, n): 左旋转字符串
- def swap(self, s, l, r): 旋转函数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LeftRotateString(self, s, n): 左旋转字符串
- def swap(self, s, l, r): 旋转函数
<|skeleton|>
class Solution:
def LeftRotateString(self, s, n):
"""左旋转字符串"""
<|body_... | a3872425745425f8ca960840120f06de4a8370bb | <|skeleton|>
class Solution:
def LeftRotateString(self, s, n):
"""左旋转字符串"""
<|body_0|>
def swap(self, s, l, r):
"""旋转函数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def LeftRotateString(self, s, n):
"""左旋转字符串"""
if not s or n < 0:
return s
s = list(s)
self.swap(s, 0, n - 1)
self.swap(s, n, len(s) - 1)
self.swap(s, 0, len(s) - 1)
return ''.join(s)
def swap(self, s, l, r):
"""旋转函数"""... | the_stack_v2_python_sparse | offer/LeftRotateString.py | xiaozuo7/algorithm_python | train | 1 | |
794db7f71331a2dc4102300ba09e4eb77216377f | [
"super().__init__(nTel)\nself.centroid = [centroid, centroid]\nself.length, self.width = (length, width)\nself.psi = psi\nself.nsb = nsb\nself.tab_inj, self.mat_event, self.geom = (None, None, None)\nself.load_telescope()",
"self.geom = self.get_camera_geometry()\nwhile True:\n centroid = [random.uniform(self.... | <|body_start_0|>
super().__init__(nTel)
self.centroid = [centroid, centroid]
self.length, self.width = (length, width)
self.psi = psi
self.nsb = nsb
self.tab_inj, self.mat_event, self.geom = (None, None, None)
self.load_telescope()
<|end_body_0|>
<|body_start_1|>... | PyGammaSimulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyGammaSimulation:
def __init__(self, nTel=0, centroid=(-0.5, 0.5), length=(0.005, 0.09), width=(0.0005, 0.003), psi=(0, 360), nsb=(10, 60)):
"""nTel=0 centroid=(-0.5, 0.5) length=(0.005, 0.05) width=(0.0005, 0.003) psi=(0, 360) nsb=(12, 25)"""
<|body_0|>
def generate_signal... | stack_v2_sparse_classes_36k_train_008226 | 3,356 | no_license | [
{
"docstring": "nTel=0 centroid=(-0.5, 0.5) length=(0.005, 0.05) width=(0.0005, 0.003) psi=(0, 360) nsb=(12, 25)",
"name": "__init__",
"signature": "def __init__(self, nTel=0, centroid=(-0.5, 0.5), length=(0.005, 0.09), width=(0.0005, 0.003), psi=(0, 360), nsb=(10, 60))"
},
{
"docstring": "sn : ... | 3 | stack_v2_sparse_classes_30k_train_013945 | Implement the Python class `PyGammaSimulation` described below.
Class description:
Implement the PyGammaSimulation class.
Method signatures and docstrings:
- def __init__(self, nTel=0, centroid=(-0.5, 0.5), length=(0.005, 0.09), width=(0.0005, 0.003), psi=(0, 360), nsb=(10, 60)): nTel=0 centroid=(-0.5, 0.5) length=(0... | Implement the Python class `PyGammaSimulation` described below.
Class description:
Implement the PyGammaSimulation class.
Method signatures and docstrings:
- def __init__(self, nTel=0, centroid=(-0.5, 0.5), length=(0.005, 0.09), width=(0.0005, 0.003), psi=(0, 360), nsb=(10, 60)): nTel=0 centroid=(-0.5, 0.5) length=(0... | 0d029e4db8b230c564c383f2c20a6a138592c5ff | <|skeleton|>
class PyGammaSimulation:
def __init__(self, nTel=0, centroid=(-0.5, 0.5), length=(0.005, 0.09), width=(0.0005, 0.003), psi=(0, 360), nsb=(10, 60)):
"""nTel=0 centroid=(-0.5, 0.5) length=(0.005, 0.05) width=(0.0005, 0.003) psi=(0, 360) nsb=(12, 25)"""
<|body_0|>
def generate_signal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyGammaSimulation:
def __init__(self, nTel=0, centroid=(-0.5, 0.5), length=(0.005, 0.09), width=(0.0005, 0.003), psi=(0, 360), nsb=(10, 60)):
"""nTel=0 centroid=(-0.5, 0.5) length=(0.005, 0.05) width=(0.0005, 0.003) psi=(0, 360) nsb=(12, 25)"""
super().__init__(nTel)
self.centroid = [c... | the_stack_v2_python_sparse | pysimulation/scripts/PyGammaSimulation.py | BoukhrisOmar/gammaWaveletsToyModelSimu | train | 0 | |
1ac5249ced391dcdd97dcd35782b72e75e1ff7e9 | [
"cmd = 'fleetrun dist_ps_all_reduce.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nout, err = pro.communicate()\nprint(out)\npro.wait()\npro.returncode == 0",
"cmd = 'fleetrun dist_ps_barrier.py'\npro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr... | <|body_start_0|>
cmd = 'fleetrun dist_ps_all_reduce.py'
pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pro.communicate()
print(out)
pro.wait()
pro.returncode == 0
<|end_body_0|>
<|body_start_1|>
cmd = 'fleetrun ... | test all api | TestPsUtileApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPsUtileApi:
"""test all api"""
def test_dist_fleet_ps_all_reduce(self):
"""test_dist_fleet_ps_all_reduce"""
<|body_0|>
def test_dist_fleet_ps_barrier(self):
"""test_dist_fleet_ps_barrier"""
<|body_1|>
def test_dist_fleet_ps_get_file_shard(self):
... | stack_v2_sparse_classes_36k_train_008227 | 2,079 | no_license | [
{
"docstring": "test_dist_fleet_ps_all_reduce",
"name": "test_dist_fleet_ps_all_reduce",
"signature": "def test_dist_fleet_ps_all_reduce(self)"
},
{
"docstring": "test_dist_fleet_ps_barrier",
"name": "test_dist_fleet_ps_barrier",
"signature": "def test_dist_fleet_ps_barrier(self)"
},
... | 4 | null | Implement the Python class `TestPsUtileApi` described below.
Class description:
test all api
Method signatures and docstrings:
- def test_dist_fleet_ps_all_reduce(self): test_dist_fleet_ps_all_reduce
- def test_dist_fleet_ps_barrier(self): test_dist_fleet_ps_barrier
- def test_dist_fleet_ps_get_file_shard(self): test... | Implement the Python class `TestPsUtileApi` described below.
Class description:
test all api
Method signatures and docstrings:
- def test_dist_fleet_ps_all_reduce(self): test_dist_fleet_ps_all_reduce
- def test_dist_fleet_ps_barrier(self): test_dist_fleet_ps_barrier
- def test_dist_fleet_ps_get_file_shard(self): test... | e3562ab40b574f06bba68df6895a055fa31a085d | <|skeleton|>
class TestPsUtileApi:
"""test all api"""
def test_dist_fleet_ps_all_reduce(self):
"""test_dist_fleet_ps_all_reduce"""
<|body_0|>
def test_dist_fleet_ps_barrier(self):
"""test_dist_fleet_ps_barrier"""
<|body_1|>
def test_dist_fleet_ps_get_file_shard(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPsUtileApi:
"""test all api"""
def test_dist_fleet_ps_all_reduce(self):
"""test_dist_fleet_ps_all_reduce"""
cmd = 'fleetrun dist_ps_all_reduce.py'
pro = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pro.communicate()
... | the_stack_v2_python_sparse | dist_cts/dist_fleet_pipeline/test_dist_fleet_ps_communicator_api.py | gentelyang/scripts | train | 0 |
3155e8e8ac5ffe622d83cc7a4cb55ba226ef511e | [
"if self.current_user is None:\n return\nfilt_dict = {}\nfilters = [('status', str), ('name', str), ('user_id', str), ('limit', int), ('earlier_than_submit', int), ('earlier_than_start', int), ('earlier_than_end', int), ('later_than_submit', int), ('later_than_start', int), ('later_than_end', int)]\nfor filt in ... | <|body_start_0|>
if self.current_user is None:
return
filt_dict = {}
filters = [('status', str), ('name', str), ('user_id', str), ('limit', int), ('earlier_than_submit', int), ('earlier_than_start', int), ('earlier_than_end', int), ('later_than_submit', int), ('later_than_start', int... | The Execution Collection API endpoints. | ExecutionCollectionAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutionCollectionAPI:
"""The Execution Collection API endpoints."""
def get(self):
"""Returns a list of all active executions. The list can be filtered by passing a non-empty JSON dictionary. Any combination of the following filters is supported: * status: one of submitted, queued,... | stack_v2_sparse_classes_36k_train_008228 | 6,687 | permissive | [
{
"docstring": "Returns a list of all active executions. The list can be filtered by passing a non-empty JSON dictionary. Any combination of the following filters is supported: * status: one of submitted, queued, starting, error, running, cleaning up, terminated * name: execution mane * user_id: user_id owning ... | 2 | stack_v2_sparse_classes_30k_train_012492 | Implement the Python class `ExecutionCollectionAPI` described below.
Class description:
The Execution Collection API endpoints.
Method signatures and docstrings:
- def get(self): Returns a list of all active executions. The list can be filtered by passing a non-empty JSON dictionary. Any combination of the following ... | Implement the Python class `ExecutionCollectionAPI` described below.
Class description:
The Execution Collection API endpoints.
Method signatures and docstrings:
- def get(self): Returns a list of all active executions. The list can be filtered by passing a non-empty JSON dictionary. Any combination of the following ... | c8e0c908af1954a8b41d0f6de23d08589564f0ab | <|skeleton|>
class ExecutionCollectionAPI:
"""The Execution Collection API endpoints."""
def get(self):
"""Returns a list of all active executions. The list can be filtered by passing a non-empty JSON dictionary. Any combination of the following filters is supported: * status: one of submitted, queued,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecutionCollectionAPI:
"""The Execution Collection API endpoints."""
def get(self):
"""Returns a list of all active executions. The list can be filtered by passing a non-empty JSON dictionary. Any combination of the following filters is supported: * status: one of submitted, queued, starting, er... | the_stack_v2_python_sparse | zoe_api/rest_api/execution.py | DistributedSystemsGroup/zoe | train | 60 |
64d3f550cdc895467fe1943c9fd6ca4a34b53f37 | [
"if current_user.is_authenticated and (current_user.group_id == 3 or current_user.id == user_id):\n user = User.query.filter_by(id=user_id).first()\n if not user:\n return jsonify({'message': 'No User'})\n user_data = {}\n user_data['username'] = user.username\n a = Group.query.get(user.group_... | <|body_start_0|>
if current_user.is_authenticated and (current_user.group_id == 3 or current_user.id == user_id):
user = User.query.filter_by(id=user_id).first()
if not user:
return jsonify({'message': 'No User'})
user_data = {}
user_data['username... | Resource for managing User details | UserApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserApi:
"""Resource for managing User details"""
def get(self, user_id):
"""Method for retrieving details about the User"""
<|body_0|>
def delete(cls, user_id):
"""Method for deleting the User"""
<|body_1|>
def put(cls, user_id):
"""Method f... | stack_v2_sparse_classes_36k_train_008229 | 5,619 | no_license | [
{
"docstring": "Method for retrieving details about the User",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "Method for deleting the User",
"name": "delete",
"signature": "def delete(cls, user_id)"
},
{
"docstring": "Method for partial updating details a... | 3 | stack_v2_sparse_classes_30k_train_013469 | Implement the Python class `UserApi` described below.
Class description:
Resource for managing User details
Method signatures and docstrings:
- def get(self, user_id): Method for retrieving details about the User
- def delete(cls, user_id): Method for deleting the User
- def put(cls, user_id): Method for partial upda... | Implement the Python class `UserApi` described below.
Class description:
Resource for managing User details
Method signatures and docstrings:
- def get(self, user_id): Method for retrieving details about the User
- def delete(cls, user_id): Method for deleting the User
- def put(cls, user_id): Method for partial upda... | 4e5e1b390ba55f714792895cb358f7cf17854a13 | <|skeleton|>
class UserApi:
"""Resource for managing User details"""
def get(self, user_id):
"""Method for retrieving details about the User"""
<|body_0|>
def delete(cls, user_id):
"""Method for deleting the User"""
<|body_1|>
def put(cls, user_id):
"""Method f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserApi:
"""Resource for managing User details"""
def get(self, user_id):
"""Method for retrieving details about the User"""
if current_user.is_authenticated and (current_user.group_id == 3 or current_user.id == user_id):
user = User.query.filter_by(id=user_id).first()
... | the_stack_v2_python_sparse | flask_project/views/user.py | vladkost43/flask_demo3 | train | 0 |
f724f1121326177b41aa01b76c078576ff5adfc5 | [
"self.after_cursor_entity_id = after_cursor_entity_id\nself.before_cursor_entity_id = before_cursor_entity_id\nself.node_id = node_id\nself.page_size = page_size",
"if dictionary is None:\n return None\nafter_cursor_entity_id = dictionary.get('afterCursorEntityId')\nbefore_cursor_entity_id = dictionary.get('be... | <|body_start_0|>
self.after_cursor_entity_id = after_cursor_entity_id
self.before_cursor_entity_id = before_cursor_entity_id
self.node_id = node_id
self.page_size = page_size
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
after_cursor_enti... | Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor will always refer to a specific source within th... | PaginationParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor ... | stack_v2_sparse_classes_36k_train_008230 | 2,821 | permissive | [
{
"docstring": "Constructor for the PaginationParameters class",
"name": "__init__",
"signature": "def __init__(self, after_cursor_entity_id=None, before_cursor_entity_id=None, node_id=None, page_size=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary ... | 2 | stack_v2_sparse_classes_30k_train_017362 | Implement the Python class `PaginationParameters` described below.
Class description:
Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the hel... | Implement the Python class `PaginationParameters` described below.
Class description:
Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the hel... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor will always r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pagination_parameters.py | cohesity/management-sdk-python | train | 24 |
30993c72838d6c0a57d2aa581df01e9aedc58dcd | [
"self.tcp_target = tcp_target\nself.tcp_port = tcp_port\nself.verbosity = verbosity\nself.peer = '{}:{}'.format(self.tcp_target, self.tcp_port)\nif is_ipv4(self.tcp_target):\n self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nelif is_ipv6(self.tcp_target):\n self.tcp_client = socket.socket(... | <|body_start_0|>
self.tcp_target = tcp_target
self.tcp_port = tcp_port
self.verbosity = verbosity
self.peer = '{}:{}'.format(self.tcp_target, self.tcp_port)
if is_ipv4(self.tcp_target):
self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif i... | TCP Client provides methods to handle communication with TCP server | TCPCli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCPCli:
"""TCP Client provides methods to handle communication with TCP server"""
def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
"""TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server po... | stack_v2_sparse_classes_36k_train_008231 | 4,620 | permissive | [
{
"docstring": "TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server port :param bool verbosity: display verbose output :return None:",
"name": "__init__",
"signature": "def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False)... | 6 | stack_v2_sparse_classes_30k_train_011024 | Implement the Python class `TCPCli` described below.
Class description:
TCP Client provides methods to handle communication with TCP server
Method signatures and docstrings:
- def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None: TCP client constructor :param str tcp_target: target TCP se... | Implement the Python class `TCPCli` described below.
Class description:
TCP Client provides methods to handle communication with TCP server
Method signatures and docstrings:
- def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None: TCP client constructor :param str tcp_target: target TCP se... | 56ae6325c08bcedd22c57b9fe11b58f1b38314ca | <|skeleton|>
class TCPCli:
"""TCP Client provides methods to handle communication with TCP server"""
def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
"""TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TCPCli:
"""TCP Client provides methods to handle communication with TCP server"""
def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
"""TCP client constructor :param str tcp_target: target TCP server ip address :param int tcp_port: target TCP server port :param boo... | the_stack_v2_python_sparse | maza/core/tcp/tcp_client.py | ArturSpirin/maza | train | 2 |
6b76bd1cd1a9b94de22650905143d43a38582306 | [
"super().vet()\nif 'sensfile' not in self.data.keys():\n msgs.warn('sensfile column not provided. Fluxing will crash if an archived sensitivity function does not exist')\n self.data['sensfile'] = ''",
"sens_files = self.path_and_files('sensfile', skip_blank=True)\nif len(sens_files) == 1 and len(self.filen... | <|body_start_0|>
super().vet()
if 'sensfile' not in self.data.keys():
msgs.warn('sensfile column not provided. Fluxing will crash if an archived sensitivity function does not exist')
self.data['sensfile'] = ''
<|end_body_0|>
<|body_start_1|>
sens_files = self.path_and_f... | Child class for the Fluxing input file | FluxFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FluxFile:
"""Child class for the Fluxing input file"""
def vet(self):
"""Check for required parts of the Fluxing input file and handle the various options for sensfile"""
<|body_0|>
def sensfiles(self):
"""Generate a list of the sensitivity files with the full pa... | stack_v2_sparse_classes_36k_train_008232 | 31,807 | permissive | [
{
"docstring": "Check for required parts of the Fluxing input file and handle the various options for sensfile",
"name": "vet",
"signature": "def vet(self)"
},
{
"docstring": "Generate a list of the sensitivity files with the full path. The files must exist and be within one of the paths (or the... | 2 | null | Implement the Python class `FluxFile` described below.
Class description:
Child class for the Fluxing input file
Method signatures and docstrings:
- def vet(self): Check for required parts of the Fluxing input file and handle the various options for sensfile
- def sensfiles(self): Generate a list of the sensitivity f... | Implement the Python class `FluxFile` described below.
Class description:
Child class for the Fluxing input file
Method signatures and docstrings:
- def vet(self): Check for required parts of the Fluxing input file and handle the various options for sensfile
- def sensfiles(self): Generate a list of the sensitivity f... | 0d2e2196afc6904050b1af4d572f5c643bb07e38 | <|skeleton|>
class FluxFile:
"""Child class for the Fluxing input file"""
def vet(self):
"""Check for required parts of the Fluxing input file and handle the various options for sensfile"""
<|body_0|>
def sensfiles(self):
"""Generate a list of the sensitivity files with the full pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FluxFile:
"""Child class for the Fluxing input file"""
def vet(self):
"""Check for required parts of the Fluxing input file and handle the various options for sensfile"""
super().vet()
if 'sensfile' not in self.data.keys():
msgs.warn('sensfile column not provided. Flu... | the_stack_v2_python_sparse | pypeit/inputfiles.py | pypeit/PypeIt | train | 136 |
b27ecf589b68010197dc32b4fc1e085e11582c80 | [
"self.session = session\nself.entry = entry\n\nasync def async_token_refresh() -> str:\n await session.async_ensure_token_valid()\n return session.token['access_token']\nself.toon = Toon(token=session.token['access_token'], session=async_get_clientsession(hass), token_refresh_method=async_token_refresh)\nsupe... | <|body_start_0|>
self.session = session
self.entry = entry
async def async_token_refresh() -> str:
await session.async_ensure_token_valid()
return session.token['access_token']
self.toon = Toon(token=session.token['access_token'], session=async_get_clientsession(... | Class to manage fetching Toon data from single endpoint. | ToonDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToonDataUpdateCoordinator:
"""Class to manage fetching Toon data from single endpoint."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session) -> None:
"""Initialize global Toon data updater."""
<|body_0|>
async def register_webhook(self... | stack_v2_sparse_classes_36k_train_008233 | 5,405 | permissive | [
{
"docstring": "Initialize global Toon data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session) -> None"
},
{
"docstring": "Register a webhook with Toon to get live updates.",
"name": "register_webhook",
"sig... | 5 | null | Implement the Python class `ToonDataUpdateCoordinator` described below.
Class description:
Class to manage fetching Toon data from single endpoint.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session) -> None: Initialize global Toon data updater.
-... | Implement the Python class `ToonDataUpdateCoordinator` described below.
Class description:
Class to manage fetching Toon data from single endpoint.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session) -> None: Initialize global Toon data updater.
-... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ToonDataUpdateCoordinator:
"""Class to manage fetching Toon data from single endpoint."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session) -> None:
"""Initialize global Toon data updater."""
<|body_0|>
async def register_webhook(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToonDataUpdateCoordinator:
"""Class to manage fetching Toon data from single endpoint."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, session: OAuth2Session) -> None:
"""Initialize global Toon data updater."""
self.session = session
self.entry = entry
a... | the_stack_v2_python_sparse | homeassistant/components/toon/coordinator.py | home-assistant/core | train | 35,501 |
d90269c7c60d93a674d47610815aa5b4deeb5cab | [
"if info and isinstance(info, _Strs):\n if len(info) > 50 or linesep in info:\n raise ValueError('invalid %s: %r' % ('info', info))\n self._info = info\nself._ok = ok if isinstance(ok, _Strs) else 'OK'\nif cancel:\n self._cancel = cancel if isinstance(cancel, _Strs) else 'Cancel'\n if other:\n ... | <|body_start_0|>
if info and isinstance(info, _Strs):
if len(info) > 50 or linesep in info:
raise ValueError('invalid %s: %r' % ('info', info))
self._info = info
self._ok = ok if isinstance(ok, _Strs) else 'OK'
if cancel:
self._cancel = cancel ... | Python Type to show an alert, wrapping ObjC C{NSAlert}. | AlertPanel | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlertPanel:
"""Python Type to show an alert, wrapping ObjC C{NSAlert}."""
def __init__(self, title=_NN_, info=_NN_, ok='OK', cancel=False, other=False, style=AlertStyle.Info, suppressable=False):
"""New L{AlertPanel}. @keyword title: The panel name and title (C{str}). @keyword info: ... | stack_v2_sparse_classes_36k_train_008234 | 20,774 | permissive | [
{
"docstring": "New L{AlertPanel}. @keyword title: The panel name and title (C{str}). @keyword info: Optional, informative message (C{str}). @keyword ok: First, OK button text (C{str}), other than 'OK'. @keyword cancel: Include a second, Cancel button (C{bool} or C{str}). @keyword other: Include a third, Other ... | 2 | stack_v2_sparse_classes_30k_train_005699 | Implement the Python class `AlertPanel` described below.
Class description:
Python Type to show an alert, wrapping ObjC C{NSAlert}.
Method signatures and docstrings:
- def __init__(self, title=_NN_, info=_NN_, ok='OK', cancel=False, other=False, style=AlertStyle.Info, suppressable=False): New L{AlertPanel}. @keyword ... | Implement the Python class `AlertPanel` described below.
Class description:
Python Type to show an alert, wrapping ObjC C{NSAlert}.
Method signatures and docstrings:
- def __init__(self, title=_NN_, info=_NN_, ok='OK', cancel=False, other=False, style=AlertStyle.Info, suppressable=False): New L{AlertPanel}. @keyword ... | 66ef079aafce26706caefcca412a1c614a99dee7 | <|skeleton|>
class AlertPanel:
"""Python Type to show an alert, wrapping ObjC C{NSAlert}."""
def __init__(self, title=_NN_, info=_NN_, ok='OK', cancel=False, other=False, style=AlertStyle.Info, suppressable=False):
"""New L{AlertPanel}. @keyword title: The panel name and title (C{str}). @keyword info: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlertPanel:
"""Python Type to show an alert, wrapping ObjC C{NSAlert}."""
def __init__(self, title=_NN_, info=_NN_, ok='OK', cancel=False, other=False, style=AlertStyle.Info, suppressable=False):
"""New L{AlertPanel}. @keyword title: The panel name and title (C{str}). @keyword info: Optional, inf... | the_stack_v2_python_sparse | pycocoa/panels.py | mrJean1/PyCocoa | train | 15 |
187eff397e6c196a407ea888f6f77a1b74ab251e | [
"mock_comment = mock.MagicMock()\nmock_comment.body = '/gcbrun trial_build.py aiohttp --sanitizer coverage address --fuzzing-engine libfuzzer'\ncomments = [mock_comment]\nexpected_command = ['aiohttp', '--sanitizer', 'coverage', 'address', '--fuzzing-engine', 'libfuzzer']\nactual_command = ci_trial_build.get_latest... | <|body_start_0|>
mock_comment = mock.MagicMock()
mock_comment.body = '/gcbrun trial_build.py aiohttp --sanitizer coverage address --fuzzing-engine libfuzzer'
comments = [mock_comment]
expected_command = ['aiohttp', '--sanitizer', 'coverage', 'address', '--fuzzing-engine', 'libfuzzer']
... | Tests for get_latest_gcbrun_command. | GetLatestGCBrunCommandTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetLatestGCBrunCommandTest:
"""Tests for get_latest_gcbrun_command."""
def test_command_parsing(self):
"""Tests that commands from GitHub comments are parsed properly."""
<|body_0|>
def test_last_comment(self):
"""Tests that the last comment from the GitHub PR is... | stack_v2_sparse_classes_36k_train_008235 | 2,218 | permissive | [
{
"docstring": "Tests that commands from GitHub comments are parsed properly.",
"name": "test_command_parsing",
"signature": "def test_command_parsing(self)"
},
{
"docstring": "Tests that the last comment from the GitHub PR is considered the command.",
"name": "test_last_comment",
"signa... | 2 | stack_v2_sparse_classes_30k_train_006378 | Implement the Python class `GetLatestGCBrunCommandTest` described below.
Class description:
Tests for get_latest_gcbrun_command.
Method signatures and docstrings:
- def test_command_parsing(self): Tests that commands from GitHub comments are parsed properly.
- def test_last_comment(self): Tests that the last comment ... | Implement the Python class `GetLatestGCBrunCommandTest` described below.
Class description:
Tests for get_latest_gcbrun_command.
Method signatures and docstrings:
- def test_command_parsing(self): Tests that commands from GitHub comments are parsed properly.
- def test_last_comment(self): Tests that the last comment ... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class GetLatestGCBrunCommandTest:
"""Tests for get_latest_gcbrun_command."""
def test_command_parsing(self):
"""Tests that commands from GitHub comments are parsed properly."""
<|body_0|>
def test_last_comment(self):
"""Tests that the last comment from the GitHub PR is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetLatestGCBrunCommandTest:
"""Tests for get_latest_gcbrun_command."""
def test_command_parsing(self):
"""Tests that commands from GitHub comments are parsed properly."""
mock_comment = mock.MagicMock()
mock_comment.body = '/gcbrun trial_build.py aiohttp --sanitizer coverage addre... | the_stack_v2_python_sparse | infra/build/functions/ci_trial_build_test.py | google/oss-fuzz | train | 9,438 |
f076b38a31c15a6ce54a7ff1c79162ccfe17464d | [
"x_values = []\ny_values = []\nfor i, row in enumerate(grid):\n for j, val in enumerate(row):\n if val == 1:\n x_values.append(i)\n y_values.append(j)\nx_values.sort()\ny_values.sort()\nif x_values:\n return self.get_min_dist(x_values) + self.get_min_dist(y_values)\nelse:\n ret... | <|body_start_0|>
x_values = []
y_values = []
for i, row in enumerate(grid):
for j, val in enumerate(row):
if val == 1:
x_values.append(i)
y_values.append(j)
x_values.sort()
y_values.sort()
if x_values:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minTotalDistance(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def get_min_dist(self, arr):
"""https://en.wikipedia.org/wiki/Median_absolute_deviation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
x_values = ... | stack_v2_sparse_classes_36k_train_008236 | 1,717 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minTotalDistance",
"signature": "def minTotalDistance(self, grid)"
},
{
"docstring": "https://en.wikipedia.org/wiki/Median_absolute_deviation.",
"name": "get_min_dist",
"signature": "def get_min_dist(self, arr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001978 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minTotalDistance(self, grid): :type grid: List[List[int]] :rtype: int
- def get_min_dist(self, arr): https://en.wikipedia.org/wiki/Median_absolute_deviation. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minTotalDistance(self, grid): :type grid: List[List[int]] :rtype: int
- def get_min_dist(self, arr): https://en.wikipedia.org/wiki/Median_absolute_deviation.
<|skeleton|>
cl... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def minTotalDistance(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def get_min_dist(self, arr):
"""https://en.wikipedia.org/wiki/Median_absolute_deviation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minTotalDistance(self, grid):
""":type grid: List[List[int]] :rtype: int"""
x_values = []
y_values = []
for i, row in enumerate(grid):
for j, val in enumerate(row):
if val == 1:
x_values.append(i)
... | the_stack_v2_python_sparse | math/leetcode_Best_Meeting_Point.py | monkeylyf/interviewjam | train | 59 | |
88275f7142b479087596e4887fbb824f1f9597aa | [
"params = base.get_params(None, locals())\nurl = '{0}/deals'.format(self.get_url())\nreturn (http.Request('GET', url, params), parsers.parse_json)",
"params = base.get_params(None, locals())\nurl = '{0}/conversion_statistics'.format(self.get_url())\nreturn (http.Request('GET', url, params), parsers.parse_json)",
... | <|body_start_0|>
params = base.get_params(None, locals())
url = '{0}/deals'.format(self.get_url())
return (http.Request('GET', url, params), parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_params(None, locals())
url = '{0}/conversion_statistics'.format(self... | Pipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pipeline:
def deals(self, filter_id=None, user_id=None, everyone=None, stage_id=None, start=None, limit=None):
"""Lists deals in a specific pipeline across all its stages. Upstream documentation: https://developers.pipedrive.com/v1#methods-Pipelines"""
<|body_0|>
def convers... | stack_v2_sparse_classes_36k_train_008237 | 2,938 | permissive | [
{
"docstring": "Lists deals in a specific pipeline across all its stages. Upstream documentation: https://developers.pipedrive.com/v1#methods-Pipelines",
"name": "deals",
"signature": "def deals(self, filter_id=None, user_id=None, everyone=None, stage_id=None, start=None, limit=None)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_008705 | Implement the Python class `Pipeline` described below.
Class description:
Implement the Pipeline class.
Method signatures and docstrings:
- def deals(self, filter_id=None, user_id=None, everyone=None, stage_id=None, start=None, limit=None): Lists deals in a specific pipeline across all its stages. Upstream documentat... | Implement the Python class `Pipeline` described below.
Class description:
Implement the Pipeline class.
Method signatures and docstrings:
- def deals(self, filter_id=None, user_id=None, everyone=None, stage_id=None, start=None, limit=None): Lists deals in a specific pipeline across all its stages. Upstream documentat... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Pipeline:
def deals(self, filter_id=None, user_id=None, everyone=None, stage_id=None, start=None, limit=None):
"""Lists deals in a specific pipeline across all its stages. Upstream documentation: https://developers.pipedrive.com/v1#methods-Pipelines"""
<|body_0|>
def convers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pipeline:
def deals(self, filter_id=None, user_id=None, everyone=None, stage_id=None, start=None, limit=None):
"""Lists deals in a specific pipeline across all its stages. Upstream documentation: https://developers.pipedrive.com/v1#methods-Pipelines"""
params = base.get_params(None, locals())
... | the_stack_v2_python_sparse | libsaas/services/pipedrive/pipelines.py | piplcom/libsaas | train | 1 | |
71322aad0e5f5652bfd1fbcec3dc673e62f544d1 | [
"if not root:\n return None\nroot.right, root.left = (root.left, root.right)\nself.invertTree(root.left)\nself.invertTree(root.right)\nreturn root",
"if not root:\n return None\nqueue = [root]\nwhile queue:\n temp = queue.pop(0)\n temp.left, temp.right = (temp.right, temp.left)\n if temp.left:\n ... | <|body_start_0|>
if not root:
return None
root.right, root.left = (root.left, root.right)
self.invertTree(root.left)
self.invertTree(root.right)
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return None
queue = [root]
wh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""递归来解决 时间复杂度:每个元素都必须访问一次,所以是 O(n) 空间复杂度:最坏的情况下,需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)"""
<|body_0|>
def invertTree_iteration(self, root: TreeNode) -> TreeNode:
"""迭代更新 时间复杂度:同样每个节点都需要入队列/出队列一次,所以是 O(n) 空间复杂度:最坏的... | stack_v2_sparse_classes_36k_train_008238 | 1,563 | no_license | [
{
"docstring": "递归来解决 时间复杂度:每个元素都必须访问一次,所以是 O(n) 空间复杂度:最坏的情况下,需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)",
"name": "invertTree",
"signature": "def invertTree(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "迭代更新 时间复杂度:同样每个节点都需要入队列/出队列一次,所以是 O(n) 空间复杂度:最坏的情况下会包含所有的叶子节点,完全二叉树叶子节点是 n/2个,所以时间复杂度是 0(n) :p... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: TreeNode) -> TreeNode: 递归来解决 时间复杂度:每个元素都必须访问一次,所以是 O(n) 空间复杂度:最坏的情况下,需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)
- def invertTree_iteration(self, root: TreeNode) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: TreeNode) -> TreeNode: 递归来解决 时间复杂度:每个元素都必须访问一次,所以是 O(n) 空间复杂度:最坏的情况下,需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)
- def invertTree_iteration(self, root: TreeNode) ... | 3b8b36bcf8a983de4d8ce29734a85b6bfbe59fbc | <|skeleton|>
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""递归来解决 时间复杂度:每个元素都必须访问一次,所以是 O(n) 空间复杂度:最坏的情况下,需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)"""
<|body_0|>
def invertTree_iteration(self, root: TreeNode) -> TreeNode:
"""迭代更新 时间复杂度:同样每个节点都需要入队列/出队列一次,所以是 O(n) 空间复杂度:最坏的... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""递归来解决 时间复杂度:每个元素都必须访问一次,所以是 O(n) 空间复杂度:最坏的情况下,需要存放 O(h) 个函数调用(h是树的高度),所以是 O(h)"""
if not root:
return None
root.right, root.left = (root.left, root.right)
self.invertTree(root.left)
self.invertTr... | the_stack_v2_python_sparse | Leetcode/226. Invert Binary Tree.py | a625687551/Leetcode | train | 0 | |
e7391aafab8f0e63f9d1488503acf607fe9f0ed1 | [
"if 0 <= i <= 2:\n if 0 <= j <= 2:\n return 0\n elif 3 <= j <= 5:\n return 1\n else:\n return 2\nelif 3 <= i <= 5:\n if 0 <= j <= 2:\n return 3\n elif 3 <= j <= 5:\n return 4\n else:\n return 5\nelif 0 <= j <= 2:\n return 6\nelif 3 <= j <= 5:\n retur... | <|body_start_0|>
if 0 <= i <= 2:
if 0 <= j <= 2:
return 0
elif 3 <= j <= 5:
return 1
else:
return 2
elif 3 <= i <= 5:
if 0 <= j <= 2:
return 3
elif 3 <= j <= 5:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_square(self, i, j):
"""Returns a number of a square(0 - 8), in which cell(i, j) is located."""
<|body_0|>
def is_good(self, num, i, j, rows, cols, squares):
"""Returns True if we can place num in cell(i, j), False otherwise."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_008239 | 4,969 | no_license | [
{
"docstring": "Returns a number of a square(0 - 8), in which cell(i, j) is located.",
"name": "find_square",
"signature": "def find_square(self, i, j)"
},
{
"docstring": "Returns True if we can place num in cell(i, j), False otherwise.",
"name": "is_good",
"signature": "def is_good(self... | 6 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_square(self, i, j): Returns a number of a square(0 - 8), in which cell(i, j) is located.
- def is_good(self, num, i, j, rows, cols, squares): Returns True if we can plac... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_square(self, i, j): Returns a number of a square(0 - 8), in which cell(i, j) is located.
- def is_good(self, num, i, j, rows, cols, squares): Returns True if we can plac... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def find_square(self, i, j):
"""Returns a number of a square(0 - 8), in which cell(i, j) is located."""
<|body_0|>
def is_good(self, num, i, j, rows, cols, squares):
"""Returns True if we can place num in cell(i, j), False otherwise."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find_square(self, i, j):
"""Returns a number of a square(0 - 8), in which cell(i, j) is located."""
if 0 <= i <= 2:
if 0 <= j <= 2:
return 0
elif 3 <= j <= 5:
return 1
else:
return 2
elif ... | the_stack_v2_python_sparse | Backtracking/sudoku/sudoku_solver.py | vladn90/Algorithms | train | 0 | |
7c3c5e87f9ada0fb82af9dd988e90bf85eb56c95 | [
"super(MonitorWrapper, self).__init__(env=env)\nself._output_fname = output_fname\nself._downsample_factor = downsample_factor\nself._recorder = imageio.get_writer(self._output_fname, mode='I')",
"observation = self.env.reset(*args, **kwargs)\nself._record_frame()\nreturn observation",
"observation, reward, don... | <|body_start_0|>
super(MonitorWrapper, self).__init__(env=env)
self._output_fname = output_fname
self._downsample_factor = downsample_factor
self._recorder = imageio.get_writer(self._output_fname, mode='I')
<|end_body_0|>
<|body_start_1|>
observation = self.env.reset(*args, **kw... | Records a video of the episode. | MonitorWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitorWrapper:
"""Records a video of the episode."""
def __init__(self, env: gym.Env, *, output_fname: str, downsample_factor: int=1) -> None:
"""Constructs a gym wrapper to record a video of the episode."""
<|body_0|>
def reset(self, *args: Any, **kwargs: Any) -> Obser... | stack_v2_sparse_classes_36k_train_008240 | 8,971 | permissive | [
{
"docstring": "Constructs a gym wrapper to record a video of the episode.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, *, output_fname: str, downsample_factor: int=1) -> None"
},
{
"docstring": "Resets the wrapped environment and initializes a new episode.",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_003688 | Implement the Python class `MonitorWrapper` described below.
Class description:
Records a video of the episode.
Method signatures and docstrings:
- def __init__(self, env: gym.Env, *, output_fname: str, downsample_factor: int=1) -> None: Constructs a gym wrapper to record a video of the episode.
- def reset(self, *ar... | Implement the Python class `MonitorWrapper` described below.
Class description:
Records a video of the episode.
Method signatures and docstrings:
- def __init__(self, env: gym.Env, *, output_fname: str, downsample_factor: int=1) -> None: Constructs a gym wrapper to record a video of the episode.
- def reset(self, *ar... | 1680aee77a53228412f9bab34068f0a9576c58e3 | <|skeleton|>
class MonitorWrapper:
"""Records a video of the episode."""
def __init__(self, env: gym.Env, *, output_fname: str, downsample_factor: int=1) -> None:
"""Constructs a gym wrapper to record a video of the episode."""
<|body_0|>
def reset(self, *args: Any, **kwargs: Any) -> Obser... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonitorWrapper:
"""Records a video of the episode."""
def __init__(self, env: gym.Env, *, output_fname: str, downsample_factor: int=1) -> None:
"""Constructs a gym wrapper to record a video of the episode."""
super(MonitorWrapper, self).__init__(env=env)
self._output_fname = outpu... | the_stack_v2_python_sparse | oatomobile/core/rl.py | OATML/oatomobile | train | 177 |
c1f0133854a286ef1d98264f6c5912d7faaceb94 | [
"raise DeprecationWarning('This endpoint has been closed to public access')\nendpoint = 'locations_getmoments'\nparams = clean_locals(locals())\nr = self.request(endpoint, params)\nif len(r) > 0:\n try:\n headers = ['TeamID', 'PlayerID', 'x_loc', 'y_loc', 'Radius', 'MomentID', 'GameClock', 'ShotClock', 'E... | <|body_start_0|>
raise DeprecationWarning('This endpoint has been closed to public access')
endpoint = 'locations_getmoments'
params = clean_locals(locals())
r = self.request(endpoint, params)
if len(r) > 0:
try:
headers = ['TeamID', 'PlayerID', 'x_loc... | Events | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Events:
def get_moments(self, game_id, event_id):
"""***Blocked Cannot Access*** Get location moments for each player throughout a single game event. :param game_id: ID of the game to get location data from. :type game_id: str :param event_id: ID of specific game event. :type event_id: i... | stack_v2_sparse_classes_36k_train_008241 | 3,519 | permissive | [
{
"docstring": "***Blocked Cannot Access*** Get location moments for each player throughout a single game event. :param game_id: ID of the game to get location data from. :type game_id: str :param event_id: ID of specific game event. :type event_id: int :returns: location data for each snapshot in the event. :r... | 2 | stack_v2_sparse_classes_30k_train_019064 | Implement the Python class `Events` described below.
Class description:
Implement the Events class.
Method signatures and docstrings:
- def get_moments(self, game_id, event_id): ***Blocked Cannot Access*** Get location moments for each player throughout a single game event. :param game_id: ID of the game to get locat... | Implement the Python class `Events` described below.
Class description:
Implement the Events class.
Method signatures and docstrings:
- def get_moments(self, game_id, event_id): ***Blocked Cannot Access*** Get location moments for each player throughout a single game event. :param game_id: ID of the game to get locat... | 87feec5fc8ff6654fdb65229a047e0ff3023a9ff | <|skeleton|>
class Events:
def get_moments(self, game_id, event_id):
"""***Blocked Cannot Access*** Get location moments for each player throughout a single game event. :param game_id: ID of the game to get location data from. :type game_id: str :param event_id: ID of specific game event. :type event_id: i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Events:
def get_moments(self, game_id, event_id):
"""***Blocked Cannot Access*** Get location moments for each player throughout a single game event. :param game_id: ID of the game to get location data from. :type game_id: str :param event_id: ID of specific game event. :type event_id: int :returns: l... | the_stack_v2_python_sparse | nba/endpoints/events.py | rozzac90/nba | train | 1 | |
b3c1daa337ed1b01db05f4dd3a428f4de5ececc4 | [
"self.last_protection_run_summary = last_protection_run_summary\nself.pagination_cookie = pagination_cookie\nself.protected_sources_summary = protected_sources_summary\nself.protection_jobs_summary = protection_jobs_summary\nself.protection_policy = protection_policy\nself.protection_runs_summary = protection_runs_... | <|body_start_0|>
self.last_protection_run_summary = last_protection_run_summary
self.pagination_cookie = pagination_cookie
self.protected_sources_summary = protected_sources_summary
self.protection_jobs_summary = protection_jobs_summary
self.protection_policy = protection_policy
... | Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the related Protection Sources and Protection Jobs. pagin... | ProtectionPolicySummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionPolicySummary:
"""Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the re... | stack_v2_sparse_classes_36k_train_008242 | 5,366 | permissive | [
{
"docstring": "Constructor for the ProtectionPolicySummary class",
"name": "__init__",
"signature": "def __init__(self, last_protection_run_summary=None, pagination_cookie=None, protected_sources_summary=None, protection_jobs_summary=None, protection_policy=None, protection_runs_summary=None)"
},
{... | 2 | null | Implement the Python class `ProtectionPolicySummary` described below.
Class description:
Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of... | Implement the Python class `ProtectionPolicySummary` described below.
Class description:
Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionPolicySummary:
"""Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectionPolicySummary:
"""Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the related Protect... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_policy_summary.py | cohesity/management-sdk-python | train | 24 |
f18f3cfc4abc6dec6f740b7fc0eae25cde99245f | [
"icrs_coord = target.coord.transform_to('icrs')\nhms, dms = icrs_coord.to_string('hmsdms', sep=':').split(' ')\nsexagesimal = JsonTarget(ra=hms, dec=dms, reference_frame=icrs_coord.frame.name, target_name=target.target_name)\nreturn sexagesimal",
"target_name = data['target_name']\nhms = data['ra']\ndms = data['d... | <|body_start_0|>
icrs_coord = target.coord.transform_to('icrs')
hms, dms = icrs_coord.to_string('hmsdms', sep=':').split(' ')
sexagesimal = JsonTarget(ra=hms, dec=dms, reference_frame=icrs_coord.frame.name, target_name=target.target_name)
return sexagesimal
<|end_body_0|>
<|body_start_1... | Marshmallow schema for the subarray_node.Target class | TargetSchema | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetSchema:
"""Marshmallow schema for the subarray_node.Target class"""
def convert_to_icrs(self, target: configure_msgs.Target, **_):
"""Process Target co-ordinates by converting them to ICRS frame before the JSON marshalling process begins. :param target: Target instance to proce... | stack_v2_sparse_classes_36k_train_008243 | 6,676 | permissive | [
{
"docstring": "Process Target co-ordinates by converting them to ICRS frame before the JSON marshalling process begins. :param target: Target instance to process :param _: kwargs passed by Marshallow :return: SexagesimalTarget with ICRS ra/dec expressed in hms/dms",
"name": "convert_to_icrs",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_004612 | Implement the Python class `TargetSchema` described below.
Class description:
Marshmallow schema for the subarray_node.Target class
Method signatures and docstrings:
- def convert_to_icrs(self, target: configure_msgs.Target, **_): Process Target co-ordinates by converting them to ICRS frame before the JSON marshallin... | Implement the Python class `TargetSchema` described below.
Class description:
Marshmallow schema for the subarray_node.Target class
Method signatures and docstrings:
- def convert_to_icrs(self, target: configure_msgs.Target, **_): Process Target co-ordinates by converting them to ICRS frame before the JSON marshallin... | 87083655aca8f8f53a26dba253a0189d8519714b | <|skeleton|>
class TargetSchema:
"""Marshmallow schema for the subarray_node.Target class"""
def convert_to_icrs(self, target: configure_msgs.Target, **_):
"""Process Target co-ordinates by converting them to ICRS frame before the JSON marshalling process begins. :param target: Target instance to proce... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetSchema:
"""Marshmallow schema for the subarray_node.Target class"""
def convert_to_icrs(self, target: configure_msgs.Target, **_):
"""Process Target co-ordinates by converting them to ICRS frame before the JSON marshalling process begins. :param target: Target instance to process :param _: ... | the_stack_v2_python_sparse | src/ska_tmc_cdm/schemas/subarray_node/configure/core.py | ska-telescope/cdm-shared-library | train | 0 |
ef57f740108f96b9686b4b3f2beb38c96836d6c4 | [
"self.set_default_value_mode(DefaultValue.Dict, default)\nif key is not None and (not isinstance(key, Member)):\n opt, types = is_optional(extract_types(key))\n key = Instance(types, optional=opt)\nif value is not None and (not isinstance(value, Member)):\n opt, types = is_optional(extract_types(value))\n ... | <|body_start_0|>
self.set_default_value_mode(DefaultValue.Dict, default)
if key is not None and (not isinstance(key, Member)):
opt, types = is_optional(extract_types(key))
key = Instance(types, optional=opt)
if value is not None and (not isinstance(value, Member)):
... | A value of type `dict`. | Dict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dict:
"""A value of type `dict`."""
def __init__(self, key=None, value=None, default=None):
"""Initialize a Dict. Parameters ---------- key : Member, type, tuple of types, or None, optional A member to use for validating the types of keys allowed in the dict. This can also be a type ... | stack_v2_sparse_classes_36k_train_008244 | 8,471 | permissive | [
{
"docstring": "Initialize a Dict. Parameters ---------- key : Member, type, tuple of types, or None, optional A member to use for validating the types of keys allowed in the dict. This can also be a type or a tuple of types, which will be wrapped with an Instance member. If this is not given, no key validation... | 4 | stack_v2_sparse_classes_30k_train_012039 | Implement the Python class `Dict` described below.
Class description:
A value of type `dict`.
Method signatures and docstrings:
- def __init__(self, key=None, value=None, default=None): Initialize a Dict. Parameters ---------- key : Member, type, tuple of types, or None, optional A member to use for validating the ty... | Implement the Python class `Dict` described below.
Class description:
A value of type `dict`.
Method signatures and docstrings:
- def __init__(self, key=None, value=None, default=None): Initialize a Dict. Parameters ---------- key : Member, type, tuple of types, or None, optional A member to use for validating the ty... | 761a52821d8c77b5718216256963682d11599c1e | <|skeleton|>
class Dict:
"""A value of type `dict`."""
def __init__(self, key=None, value=None, default=None):
"""Initialize a Dict. Parameters ---------- key : Member, type, tuple of types, or None, optional A member to use for validating the types of keys allowed in the dict. This can also be a type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dict:
"""A value of type `dict`."""
def __init__(self, key=None, value=None, default=None):
"""Initialize a Dict. Parameters ---------- key : Member, type, tuple of types, or None, optional A member to use for validating the types of keys allowed in the dict. This can also be a type or a tuple of... | the_stack_v2_python_sparse | atom/dict.py | nucleic/atom | train | 251 |
46d29b031bf6c5c4f2ce7f642e336055f97dacf0 | [
"flavors_controller = self.driver.manager.flavors_controller\nresult = flavors_controller.list()\nflavor_list = [flavor_response.Model(item, self) for item in result]\nreturn {'flavors': flavor_list}",
"flavors_controller = self.driver.manager.flavors_controller\ntry:\n result = flavors_controller.get(flavor_i... | <|body_start_0|>
flavors_controller = self.driver.manager.flavors_controller
result = flavors_controller.list()
flavor_list = [flavor_response.Model(item, self) for item in result]
return {'flavors': flavor_list}
<|end_body_0|>
<|body_start_1|>
flavors_controller = self.driver.m... | FlavorsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlavorsController:
def get_all(self):
"""get all flavor list."""
<|body_0|>
def get_one(self, flavor_id):
"""get_one :param flavor_model :returns JSON flavor(HTTP 200) or HTTP 404"""
<|body_1|>
def post(self):
"""POST :returns JSON flavor(HTTP 20... | stack_v2_sparse_classes_36k_train_008245 | 3,772 | permissive | [
{
"docstring": "get all flavor list.",
"name": "get_all",
"signature": "def get_all(self)"
},
{
"docstring": "get_one :param flavor_model :returns JSON flavor(HTTP 200) or HTTP 404",
"name": "get_one",
"signature": "def get_one(self, flavor_id)"
},
{
"docstring": "POST :returns J... | 4 | stack_v2_sparse_classes_30k_train_019196 | Implement the Python class `FlavorsController` described below.
Class description:
Implement the FlavorsController class.
Method signatures and docstrings:
- def get_all(self): get all flavor list.
- def get_one(self, flavor_id): get_one :param flavor_model :returns JSON flavor(HTTP 200) or HTTP 404
- def post(self):... | Implement the Python class `FlavorsController` described below.
Class description:
Implement the FlavorsController class.
Method signatures and docstrings:
- def get_all(self): get all flavor list.
- def get_one(self, flavor_id): get_one :param flavor_model :returns JSON flavor(HTTP 200) or HTTP 404
- def post(self):... | 0620ff595f8fcaa445b684de99ad130a3c398461 | <|skeleton|>
class FlavorsController:
def get_all(self):
"""get all flavor list."""
<|body_0|>
def get_one(self, flavor_id):
"""get_one :param flavor_model :returns JSON flavor(HTTP 200) or HTTP 404"""
<|body_1|>
def post(self):
"""POST :returns JSON flavor(HTTP 20... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlavorsController:
def get_all(self):
"""get all flavor list."""
flavors_controller = self.driver.manager.flavors_controller
result = flavors_controller.list()
flavor_list = [flavor_response.Model(item, self) for item in result]
return {'flavors': flavor_list}
def ... | the_stack_v2_python_sparse | poppy/transport/pecan/controllers/v1/flavors.py | rackerlabs/poppy | train | 3 | |
e5b841e99865ca938785ae944275e488bfbe2374 | [
"self.min = np.array([0.0, 0.0])\nself.value = 0.0\nself.domain = np.array([[-1, 1], [-1, 1]])\nself.n = 2\nself.smooth = True\nself.info = [True, False, False]\nself.latex_name = 'Sum of Different Powers Function'\nself.latex_type = 'Bowl-Shaped'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = \\\\sum_{i=0}^d |x_i|^... | <|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-1, 1], [-1, 1]])
self.n = 2
self.smooth = True
self.info = [True, False, False]
self.latex_name = 'Sum of Different Powers Function'
self.latex_type = 'Bowl-Shaped'... | Sum of Different Powers Function. | SumOfDifferentPowers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumOfDifferentPowers:
"""Sum of Different Powers Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([0.0, 0.0])
self.val... | stack_v2_sparse_classes_36k_train_008246 | 1,055 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013985 | Implement the Python class `SumOfDifferentPowers` described below.
Class description:
Sum of Different Powers Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `SumOfDifferentPowers` described below.
Class description:
Sum of Different Powers Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class SumOfDifferentPowers:
"""Sum of Different Powers Function."""
de... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class SumOfDifferentPowers:
"""Sum of Different Powers Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SumOfDifferentPowers:
"""Sum of Different Powers Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-1, 1], [-1, 1]])
self.n = 2
self.smooth = True
self.info = [True, False, ... | the_stack_v2_python_sparse | ctf/functions2d/sum_of_different_powers.py | cntaylor/ctf | train | 1 |
05ca6862a977af4021f94b6cbb2c72ceb852579d | [
"if unique_id is not None:\n path = create_url('/v3/table/import_with_id/{db}/{table}/{unique_id}/{format}', db=db, table=table, unique_id=unique_id, format=format)\nelse:\n path = create_url('/v3/table/import/{db}/{table}/{format}', db=db, table=table, format=format)\nkwargs = {}\nwith self.put(path, bytes_o... | <|body_start_0|>
if unique_id is not None:
path = create_url('/v3/table/import_with_id/{db}/{table}/{unique_id}/{format}', db=db, table=table, unique_id=unique_id, format=format)
else:
path = create_url('/v3/table/import/{db}/{table}/{format}', db=db, table=table, format=format)
... | Import data into Treasure Data Service. This class is inherited by :class:`tdclient.api.API`. | ImportAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportAPI:
"""Import data into Treasure Data Service. This class is inherited by :class:`tdclient.api.API`."""
def import_data(self, db, table, format, bytes_or_stream, size, unique_id=None):
"""Import data into Treasure Data Service This method expects data from a file-like object f... | stack_v2_sparse_classes_36k_train_008247 | 2,803 | permissive | [
{
"docstring": "Import data into Treasure Data Service This method expects data from a file-like object formatted with \"msgpack.gz\". Args: db (str): name of a database table (str): name of a table format (str): format of data type (e.g. \"msgpack.gz\") bytes_or_stream (str or file-like): a byte string or a fi... | 2 | stack_v2_sparse_classes_30k_train_002245 | Implement the Python class `ImportAPI` described below.
Class description:
Import data into Treasure Data Service. This class is inherited by :class:`tdclient.api.API`.
Method signatures and docstrings:
- def import_data(self, db, table, format, bytes_or_stream, size, unique_id=None): Import data into Treasure Data S... | Implement the Python class `ImportAPI` described below.
Class description:
Import data into Treasure Data Service. This class is inherited by :class:`tdclient.api.API`.
Method signatures and docstrings:
- def import_data(self, db, table, format, bytes_or_stream, size, unique_id=None): Import data into Treasure Data S... | aa6b1ffe886483cf4a41557d7e72063e49d6c787 | <|skeleton|>
class ImportAPI:
"""Import data into Treasure Data Service. This class is inherited by :class:`tdclient.api.API`."""
def import_data(self, db, table, format, bytes_or_stream, size, unique_id=None):
"""Import data into Treasure Data Service This method expects data from a file-like object f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImportAPI:
"""Import data into Treasure Data Service. This class is inherited by :class:`tdclient.api.API`."""
def import_data(self, db, table, format, bytes_or_stream, size, unique_id=None):
"""Import data into Treasure Data Service This method expects data from a file-like object formatted with... | the_stack_v2_python_sparse | tdclient/import_api.py | treasure-data/td-client-python | train | 41 |
11cc213356675a87161149b8bbc148e91e5ad17f | [
"self.logger = getLogger(__name__)\nif log_handlers:\n for h in log_handlers:\n self.logger.addHandler(h)\nself.logger.debug('Initializing')\nself.latest_version = self.get_latest_version()\nself.logger.debug('Initialized')",
"self.logger.debug('running')\nif self.latest_version < 0:\n self.logger.de... | <|body_start_0|>
self.logger = getLogger(__name__)
if log_handlers:
for h in log_handlers:
self.logger.addHandler(h)
self.logger.debug('Initializing')
self.latest_version = self.get_latest_version()
self.logger.debug('Initialized')
<|end_body_0|>
<|bo... | Checks version number against latest version from the site | VersionChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionChecker:
"""Checks version number against latest version from the site"""
def __init__(self, log_handlers: [StreamHandler]=None):
"""Initialize the version checker :return None:"""
<|body_0|>
def check_version(self) -> int:
"""Compare version numbers. :ret... | stack_v2_sparse_classes_36k_train_008248 | 2,923 | no_license | [
{
"docstring": "Initialize the version checker :return None:",
"name": "__init__",
"signature": "def __init__(self, log_handlers: [StreamHandler]=None)"
},
{
"docstring": "Compare version numbers. :return int: return -1 if unable to get the latest version return 1 if the latest version is newer ... | 3 | stack_v2_sparse_classes_30k_train_010355 | Implement the Python class `VersionChecker` described below.
Class description:
Checks version number against latest version from the site
Method signatures and docstrings:
- def __init__(self, log_handlers: [StreamHandler]=None): Initialize the version checker :return None:
- def check_version(self) -> int: Compare ... | Implement the Python class `VersionChecker` described below.
Class description:
Checks version number against latest version from the site
Method signatures and docstrings:
- def __init__(self, log_handlers: [StreamHandler]=None): Initialize the version checker :return None:
- def check_version(self) -> int: Compare ... | a95d08386b03a44047f5b922456ca3048eb8abd4 | <|skeleton|>
class VersionChecker:
"""Checks version number against latest version from the site"""
def __init__(self, log_handlers: [StreamHandler]=None):
"""Initialize the version checker :return None:"""
<|body_0|>
def check_version(self) -> int:
"""Compare version numbers. :ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VersionChecker:
"""Checks version number against latest version from the site"""
def __init__(self, log_handlers: [StreamHandler]=None):
"""Initialize the version checker :return None:"""
self.logger = getLogger(__name__)
if log_handlers:
for h in log_handlers:
... | the_stack_v2_python_sparse | RSCompanionAsync/Model/version_checker.py | USnark772/RSCompanionV3 | train | 0 |
e327482164e02c7b6e65a1e4d2ecf6dcc8d2c3f2 | [
"if files is None:\n files = Files()\nschema = None\nGenericXML.__init__(self, infile, schema=schema)",
"expect(subgroup is None, 'This class does not support subgroups')\nvalue = None\nnode = None\nnames = item.split('/')\nnode = None\nfor name in names:\n node = self.scan_child(name, root=node)\nif node i... | <|body_start_0|>
if files is None:
files = Files()
schema = None
GenericXML.__init__(self, infile, schema=schema)
<|end_body_0|>
<|body_start_1|>
expect(subgroup is None, 'This class does not support subgroups')
value = None
node = None
names = item.s... | Stream | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stream:
def __init__(self, infile=None, files=None):
"""initialize an object"""
<|body_0|>
def get_value(self, item, attribute=None, resolved=True, subgroup=None):
"""Get Value of fields in a stream.xml file"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008249 | 1,486 | permissive | [
{
"docstring": "initialize an object",
"name": "__init__",
"signature": "def __init__(self, infile=None, files=None)"
},
{
"docstring": "Get Value of fields in a stream.xml file",
"name": "get_value",
"signature": "def get_value(self, item, attribute=None, resolved=True, subgroup=None)"
... | 2 | null | Implement the Python class `Stream` described below.
Class description:
Implement the Stream class.
Method signatures and docstrings:
- def __init__(self, infile=None, files=None): initialize an object
- def get_value(self, item, attribute=None, resolved=True, subgroup=None): Get Value of fields in a stream.xml file | Implement the Python class `Stream` described below.
Class description:
Implement the Stream class.
Method signatures and docstrings:
- def __init__(self, infile=None, files=None): initialize an object
- def get_value(self, item, attribute=None, resolved=True, subgroup=None): Get Value of fields in a stream.xml file
... | 02fad90a379cdbd3c1106cbd63324480f0bf7a22 | <|skeleton|>
class Stream:
def __init__(self, infile=None, files=None):
"""initialize an object"""
<|body_0|>
def get_value(self, item, attribute=None, resolved=True, subgroup=None):
"""Get Value of fields in a stream.xml file"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stream:
def __init__(self, infile=None, files=None):
"""initialize an object"""
if files is None:
files = Files()
schema = None
GenericXML.__init__(self, infile, schema=schema)
def get_value(self, item, attribute=None, resolved=True, subgroup=None):
"""... | the_stack_v2_python_sparse | CIME/XML/stream.py | ESMCI/cime | train | 159 | |
01b8662ad1878d750ad7c1bf8e9c859ddbbd3d95 | [
"super(FFNLateConcat, self).__init__()\nassert embeddings_dim % 2 == 0, 'Are you using concatenated embeddings?'\nself.linear1 = nn.Sequential(nn.Linear(embeddings_dim // 2, hidden_dim), nn.Dropout(dropout), nn.ReLU(), nn.BatchNorm1d(hidden_dim))\nself.linear2 = nn.Sequential(nn.Linear(embeddings_dim // 2, hidden_d... | <|body_start_0|>
super(FFNLateConcat, self).__init__()
assert embeddings_dim % 2 == 0, 'Are you using concatenated embeddings?'
self.linear1 = nn.Sequential(nn.Linear(embeddings_dim // 2, hidden_dim), nn.Dropout(dropout), nn.ReLU(), nn.BatchNorm1d(hidden_dim))
self.linear2 = nn.Sequentia... | FFNLateConcat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFNLateConcat:
def __init__(self, embeddings_dim: int=1024, output_dim: int=12, hidden_dim: int=32, dropout: float=0.25):
"""Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimensi... | stack_v2_sparse_classes_36k_train_008250 | 1,642 | no_license | [
{
"docstring": "Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimension of the hidden layers output_dim: output dimension (number of classes that should be classified) dropout: dropout ratio of every la... | 2 | stack_v2_sparse_classes_30k_train_012189 | Implement the Python class `FFNLateConcat` described below.
Class description:
Implement the FFNLateConcat class.
Method signatures and docstrings:
- def __init__(self, embeddings_dim: int=1024, output_dim: int=12, hidden_dim: int=32, dropout: float=0.25): Simple Feed forward model with default parameters like the ne... | Implement the Python class `FFNLateConcat` described below.
Class description:
Implement the FFNLateConcat class.
Method signatures and docstrings:
- def __init__(self, embeddings_dim: int=1024, output_dim: int=12, hidden_dim: int=32, dropout: float=0.25): Simple Feed forward model with default parameters like the ne... | cf294348cbb838cbbd33f27c3c58d29a88eb137e | <|skeleton|>
class FFNLateConcat:
def __init__(self, embeddings_dim: int=1024, output_dim: int=12, hidden_dim: int=32, dropout: float=0.25):
"""Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimensi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFNLateConcat:
def __init__(self, embeddings_dim: int=1024, output_dim: int=12, hidden_dim: int=32, dropout: float=0.25):
"""Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimension of the hidd... | the_stack_v2_python_sparse | models/legacy/ffn_late_concat.py | bioinformatica/protein-localization | train | 0 | |
5b5a1341f99b8f2af65f172a887530ca8af76967 | [
"print('Please start the Unity simulation and click on the environment window.')\nfor i in range(10):\n print(str(10 - i), end=' ', flush=True)\n time.sleep(1)\nprint('Go!')\nprint('Generating Unity wrapper...', end=' ', flush=True)\nself.keyboard = Controller()\nself.state = self.reset()\nself.timeout = time... | <|body_start_0|>
print('Please start the Unity simulation and click on the environment window.')
for i in range(10):
print(str(10 - i), end=' ', flush=True)
time.sleep(1)
print('Go!')
print('Generating Unity wrapper...', end=' ', flush=True)
self.keyboard ... | Machine learning class that uses a neural network to output trained actions based on current states. | Unity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unity:
"""Machine learning class that uses a neural network to output trained actions based on current states."""
def __init__(self, timeout: int=60):
"""Initialise the neural network."""
<|body_0|>
def reset(self):
"""Reset the environment (returns state)."""
... | stack_v2_sparse_classes_36k_train_008251 | 4,251 | no_license | [
{
"docstring": "Initialise the neural network.",
"name": "__init__",
"signature": "def __init__(self, timeout: int=60)"
},
{
"docstring": "Reset the environment (returns state).",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "Time step the environment.",
... | 5 | stack_v2_sparse_classes_30k_train_008357 | Implement the Python class `Unity` described below.
Class description:
Machine learning class that uses a neural network to output trained actions based on current states.
Method signatures and docstrings:
- def __init__(self, timeout: int=60): Initialise the neural network.
- def reset(self): Reset the environment (... | Implement the Python class `Unity` described below.
Class description:
Machine learning class that uses a neural network to output trained actions based on current states.
Method signatures and docstrings:
- def __init__(self, timeout: int=60): Initialise the neural network.
- def reset(self): Reset the environment (... | c72db39f7e49bd2c4ba9d8446f6ac7b3678928fd | <|skeleton|>
class Unity:
"""Machine learning class that uses a neural network to output trained actions based on current states."""
def __init__(self, timeout: int=60):
"""Initialise the neural network."""
<|body_0|>
def reset(self):
"""Reset the environment (returns state)."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Unity:
"""Machine learning class that uses a neural network to output trained actions based on current states."""
def __init__(self, timeout: int=60):
"""Initialise the neural network."""
print('Please start the Unity simulation and click on the environment window.')
for i in rang... | the_stack_v2_python_sparse | Machine_Learning/Unity.py | JamesNunns/Robotics-Group-Studies | train | 8 |
f6444c2a309b59ce75273ddae31e0927135c90d0 | [
"res, stack = ([], [])\nwhile head:\n while stack and stack[-1][1] < head.val:\n res[stack.pop()[0]] = head.val\n stack.append((len(res), head.val))\n res.append(0)\n head = head.next\nreturn res",
"A, node = ([], head)\nwhile node:\n A.append(node.val)\n node = node.next\nstack = []\nfor... | <|body_start_0|>
res, stack = ([], [])
while head:
while stack and stack[-1][1] < head.val:
res[stack.pop()[0]] = head.val
stack.append((len(res), head.val))
res.append(0)
head = head.next
return res
<|end_body_0|>
<|body_start_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextLargerNodes_OJ(self, head):
""":type head: ListNode :rtype: list[int]"""
<|body_0|>
def nextLargerNodes(self, head):
""":type head: ListNode :rtype: list[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res, stack = ([], [])
... | stack_v2_sparse_classes_36k_train_008252 | 2,918 | no_license | [
{
"docstring": ":type head: ListNode :rtype: list[int]",
"name": "nextLargerNodes_OJ",
"signature": "def nextLargerNodes_OJ(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: list[int]",
"name": "nextLargerNodes",
"signature": "def nextLargerNodes(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextLargerNodes_OJ(self, head): :type head: ListNode :rtype: list[int]
- def nextLargerNodes(self, head): :type head: ListNode :rtype: list[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextLargerNodes_OJ(self, head): :type head: ListNode :rtype: list[int]
- def nextLargerNodes(self, head): :type head: ListNode :rtype: list[int]
<|skeleton|>
class Solution:... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def nextLargerNodes_OJ(self, head):
""":type head: ListNode :rtype: list[int]"""
<|body_0|>
def nextLargerNodes(self, head):
""":type head: ListNode :rtype: list[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextLargerNodes_OJ(self, head):
""":type head: ListNode :rtype: list[int]"""
res, stack = ([], [])
while head:
while stack and stack[-1][1] < head.val:
res[stack.pop()[0]] = head.val
stack.append((len(res), head.val))
re... | the_stack_v2_python_sparse | code1019NextGreaterNodeInLinkedList.py | cybelewang/leetcode-python | train | 0 | |
2c9de69a49f13f14a8e37bb4b44036914a38c7c6 | [
"cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)\nresponse = create_response(200)\nif cert_setting.count() > 0:\n response.data = {'flag': True}\nelse:\n response.data = {'flag': False}\nreturn response.get_response()",
"cert_setting = WxCertSettings.objects.filter(owner_id=request... | <|body_start_0|>
cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)
response = create_response(200)
if cert_setting.count() > 0:
response.data = {'flag': True}
else:
response.data = {'flag': False}
return response.get_response()
<|en... | Group | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group:
def api_get(request):
"""响应GET"""
<|body_0|>
def get(request):
"""响应GET"""
<|body_1|>
def api_put(request):
"""响应PUT"""
<|body_2|>
def api_post(request):
"""响应POST"""
<|body_3|>
def api_delete(request):
... | stack_v2_sparse_classes_36k_train_008253 | 4,576 | no_license | [
{
"docstring": "响应GET",
"name": "api_get",
"signature": "def api_get(request)"
},
{
"docstring": "响应GET",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "响应PUT",
"name": "api_put",
"signature": "def api_put(request)"
},
{
"docstring": "响应POST",
... | 5 | stack_v2_sparse_classes_30k_train_005715 | Implement the Python class `Group` described below.
Class description:
Implement the Group class.
Method signatures and docstrings:
- def api_get(request): 响应GET
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE | Implement the Python class `Group` described below.
Class description:
Implement the Group class.
Method signatures and docstrings:
- def api_get(request): 响应GET
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE
<|skeleton|>
class Group:
... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Group:
def api_get(request):
"""响应GET"""
<|body_0|>
def get(request):
"""响应GET"""
<|body_1|>
def api_put(request):
"""响应PUT"""
<|body_2|>
def api_post(request):
"""响应POST"""
<|body_3|>
def api_delete(request):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Group:
def api_get(request):
"""响应GET"""
cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)
response = create_response(200)
if cert_setting.count() > 0:
response.data = {'flag': True}
else:
response.data = {'flag': False}
... | the_stack_v2_python_sparse | weapp/apps/customerized_apps/group/group.py | chengdg/weizoom | train | 1 | |
1e611737a52ac21b9885d3d4a26c8c3de1a43cd7 | [
"global _SESSIONS\nif not _SESSIONS:\n from evennia.server.sessionhandler import SESSIONS as _SESSIONS\nif ev_channel:\n channel = search.channel_search(ev_channel)\n if not channel:\n raise RuntimeError(\"Evennia Channel '%s' not found.\" % ev_channel)\n channel = channel[0]\n channel.connect... | <|body_start_0|>
global _SESSIONS
if not _SESSIONS:
from evennia.server.sessionhandler import SESSIONS as _SESSIONS
if ev_channel:
channel = search.channel_search(ev_channel)
if not channel:
raise RuntimeError("Evennia Channel '%s' not found." ... | IMC2 Bot | IMC2Bot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IMC2Bot:
"""IMC2 Bot"""
def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None, imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None):
"""Start by telling the portal to start a new session Args: ev_channel (str, optional): Key of the Evennia channel to connect to... | stack_v2_sparse_classes_36k_train_008254 | 13,744 | permissive | [
{
"docstring": "Start by telling the portal to start a new session Args: ev_channel (str, optional): Key of the Evennia channel to connect to. imc2_network (str, optional): IMC2 network name. imc2_mudname (str, optional): Registered mudname (if not given, use settings.SERVERNAME). imc2_port (int, optional): Por... | 3 | stack_v2_sparse_classes_30k_train_015926 | Implement the Python class `IMC2Bot` described below.
Class description:
IMC2 Bot
Method signatures and docstrings:
- def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None, imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None): Start by telling the portal to start a new session Args: ev_channel ... | Implement the Python class `IMC2Bot` described below.
Class description:
IMC2 Bot
Method signatures and docstrings:
- def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None, imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None): Start by telling the portal to start a new session Args: ev_channel ... | 384d08f9d877c7ad758292822e6f04292fdad047 | <|skeleton|>
class IMC2Bot:
"""IMC2 Bot"""
def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None, imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None):
"""Start by telling the portal to start a new session Args: ev_channel (str, optional): Key of the Evennia channel to connect to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IMC2Bot:
"""IMC2 Bot"""
def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None, imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None):
"""Start by telling the portal to start a new session Args: ev_channel (str, optional): Key of the Evennia channel to connect to. imc2_networ... | the_stack_v2_python_sparse | evennia/players/bots.py | robbintt/evennia | train | 1 |
d9764da633d7d0165f274e36e493ce62af080c72 | [
"super().__init__()\nself.embed_dim, self.n_heads, self.head_dim, self.n_latents = (embed_dim, n_heads, head_dim, n_latents)\nself.qk_layer_norms = config.perceiver_config.qk_layer_norms_perceiver\nself.latents = nn.Parameter(torch.randn(self.n_latents, self.embed_dim), requires_grad=True)\nself.intermediate_dim = ... | <|body_start_0|>
super().__init__()
self.embed_dim, self.n_heads, self.head_dim, self.n_latents = (embed_dim, n_heads, head_dim, n_latents)
self.qk_layer_norms = config.perceiver_config.qk_layer_norms_perceiver
self.latents = nn.Parameter(torch.randn(self.n_latents, self.embed_dim), requ... | IdeficsPerceiverResampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdeficsPerceiverResampler:
def __init__(self, config: IdeficsConfig, embed_dim: int, depth: int, n_heads: int, head_dim: int, n_latents: int) -> None:
"""Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or MAE) of a given dimension,... | stack_v2_sparse_classes_36k_train_008255 | 9,432 | permissive | [
{
"docstring": "Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or MAE) of a given dimension, performs `depth` blocks of cross-attention with a fixed `n_latents` inputs, then returns a Tensor of shape [bsz, n_latents, embed_dim]. :param embed_dim: Dimensi... | 2 | stack_v2_sparse_classes_30k_train_020020 | Implement the Python class `IdeficsPerceiverResampler` described below.
Class description:
Implement the IdeficsPerceiverResampler class.
Method signatures and docstrings:
- def __init__(self, config: IdeficsConfig, embed_dim: int, depth: int, n_heads: int, head_dim: int, n_latents: int) -> None: Instantiates a Perce... | Implement the Python class `IdeficsPerceiverResampler` described below.
Class description:
Implement the IdeficsPerceiverResampler class.
Method signatures and docstrings:
- def __init__(self, config: IdeficsConfig, embed_dim: int, depth: int, n_heads: int, head_dim: int, n_latents: int) -> None: Instantiates a Perce... | 4fa0aff21ee083d0197a898cdf17ff476fae2ac3 | <|skeleton|>
class IdeficsPerceiverResampler:
def __init__(self, config: IdeficsConfig, embed_dim: int, depth: int, n_heads: int, head_dim: int, n_latents: int) -> None:
"""Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or MAE) of a given dimension,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdeficsPerceiverResampler:
def __init__(self, config: IdeficsConfig, embed_dim: int, depth: int, n_heads: int, head_dim: int, n_latents: int) -> None:
"""Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or MAE) of a given dimension, performs `dep... | the_stack_v2_python_sparse | src/transformers/models/idefics/perceiver.py | huggingface/transformers | train | 102,193 | |
f3bde1c5857b8936dd530f1bea88282a04cfdb15 | [
"self.window_sum = 0\nself.window_size = size\nself.window_dq = collections.deque()",
"if self.window_size == 0:\n return 0\nif len(self.window_dq) < self.window_size:\n self.window_dq.append(val)\n self.window_sum += val\n return self.window_sum / float(len(self.window_dq))\nelif len(self.window_dq) ... | <|body_start_0|>
self.window_sum = 0
self.window_size = size
self.window_dq = collections.deque()
<|end_body_0|>
<|body_start_1|>
if self.window_size == 0:
return 0
if len(self.window_dq) < self.window_size:
self.window_dq.append(val)
self.win... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.window_sum = 0
self.wind... | stack_v2_sparse_classes_36k_train_008256 | 924 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | f05aac9aeadec1febe4c8323849c0a9f07a1fd1c | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.window_sum = 0
self.window_size = size
self.window_dq = collections.deque()
def next(self, val):
""":type val: int :rtype: float"""
if self.window_size ... | the_stack_v2_python_sparse | Mocks/Amazon/Easy/346.Moving_Average_from_Data_Stream.py | ramakanthd92/LeetCode | train | 2 | |
b675b1a64fc89fedc36ca5187474ba5c2ef399b7 | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(units=vocab)",
"batch, units = s_pre... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Den... | doc | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""doc"""
def __init__(self, vocab, embedding, units, batch):
"""doc"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""doc"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(RNNDecoder, self).__init__()
self.embed... | stack_v2_sparse_classes_36k_train_008257 | 1,304 | no_license | [
{
"docstring": "doc",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "doc",
"name": "call",
"signature": "def call(self, x, s_prev, hidden_states)"
}
] | 2 | null | Implement the Python class `RNNDecoder` described below.
Class description:
doc
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): doc
- def call(self, x, s_prev, hidden_states): doc | Implement the Python class `RNNDecoder` described below.
Class description:
doc
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): doc
- def call(self, x, s_prev, hidden_states): doc
<|skeleton|>
class RNNDecoder:
"""doc"""
def __init__(self, vocab, embedding, units, bat... | 3bffd1391b3fc790f0137d0afbe90eb8e2f7d713 | <|skeleton|>
class RNNDecoder:
"""doc"""
def __init__(self, vocab, embedding, units, batch):
"""doc"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""doc"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""doc"""
def __init__(self, vocab, embedding, units, batch):
"""doc"""
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=units, recurrent_initializer='gloro... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | pafuentess/holbertonschool-machine_learning | train | 0 |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"try:\n show = db.show_by_id(show_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('Show with ID %s not found' % show_id)\nargs = series_list_parser.parse_args()\nbegin = args.get('begin')\nlatest = args.get('latest')\nreturn jsonify(series_details(show, begin, latest))",
"try:\n show = ... | <|body_start_0|>
try:
show = db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('Show with ID %s not found' % show_id)
args = series_list_parser.parse_args()
begin = args.get('begin')
latest = args.get('latest')
retur... | SeriesShowAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
<|body_0|>
def delete(self, show_id, session):
"""Remove series from DB"""
<|body_1|>
def put(self, show_id, session):
"""Set the initial episode of an existing show"""
... | stack_v2_sparse_classes_36k_train_008258 | 47,001 | permissive | [
{
"docstring": "Get show details by ID",
"name": "get",
"signature": "def get(self, show_id, session)"
},
{
"docstring": "Remove series from DB",
"name": "delete",
"signature": "def delete(self, show_id, session)"
},
{
"docstring": "Set the initial episode of an existing show",
... | 3 | stack_v2_sparse_classes_30k_val_000235 | Implement the Python class `SeriesShowAPI` described below.
Class description:
Implement the SeriesShowAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get show details by ID
- def delete(self, show_id, session): Remove series from DB
- def put(self, show_id, session): Set the initial e... | Implement the Python class `SeriesShowAPI` described below.
Class description:
Implement the SeriesShowAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get show details by ID
- def delete(self, show_id, session): Remove series from DB
- def put(self, show_id, session): Set the initial e... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
<|body_0|>
def delete(self, show_id, session):
"""Remove series from DB"""
<|body_1|>
def put(self, show_id, session):
"""Set the initial episode of an existing show"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeriesShowAPI:
def get(self, show_id, session):
"""Get show details by ID"""
try:
show = db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('Show with ID %s not found' % show_id)
args = series_list_parser.parse_args()
... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
897fbe15b4915c216ea5e4d98c3e4faa4676b9a2 | [
"user = self._val_service.validate_user_model(data)\ntoken = self._auth_service.get_token(user.email)\nuser.access_token = token\nuser.updated_at = dt.datetime.utcnow()\nuser.save()\nreturn user",
"email = data['email']\npassword = data['password']\nif email is None:\n raise ValueError('Email is required.')\ni... | <|body_start_0|>
user = self._val_service.validate_user_model(data)
token = self._auth_service.get_token(user.email)
user.access_token = token
user.updated_at = dt.datetime.utcnow()
user.save()
return user
<|end_body_0|>
<|body_start_1|>
email = data['email']
... | AuthRepository | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthRepository:
def register_user(self, data: dict) -> User:
"""Allows a user to register a new account."""
<|body_0|>
def login(self, data: dict) -> User:
"""Allows a user to login with email and password."""
<|body_1|>
def logout(self, context: dict) -... | stack_v2_sparse_classes_36k_train_008259 | 2,377 | permissive | [
{
"docstring": "Allows a user to register a new account.",
"name": "register_user",
"signature": "def register_user(self, data: dict) -> User"
},
{
"docstring": "Allows a user to login with email and password.",
"name": "login",
"signature": "def login(self, data: dict) -> User"
},
{... | 3 | stack_v2_sparse_classes_30k_test_000800 | Implement the Python class `AuthRepository` described below.
Class description:
Implement the AuthRepository class.
Method signatures and docstrings:
- def register_user(self, data: dict) -> User: Allows a user to register a new account.
- def login(self, data: dict) -> User: Allows a user to login with email and pas... | Implement the Python class `AuthRepository` described below.
Class description:
Implement the AuthRepository class.
Method signatures and docstrings:
- def register_user(self, data: dict) -> User: Allows a user to register a new account.
- def login(self, data: dict) -> User: Allows a user to login with email and pas... | 41f76fe698380aa946e35d9879dd3997a4ac5520 | <|skeleton|>
class AuthRepository:
def register_user(self, data: dict) -> User:
"""Allows a user to register a new account."""
<|body_0|>
def login(self, data: dict) -> User:
"""Allows a user to login with email and password."""
<|body_1|>
def logout(self, context: dict) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthRepository:
def register_user(self, data: dict) -> User:
"""Allows a user to register a new account."""
user = self._val_service.validate_user_model(data)
token = self._auth_service.get_token(user.email)
user.access_token = token
user.updated_at = dt.datetime.utcnow... | the_stack_v2_python_sparse | app/modules/core/auth/repository.py | CraigWhitley/ariadne-mongo-server | train | 2 | |
cb5d53d3bb58a92c74a073661654680e634dca3f | [
"def inner(*args, **kwargs):\n try:\n return f(*args, **kwargs)\n except Exception as e:\n args[0].write('You have this exception')\n args[0].write('Exception in method: %s' % str(f.__name__))\n args[0].write('PYTHON SAYS: %s' % str(e))\n return None\nreturn inner",
"def w... | <|body_start_0|>
def inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
args[0].write('You have this exception')
args[0].write('Exception in method: %s' % str(f.__name__))
args[0].write('PYTHON SAY... | Wrapit class to hold decorator functions | Wrapit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wrapit:
"""Wrapit class to hold decorator functions"""
def _exceptionHandler(f):
"""Decorator to handle exceptions"""
<|body_0|>
def _screenshot(func):
"""Decorator for taking screenshots"""
<|body_1|>
def _check_browser_console_log(func):
""... | stack_v2_sparse_classes_36k_train_008260 | 2,782 | permissive | [
{
"docstring": "Decorator to handle exceptions",
"name": "_exceptionHandler",
"signature": "def _exceptionHandler(f)"
},
{
"docstring": "Decorator for taking screenshots",
"name": "_screenshot",
"signature": "def _screenshot(func)"
},
{
"docstring": "Decorator to check the browse... | 3 | stack_v2_sparse_classes_30k_train_008453 | Implement the Python class `Wrapit` described below.
Class description:
Wrapit class to hold decorator functions
Method signatures and docstrings:
- def _exceptionHandler(f): Decorator to handle exceptions
- def _screenshot(func): Decorator for taking screenshots
- def _check_browser_console_log(func): Decorator to c... | Implement the Python class `Wrapit` described below.
Class description:
Wrapit class to hold decorator functions
Method signatures and docstrings:
- def _exceptionHandler(f): Decorator to handle exceptions
- def _screenshot(func): Decorator for taking screenshots
- def _check_browser_console_log(func): Decorator to c... | 17b9d6095b881c6e9f25f8a467d90fc4bb6cef91 | <|skeleton|>
class Wrapit:
"""Wrapit class to hold decorator functions"""
def _exceptionHandler(f):
"""Decorator to handle exceptions"""
<|body_0|>
def _screenshot(func):
"""Decorator for taking screenshots"""
<|body_1|>
def _check_browser_console_log(func):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wrapit:
"""Wrapit class to hold decorator functions"""
def _exceptionHandler(f):
"""Decorator to handle exceptions"""
def inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
args[0].write('You have this exce... | the_stack_v2_python_sparse | utils/Wrapit.py | qxf2/qxf2-page-object-model | train | 263 |
898844c574a735ddd0b2c73f92daf849c700c4e1 | [
"adm = ApplikationsAdministration()\neintrag = adm.get_listeneintrag_by_id(id)\nadm.delete_listeneintrag(eintrag)\nreturn eintrag",
"adm = ApplikationsAdministration()\neintrag = Listeneintrag.from_dict(api.payload)\nif eintrag is not None:\n eintrag.set_id(id)\n eintrag.set_aenderungs_zeitpunkt_now()\n ... | <|body_start_0|>
adm = ApplikationsAdministration()
eintrag = adm.get_listeneintrag_by_id(id)
adm.delete_listeneintrag(eintrag)
return eintrag
<|end_body_0|>
<|body_start_1|>
adm = ApplikationsAdministration()
eintrag = Listeneintrag.from_dict(api.payload)
if ein... | ListeneintragOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListeneintragOperations:
def delete(self, id):
"""Löschen eines Listeneintrages anhand einer id"""
<|body_0|>
def put(self, id):
"""Update eines durch eine id bestimmten Listeneintrag"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = Applikation... | stack_v2_sparse_classes_36k_train_008261 | 23,456 | no_license | [
{
"docstring": "Löschen eines Listeneintrages anhand einer id",
"name": "delete",
"signature": "def delete(self, id)"
},
{
"docstring": "Update eines durch eine id bestimmten Listeneintrag",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013359 | Implement the Python class `ListeneintragOperations` described below.
Class description:
Implement the ListeneintragOperations class.
Method signatures and docstrings:
- def delete(self, id): Löschen eines Listeneintrages anhand einer id
- def put(self, id): Update eines durch eine id bestimmten Listeneintrag | Implement the Python class `ListeneintragOperations` described below.
Class description:
Implement the ListeneintragOperations class.
Method signatures and docstrings:
- def delete(self, id): Löschen eines Listeneintrages anhand einer id
- def put(self, id): Update eines durch eine id bestimmten Listeneintrag
<|skel... | d4a2b196f21a5379188cb78b31c59d69f739964f | <|skeleton|>
class ListeneintragOperations:
def delete(self, id):
"""Löschen eines Listeneintrages anhand einer id"""
<|body_0|>
def put(self, id):
"""Update eines durch eine id bestimmten Listeneintrag"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListeneintragOperations:
def delete(self, id):
"""Löschen eines Listeneintrages anhand einer id"""
adm = ApplikationsAdministration()
eintrag = adm.get_listeneintrag_by_id(id)
adm.delete_listeneintrag(eintrag)
return eintrag
def put(self, id):
"""Update ein... | the_stack_v2_python_sparse | src/main.py | SvenjaHolzinger/SoftwarePraktikum | train | 0 | |
72949bfc49a65cb824eb63d8dc1a5655dca21f21 | [
"if kwargs.get('urn', None) is not None:\n crs = crs_from_urn(kwargs['urn'])\nelse:\n crs = crs_from_karta(geoms[0].crs)\nif geom._geotype == 'Point':\n g = picogeojson.Point(geom.vertex(), crs)\nelif geom._geotype == 'Line':\n g = picogeojson.LineString(_as_nested_lists(geom.vertices()), crs)\nelif geo... | <|body_start_0|>
if kwargs.get('urn', None) is not None:
crs = crs_from_urn(kwargs['urn'])
else:
crs = crs_from_karta(geoms[0].crs)
if geom._geotype == 'Point':
g = picogeojson.Point(geom.vertex(), crs)
elif geom._geotype == 'Line':
g = pic... | Mixin class to be added to geometry objects, adding geojson functionality. | GeoJSONOutMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoJSONOutMixin:
"""Mixin class to be added to geometry objects, adding geojson functionality."""
def _as_named_tuple(geom, **kwargs):
"""Convert a Geometry instance to a GeoJSON-structured named tuple. Parameters ---------- geom : subtypes of karta.Geometry karta vector geometries t... | stack_v2_sparse_classes_36k_train_008262 | 5,252 | permissive | [
{
"docstring": "Convert a Geometry instance to a GeoJSON-structured named tuple. Parameters ---------- geom : subtypes of karta.Geometry karta vector geometries to convert urn : str, optional URN defining a specific CRS to use Returns ------- Either a Feature or a FeatureCollection Raises ------ TypeError if on... | 3 | stack_v2_sparse_classes_30k_train_019728 | Implement the Python class `GeoJSONOutMixin` described below.
Class description:
Mixin class to be added to geometry objects, adding geojson functionality.
Method signatures and docstrings:
- def _as_named_tuple(geom, **kwargs): Convert a Geometry instance to a GeoJSON-structured named tuple. Parameters ---------- ge... | Implement the Python class `GeoJSONOutMixin` described below.
Class description:
Mixin class to be added to geometry objects, adding geojson functionality.
Method signatures and docstrings:
- def _as_named_tuple(geom, **kwargs): Convert a Geometry instance to a GeoJSON-structured named tuple. Parameters ---------- ge... | b35d8cbcfb62e9f1d826a5c73605d34a0c0990b6 | <|skeleton|>
class GeoJSONOutMixin:
"""Mixin class to be added to geometry objects, adding geojson functionality."""
def _as_named_tuple(geom, **kwargs):
"""Convert a Geometry instance to a GeoJSON-structured named tuple. Parameters ---------- geom : subtypes of karta.Geometry karta vector geometries t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeoJSONOutMixin:
"""Mixin class to be added to geometry objects, adding geojson functionality."""
def _as_named_tuple(geom, **kwargs):
"""Convert a Geometry instance to a GeoJSON-structured named tuple. Parameters ---------- geom : subtypes of karta.Geometry karta vector geometries to convert urn... | the_stack_v2_python_sparse | karta/vector/_geojson.py | AristotleWang/karta | train | 0 |
9bf558bb460aabd2fceea414d998fb0f69312652 | [
"pubsub_stanza = self.xmpp['xep_0060'].stanza\nregister_stanza_plugin(pubsub_stanza.EventItem, stanza)\nself.add_interest(stanza.namespace)\nself.xmpp['xep_0030'].add_feature(stanza.namespace)\nself.xmpp['xep_0060'].map_node_event(stanza.namespace, name)",
"if not isinstance(namespace, set) and (not isinstance(na... | <|body_start_0|>
pubsub_stanza = self.xmpp['xep_0060'].stanza
register_stanza_plugin(pubsub_stanza.EventItem, stanza)
self.add_interest(stanza.namespace)
self.xmpp['xep_0030'].add_feature(stanza.namespace)
self.xmpp['xep_0060'].map_node_event(stanza.namespace, name)
<|end_body_0|... | XEP-0163: Personal Eventing Protocol (PEP) | XEP_0163 | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XEP_0163:
"""XEP-0163: Personal Eventing Protocol (PEP)"""
def register_pep(self, name, stanza):
"""Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from th... | stack_v2_sparse_classes_36k_train_008263 | 4,561 | permissive | [
{
"docstring": "Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from the PEP content's namespace to the given name. :param str name: The event name prefix to use for PEP events. :para... | 4 | stack_v2_sparse_classes_30k_train_003789 | Implement the Python class `XEP_0163` described below.
Class description:
XEP-0163: Personal Eventing Protocol (PEP)
Method signatures and docstrings:
- def register_pep(self, name, stanza): Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Registe... | Implement the Python class `XEP_0163` described below.
Class description:
XEP-0163: Personal Eventing Protocol (PEP)
Method signatures and docstrings:
- def register_pep(self, name, stanza): Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Registe... | cc1d470397de768ffcc41d2ed5ac3118d19f09f5 | <|skeleton|>
class XEP_0163:
"""XEP-0163: Personal Eventing Protocol (PEP)"""
def register_pep(self, name, stanza):
"""Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XEP_0163:
"""XEP-0163: Personal Eventing Protocol (PEP)"""
def register_pep(self, name, stanza):
"""Setup and configure events and stanza registration for the given PEP stanza: - Add disco feature for the PEP content. - Register disco interest in the PEP content. - Map events from the PEP content... | the_stack_v2_python_sparse | sleekxmpp/plugins/xep_0163.py | fritzy/SleekXMPP | train | 658 |
04a8c9d0ae2fe62df133beba6a959cb9cabb8f9c | [
"self.enabled = True\nself.id = TikBreakPoint.next_id\nself.ast_node = ast_node\nTikBreakPoint.next_id += 1\nTikBreakPoint.num_break_points += 1",
"if not other:\n return False\nreturn self.id == other.id",
"source_info = self.ast_node.source_info\nif self.enabled:\n disp = 'yes '\nelse:\n disp = 'no ... | <|body_start_0|>
self.enabled = True
self.id = TikBreakPoint.next_id
self.ast_node = ast_node
TikBreakPoint.next_id += 1
TikBreakPoint.num_break_points += 1
<|end_body_0|>
<|body_start_1|>
if not other:
return False
return self.id == other.id
<|end_bo... | Class TikeBreakPoint | TikBreakPoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TikBreakPoint:
"""Class TikeBreakPoint"""
def __init__(self, ast_node):
"""Initialize class TikBreakPoint Parameters ---------- ast_node: Node of Abstract Syntax Trees This is a Class STMT instance. enable:A parameter for enabling break point Returns ---------- No returns"""
... | stack_v2_sparse_classes_36k_train_008264 | 17,883 | no_license | [
{
"docstring": "Initialize class TikBreakPoint Parameters ---------- ast_node: Node of Abstract Syntax Trees This is a Class STMT instance. enable:A parameter for enabling break point Returns ---------- No returns",
"name": "__init__",
"signature": "def __init__(self, ast_node)"
},
{
"docstring"... | 4 | null | Implement the Python class `TikBreakPoint` described below.
Class description:
Class TikeBreakPoint
Method signatures and docstrings:
- def __init__(self, ast_node): Initialize class TikBreakPoint Parameters ---------- ast_node: Node of Abstract Syntax Trees This is a Class STMT instance. enable:A parameter for enabl... | Implement the Python class `TikBreakPoint` described below.
Class description:
Class TikeBreakPoint
Method signatures and docstrings:
- def __init__(self, ast_node): Initialize class TikBreakPoint Parameters ---------- ast_node: Node of Abstract Syntax Trees This is a Class STMT instance. enable:A parameter for enabl... | 148511a31bfd195df889291946c43bb585acb546 | <|skeleton|>
class TikBreakPoint:
"""Class TikeBreakPoint"""
def __init__(self, ast_node):
"""Initialize class TikBreakPoint Parameters ---------- ast_node: Node of Abstract Syntax Trees This is a Class STMT instance. enable:A parameter for enabling break point Returns ---------- No returns"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TikBreakPoint:
"""Class TikeBreakPoint"""
def __init__(self, ast_node):
"""Initialize class TikBreakPoint Parameters ---------- ast_node: Node of Abstract Syntax Trees This is a Class STMT instance. enable:A parameter for enabling break point Returns ---------- No returns"""
self.enabled ... | the_stack_v2_python_sparse | convertor/huawei/te/tik/debugger.py | jizhuoran/caffe-huawei-atlas-convertor | train | 4 |
e5d8b363f23db4b0d93db547816e629e6c2cd150 | [
"session = web.ctx.session\nnav = get_nav_bar(session)\nip_addr = web.ctx['ip']\npath = web.ctx['fullpath']\nsession.ip = ip_addr\nsession.header = web.ctx.env['HTTP_USER_AGENT']\ndata = web.input()\ntoken = data.reset_token\nusername = search_for_token(token, ip_addr, path)\ntry:\n if session.ip == web.ctx['ip'... | <|body_start_0|>
session = web.ctx.session
nav = get_nav_bar(session)
ip_addr = web.ctx['ip']
path = web.ctx['fullpath']
session.ip = ip_addr
session.header = web.ctx.env['HTTP_USER_AGENT']
data = web.input()
token = data.reset_token
username = sea... | Two_FA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Two_FA:
def GET(self):
"""Get the rest_password form :return: A page with the Change_password form"""
<|body_0|>
def POST(self):
"""Handle input data and change password in database :return: Main page"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008265 | 3,431 | no_license | [
{
"docstring": "Get the rest_password form :return: A page with the Change_password form",
"name": "GET",
"signature": "def GET(self)"
},
{
"docstring": "Handle input data and change password in database :return: Main page",
"name": "POST",
"signature": "def POST(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017119 | Implement the Python class `Two_FA` described below.
Class description:
Implement the Two_FA class.
Method signatures and docstrings:
- def GET(self): Get the rest_password form :return: A page with the Change_password form
- def POST(self): Handle input data and change password in database :return: Main page | Implement the Python class `Two_FA` described below.
Class description:
Implement the Two_FA class.
Method signatures and docstrings:
- def GET(self): Get the rest_password form :return: A page with the Change_password form
- def POST(self): Handle input data and change password in database :return: Main page
<|skel... | 35d7952b815f503bd2c2b72fc4f78cbc25c4540f | <|skeleton|>
class Two_FA:
def GET(self):
"""Get the rest_password form :return: A page with the Change_password form"""
<|body_0|>
def POST(self):
"""Handle input data and change password in database :return: Main page"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Two_FA:
def GET(self):
"""Get the rest_password form :return: A page with the Change_password form"""
session = web.ctx.session
nav = get_nav_bar(session)
ip_addr = web.ctx['ip']
path = web.ctx['fullpath']
session.ip = ip_addr
session.header = web.ctx.en... | the_stack_v2_python_sparse | src/app/views/two_fa.py | Zmrihawy/Pen-testingGroup80 | train | 0 | |
aacecedb5644f50405c09d60a864fd58ec702737 | [
"self.base_path = base_path\nself.folder = folder\nself.ext = ext\nself.prefix = prefix\nself.suffix = suffix\nself.rename = do_rename\nself.files_to_rename = list()",
"directory = os.path.join(self.base_path, self.folder)\nif not os.path.isdir(directory):\n raise RuntimeError('Non-existent folder: {:s}'.forma... | <|body_start_0|>
self.base_path = base_path
self.folder = folder
self.ext = ext
self.prefix = prefix
self.suffix = suffix
self.rename = do_rename
self.files_to_rename = list()
<|end_body_0|>
<|body_start_1|>
directory = os.path.join(self.base_path, self.f... | Rename all files in the folder. | Renamer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Renamer:
"""Rename all files in the folder."""
def __init__(self, base_path, folder, ext, prefix, suffix, do_rename):
""":param base_path: The base path. :param folder: The folder in the base path where files are to be renamed. :param ext: Extension :param prefix: The prefix of the n... | stack_v2_sparse_classes_36k_train_008266 | 5,844 | permissive | [
{
"docstring": ":param base_path: The base path. :param folder: The folder in the base path where files are to be renamed. :param ext: Extension :param prefix: The prefix of the new file name. :param suffix: The suffix of the new file name. :param do_rename: True if renaming is to occur.",
"name": "__init__... | 3 | null | Implement the Python class `Renamer` described below.
Class description:
Rename all files in the folder.
Method signatures and docstrings:
- def __init__(self, base_path, folder, ext, prefix, suffix, do_rename): :param base_path: The base path. :param folder: The folder in the base path where files are to be renamed.... | Implement the Python class `Renamer` described below.
Class description:
Rename all files in the folder.
Method signatures and docstrings:
- def __init__(self, base_path, folder, ext, prefix, suffix, do_rename): :param base_path: The base path. :param folder: The folder in the base path where files are to be renamed.... | e696d92dcdc452cbde5df77d06877404542a3aae | <|skeleton|>
class Renamer:
"""Rename all files in the folder."""
def __init__(self, base_path, folder, ext, prefix, suffix, do_rename):
""":param base_path: The base path. :param folder: The folder in the base path where files are to be renamed. :param ext: Extension :param prefix: The prefix of the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Renamer:
"""Rename all files in the folder."""
def __init__(self, base_path, folder, ext, prefix, suffix, do_rename):
""":param base_path: The base path. :param folder: The folder in the base path where files are to be renamed. :param ext: Extension :param prefix: The prefix of the new file name.... | the_stack_v2_python_sparse | src/Admin/AddTestPrefix.py | Kitware/vtk-examples | train | 162 |
e91db422cfa51cc16646b53f7c3e28bfa1eb264a | [
"if not self.numero_ordine.data:\n self.errlist.append('Manca numero ordine')\nif not self.data_ordine.data:\n self.errlist.append('Manca data ordine')\nif not self.descrizione_ordine.data:\n self.errlist.append('Manca descrizione ordine')\nif not self.costo_ordine.validate():\n self.errlist.append('Cos... | <|body_start_0|>
if not self.numero_ordine.data:
self.errlist.append('Manca numero ordine')
if not self.data_ordine.data:
self.errlist.append('Manca data ordine')
if not self.descrizione_ordine.data:
self.errlist.append('Manca descrizione ordine')
if n... | form per definizione ordine | Ordine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ordine:
"""form per definizione ordine"""
def validate(self):
"""Validazione specifica per il form"""
<|body_0|>
def renderme(self, d_prat):
"""rendering del form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.numero_ordine.data:
... | stack_v2_sparse_classes_36k_train_008267 | 29,683 | no_license | [
{
"docstring": "Validazione specifica per il form",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "rendering del form",
"name": "renderme",
"signature": "def renderme(self, d_prat)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007537 | Implement the Python class `Ordine` described below.
Class description:
form per definizione ordine
Method signatures and docstrings:
- def validate(self): Validazione specifica per il form
- def renderme(self, d_prat): rendering del form | Implement the Python class `Ordine` described below.
Class description:
form per definizione ordine
Method signatures and docstrings:
- def validate(self): Validazione specifica per il form
- def renderme(self, d_prat): rendering del form
<|skeleton|>
class Ordine:
"""form per definizione ordine"""
def vali... | 66f5899eaddc4e0bfcb24cfa04f8573d6dc2eb47 | <|skeleton|>
class Ordine:
"""form per definizione ordine"""
def validate(self):
"""Validazione specifica per il form"""
<|body_0|>
def renderme(self, d_prat):
"""rendering del form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ordine:
"""form per definizione ordine"""
def validate(self):
"""Validazione specifica per il form"""
if not self.numero_ordine.data:
self.errlist.append('Manca numero ordine')
if not self.data_ordine.data:
self.errlist.append('Manca data ordine')
i... | the_stack_v2_python_sparse | bin/forms.py | lfini/acquisti | train | 0 |
85d03b507c8c0f2827bcaceec43ee753d30b3999 | [
"if not root:\n return ''\nres = []\nnodes = queue.Queue()\nnodes.put(root)\nwhile not nodes.empty():\n n = nodes.get()\n if n != None:\n nodes.put(n.left)\n nodes.put(n.right)\n res.append(str(n.val))\n else:\n res.append('null')\nreturn ','.join(res)",
"if len(data) == 0:... | <|body_start_0|>
if not root:
return ''
res = []
nodes = queue.Queue()
nodes.put(root)
while not nodes.empty():
n = nodes.get()
if n != None:
nodes.put(n.left)
nodes.put(n.right)
res.append(str(n.... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_008268 | 1,683 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9a0e41d2d718803eb297430995e464fcab472a55 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
res = []
nodes = queue.Queue()
nodes.put(root)
while not nodes.empty():
n = nodes.get()
if n !=... | the_stack_v2_python_sparse | leetcode/297.py | evinpinar/competitive_python | train | 0 | |
78e10f6bc4b8a3840324f633a5fc7870948f0730 | [
"m = self.gap().InvariantBilinearForm()['matrix'].matrix()\nm.set_immutable()\nreturn m",
"m = self.gap().InvariantQuadraticForm()['matrix'].matrix()\nm.set_immutable()\nreturn m"
] | <|body_start_0|>
m = self.gap().InvariantBilinearForm()['matrix'].matrix()
m.set_immutable()
return m
<|end_body_0|>
<|body_start_1|>
m = self.gap().InvariantQuadraticForm()['matrix'].matrix()
m.set_immutable()
return m
<|end_body_1|>
| OrthogonalMatrixGroup_gap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrthogonalMatrixGroup_gap:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determin... | stack_v2_sparse_classes_36k_train_008269 | 13,931 | no_license | [
{
"docstring": "Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determines the orthogonal group. EXAMPLES:: sage: G = GO(4, GF(7), -1) sage: G.in... | 2 | stack_v2_sparse_classes_30k_train_002589 | Implement the Python class `OrthogonalMatrixGroup_gap` described below.
Class description:
Implement the OrthogonalMatrixGroup_gap class.
Method signatures and docstrings:
- def invariant_bilinear_form(self): Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for eve... | Implement the Python class `OrthogonalMatrixGroup_gap` described below.
Class description:
Implement the OrthogonalMatrixGroup_gap class.
Method signatures and docstrings:
- def invariant_bilinear_form(self): Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for eve... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class OrthogonalMatrixGroup_gap:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrthogonalMatrixGroup_gap:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix `M` such that, for every group element g, the identity `g m g^T = m` holds. In characteristic different from two, this uniquely determines the orthogo... | the_stack_v2_python_sparse | sage/src/sage/groups/matrix_gps/orthogonal.py | bopopescu/geosci | train | 0 | |
cab0d5d07f80fc8bfe05cd39d65bb6fbffdcc099 | [
"if mode == PrimerMode.LYAPUNOV:\n from src.lyap.primer_lyap import PrimerLyap\n return PrimerLyap(f, **kw)\nif mode == PrimerMode.BARRIER:\n xd = kw.get(CegisConfig.XD.k)\n xi = kw.get(CegisConfig.XI.k)\n xu = kw.get(CegisConfig.XU.k)\n from src.barrier.primer_barrier import PrimerBarrier\n re... | <|body_start_0|>
if mode == PrimerMode.LYAPUNOV:
from src.lyap.primer_lyap import PrimerLyap
return PrimerLyap(f, **kw)
if mode == PrimerMode.BARRIER:
xd = kw.get(CegisConfig.XD.k)
xi = kw.get(CegisConfig.XI.k)
xu = kw.get(CegisConfig.XU.k)
... | Primer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Primer:
def create_Primer(f, mode, **kw):
"""Instantiate either a PrimerLyap or PrimerBarrier object, depending on keyword argument 'mode'. :param f: dynamical system as list of sympy expressions or as python function (requires nested functions for domains)."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_008270 | 2,932 | permissive | [
{
"docstring": "Instantiate either a PrimerLyap or PrimerBarrier object, depending on keyword argument 'mode'. :param f: dynamical system as list of sympy expressions or as python function (requires nested functions for domains).",
"name": "create_Primer",
"signature": "def create_Primer(f, mode, **kw)"... | 3 | stack_v2_sparse_classes_30k_train_021029 | Implement the Python class `Primer` described below.
Class description:
Implement the Primer class.
Method signatures and docstrings:
- def create_Primer(f, mode, **kw): Instantiate either a PrimerLyap or PrimerBarrier object, depending on keyword argument 'mode'. :param f: dynamical system as list of sympy expressio... | Implement the Python class `Primer` described below.
Class description:
Implement the Primer class.
Method signatures and docstrings:
- def create_Primer(f, mode, **kw): Instantiate either a PrimerLyap or PrimerBarrier object, depending on keyword argument 'mode'. :param f: dynamical system as list of sympy expressio... | f5b8e2bba80d8792b149ee75b51d3ee74df9b88e | <|skeleton|>
class Primer:
def create_Primer(f, mode, **kw):
"""Instantiate either a PrimerLyap or PrimerBarrier object, depending on keyword argument 'mode'. :param f: dynamical system as list of sympy expressions or as python function (requires nested functions for domains)."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Primer:
def create_Primer(f, mode, **kw):
"""Instantiate either a PrimerLyap or PrimerBarrier object, depending on keyword argument 'mode'. :param f: dynamical system as list of sympy expressions or as python function (requires nested functions for domains)."""
if mode == PrimerMode.LYAPUNOV:
... | the_stack_v2_python_sparse | src/shared/components/Primer.py | liw17015/fossil | train | 0 | |
660e8c3008156b24758079d3954032cbafaf2d3c | [
"create_count = 0\nnext(csvreader)\nfor row in csvreader:\n mt, created = MobilePayTransaction.objects.get_or_create(event=row[0], currency=row[1], amount=Decimal(row[2].replace(',', '.')), mobilepay_created=row[3], comment=row[6], transaction_id=row[7] or None, payment_point=row[9], myshop_number=row[10], defau... | <|body_start_0|>
create_count = 0
next(csvreader)
for row in csvreader:
mt, created = MobilePayTransaction.objects.get_or_create(event=row[0], currency=row[1], amount=Decimal(row[2].replace(',', '.')), mobilepay_created=row[3], comment=row[6], transaction_id=row[7] or None, payment_p... | MobilePayCSVImporter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobilePayCSVImporter:
def import_mobilepay_transfer_csv(csvreader):
"""Import a CSV file with MobilePay transactions. Assumes a CSV structure like in testdata/MobilePay_Transfer_overview_csv_MyShop_25-08-2021_14-09-2021.csv with these headers: Event;Currency;Amount;Date and time;Customer... | stack_v2_sparse_classes_36k_train_008271 | 47,704 | permissive | [
{
"docstring": "Import a CSV file with MobilePay transactions. Assumes a CSV structure like in testdata/MobilePay_Transfer_overview_csv_MyShop_25-08-2021_14-09-2021.csv with these headers: Event;Currency;Amount;Date and time;Customer name;MP-number;Comment;TransactionID;TransferID;Payment point;MyShop-Number;Ba... | 2 | null | Implement the Python class `MobilePayCSVImporter` described below.
Class description:
Implement the MobilePayCSVImporter class.
Method signatures and docstrings:
- def import_mobilepay_transfer_csv(csvreader): Import a CSV file with MobilePay transactions. Assumes a CSV structure like in testdata/MobilePay_Transfer_o... | Implement the Python class `MobilePayCSVImporter` described below.
Class description:
Implement the MobilePayCSVImporter class.
Method signatures and docstrings:
- def import_mobilepay_transfer_csv(csvreader): Import a CSV file with MobilePay transactions. Assumes a CSV structure like in testdata/MobilePay_Transfer_o... | 767deb7f58429e9162e0c2ef79be9f0f38f37ce1 | <|skeleton|>
class MobilePayCSVImporter:
def import_mobilepay_transfer_csv(csvreader):
"""Import a CSV file with MobilePay transactions. Assumes a CSV structure like in testdata/MobilePay_Transfer_overview_csv_MyShop_25-08-2021_14-09-2021.csv with these headers: Event;Currency;Amount;Date and time;Customer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobilePayCSVImporter:
def import_mobilepay_transfer_csv(csvreader):
"""Import a CSV file with MobilePay transactions. Assumes a CSV structure like in testdata/MobilePay_Transfer_overview_csv_MyShop_25-08-2021_14-09-2021.csv with these headers: Event;Currency;Amount;Date and time;Customer name;MP-numbe... | the_stack_v2_python_sparse | src/economy/utils.py | bornhack/bornhack-website | train | 9 | |
4d41dc198bbe1fb5916965a71d6d87258b1c869c | [
"self.config = config\nself.loss = config['network']['loss']\nself.optimizer = self.set_optimizer(self.config['train']['optimizer'], self.config['train']['learning_rate'])",
"if optimizer_name == 'adam':\n optimizer = Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\nelif optimizer... | <|body_start_0|>
self.config = config
self.loss = config['network']['loss']
self.optimizer = self.set_optimizer(self.config['train']['optimizer'], self.config['train']['learning_rate'])
<|end_body_0|>
<|body_start_1|>
if optimizer_name == 'adam':
optimizer = Adam(lr=lr, beta... | BaseModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModel:
def __init__(self, config):
"""Base constructor"""
<|body_0|>
def set_optimizer(self, optimizer_name, lr):
"""Select the optimizer Parameters ------ optimizer_name: name of the optimizer, either adam, sgd, rmsprop, adagrad, adadelta lr: fload learning rate... | stack_v2_sparse_classes_36k_train_008272 | 1,578 | no_license | [
{
"docstring": "Base constructor",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Select the optimizer Parameters ------ optimizer_name: name of the optimizer, either adam, sgd, rmsprop, adagrad, adadelta lr: fload learning rate Raises ------ Exception",
"na... | 2 | stack_v2_sparse_classes_30k_train_000381 | Implement the Python class `BaseModel` described below.
Class description:
Implement the BaseModel class.
Method signatures and docstrings:
- def __init__(self, config): Base constructor
- def set_optimizer(self, optimizer_name, lr): Select the optimizer Parameters ------ optimizer_name: name of the optimizer, either... | Implement the Python class `BaseModel` described below.
Class description:
Implement the BaseModel class.
Method signatures and docstrings:
- def __init__(self, config): Base constructor
- def set_optimizer(self, optimizer_name, lr): Select the optimizer Parameters ------ optimizer_name: name of the optimizer, either... | a4a767f34f735e50dc9e23be1765463a22a56814 | <|skeleton|>
class BaseModel:
def __init__(self, config):
"""Base constructor"""
<|body_0|>
def set_optimizer(self, optimizer_name, lr):
"""Select the optimizer Parameters ------ optimizer_name: name of the optimizer, either adam, sgd, rmsprop, adagrad, adadelta lr: fload learning rate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseModel:
def __init__(self, config):
"""Base constructor"""
self.config = config
self.loss = config['network']['loss']
self.optimizer = self.set_optimizer(self.config['train']['optimizer'], self.config['train']['learning_rate'])
def set_optimizer(self, optimizer_name, lr... | the_stack_v2_python_sparse | base/base_model.py | giovanniguidi/FCN-keras | train | 30 | |
9e50dfaa66c55f1f8831248709f82ddc9703d7d5 | [
"product_id = request.args.get('product_id')\ntenant_id = get_jwt_claims()['tenant_id']\nlogger.debug('Get method is invoked to retrieve a product with product_id {0} and tenant_id {1}'.format(product_id, tenant_id))\nproduct = self.product_service.get(int(product_id), tenant_id)\nreturn results(status='success', m... | <|body_start_0|>
product_id = request.args.get('product_id')
tenant_id = get_jwt_claims()['tenant_id']
logger.debug('Get method is invoked to retrieve a product with product_id {0} and tenant_id {1}'.format(product_id, tenant_id))
product = self.product_service.get(int(product_id), tenan... | ProductController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductController:
def get(self):
"""This controller method is to retrieve an existing product This needs jwt authentication and retrieves user id and tenant id from it It invokes get method in the product service module"""
<|body_0|>
def post(self):
"""This controll... | stack_v2_sparse_classes_36k_train_008273 | 2,762 | no_license | [
{
"docstring": "This controller method is to retrieve an existing product This needs jwt authentication and retrieves user id and tenant id from it It invokes get method in the product service module",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "This controller method is to ad... | 3 | stack_v2_sparse_classes_30k_train_013614 | Implement the Python class `ProductController` described below.
Class description:
Implement the ProductController class.
Method signatures and docstrings:
- def get(self): This controller method is to retrieve an existing product This needs jwt authentication and retrieves user id and tenant id from it It invokes ge... | Implement the Python class `ProductController` described below.
Class description:
Implement the ProductController class.
Method signatures and docstrings:
- def get(self): This controller method is to retrieve an existing product This needs jwt authentication and retrieves user id and tenant id from it It invokes ge... | fe9cb286338dce008b1e78b66ff0b4f6a04ee94b | <|skeleton|>
class ProductController:
def get(self):
"""This controller method is to retrieve an existing product This needs jwt authentication and retrieves user id and tenant id from it It invokes get method in the product service module"""
<|body_0|>
def post(self):
"""This controll... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductController:
def get(self):
"""This controller method is to retrieve an existing product This needs jwt authentication and retrieves user id and tenant id from it It invokes get method in the product service module"""
product_id = request.args.get('product_id')
tenant_id = get_jw... | the_stack_v2_python_sparse | productmanagement/product/controller/productcontroller.py | rnama22/amzorbit | train | 0 | |
8fd6f8a1b069db2a6c5b054ea9dc4b1423e72e86 | [
"self.lazy = lazy\nif fields_mapping:\n self.fields_mapping = fields_mapping\nelse:\n self.fields_mapping = self.DEFAULT_FIELDS_MAPPING",
"if not self.lazy:\n return True\nreturn any(data_combined.values())",
"errors = {}\nfor field_name, mapping in self.fields_mapping.items():\n if not mapping['req... | <|body_start_0|>
self.lazy = lazy
if fields_mapping:
self.fields_mapping = fields_mapping
else:
self.fields_mapping = self.DEFAULT_FIELDS_MAPPING
<|end_body_0|>
<|body_start_1|>
if not self.lazy:
return True
return any(data_combined.values())
... | Validator for addresses. | AddressValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressValidator:
"""Validator for addresses."""
def __init__(self, lazy=False, fields_mapping=None):
"""Init the params. :param lazy: True if you want to skip validation when none of the fields are set. Useful when validating an extra and optional address where some fields become re... | stack_v2_sparse_classes_36k_train_008274 | 2,486 | permissive | [
{
"docstring": "Init the params. :param lazy: True if you want to skip validation when none of the fields are set. Useful when validating an extra and optional address where some fields become required only if any of the fields are set. :fields_mapping: dict with the field as a key and the value as a dict with ... | 4 | null | Implement the Python class `AddressValidator` described below.
Class description:
Validator for addresses.
Method signatures and docstrings:
- def __init__(self, lazy=False, fields_mapping=None): Init the params. :param lazy: True if you want to skip validation when none of the fields are set. Useful when validating ... | Implement the Python class `AddressValidator` described below.
Class description:
Validator for addresses.
Method signatures and docstrings:
- def __init__(self, lazy=False, fields_mapping=None): Init the params. :param lazy: True if you want to skip validation when none of the fields are set. Useful when validating ... | a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e | <|skeleton|>
class AddressValidator:
"""Validator for addresses."""
def __init__(self, lazy=False, fields_mapping=None):
"""Init the params. :param lazy: True if you want to skip validation when none of the fields are set. Useful when validating an extra and optional address where some fields become re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddressValidator:
"""Validator for addresses."""
def __init__(self, lazy=False, fields_mapping=None):
"""Init the params. :param lazy: True if you want to skip validation when none of the fields are set. Useful when validating an extra and optional address where some fields become required only i... | the_stack_v2_python_sparse | datahub/core/validators/address.py | cgsunkel/data-hub-api | train | 0 |
2083ec2f77dc3f6ae12627ab4cac5f1099e800af | [
"for i in range(n, 0, -1):\n if isBadVersion(i) is True:\n return i\nreturn -1",
"if isBadVersion(1):\n return 1\nl = 1\nr = n\nwhile l < r:\n m = (l + r) // 2\n if isBadVersion(m):\n r = m\n else:\n l = m + 1\nreturn l"
] | <|body_start_0|>
for i in range(n, 0, -1):
if isBadVersion(i) is True:
return i
return -1
<|end_body_0|>
<|body_start_1|>
if isBadVersion(1):
return 1
l = 1
r = n
while l < r:
m = (l + r) // 2
if isBadVersio... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstBadVersion(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def firstBadVersion1(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(n, 0, -1):
if isBadVersion(i) is ... | stack_v2_sparse_classes_36k_train_008275 | 1,524 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "firstBadVersion",
"signature": "def firstBadVersion(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "firstBadVersion1",
"signature": "def firstBadVersion1(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstBadVersion(self, n): :type n: int :rtype: int
- def firstBadVersion1(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstBadVersion(self, n): :type n: int :rtype: int
- def firstBadVersion1(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def firstBadVersion(self, n):
... | 166d97f36bbeea74c84ec57466bd0a65b608ed09 | <|skeleton|>
class Solution:
def firstBadVersion(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def firstBadVersion1(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstBadVersion(self, n):
""":type n: int :rtype: int"""
for i in range(n, 0, -1):
if isBadVersion(i) is True:
return i
return -1
def firstBadVersion1(self, n):
""":type n: int :rtype: int"""
if isBadVersion(1):
... | the_stack_v2_python_sparse | leetcode/base/sort_and_search/第一个错误版本.py | Activity00/Python | train | 0 | |
f848cb7d3cfb3e50b0eed557413346816a3f221b | [
"def helper(nums, start, end):\n if start == end:\n return start\n count = 0\n mid = (start + end) // 2\n for num in nums:\n if num >= start and num <= mid:\n count += 1\n if count <= mid - start + 1:\n return helper(nums, mid + 1, end)\n else:\n return helpe... | <|body_start_0|>
def helper(nums, start, end):
if start == end:
return start
count = 0
mid = (start + end) // 2
for num in nums:
if num >= start and num <= mid:
count += 1
if count <= mid - start + 1:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(nums, start, end):
... | stack_v2_sparse_classes_36k_train_008276 | 968 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000472 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findDu... | 0fc972e5cd2baf1b5ddf8b192962629f40bc3bf4 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
def helper(nums, start, end):
if start == end:
return start
count = 0
mid = (start + end) // 2
for num in nums:
if num >= start and n... | the_stack_v2_python_sparse | problems/287. Find the Duplicate Number.py | yukiii-zhong/Leetcode | train | 2 | |
2f7e5d095a0e9b436628654d1fdbf28f936edc58 | [
"try:\n pl_module.model = pl_module.model.to(memory_format=torch.channels_last)\nexcept Exception as e:\n warning(f'Convert model to channels last failed, fall back to origin memory format. Exception msg: {e}')\n return super().setup(trainer, pl_module, stage)\nfn_old = getattr(pl_modul... | <|body_start_0|>
try:
pl_module.model = pl_module.model.to(memory_format=torch.channels_last)
except Exception as e:
warning(f'Convert model to channels last failed, fall back to origin memory format. Exception msg: {e}')
return super().setup(train... | Custom pl.Callback for converting model and data to channels_last. | ChannelsLastCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelsLastCallback:
"""Custom pl.Callback for converting model and data to channels_last."""
def setup(self, trainer, pl_module, stage: Optional[str]=None) -> None:
"""Override hook setup to convert model to channels_last and wrap DataHook."""
<|body_0|>
def teardown(s... | stack_v2_sparse_classes_36k_train_008277 | 3,374 | permissive | [
{
"docstring": "Override hook setup to convert model to channels_last and wrap DataHook.",
"name": "setup",
"signature": "def setup(self, trainer, pl_module, stage: Optional[str]=None) -> None"
},
{
"docstring": "Undo the changes to pl_module at end of fit, validate, tests, or predict.",
"na... | 2 | stack_v2_sparse_classes_30k_train_003887 | Implement the Python class `ChannelsLastCallback` described below.
Class description:
Custom pl.Callback for converting model and data to channels_last.
Method signatures and docstrings:
- def setup(self, trainer, pl_module, stage: Optional[str]=None) -> None: Override hook setup to convert model to channels_last and... | Implement the Python class `ChannelsLastCallback` described below.
Class description:
Custom pl.Callback for converting model and data to channels_last.
Method signatures and docstrings:
- def setup(self, trainer, pl_module, stage: Optional[str]=None) -> None: Override hook setup to convert model to channels_last and... | 95f677ab34867f1d91df0ed8e1bc760ea610f791 | <|skeleton|>
class ChannelsLastCallback:
"""Custom pl.Callback for converting model and data to channels_last."""
def setup(self, trainer, pl_module, stage: Optional[str]=None) -> None:
"""Override hook setup to convert model to channels_last and wrap DataHook."""
<|body_0|>
def teardown(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelsLastCallback:
"""Custom pl.Callback for converting model and data to channels_last."""
def setup(self, trainer, pl_module, stage: Optional[str]=None) -> None:
"""Override hook setup to convert model to channels_last and wrap DataHook."""
try:
pl_module.model = pl_modul... | the_stack_v2_python_sparse | python/nano/src/bigdl/nano/pytorch/utils.py | helenlly/BigDL | train | 0 |
d95a73db8eb3c8595e3fe5fa47ffab5f91d8c308 | [
"n = len(string)\nwhile i >= 0 and j < n and (string[i] == string[j]):\n i -= 1\n j += 1\nreturn (i + 1, j - 1)",
"n = len(string)\nx, y = (0, 0)\nfor i in range(n - 1):\n res1 = self.expand(string, i, i)\n res2 = self.expand(string, i, i + 1)\n length_1 = res1[1] - res1[0]\n length_2 = res2[1] ... | <|body_start_0|>
n = len(string)
while i >= 0 and j < n and (string[i] == string[j]):
i -= 1
j += 1
return (i + 1, j - 1)
<|end_body_0|>
<|body_start_1|>
n = len(string)
x, y = (0, 0)
for i in range(n - 1):
res1 = self.expand(string, i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def expand(self, string, i, j):
"""Returns start, end indices of longest palindromic substring expanded from i, j."""
<|body_0|>
def longest_palindrome(self, string):
"""Algorithm is based on idea to expand palindrome from the center. Algorithm description:... | stack_v2_sparse_classes_36k_train_008278 | 2,034 | no_license | [
{
"docstring": "Returns start, end indices of longest palindromic substring expanded from i, j.",
"name": "expand",
"signature": "def expand(self, string, i, j)"
},
{
"docstring": "Algorithm is based on idea to expand palindrome from the center. Algorithm description: 1) Choose a 1-letter or 2-l... | 2 | stack_v2_sparse_classes_30k_val_000697 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def expand(self, string, i, j): Returns start, end indices of longest palindromic substring expanded from i, j.
- def longest_palindrome(self, string): Algorithm is based on idea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def expand(self, string, i, j): Returns start, end indices of longest palindromic substring expanded from i, j.
- def longest_palindrome(self, string): Algorithm is based on idea... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def expand(self, string, i, j):
"""Returns start, end indices of longest palindromic substring expanded from i, j."""
<|body_0|>
def longest_palindrome(self, string):
"""Algorithm is based on idea to expand palindrome from the center. Algorithm description:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def expand(self, string, i, j):
"""Returns start, end indices of longest palindromic substring expanded from i, j."""
n = len(string)
while i >= 0 and j < n and (string[i] == string[j]):
i -= 1
j += 1
return (i + 1, j - 1)
def longest_pali... | the_stack_v2_python_sparse | Strings/longest_palindromic_substring/longest_expand.py | vladn90/Algorithms | train | 0 | |
53ddbf8a2f617c303a1078235e6a1f2b14b24f70 | [
"object.__init__(self)\nassert isinstance(point, Point)\nself.pos = point\nself._pos_f = PointF.from_point(point)\nrospy.Subscriber(name + '/cmd_vel', Twist, self._velocity_callback)\nself._pose_pub = rospy.Publisher(name + '/pose', Pose, queue_size=10)\nself._colour_pub = rospy.Publisher(name + '/color_sensor', Co... | <|body_start_0|>
object.__init__(self)
assert isinstance(point, Point)
self.pos = point
self._pos_f = PointF.from_point(point)
rospy.Subscriber(name + '/cmd_vel', Twist, self._velocity_callback)
self._pose_pub = rospy.Publisher(name + '/pose', Pose, queue_size=10)
... | The turtle class | Turtle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Turtle:
"""The turtle class"""
def __init__(self, name, point):
"""Ctor"""
<|body_0|>
def _velocity_callback(self, data):
"""Set the velocity based on the callback."""
<|body_1|>
def update(self, dtime, background, canvas_width, canvas_height):
... | stack_v2_sparse_classes_36k_train_008279 | 2,528 | no_license | [
{
"docstring": "Ctor",
"name": "__init__",
"signature": "def __init__(self, name, point)"
},
{
"docstring": "Set the velocity based on the callback.",
"name": "_velocity_callback",
"signature": "def _velocity_callback(self, data)"
},
{
"docstring": "Update the turtle state and po... | 3 | stack_v2_sparse_classes_30k_train_002701 | Implement the Python class `Turtle` described below.
Class description:
The turtle class
Method signatures and docstrings:
- def __init__(self, name, point): Ctor
- def _velocity_callback(self, data): Set the velocity based on the callback.
- def update(self, dtime, background, canvas_width, canvas_height): Update th... | Implement the Python class `Turtle` described below.
Class description:
The turtle class
Method signatures and docstrings:
- def __init__(self, name, point): Ctor
- def _velocity_callback(self, data): Set the velocity based on the callback.
- def update(self, dtime, background, canvas_width, canvas_height): Update th... | f268988b607118c8aa7e94eff6165e44c9a40dff | <|skeleton|>
class Turtle:
"""The turtle class"""
def __init__(self, name, point):
"""Ctor"""
<|body_0|>
def _velocity_callback(self, data):
"""Set the velocity based on the callback."""
<|body_1|>
def update(self, dtime, background, canvas_width, canvas_height):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Turtle:
"""The turtle class"""
def __init__(self, name, point):
"""Ctor"""
object.__init__(self)
assert isinstance(point, Point)
self.pos = point
self._pos_f = PointF.from_point(point)
rospy.Subscriber(name + '/cmd_vel', Twist, self._velocity_callback)
... | the_stack_v2_python_sparse | catkin_ws/src/py_turtlesim/src/turtle.py | tum-i4/rritbed | train | 1 |
37ca3f2cdf04cbf4b0510e4bbb049dea71a525c7 | [
"torch.nn.Embedding.__init__(self, num_embeddings=num_embeddings, embedding_dim=embedding_dim, max_norm=max_norm, norm_type=norm_type, scale_grad_by_freq=scale_grad_by_freq, sparse=sparse)\nself.dropout = dropout\nassert 1.0 > dropout >= 0.0, 'Dropout must be >= 0.0 and < 1.0'\nself.scale = scale",
"if self.train... | <|body_start_0|>
torch.nn.Embedding.__init__(self, num_embeddings=num_embeddings, embedding_dim=embedding_dim, max_norm=max_norm, norm_type=norm_type, scale_grad_by_freq=scale_grad_by_freq, sparse=sparse)
self.dropout = dropout
assert 1.0 > dropout >= 0.0, 'Dropout must be >= 0.0 and < 1.0'
... | Class for dropping out embeddings by zero'ing out parameters in the embedding matrix. This is equivalent to dropping out particular words, e.g., in the sentence 'the quick brown fox jumps over the lazy dog', dropping out 'the' would lead to the sentence '### quick brown fox jumps over ### lazy dog' (in the embedding ve... | EmbeddingDropout | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbeddingDropout:
"""Class for dropping out embeddings by zero'ing out parameters in the embedding matrix. This is equivalent to dropping out particular words, e.g., in the sentence 'the quick brown fox jumps over the lazy dog', dropping out 'the' would lead to the sentence '### quick brown fox j... | stack_v2_sparse_classes_36k_train_008280 | 40,340 | permissive | [
{
"docstring": "Embedding constructor. Args: dropout: Dropout probability. scale: Used to scale parameters of embedding weight matrix that are not dropped out. Note that this is _in addition_ to the `1/(1 - dropout)` scaling. See `torch.nn.Embedding` for remaining arguments.",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_011584 | Implement the Python class `EmbeddingDropout` described below.
Class description:
Class for dropping out embeddings by zero'ing out parameters in the embedding matrix. This is equivalent to dropping out particular words, e.g., in the sentence 'the quick brown fox jumps over the lazy dog', dropping out 'the' would lead... | Implement the Python class `EmbeddingDropout` described below.
Class description:
Class for dropping out embeddings by zero'ing out parameters in the embedding matrix. This is equivalent to dropping out particular words, e.g., in the sentence 'the quick brown fox jumps over the lazy dog', dropping out 'the' would lead... | 8a32196ce342b8ad9e3885895735d1286e25beba | <|skeleton|>
class EmbeddingDropout:
"""Class for dropping out embeddings by zero'ing out parameters in the embedding matrix. This is equivalent to dropping out particular words, e.g., in the sentence 'the quick brown fox jumps over the lazy dog', dropping out 'the' would lead to the sentence '### quick brown fox j... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmbeddingDropout:
"""Class for dropping out embeddings by zero'ing out parameters in the embedding matrix. This is equivalent to dropping out particular words, e.g., in the sentence 'the quick brown fox jumps over the lazy dog', dropping out 'the' would lead to the sentence '### quick brown fox jumps over ###... | the_stack_v2_python_sparse | aw_nas/ops/ops.py | blyucs/aw_nas | train | 0 |
ba673a5211d0569b5aadd295db90d517f2387b26 | [
"if pretty:\n return self.as_dict(as_json_pretty=True)\nreturn self.as_dict(as_json=True)",
"as_json = kwargs.get('as_json', False)\nas_json_pretty = kwargs.get('as_json_pretty', False)\nod = OrderedDict()\nfor param in self.FIELDS_TO_SERIALIZE:\n od[param] = self.__dict__.get(param)\nif as_json:\n retur... | <|body_start_0|>
if pretty:
return self.as_dict(as_json_pretty=True)
return self.as_dict(as_json=True)
<|end_body_0|>
<|body_start_1|>
as_json = kwargs.get('as_json', False)
as_json_pretty = kwargs.get('as_json_pretty', False)
od = OrderedDict()
for param in ... | New user class to hold extra attributes in the future | User | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""New user class to hold extra attributes in the future"""
def as_json(self, pretty=False):
"""Return as a JSON string"""
<|body_0|>
def as_dict(self, **kwargs):
"""Return as an OrderedDict"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008281 | 1,223 | permissive | [
{
"docstring": "Return as a JSON string",
"name": "as_json",
"signature": "def as_json(self, pretty=False)"
},
{
"docstring": "Return as an OrderedDict",
"name": "as_dict",
"signature": "def as_dict(self, **kwargs)"
}
] | 2 | null | Implement the Python class `User` described below.
Class description:
New user class to hold extra attributes in the future
Method signatures and docstrings:
- def as_json(self, pretty=False): Return as a JSON string
- def as_dict(self, **kwargs): Return as an OrderedDict | Implement the Python class `User` described below.
Class description:
New user class to hold extra attributes in the future
Method signatures and docstrings:
- def as_json(self, pretty=False): Return as a JSON string
- def as_dict(self, **kwargs): Return as an OrderedDict
<|skeleton|>
class User:
"""New user cla... | e5f820557d6646df525ceed15e17d79f4159cf0a | <|skeleton|>
class User:
"""New user class to hold extra attributes in the future"""
def as_json(self, pretty=False):
"""Return as a JSON string"""
<|body_0|>
def as_dict(self, **kwargs):
"""Return as an OrderedDict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""New user class to hold extra attributes in the future"""
def as_json(self, pretty=False):
"""Return as a JSON string"""
if pretty:
return self.as_dict(as_json_pretty=True)
return self.as_dict(as_json=True)
def as_dict(self, **kwargs):
"""Return as... | the_stack_v2_python_sparse | tworaven_apps/raven_auth/models.py | TwoRavens/TwoRavens | train | 21 |
e7de1083ef3d794c292c21d9936230232ec7eb7a | [
"self.type = 'FILL'\nself.timeindex = timeindex\nself.symbol = symbol\nself.exchange = exchange\nself.quantity = quantity\nself.direction = direction\nself.fill_cost = fill_cost\nif commission is None:\n self.commission = self.calculate_ib_commission()\nelse:\n self.commission = commission",
"full_cost = 1.... | <|body_start_0|>
self.type = 'FILL'
self.timeindex = timeindex
self.symbol = symbol
self.exchange = exchange
self.quantity = quantity
self.direction = direction
self.fill_cost = fill_cost
if commission is None:
self.commission = self.calculate_... | Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. | FillEvent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillEvent:
"""Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage."""
def __init__(self, timeindex, symbol, exchange, quantity, dire... | stack_v2_sparse_classes_36k_train_008282 | 4,992 | no_license | [
{
"docstring": "Initializes the FillEvent object. Sets the symbol, exchange, quantity, direction, cost of fill, and an optional commission. If commission is not provided, the Fill object will calculate it based on the trade size and Interactive Brokers fees. Parameters ---------- @timeindex: The bar-resolution ... | 2 | stack_v2_sparse_classes_30k_train_003544 | Implement the Python class `FillEvent` described below.
Class description:
Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage.
Method signatures and docstrin... | Implement the Python class `FillEvent` described below.
Class description:
Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage.
Method signatures and docstrin... | c0fa7da1903fc531d7be00ef468b498c631e3e1d | <|skeleton|>
class FillEvent:
"""Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage."""
def __init__(self, timeindex, symbol, exchange, quantity, dire... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FillEvent:
"""Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage."""
def __init__(self, timeindex, symbol, exchange, quantity, direction, fill_c... | the_stack_v2_python_sparse | EventDrivenBacktester/EventClasses.py | nicktheodore/EventDrivenBacktestingEngine | train | 0 |
62e29c28c29e7da1f3876724d982c8fa2d567774 | [
"self.month = month\nself.day = day\nself.year = year",
"months = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\noutput = months[self.month] + ' '\noutput += str(self.day) + ', '\noutput += str(self.year)\nreturn output",
"daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, ... | <|body_start_0|>
self.month = month
self.day = day
self.year = year
<|end_body_0|>
<|body_start_1|>
months = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
output = months[self.month] + ' '
output += str(self.day) + ', '
... | class to represent a date | Date | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Date:
"""class to represent a date"""
def __init__(self, month, day, year):
"""Date(month,day,year) -> Date"""
<|body_0|>
def __str__(self):
"""str(Date) -> str returns date in readable format"""
<|body_1|>
def go_to_next_day(self):
"""Date.g... | stack_v2_sparse_classes_36k_train_008283 | 1,499 | no_license | [
{
"docstring": "Date(month,day,year) -> Date",
"name": "__init__",
"signature": "def __init__(self, month, day, year)"
},
{
"docstring": "str(Date) -> str returns date in readable format",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Date.go_to_next_day(... | 3 | stack_v2_sparse_classes_30k_train_013998 | Implement the Python class `Date` described below.
Class description:
class to represent a date
Method signatures and docstrings:
- def __init__(self, month, day, year): Date(month,day,year) -> Date
- def __str__(self): str(Date) -> str returns date in readable format
- def go_to_next_day(self): Date.go_to_next_day()... | Implement the Python class `Date` described below.
Class description:
class to represent a date
Method signatures and docstrings:
- def __init__(self, month, day, year): Date(month,day,year) -> Date
- def __str__(self): str(Date) -> str returns date in readable format
- def go_to_next_day(self): Date.go_to_next_day()... | 8581d65cd362505d312b9dd6cb3e0d4e689146f4 | <|skeleton|>
class Date:
"""class to represent a date"""
def __init__(self, month, day, year):
"""Date(month,day,year) -> Date"""
<|body_0|>
def __str__(self):
"""str(Date) -> str returns date in readable format"""
<|body_1|>
def go_to_next_day(self):
"""Date.g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Date:
"""class to represent a date"""
def __init__(self, month, day, year):
"""Date(month,day,year) -> Date"""
self.month = month
self.day = day
self.year = year
def __str__(self):
"""str(Date) -> str returns date in readable format"""
months = ['', 'J... | the_stack_v2_python_sparse | MyOldCode/Date.py | zoelxi/LearningPython | train | 0 |
76bd06a35b90e91d728cbef2fcbb340d055c44e1 | [
"if roles.Roles.is_super_admin():\n exit_url = '%s?tab=google_service_account' % handler.LINK_URL\nelse:\n exit_url = cls.request.referer\nrest_url = GoogleServiceAccountRESTHandler.URI\ntemplate_values = {}\ntemplate_values['page_title'] = handler.format_title('Google Service Accounts')\ncontent = safe_dom.N... | <|body_start_0|>
if roles.Roles.is_super_admin():
exit_url = '%s?tab=google_service_account' % handler.LINK_URL
else:
exit_url = cls.request.referer
rest_url = GoogleServiceAccountRESTHandler.URI
template_values = {}
template_values['page_title'] = handler... | GoogleServiceAccountBaseAdminHandler | [
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleServiceAccountBaseAdminHandler:
def get_google_service_account(cls, handler):
"""Displays list of service account settings."""
<|body_0|>
def get_edit_google_service_account(cls, handler):
"""Handles 'get_add_google_service_account_settings' action and renders ... | stack_v2_sparse_classes_36k_train_008284 | 13,602 | permissive | [
{
"docstring": "Displays list of service account settings.",
"name": "get_google_service_account",
"signature": "def get_google_service_account(cls, handler)"
},
{
"docstring": "Handles 'get_add_google_service_account_settings' action and renders new course entry editor.",
"name": "get_edit_... | 3 | stack_v2_sparse_classes_30k_test_000263 | Implement the Python class `GoogleServiceAccountBaseAdminHandler` described below.
Class description:
Implement the GoogleServiceAccountBaseAdminHandler class.
Method signatures and docstrings:
- def get_google_service_account(cls, handler): Displays list of service account settings.
- def get_edit_google_service_acc... | Implement the Python class `GoogleServiceAccountBaseAdminHandler` described below.
Class description:
Implement the GoogleServiceAccountBaseAdminHandler class.
Method signatures and docstrings:
- def get_google_service_account(cls, handler): Displays list of service account settings.
- def get_edit_google_service_acc... | 2bca9d64499e160b2da9bed6e97fcda712feec72 | <|skeleton|>
class GoogleServiceAccountBaseAdminHandler:
def get_google_service_account(cls, handler):
"""Displays list of service account settings."""
<|body_0|>
def get_edit_google_service_account(cls, handler):
"""Handles 'get_add_google_service_account_settings' action and renders ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleServiceAccountBaseAdminHandler:
def get_google_service_account(cls, handler):
"""Displays list of service account settings."""
if roles.Roles.is_super_admin():
exit_url = '%s?tab=google_service_account' % handler.LINK_URL
else:
exit_url = cls.request.refer... | the_stack_v2_python_sparse | coursebuilder/modules/google_service_account/settings.py | RavinderSinghPB/seek | train | 0 | |
2fafeff01fd9c8bbb36d7de72e6b257c7c0b2e71 | [
"load_bigquery_table_kwargs = {'csv_field_delimiter': ',', 'csv_quote_character': '\"', 'csv_skip_leading_rows': 1, 'csv_allow_quoted_newlines': True, 'write_disposition': bigquery.WriteDisposition.WRITE_APPEND, 'ignore_unknown_values': True}\nif table_descriptions is None:\n table_descriptions = {dag_id: 'The O... | <|body_start_0|>
load_bigquery_table_kwargs = {'csv_field_delimiter': ',', 'csv_quote_character': '"', 'csv_skip_leading_rows': 1, 'csv_allow_quoted_newlines': True, 'write_disposition': bigquery.WriteDisposition.WRITE_APPEND, 'ignore_unknown_values': True}
if table_descriptions is None:
tab... | A telescope that harvests the Open Citations COCI CSV dataset . http://opencitations.net/index/coci | OpenCitationsTelescope | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenCitationsTelescope:
"""A telescope that harvests the Open Citations COCI CSV dataset . http://opencitations.net/index/coci"""
def __init__(self, dag_id: str=DAG_ID, start_date: pendulum.DateTime=pendulum.datetime(2018, 7, 1), schedule_interval: str='@weekly', dataset_id: str=DAG_ID, sche... | stack_v2_sparse_classes_36k_train_008285 | 9,464 | permissive | [
{
"docstring": ":param dag_id: the id of the DAG. :param start_date: the start date of the DAG. :param schedule_interval: the schedule interval of the DAG. :param dataset_id: the BigQuery dataset id. :param schema_folder: the SQL schema path. :param queue: Queue to run tasks on. :param dataset_description: desc... | 5 | stack_v2_sparse_classes_30k_train_013849 | Implement the Python class `OpenCitationsTelescope` described below.
Class description:
A telescope that harvests the Open Citations COCI CSV dataset . http://opencitations.net/index/coci
Method signatures and docstrings:
- def __init__(self, dag_id: str=DAG_ID, start_date: pendulum.DateTime=pendulum.datetime(2018, 7... | Implement the Python class `OpenCitationsTelescope` described below.
Class description:
A telescope that harvests the Open Citations COCI CSV dataset . http://opencitations.net/index/coci
Method signatures and docstrings:
- def __init__(self, dag_id: str=DAG_ID, start_date: pendulum.DateTime=pendulum.datetime(2018, 7... | 6a6669a29344d394b0bfe85a543dadddb9f09293 | <|skeleton|>
class OpenCitationsTelescope:
"""A telescope that harvests the Open Citations COCI CSV dataset . http://opencitations.net/index/coci"""
def __init__(self, dag_id: str=DAG_ID, start_date: pendulum.DateTime=pendulum.datetime(2018, 7, 1), schedule_interval: str='@weekly', dataset_id: str=DAG_ID, sche... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenCitationsTelescope:
"""A telescope that harvests the Open Citations COCI CSV dataset . http://opencitations.net/index/coci"""
def __init__(self, dag_id: str=DAG_ID, start_date: pendulum.DateTime=pendulum.datetime(2018, 7, 1), schedule_interval: str='@weekly', dataset_id: str=DAG_ID, schema_folder: st... | the_stack_v2_python_sparse | academic_observatory_workflows/workflows/open_citations_telescope.py | The-Academic-Observatory/academic-observatory-workflows | train | 13 |
30eb914d5078bf89955a64c5afdd75d8157a245a | [
"visited = set()\nnode = headA\nwhile node:\n visited.add(id(node))\n node = node.next\nnode = headB\nwhile node:\n if id(node) in visited:\n return node\n node = node.next",
"n1 = headA\nn2 = headB\nwhile id(n1) != id(n2):\n n1 = n1.next if n1 else headB\n n2 = n2.next if n2 else headA\n... | <|body_start_0|>
visited = set()
node = headA
while node:
visited.add(id(node))
node = node.next
node = headB
while node:
if id(node) in visited:
return node
node = node.next
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
"""06/18/2022 11:06 Time Complexity: O(n) Space Complexity: O(n)"""
<|body_0|>
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
"""0... | stack_v2_sparse_classes_36k_train_008286 | 5,049 | no_license | [
{
"docstring": "06/18/2022 11:06 Time Complexity: O(n) Space Complexity: O(n)",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]"
},
{
"docstring": "06/18/2022 12:53 Time Complexity: O(n) Space Complexity: O(1)",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 06/18/2022 11:06 Time Complexity: O(n) Space Complexity: O(n)
- def getIntersectionNode(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 06/18/2022 11:06 Time Complexity: O(n) Space Complexity: O(n)
- def getIntersectionNode(sel... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
"""06/18/2022 11:06 Time Complexity: O(n) Space Complexity: O(n)"""
<|body_0|>
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
"""0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
"""06/18/2022 11:06 Time Complexity: O(n) Space Complexity: O(n)"""
visited = set()
node = headA
while node:
visited.add(id(node))
node = node.next
n... | the_stack_v2_python_sparse | leetcode/solved/160_Intersection_of_Two_Linked_Lists/solution.py | sungminoh/algorithms | train | 0 | |
6c42b568bcce425fcb5cab688a4475b8c4f0b2d6 | [
"template = self.template\nvariables = self.get_variables()\nexternal_ip_list = variables['NLBIps'].split(',')\ninternal_ip_list = variables['InternalNLBIps'].split(',')\nip_list = []\nip_list.extend(external_ip_list)\nip_list.extend(internal_ip_list)\nsshkeyspecified = 'SSHKeySpecified'\ntemplate.add_condition(ssh... | <|body_start_0|>
template = self.template
variables = self.get_variables()
external_ip_list = variables['NLBIps'].split(',')
internal_ip_list = variables['InternalNLBIps'].split(',')
ip_list = []
ip_list.extend(external_ip_list)
ip_list.extend(internal_ip_list)
... | Extend Stacker Blueprint class. | AutoScalingGroup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoScalingGroup:
"""Extend Stacker Blueprint class."""
def add_asg(self):
"""Add ASG to template."""
<|body_0|>
def create_template(self):
"""Create template (main function called by Stacker)."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tem... | stack_v2_sparse_classes_36k_train_008287 | 15,095 | no_license | [
{
"docstring": "Add ASG to template.",
"name": "add_asg",
"signature": "def add_asg(self)"
},
{
"docstring": "Create template (main function called by Stacker).",
"name": "create_template",
"signature": "def create_template(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015333 | Implement the Python class `AutoScalingGroup` described below.
Class description:
Extend Stacker Blueprint class.
Method signatures and docstrings:
- def add_asg(self): Add ASG to template.
- def create_template(self): Create template (main function called by Stacker). | Implement the Python class `AutoScalingGroup` described below.
Class description:
Extend Stacker Blueprint class.
Method signatures and docstrings:
- def add_asg(self): Add ASG to template.
- def create_template(self): Create template (main function called by Stacker).
<|skeleton|>
class AutoScalingGroup:
"""Ext... | befa3a3a50a26d4ba7fdc9a08e35fbf1128bcb55 | <|skeleton|>
class AutoScalingGroup:
"""Extend Stacker Blueprint class."""
def add_asg(self):
"""Add ASG to template."""
<|body_0|>
def create_template(self):
"""Create template (main function called by Stacker)."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoScalingGroup:
"""Extend Stacker Blueprint class."""
def add_asg(self):
"""Add ASG to template."""
template = self.template
variables = self.get_variables()
external_ip_list = variables['NLBIps'].split(',')
internal_ip_list = variables['InternalNLBIps'].split(',... | the_stack_v2_python_sparse | stacker/asg-nlb-squid-instance/squid_server/squid_server_blueprints/asg.py | threadstonesecure/cfn_templates | train | 0 |
4fded86a013927c0c8dc12cd2d6ed17a66037a6d | [
"self.error = gtol\nif weight != None:\n self.weight = weight\nelse:\n self.weight = 1",
"gradient = state['function'].gradient(state['new_parameters'])\nvalue = (self.weight * numpy.abs(gradient) < self.error).all()\nif value:\n state['istop'] = defaults.SMALL_DF\nreturn value"
] | <|body_start_0|>
self.error = gtol
if weight != None:
self.weight = weight
else:
self.weight = 1
<|end_body_0|>
<|body_start_1|>
gradient = state['function'].gradient(state['new_parameters'])
value = (self.weight * numpy.abs(gradient) < self.error).all()
... | The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance | GradientCriterion | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientCriterion:
"""The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance"""
def __init__(self, gtol, weight=None):
"""Initializes the criterion with an error fraction and the weight assigned for each parameter"""
... | stack_v2_sparse_classes_36k_train_008288 | 4,758 | permissive | [
{
"docstring": "Initializes the criterion with an error fraction and the weight assigned for each parameter",
"name": "__init__",
"signature": "def __init__(self, gtol, weight=None)"
},
{
"docstring": "Computes the stopping criterion",
"name": "__call__",
"signature": "def __call__(self,... | 2 | stack_v2_sparse_classes_30k_train_020838 | Implement the Python class `GradientCriterion` described below.
Class description:
The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance
Method signatures and docstrings:
- def __init__(self, gtol, weight=None): Initializes the criterion with an error frac... | Implement the Python class `GradientCriterion` described below.
Class description:
The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance
Method signatures and docstrings:
- def __init__(self, gtol, weight=None): Initializes the criterion with an error frac... | 3d298e908ff55340cd3612078508be0c791f63a8 | <|skeleton|>
class GradientCriterion:
"""The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance"""
def __init__(self, gtol, weight=None):
"""Initializes the criterion with an error fraction and the weight assigned for each parameter"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientCriterion:
"""The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance"""
def __init__(self, gtol, weight=None):
"""Initializes the criterion with an error fraction and the weight assigned for each parameter"""
self.error ... | the_stack_v2_python_sparse | PyDSTool/Toolbox/optimizers/criterion/criteria.py | mdlama/pydstool | train | 2 |
47c71ca91a7dd0bd27a51e4b155dab3c1279b638 | [
"timeseries = TimeSeriesPerm.objects.filter(timeseries_id=self, username=healthcare, perm_value__in=[2, 3])\nif timeseries.count() == 0:\n return False\nelse:\n return True",
"if self.patient_id == patient:\n return True\nelse:\n return False"
] | <|body_start_0|>
timeseries = TimeSeriesPerm.objects.filter(timeseries_id=self, username=healthcare, perm_value__in=[2, 3])
if timeseries.count() == 0:
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
if self.patient_id == patient:
retur... | TimeSeries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSeries:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the timeseries."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_008289 | 12,031 | no_license | [
{
"docstring": "Checks if a user has permissions to view the timeseries.",
"name": "has_permission",
"signature": "def has_permission(self, healthcare)"
},
{
"docstring": "Checks if the record belongs to the patient.",
"name": "is_patient",
"signature": "def is_patient(self, patient)"
... | 2 | null | Implement the Python class `TimeSeries` described below.
Class description:
Implement the TimeSeries class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the timeseries.
- def is_patient(self, patient): Checks if the record belongs to the patient. | Implement the Python class `TimeSeries` described below.
Class description:
Implement the TimeSeries class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the timeseries.
- def is_patient(self, patient): Checks if the record belongs to the patient.
... | 685c2b9d40fb24ca1735352846a39fdf5d3728eb | <|skeleton|>
class TimeSeries:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the timeseries."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeSeries:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the timeseries."""
timeseries = TimeSeriesPerm.objects.filter(timeseries_id=self, username=healthcare, perm_value__in=[2, 3])
if timeseries.count() == 0:
return False
else:... | the_stack_v2_python_sparse | patientrecords/models.py | guekling/ifs4205team1 | train | 0 | |
750d68a880d4ef486ff4ce430cb6dce1a705bbfd | [
"allure.dynamic.title('Testing toJadenCase function (positive)')\nallure.dynamic.severity(allure.severity_level.NORMAL)\nallure.dynamic.description_html('<h3>Codewars badge:</h3><img src=\"https://www.codewars.com/users/myFirstCode/badges/large\"><h3>Test Description:</h3><p></p>')\nwith allure.step('Pass string an... | <|body_start_0|>
allure.dynamic.title('Testing toJadenCase function (positive)')
allure.dynamic.severity(allure.severity_level.NORMAL)
allure.dynamic.description_html('<h3>Codewars badge:</h3><img src="https://www.codewars.com/users/myFirstCode/badges/large"><h3>Test Description:</h3><p></p>')
... | Testing toJadenCase function | JadenCasingStringsTestCase | [
"Unlicense",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JadenCasingStringsTestCase:
"""Testing toJadenCase function"""
def test_to_jaden_case_positive(self):
"""Simple positive test :return:"""
<|body_0|>
def test_to_jaden_case_negative(self):
"""Simple negative test :return:"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_008290 | 2,430 | permissive | [
{
"docstring": "Simple positive test :return:",
"name": "test_to_jaden_case_positive",
"signature": "def test_to_jaden_case_positive(self)"
},
{
"docstring": "Simple negative test :return:",
"name": "test_to_jaden_case_negative",
"signature": "def test_to_jaden_case_negative(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015508 | Implement the Python class `JadenCasingStringsTestCase` described below.
Class description:
Testing toJadenCase function
Method signatures and docstrings:
- def test_to_jaden_case_positive(self): Simple positive test :return:
- def test_to_jaden_case_negative(self): Simple negative test :return: | Implement the Python class `JadenCasingStringsTestCase` described below.
Class description:
Testing toJadenCase function
Method signatures and docstrings:
- def test_to_jaden_case_positive(self): Simple positive test :return:
- def test_to_jaden_case_negative(self): Simple negative test :return:
<|skeleton|>
class J... | ba3ea81125b6082d867f0ae34c6c9be15e153966 | <|skeleton|>
class JadenCasingStringsTestCase:
"""Testing toJadenCase function"""
def test_to_jaden_case_positive(self):
"""Simple positive test :return:"""
<|body_0|>
def test_to_jaden_case_negative(self):
"""Simple negative test :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JadenCasingStringsTestCase:
"""Testing toJadenCase function"""
def test_to_jaden_case_positive(self):
"""Simple positive test :return:"""
allure.dynamic.title('Testing toJadenCase function (positive)')
allure.dynamic.severity(allure.severity_level.NORMAL)
allure.dynamic.de... | the_stack_v2_python_sparse | kyu_7/jaden_casing_strings/test_jaden_casing_strings.py | qamine-test/codewars | train | 0 |
d05ae6bb6b648874f0d260186247c181631e65d3 | [
"self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), 'image/key/sha256': tf.FixedLenFeature((), tf.string, default_value=''), 'im... | <|body_start_0|>
self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), 'image/key/sha256': tf.FixedLenFeature((), tf.string, de... | Tensorflow Example proto decoder. | TfExampleDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TfExampleDecoder:
"""Tensorflow Example proto decoder."""
def __init__(self):
"""Constructor sets keys_to_features and items_to_handlers."""
<|body_0|>
def decode(self, tf_example_string_tensor):
"""Decodes serialized tensorflow example and returns a tensor dicti... | stack_v2_sparse_classes_36k_train_008291 | 8,482 | permissive | [
{
"docstring": "Constructor sets keys_to_features and items_to_handlers.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Decodes serialized tensorflow example and returns a tensor dictionary. Args: tf_example_string_tensor: a string tensor holding a serialized tensorfl... | 2 | null | Implement the Python class `TfExampleDecoder` described below.
Class description:
Tensorflow Example proto decoder.
Method signatures and docstrings:
- def __init__(self): Constructor sets keys_to_features and items_to_handlers.
- def decode(self, tf_example_string_tensor): Decodes serialized tensorflow example and r... | Implement the Python class `TfExampleDecoder` described below.
Class description:
Tensorflow Example proto decoder.
Method signatures and docstrings:
- def __init__(self): Constructor sets keys_to_features and items_to_handlers.
- def decode(self, tf_example_string_tensor): Decodes serialized tensorflow example and r... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class TfExampleDecoder:
"""Tensorflow Example proto decoder."""
def __init__(self):
"""Constructor sets keys_to_features and items_to_handlers."""
<|body_0|>
def decode(self, tf_example_string_tensor):
"""Decodes serialized tensorflow example and returns a tensor dicti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TfExampleDecoder:
"""Tensorflow Example proto decoder."""
def __init__(self):
"""Constructor sets keys_to_features and items_to_handlers."""
self.keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, def... | the_stack_v2_python_sparse | TensorFlow/computer_vision/SSD_ResNet34/object_detection/tf_example_decoder.py | HabanaAI/Model-References | train | 108 |
511f999fb628e26e60b6c6f258549e5bffd307d8 | [
"self.iscsi_access = iscsi_access\nself.nfs_4_access = nfs_4_access\nself.nfs_access = nfs_access\nself.s3_access = s3_access\nself.smb_access = smb_access\nself.swift_access = swift_access",
"if dictionary is None:\n return None\niscsi_access = dictionary.get('iscsiAccess')\nnfs_4_access = dictionary.get('nfs... | <|body_start_0|>
self.iscsi_access = iscsi_access
self.nfs_4_access = nfs_4_access
self.nfs_access = nfs_access
self.s3_access = s3_access
self.smb_access = smb_access
self.swift_access = swift_access
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4.1 will be disabled by default in all configurations. nfs_access ... | ViewIdMappingProto_ProtocolAccessInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewIdMappingProto_ProtocolAccessInfo:
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4... | stack_v2_sparse_classes_36k_train_008292 | 2,769 | permissive | [
{
"docstring": "Constructor for the ViewIdMappingProto_ProtocolAccessInfo class",
"name": "__init__",
"signature": "def __init__(self, iscsi_access=None, nfs_4_access=None, nfs_access=None, s3_access=None, smb_access=None, swift_access=None)"
},
{
"docstring": "Creates an instance of this model ... | 2 | null | Implement the Python class `ViewIdMappingProto_ProtocolAccessInfo` described below.
Class description:
Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control fo... | Implement the Python class `ViewIdMappingProto_ProtocolAccessInfo` described below.
Class description:
Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control fo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewIdMappingProto_ProtocolAccessInfo:
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewIdMappingProto_ProtocolAccessInfo:
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model. TODO: type description here. Attributes: iscsi_access (int): Access control for iSCSI protocol for this view. nfs_4_access (int): Access control for NFSv4.1 protocol for this view. NFSv4.1 will be di... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_id_mapping_proto_protocol_access_info.py | cohesity/management-sdk-python | train | 24 |
2b9ee447adfbf4f246bacde3fe8c34229d957ec0 | [
"base.Action.__init__(self, self.__doMakeGif)\nself.__name = '{}_{}'.format(type(self).__name__, id(self))\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx\nself.__panel = panel\nself.__overlayList.addListener('overlays', self.__name, self.__selectedOverlayChanged)\nself.__displayCtx.addListener('s... | <|body_start_0|>
base.Action.__init__(self, self.__doMakeGif)
self.__name = '{}_{}'.format(type(self).__name__, id(self))
self.__overlayList = overlayList
self.__displayCtx = displayCtx
self.__panel = panel
self.__overlayList.addListener('overlays', self.__name, self.__se... | The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings. | MovieGifAction | [
"BSD-3-Clause",
"CC-BY-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieGifAction:
"""The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings."""
def __init__(self, overlayList, displayCtx, panel):
"""Create a ``MovieGifAction``. :arg ov... | stack_v2_sparse_classes_36k_train_008293 | 9,924 | permissive | [
{
"docstring": "Create a ``MovieGifAction``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The :class:`.DisplayContext`. :arg panel: The :class:`.CanvasPanel` to generate the animated GIF for.",
"name": "__init__",
"signature": "def __init__(self, overlayList, displayCtx, panel)"
},
... | 4 | stack_v2_sparse_classes_30k_val_000801 | Implement the Python class `MovieGifAction` described below.
Class description:
The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings.
Method signatures and docstrings:
- def __init__(self, overlayList,... | Implement the Python class `MovieGifAction` described below.
Class description:
The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings.
Method signatures and docstrings:
- def __init__(self, overlayList,... | 46ccb4fe2b2346eb57576247f49714032b61307a | <|skeleton|>
class MovieGifAction:
"""The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings."""
def __init__(self, overlayList, displayCtx, panel):
"""Create a ``MovieGifAction``. :arg ov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovieGifAction:
"""The ``MovieGifAction`` allows the user to save an animated gif of the currently selected overlay in a :class:`.CanvasPanel`, according to the current movie mode settings."""
def __init__(self, overlayList, displayCtx, panel):
"""Create a ``MovieGifAction``. :arg overlayList: Th... | the_stack_v2_python_sparse | fsleyes/actions/moviegif.py | sanjayankur31/fsleyes | train | 1 |
60708da1a81492fc5a92b6bd9022513905a696f7 | [
"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... | A set of methods for the Yandex Translate service. | TranslationServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TranslationServiceServicer:
"""A set of methods for the Yandex Translate service."""
def Translate(self, request, context):
"""Translates the text to the specified language."""
<|body_0|>
def DetectLanguage(self, request, context):
"""Detects the language of the ... | stack_v2_sparse_classes_36k_train_008294 | 3,979 | permissive | [
{
"docstring": "Translates the text to the specified language.",
"name": "Translate",
"signature": "def Translate(self, request, context)"
},
{
"docstring": "Detects the language of the text.",
"name": "DetectLanguage",
"signature": "def DetectLanguage(self, request, context)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_003910 | Implement the Python class `TranslationServiceServicer` described below.
Class description:
A set of methods for the Yandex Translate service.
Method signatures and docstrings:
- def Translate(self, request, context): Translates the text to the specified language.
- def DetectLanguage(self, request, context): Detects... | Implement the Python class `TranslationServiceServicer` described below.
Class description:
A set of methods for the Yandex Translate service.
Method signatures and docstrings:
- def Translate(self, request, context): Translates the text to the specified language.
- def DetectLanguage(self, request, context): Detects... | 980e2c5d848eadb42799132b35a9f58ab7b27157 | <|skeleton|>
class TranslationServiceServicer:
"""A set of methods for the Yandex Translate service."""
def Translate(self, request, context):
"""Translates the text to the specified language."""
<|body_0|>
def DetectLanguage(self, request, context):
"""Detects the language of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TranslationServiceServicer:
"""A set of methods for the Yandex Translate service."""
def Translate(self, request, context):
"""Translates the text to the specified language."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
r... | the_stack_v2_python_sparse | yandex/cloud/ai/translate/v2/translation_service_pb2_grpc.py | IIKovalenko/python-sdk | train | 1 |
318d01d7a933a8c568a3868987ae78244b5de79e | [
"res = []\n\ndef preorder(node):\n if node:\n res.append(node.val)\n preorder(node.left)\n preorder(node.right)\npreorder(root)\nreturn ' '.join(map(str, res))",
"nodes = [int(x) for x in data.split()]\nif not nodes:\n return None\n\ndef buildbst(minv, maxv):\n if nodes and minv < no... | <|body_start_0|>
res = []
def preorder(node):
if node:
res.append(node.val)
preorder(node.left)
preorder(node.right)
preorder(root)
return ' '.join(map(str, res))
<|end_body_0|>
<|body_start_1|>
nodes = [int(x) for x i... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_008295 | 1,294 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | e807ae43a0a253deaa6c9ed1c592fa3a14a6cab8 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def preorder(node):
if node:
res.append(node.val)
preorder(node.left)
preorder(node.right)
preorder(... | the_stack_v2_python_sparse | Medium/Serialize and deserialize BST.py | uathena1991/Leetcode | train | 1 | |
765960cefd69e56fe3a82a1ddd7a1474de3e82f8 | [
"if params:\n url = url_concat(url, params)\nhttp_client = AsyncHTTPClient()\nresponse = await http_client.fetch(url, method='GET', headers=headers, request_timeout=timeout)\nif response.code not in (200, 201, 202, 203, 204, 205, 206):\n logger.error('url:', url, 'response code:', response.code, 'response bod... | <|body_start_0|>
if params:
url = url_concat(url, params)
http_client = AsyncHTTPClient()
response = await http_client.fetch(url, method='GET', headers=headers, request_timeout=timeout)
if response.code not in (200, 201, 202, 203, 204, 205, 206):
logger.error('url... | a wrapper of async http request | AsyncHttpRequests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncHttpRequests:
"""a wrapper of async http request"""
async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30):
"""HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf... | stack_v2_sparse_classes_36k_train_008296 | 3,653 | permissive | [
{
"docstring": "HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf-8解码 @param parse_json 是否解析返回body为json格式,默认为True @param timeout 请求超时时间,默认30秒 @return data 返回的http body",
"name": "get",
"signature": "async def get(cls, url, params=N... | 2 | stack_v2_sparse_classes_30k_train_009027 | Implement the Python class `AsyncHttpRequests` described below.
Class description:
a wrapper of async http request
Method signatures and docstrings:
- async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30): HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param ... | Implement the Python class `AsyncHttpRequests` described below.
Class description:
a wrapper of async http request
Method signatures and docstrings:
- async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30): HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param ... | 931fca8fab9d7397c52cf9e76a76b1c60e190403 | <|skeleton|>
class AsyncHttpRequests:
"""a wrapper of async http request"""
async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30):
"""HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncHttpRequests:
"""a wrapper of async http request"""
async def get(cls, url, params=None, headers=None, decode_type='utf-8', parse_json=True, timeout=30):
"""HTTP GET 请求 @param url 请求url @param params 请求的uri qurey参数 @param headers 请求的header参数 @param decode_type 返回body解码格式,默认使用utf-8解码 @param p... | the_stack_v2_python_sparse | src/utils/http_client.py | Karmenzind/fp-server | train | 180 |
9ecf5be9dab65c1850dee52e34715500c48ff671 | [
"super(PointNetEstimation, self).__init__()\nself.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=False)\nself.concat = ms.ops.Concat(axis=1)\nself.wconv1 = WarpConv1d(3, 128, kernel_size=1, BN=True, use_activity=True)\nself.wconv2 = WarpConv1d(128, 128, kernel_size=1, BN=True, use_activity=True)\nself.wconv3 = W... | <|body_start_0|>
super(PointNetEstimation, self).__init__()
self.max_op = ms.ops.ArgMaxWithValue(axis=2, keep_dims=False)
self.concat = ms.ops.Concat(axis=1)
self.wconv1 = WarpConv1d(3, 128, kernel_size=1, BN=True, use_activity=True)
self.wconv2 = WarpConv1d(128, 128, kernel_size... | PointNetEstimation | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def construct(self, pts: ms.Tenso... | stack_v2_sparse_classes_36k_train_008297 | 19,684 | permissive | [
{
"docstring": "v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]",
"name": "__init__",
"signature": "def __init__(self, n_classes=3)"
},
{
"docstring": ":param pts: [bs,3,m]... | 2 | null | Implement the Python class `PointNetEstimation` described below.
Class description:
Implement the PointNetEstimation class.
Method signatures and docstrings:
- def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param... | Implement the Python class `PointNetEstimation` described below.
Class description:
Implement the PointNetEstimation class.
Method signatures and docstrings:
- def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def construct(self, pts: ms.Tenso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet @input [bs,3,m=512] @return box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4] :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
super(PointNetEstimation, self).__init__()
self.max_op ... | the_stack_v2_python_sparse | research/cv/frustum-pointnet/src/frustum_pointnets_v1.py | mindspore-ai/models | train | 301 | |
4f591ff1b4d2662d55479682e1cee2f827db8fb2 | [
"super().__init__(['Sigout'], flows)\nself.failrate = 1e-06\nself.assoc_modes({'no_sig': [1.0, [1.5, 1.0, 1.0], 10000]})",
"if self.has_fault('no_sig'):\n self.Sigout.power = 0.0\nelif time < 5:\n self.Sigout.power = 0.0\nelif time < 50:\n self.Sigout.power = 1.0\nelse:\n self.Sigout.power = 0.0"
] | <|body_start_0|>
super().__init__(['Sigout'], flows)
self.failrate = 1e-06
self.assoc_modes({'no_sig': [1.0, [1.5, 1.0, 1.0], 10000]})
<|end_body_0|>
<|body_start_1|>
if self.has_fault('no_sig'):
self.Sigout.power = 0.0
elif time < 5:
self.Sigout.power = ... | Import Signal is the on/off switch | ImportSig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportSig:
"""Import Signal is the on/off switch"""
def __init__(self, flows):
"""Here the main flow is the signal"""
<|body_0|>
def behavior(self, time):
"""This function has time-dependent behavior. To have different operational modes depending on the time, use... | stack_v2_sparse_classes_36k_train_008298 | 13,659 | permissive | [
{
"docstring": "Here the main flow is the signal",
"name": "__init__",
"signature": "def __init__(self, flows)"
},
{
"docstring": "This function has time-dependent behavior. To have different operational modes depending on the time, use if/else statements on the time variable, which is the syste... | 2 | null | Implement the Python class `ImportSig` described below.
Class description:
Import Signal is the on/off switch
Method signatures and docstrings:
- def __init__(self, flows): Here the main flow is the signal
- def behavior(self, time): This function has time-dependent behavior. To have different operational modes depen... | Implement the Python class `ImportSig` described below.
Class description:
Import Signal is the on/off switch
Method signatures and docstrings:
- def __init__(self, flows): Here the main flow is the signal
- def behavior(self, time): This function has time-dependent behavior. To have different operational modes depen... | 2d87c415c036f44fe10310500788f5ab697e618d | <|skeleton|>
class ImportSig:
"""Import Signal is the on/off switch"""
def __init__(self, flows):
"""Here the main flow is the signal"""
<|body_0|>
def behavior(self, time):
"""This function has time-dependent behavior. To have different operational modes depending on the time, use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImportSig:
"""Import Signal is the on/off switch"""
def __init__(self, flows):
"""Here the main flow is the signal"""
super().__init__(['Sigout'], flows)
self.failrate = 1e-06
self.assoc_modes({'no_sig': [1.0, [1.5, 1.0, 1.0], 10000]})
def behavior(self, time):
... | the_stack_v2_python_sparse | pump example/ex_pump.py | DesignEngrLab/fmdtools | train | 10 |
504d30574143337767aae49e8d80b71e886628bc | [
"job_id = self.get_argument('job_id')\nfeatures = self.request.arguments['features']\nms = Archive.get_merging_scheme_from_job(ProcessingJob(job_id))\nresponse = Archive.retrieve_feature_values(archive_merging_scheme=ms, features=features)\nself.write(response)",
"req_path = self.get_argument('path')\nreq_value =... | <|body_start_0|>
job_id = self.get_argument('job_id')
features = self.request.arguments['features']
ms = Archive.get_merging_scheme_from_job(ProcessingJob(job_id))
response = Archive.retrieve_feature_values(archive_merging_scheme=ms, features=features)
self.write(response)
<|end_... | APIArchiveObservations | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIArchiveObservations:
def post(self):
"""Retrieves the archiving information Returns ------- dict The contents of the analysis keyed by sample id Notes ----- Argument "path" must be the Qiita job_id which is used to infer the merging scheme. Argument "features" is a list of feature ide... | stack_v2_sparse_classes_36k_train_008299 | 2,073 | permissive | [
{
"docstring": "Retrieves the archiving information Returns ------- dict The contents of the analysis keyed by sample id Notes ----- Argument \"path\" must be the Qiita job_id which is used to infer the merging scheme. Argument \"features\" is a list of feature identifier, e.g. Deblur sequences. Feature identif... | 2 | stack_v2_sparse_classes_30k_train_021217 | Implement the Python class `APIArchiveObservations` described below.
Class description:
Implement the APIArchiveObservations class.
Method signatures and docstrings:
- def post(self): Retrieves the archiving information Returns ------- dict The contents of the analysis keyed by sample id Notes ----- Argument "path" m... | Implement the Python class `APIArchiveObservations` described below.
Class description:
Implement the APIArchiveObservations class.
Method signatures and docstrings:
- def post(self): Retrieves the archiving information Returns ------- dict The contents of the analysis keyed by sample id Notes ----- Argument "path" m... | 2c05960d712593368237c7c4efe9606a7919f892 | <|skeleton|>
class APIArchiveObservations:
def post(self):
"""Retrieves the archiving information Returns ------- dict The contents of the analysis keyed by sample id Notes ----- Argument "path" must be the Qiita job_id which is used to infer the merging scheme. Argument "features" is a list of feature ide... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIArchiveObservations:
def post(self):
"""Retrieves the archiving information Returns ------- dict The contents of the analysis keyed by sample id Notes ----- Argument "path" must be the Qiita job_id which is used to infer the merging scheme. Argument "features" is a list of feature identifier, e.g. ... | the_stack_v2_python_sparse | qiita_db/handlers/archive.py | yotohoshi/qiita | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.