blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9e2d0f0305cdf761828bfc3c49d6c1157376008e | [
"if profile_name:\n session = boto3.session.Session(profile_name=profile_name, region_name=region)\n self.ec2 = session.client('ec2', region_name=region)\nelse:\n self.ec2 = boto3.client('ec2', region_name=region)\nself.account_name = profile_name\nt = time.time()\nself.start_time = datetime.datetime.utcfr... | <|body_start_0|>
if profile_name:
session = boto3.session.Session(profile_name=profile_name, region_name=region)
self.ec2 = session.client('ec2', region_name=region)
else:
self.ec2 = boto3.client('ec2', region_name=region)
self.account_name = profile_name
... | Spot price data and methods | AWSSpotPriceForRegion | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSSpotPriceForRegion:
"""Spot price data and methods"""
def __init__(self, region=REGION, profile_name=None):
""":type region: :obj:`str` :arg region: AWS region name :type profile_name: :obj:`str` :arg profile_name: legal AWS profile name"""
<|body_0|>
def init_query(s... | stack_v2_sparse_classes_10k_train_007200 | 6,849 | permissive | [
{
"docstring": ":type region: :obj:`str` :arg region: AWS region name :type profile_name: :obj:`str` :arg profile_name: legal AWS profile name",
"name": "__init__",
"signature": "def __init__(self, region=REGION, profile_name=None)"
},
{
"docstring": "Init AWS spot price query :type spot_price_h... | 4 | stack_v2_sparse_classes_30k_val_000047 | Implement the Python class `AWSSpotPriceForRegion` described below.
Class description:
Spot price data and methods
Method signatures and docstrings:
- def __init__(self, region=REGION, profile_name=None): :type region: :obj:`str` :arg region: AWS region name :type profile_name: :obj:`str` :arg profile_name: legal AWS... | Implement the Python class `AWSSpotPriceForRegion` described below.
Class description:
Spot price data and methods
Method signatures and docstrings:
- def __init__(self, region=REGION, profile_name=None): :type region: :obj:`str` :arg region: AWS region name :type profile_name: :obj:`str` :arg profile_name: legal AWS... | 842fdc91a31879084906d71a7d0c317e5035a925 | <|skeleton|>
class AWSSpotPriceForRegion:
"""Spot price data and methods"""
def __init__(self, region=REGION, profile_name=None):
""":type region: :obj:`str` :arg region: AWS region name :type profile_name: :obj:`str` :arg profile_name: legal AWS profile name"""
<|body_0|>
def init_query(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AWSSpotPriceForRegion:
"""Spot price data and methods"""
def __init__(self, region=REGION, profile_name=None):
""":type region: :obj:`str` :arg region: AWS region name :type profile_name: :obj:`str` :arg profile_name: legal AWS profile name"""
if profile_name:
session = boto3.... | the_stack_v2_python_sparse | src/decisionengine_modules/AWS/transforms/AWSSpotPrice.py | HEPCloud/decisionengine_modules | train | 2 |
b04fd945061f57090941fd0c5021759af2ae09ba | [
"PermShkMinNext = np.min(self.IncShkDstn.atoms[0])\nTranShkMinNext = np.min(self.IncShkDstn.atoms[1])\nself.BoroCnstNat = (self.solution_next.attrs['m_nrm_min'] - TranShkMinNext) * (self.params.PermGroFac * PermShkMinNext) / self.params.Rfree",
"next_state = {}\nnext_state['mNrm'] = post_state['aNrm'] * params.Rf... | <|body_start_0|>
PermShkMinNext = np.min(self.IncShkDstn.atoms[0])
TranShkMinNext = np.min(self.IncShkDstn.atoms[1])
self.BoroCnstNat = (self.solution_next.attrs['m_nrm_min'] - TranShkMinNext) * (self.params.PermGroFac * PermShkMinNext) / self.params.Rfree
<|end_body_0|>
<|body_start_1|>
... | Solver for IndShockLabeledType. | ConsIndShockLabeledSolver | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsIndShockLabeledSolver:
"""Solver for IndShockLabeledType."""
def calculate_borrowing_constraint(self):
"""Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of ... | stack_v2_sparse_classes_10k_train_007201 | 40,507 | permissive | [
{
"docstring": "Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of income uncertainty.",
"name": "calculate_borrowing_constraint",
"signature": "def calculate_borrowing_constraint(s... | 4 | stack_v2_sparse_classes_30k_train_003003 | Implement the Python class `ConsIndShockLabeledSolver` described below.
Class description:
Solver for IndShockLabeledType.
Method signatures and docstrings:
- def calculate_borrowing_constraint(self): Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight... | Implement the Python class `ConsIndShockLabeledSolver` described below.
Class description:
Solver for IndShockLabeledType.
Method signatures and docstrings:
- def calculate_borrowing_constraint(self): Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class ConsIndShockLabeledSolver:
"""Solver for IndShockLabeledType."""
def calculate_borrowing_constraint(self):
"""Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConsIndShockLabeledSolver:
"""Solver for IndShockLabeledType."""
def calculate_borrowing_constraint(self):
"""Calculate the minimum allowable value of money resources in this period. This is different from the perfect foresight natural borrowing constraint because of the presence of income uncert... | the_stack_v2_python_sparse | HARK/ConsumptionSaving/ConsLabeledModel.py | econ-ark/HARK | train | 315 |
05a152f09390369a6d9d02a0febe6cec74d508b7 | [
"response = {'success': False, 'message': 'something went wrong', 'data': []}\ntry:\n user = request.user\n redis_data = red.hvals(str(user.id) + 'label')\n if len(redis_data) == 0:\n labels = Label.objects.filter(user_id=user.id)\n label_name = [i.name for i in labels]\n logger.info('... | <|body_start_0|>
response = {'success': False, 'message': 'something went wrong', 'data': []}
try:
user = request.user
redis_data = red.hvals(str(user.id) + 'label')
if len(redis_data) == 0:
labels = Label.objects.filter(user_id=user.id)
... | Summary: -------- Label create class will let authorized user to get and create label. Methods: -------- get: User will get all the created labels by the user. post: User will able to create more labels. | LabelsCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelsCreate:
"""Summary: -------- Label create class will let authorized user to get and create label. Methods: -------- get: User will get all the created labels by the user. post: User will able to create more labels."""
def get(self, request):
"""Summary: -------- label will be f... | stack_v2_sparse_classes_10k_train_007202 | 30,711 | no_license | [
{
"docstring": "Summary: -------- label will be fetched by the User. Exception: ---------- Exception: if anything goes wrong. Returns: -------- response: User will get all the created labels by the user or error msg if label id does not exist.",
"name": "get",
"signature": "def get(self, request)"
},
... | 2 | stack_v2_sparse_classes_30k_train_001008 | Implement the Python class `LabelsCreate` described below.
Class description:
Summary: -------- Label create class will let authorized user to get and create label. Methods: -------- get: User will get all the created labels by the user. post: User will able to create more labels.
Method signatures and docstrings:
- ... | Implement the Python class `LabelsCreate` described below.
Class description:
Summary: -------- Label create class will let authorized user to get and create label. Methods: -------- get: User will get all the created labels by the user. post: User will able to create more labels.
Method signatures and docstrings:
- ... | f4035742d959f493f93a593f49e2fcacb721f85d | <|skeleton|>
class LabelsCreate:
"""Summary: -------- Label create class will let authorized user to get and create label. Methods: -------- get: User will get all the created labels by the user. post: User will able to create more labels."""
def get(self, request):
"""Summary: -------- label will be f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LabelsCreate:
"""Summary: -------- Label create class will let authorized user to get and create label. Methods: -------- get: User will get all the created labels by the user. post: User will able to create more labels."""
def get(self, request):
"""Summary: -------- label will be fetched by the... | the_stack_v2_python_sparse | note/views.py | nk900600/fundooapp | train | 3 |
57afabfaf156351e8508aa1f86d0a664f6549914 | [
"if not root:\n return False\nif not root.left and (not root.right):\n return root.val == sum\nreturn self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)",
"if not root:\n return False\nstack = [(root.val, root)]\nwhile stack:\n value, node = stack.pop()\n if n... | <|body_start_0|>
if not root:
return False
if not root.left and (not root.right):
return root.val == sum
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
<|end_body_0|>
<|body_start_1|>
if not root:
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""递归 到某个节点时,判断其是否是叶子节点并且值是否等于sum 若不是,则递归判断左右子树 注: 递归判断时,需要减去当前root的值"""
<|body_0|>
def hasPathSum_1(self, root: TreeNode, sum: int) -> bool:
"""迭代 每次把之前节点的值加起来"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_007203 | 1,824 | no_license | [
{
"docstring": "递归 到某个节点时,判断其是否是叶子节点并且值是否等于sum 若不是,则递归判断左右子树 注: 递归判断时,需要减去当前root的值",
"name": "hasPathSum",
"signature": "def hasPathSum(self, root: TreeNode, sum: int) -> bool"
},
{
"docstring": "迭代 每次把之前节点的值加起来",
"name": "hasPathSum_1",
"signature": "def hasPathSum_1(self, root: TreeNod... | 2 | stack_v2_sparse_classes_30k_train_001384 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root: TreeNode, sum: int) -> bool: 递归 到某个节点时,判断其是否是叶子节点并且值是否等于sum 若不是,则递归判断左右子树 注: 递归判断时,需要减去当前root的值
- def hasPathSum_1(self, root: TreeNode, sum: int) -> b... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root: TreeNode, sum: int) -> bool: 递归 到某个节点时,判断其是否是叶子节点并且值是否等于sum 若不是,则递归判断左右子树 注: 递归判断时,需要减去当前root的值
- def hasPathSum_1(self, root: TreeNode, sum: int) -> b... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""递归 到某个节点时,判断其是否是叶子节点并且值是否等于sum 若不是,则递归判断左右子树 注: 递归判断时,需要减去当前root的值"""
<|body_0|>
def hasPathSum_1(self, root: TreeNode, sum: int) -> bool:
"""迭代 每次把之前节点的值加起来"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""递归 到某个节点时,判断其是否是叶子节点并且值是否等于sum 若不是,则递归判断左右子树 注: 递归判断时,需要减去当前root的值"""
if not root:
return False
if not root.left and (not root.right):
return root.val == sum
return self.hasPathSum(root... | the_stack_v2_python_sparse | algorithm/leetcode/tree/17-路径总和.py | lxconfig/UbuntuCode_bak | train | 0 | |
b502a3a0e6ba53d161946be8bb8a45b34c298549 | [
"self.c = capacity\nself.table = {}\nself.head = LinkList(0)\nself.tail = LinkList(0)\nself.head.next, self.tail.prev = (self.tail, self.head)",
"if key not in self.table:\n return -1\nvalue, node = self.table[key]\nnode.prev.next, node.next.prev = (node.next, node.prev)\nself.tail.prev.next, self.tail.prev, n... | <|body_start_0|>
self.c = capacity
self.table = {}
self.head = LinkList(0)
self.tail = LinkList(0)
self.head.next, self.tail.prev = (self.tail, self.head)
<|end_body_0|>
<|body_start_1|>
if key not in self.table:
return -1
value, node = self.table[key... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_007204 | 2,073 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | a041962eeab9192799ad7f74b4bbd3e4f74933d0 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.c = capacity
self.table = {}
self.head = LinkList(0)
self.tail = LinkList(0)
self.head.next, self.tail.prev = (self.tail, self.head)
def get(self, key):
""":rtype: int"""
... | the_stack_v2_python_sparse | codes/146. LRU Cache.py | zcgu/leetcode | train | 1 | |
d4b714bab87a12cf3b3f95196b6e6636aef41b43 | [
"count = 0\nfor word in words:\n a = list(chars)\n flag = 1\n for s in word:\n if s not in a:\n flag = 0\n break\n a.remove(s)\n if flag == 1:\n count += len(word)\nreturn count",
"count = 0\nfor word in words:\n for s in word:\n if word.count(s) > ... | <|body_start_0|>
count = 0
for word in words:
a = list(chars)
flag = 1
for s in word:
if s not in a:
flag = 0
break
a.remove(s)
if flag == 1:
count += len(word)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:"""
<|body_0|>
def countCharacters2(self, words: List[str], chars: str) -> int... | stack_v2_sparse_classes_10k_train_007205 | 3,028 | no_license | [
{
"docstring": "执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:",
"name": "countCharacters",
"signature": "def countCharacters(self, words: List[str], chars: str) -> int"
},
{
"docstring": "执行用时 :104 ms, 在所有 Python3 提交中击败了9... | 3 | stack_v2_sparse_classes_30k_train_004830 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countCharacters(self, words: List[str], chars: str) -> int: 执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countCharacters(self, words: List[str], chars: str) -> int: 执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :r... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:"""
<|body_0|>
def countCharacters2(self, words: List[str], chars: str) -> int... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
"""执行用时 :280 ms, 在所有 Python3 提交中击败了31.76%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.11%的用户 :param words: :param chars: :return:"""
count = 0
for word in words:
a = list(chars)
flag = 1
... | the_stack_v2_python_sparse | LeetCode/1160. Find Words That Can Be Formed by Characters.py | yiming1012/MyLeetCode | train | 2 | |
07a7f26fcabc5488a5f3907a550fc92af83078ae | [
"with io.open(filename, 'r', encoding='ascii') as file_handle:\n tokens = []\n version = 1\n count = 0\n for count, line in enumerate(file_handle):\n line_tokens = line.split()\n if count == 0:\n if len(line_tokens) > 0 and line_tokens[0] == 'XPARM.XDS':\n version... | <|body_start_0|>
with io.open(filename, 'r', encoding='ascii') as file_handle:
tokens = []
version = 1
count = 0
for count, line in enumerate(file_handle):
line_tokens = line.split()
if count == 0:
if len(line_to... | A class to read the XPARM.XDS/GXPARM.XDS file used in XDS | reader | [
"BSD-3-Clause-LBNL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class reader:
"""A class to read the XPARM.XDS/GXPARM.XDS file used in XDS"""
def find_version(filename):
"""Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XD... | stack_v2_sparse_classes_10k_train_007206 | 11,104 | permissive | [
{
"docstring": "Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XDS it is the new style version 2 file. If the file contains segment definitions then it is a version 3 file. Params:... | 5 | null | Implement the Python class `reader` described below.
Class description:
A class to read the XPARM.XDS/GXPARM.XDS file used in XDS
Method signatures and docstrings:
- def find_version(filename): Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the o... | Implement the Python class `reader` described below.
Class description:
A class to read the XPARM.XDS/GXPARM.XDS file used in XDS
Method signatures and docstrings:
- def find_version(filename): Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the o... | 7f4dfb6c873fd560920f697cbfd8a5ff6eed82fa | <|skeleton|>
class reader:
"""A class to read the XPARM.XDS/GXPARM.XDS file used in XDS"""
def find_version(filename):
"""Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XD... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class reader:
"""A class to read the XPARM.XDS/GXPARM.XDS file used in XDS"""
def find_version(filename):
"""Check the version if the given file is a (G)XPARM.XDS file. If the file contains exactly 11 lines and 42 tokens, it is the old style version 1 file. If the file starts with XPARM.XDS it is the n... | the_stack_v2_python_sparse | iotbx/xds/xparm.py | cctbx/cctbx_project | train | 206 |
fdfb16032d63dccfe736757871f28ac55b96b3da | [
"self._filename = None\nself._data = None\nself.uhecr = {}\nself.source = {}\nself.detector = {}",
"if label == None:\n label = 'VCV_AGN'\nnew_source = Source(filename, label)\nself.source = new_source",
"if label == None:\n label = 'auger2010'\nnew_uhecr = Uhecr(filename, label)\nself.uhecr = new_uhecr",... | <|body_start_0|>
self._filename = None
self._data = None
self.uhecr = {}
self.source = {}
self.detector = {}
<|end_body_0|>
<|body_start_1|>
if label == None:
label = 'VCV_AGN'
new_source = Source(filename, label)
self.source = new_source
<|en... | A container for high level storage of data. | Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Data:
"""A container for high level storage of data."""
def __init__(self):
"""A container for high level storage of data."""
<|body_0|>
def add_source(self, filename, label=None):
"""Add a source object to the data cotainer :param filename: name of the file cont... | stack_v2_sparse_classes_10k_train_007207 | 15,467 | no_license | [
{
"docstring": "A container for high level storage of data.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add a source object to the data cotainer :param filename: name of the file containing the object's data :param label: reference label for the source object",
... | 6 | stack_v2_sparse_classes_30k_train_006013 | Implement the Python class `Data` described below.
Class description:
A container for high level storage of data.
Method signatures and docstrings:
- def __init__(self): A container for high level storage of data.
- def add_source(self, filename, label=None): Add a source object to the data cotainer :param filename: ... | Implement the Python class `Data` described below.
Class description:
A container for high level storage of data.
Method signatures and docstrings:
- def __init__(self): A container for high level storage of data.
- def add_source(self, filename, label=None): Add a source object to the data cotainer :param filename: ... | 0c1894ce8d9f5daed539240d3ac86e645d6de44c | <|skeleton|>
class Data:
"""A container for high level storage of data."""
def __init__(self):
"""A container for high level storage of data."""
<|body_0|>
def add_source(self, filename, label=None):
"""Add a source object to the data cotainer :param filename: name of the file cont... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Data:
"""A container for high level storage of data."""
def __init__(self):
"""A container for high level storage of data."""
self._filename = None
self._data = None
self.uhecr = {}
self.source = {}
self.detector = {}
def add_source(self, filename, lab... | the_stack_v2_python_sparse | stan_implementation/analysis_interface/interfaces/data.py | cescalara/soiaporn_model | train | 1 |
f88e2aa034f036743d61603dd9a2101d95c4c49d | [
"if self.shift >= 12 and (not isinstance(self, OffsetVariable)):\n return OffsetVariable(rank=self.rank, name=self.name, shift=self.shift, units=self.units, parent=self.parent)\nreturn self",
"if self.shift >= 12 and isinstance(self, OffsetVariable):\n return StandardVariable(rank=self.rank, name=self.name,... | <|body_start_0|>
if self.shift >= 12 and (not isinstance(self, OffsetVariable)):
return OffsetVariable(rank=self.rank, name=self.name, shift=self.shift, units=self.units, parent=self.parent)
return self
<|end_body_0|>
<|body_start_1|>
if self.shift >= 12 and isinstance(self, OffsetV... | A variable with its associated name, shift (in months), and units. | Variable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Variable:
"""A variable with its associated name, shift (in months), and units."""
def get_offset(self):
"""Return a transformed Variable if there is a large (>12) shift."""
<|body_0|>
def get_standard(self):
"""The inverse of `get_offset()`."""
<|body_1|... | stack_v2_sparse_classes_10k_train_007208 | 9,986 | permissive | [
{
"docstring": "Return a transformed Variable if there is a large (>12) shift.",
"name": "get_offset",
"signature": "def get_offset(self)"
},
{
"docstring": "The inverse of `get_offset()`.",
"name": "get_standard",
"signature": "def get_standard(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001730 | Implement the Python class `Variable` described below.
Class description:
A variable with its associated name, shift (in months), and units.
Method signatures and docstrings:
- def get_offset(self): Return a transformed Variable if there is a large (>12) shift.
- def get_standard(self): The inverse of `get_offset()`. | Implement the Python class `Variable` described below.
Class description:
A variable with its associated name, shift (in months), and units.
Method signatures and docstrings:
- def get_offset(self): Return a transformed Variable if there is a large (>12) shift.
- def get_standard(self): The inverse of `get_offset()`.... | 4187f5bfce0595d98361a9264793c25607043047 | <|skeleton|>
class Variable:
"""A variable with its associated name, shift (in months), and units."""
def get_offset(self):
"""Return a transformed Variable if there is a large (>12) shift."""
<|body_0|>
def get_standard(self):
"""The inverse of `get_offset()`."""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Variable:
"""A variable with its associated name, shift (in months), and units."""
def get_offset(self):
"""Return a transformed Variable if there is a large (>12) shift."""
if self.shift >= 12 and (not isinstance(self, OffsetVariable)):
return OffsetVariable(rank=self.rank, n... | the_stack_v2_python_sparse | src/empirical_fire_modelling/variable.py | akuhnregnier/empirical-fire-modelling | train | 0 |
f8ae240497f8b672335581c378632cd63f513426 | [
"allnode = []\nself.findAllNode(root, allnode)\nerror1 = allnode[0]\nfor i in range(len(allnode) - 1):\n if allnode[i].val > allnode[i + 1].val:\n error1 = allnode[i]\n break\nerror2 = allnode[len(allnode) - 1]\nfor i in range(len(allnode) - 1, 0, -1):\n if allnode[i].val < allnode[i - 1].val:\n... | <|body_start_0|>
allnode = []
self.findAllNode(root, allnode)
error1 = allnode[0]
for i in range(len(allnode) - 1):
if allnode[i].val > allnode[i + 1].val:
error1 = allnode[i]
break
error2 = allnode[len(allnode) - 1]
for i in ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def findAllNode(self, root, res):
"""找错误点 :param root: :param res: :return:"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_007209 | 1,513 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "recoverTree",
"signature": "def recoverTree(self, root)"
},
{
"docstring": "找错误点 :param root: :param res: :return:",
"name": "findAllNode",
"signature": "def findAllNode(sel... | 2 | stack_v2_sparse_classes_30k_train_001074 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def findAllNode(self, root, res): 找错误点 :param root: :param ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def findAllNode(self, root, res): 找错误点 :param root: :param ... | beabfd31379f44ffd767fc676912db5022495b53 | <|skeleton|>
class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def findAllNode(self, root, res):
"""找错误点 :param root: :param res: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
allnode = []
self.findAllNode(root, allnode)
error1 = allnode[0]
for i in range(len(allnode) - 1):
if allnode[i].val > allnod... | the_stack_v2_python_sparse | leetCode/tree/099recoverTree.py | fatezy/Algorithm | train | 1 | |
12033b48fdd9011707e972f6aedc5bc3fbcdb7d2 | [
"user = get_object_or_404(DashUser, uuid=request.data['userID'])\nscenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])\nuser_scenario = UserScenario.objects.filter(userID=user, scenarioID=scenario)\nif user_scenario:\n msg = scenario.name + ' scenario is already subscribed'\n return Respons... | <|body_start_0|>
user = get_object_or_404(DashUser, uuid=request.data['userID'])
scenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])
user_scenario = UserScenario.objects.filter(userID=user, scenarioID=scenario)
if user_scenario:
msg = scenario.name + ' sce... | SubscribeScenario | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscribeScenario:
def post(self, request):
"""To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }"""
<|body_0|>
def delete(self, request):
"""To unsubscribe existing scenario of the user # Format { "uuid": "<USERSCENARIO... | stack_v2_sparse_classes_10k_train_007210 | 16,902 | no_license | [
{
"docstring": "To subscribe a new scenario # Format { \"userID\": \"<USER UUID>\", \"scenarioID\": \"<SCENARIO UUID>\" }",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "To unsubscribe existing scenario of the user # Format { \"uuid\": \"<USERSCENARIO UUID>\" }",
... | 2 | stack_v2_sparse_classes_30k_val_000309 | Implement the Python class `SubscribeScenario` described below.
Class description:
Implement the SubscribeScenario class.
Method signatures and docstrings:
- def post(self, request): To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }
- def delete(self, request): To unsub... | Implement the Python class `SubscribeScenario` described below.
Class description:
Implement the SubscribeScenario class.
Method signatures and docstrings:
- def post(self, request): To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }
- def delete(self, request): To unsub... | 9cb5303df8c54f1d26e72557680c35aa4d0b74d0 | <|skeleton|>
class SubscribeScenario:
def post(self, request):
"""To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }"""
<|body_0|>
def delete(self, request):
"""To unsubscribe existing scenario of the user # Format { "uuid": "<USERSCENARIO... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubscribeScenario:
def post(self, request):
"""To subscribe a new scenario # Format { "userID": "<USER UUID>", "scenarioID": "<SCENARIO UUID>" }"""
user = get_object_or_404(DashUser, uuid=request.data['userID'])
scenario = get_object_or_404(Scenario, uuid=request.data['scenarioID'])
... | the_stack_v2_python_sparse | apps/apis/views.py | guyandtheworld/news-serve-api | train | 2 | |
b4ecf900864f187a7f38127cf75a8c2e680246cc | [
"self.__urlBase = 'https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events=history&crumb={3}'\ntry:\n self.cookie_man = cm.CookieManager()\nexcept ValueError as e:\n logger.logger.log(logger.FATAL_ERROR, 'Error occurred while obtaining cookie: {0}'.format(str(e)))\n... | <|body_start_0|>
self.__urlBase = 'https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events=history&crumb={3}'
try:
self.cookie_man = cm.CookieManager()
except ValueError as e:
logger.logger.log(logger.FATAL_ERROR, 'Error occurre... | DownloaderYahoo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloaderYahoo:
def __init__(self):
"""Initialization function"""
<|body_0|>
def getHistoricalData(self, ticker_list, max_number_of_days=-1, final_date=None):
"""Obtains the entirety of the historical data fore each of the stocks that is possible @param final_date: ... | stack_v2_sparse_classes_10k_train_007211 | 4,421 | permissive | [
{
"docstring": "Initialization function",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Obtains the entirety of the historical data fore each of the stocks that is possible @param final_date: datetime.datetime object matching the final day in the period stock data shou... | 3 | stack_v2_sparse_classes_30k_train_001837 | Implement the Python class `DownloaderYahoo` described below.
Class description:
Implement the DownloaderYahoo class.
Method signatures and docstrings:
- def __init__(self): Initialization function
- def getHistoricalData(self, ticker_list, max_number_of_days=-1, final_date=None): Obtains the entirety of the historic... | Implement the Python class `DownloaderYahoo` described below.
Class description:
Implement the DownloaderYahoo class.
Method signatures and docstrings:
- def __init__(self): Initialization function
- def getHistoricalData(self, ticker_list, max_number_of_days=-1, final_date=None): Obtains the entirety of the historic... | 37411c1204ecf69040ba2a1658013e4bf71eef9d | <|skeleton|>
class DownloaderYahoo:
def __init__(self):
"""Initialization function"""
<|body_0|>
def getHistoricalData(self, ticker_list, max_number_of_days=-1, final_date=None):
"""Obtains the entirety of the historical data fore each of the stocks that is possible @param final_date: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DownloaderYahoo:
def __init__(self):
"""Initialization function"""
self.__urlBase = 'https://query1.finance.yahoo.com/v7/finance/download/{0}?period1={1}&period2={2}&interval=1d&events=history&crumb={3}'
try:
self.cookie_man = cm.CookieManager()
except ValueError as... | the_stack_v2_python_sparse | src/stock_data_downloading_module/stock_data_downloading/downloader_yahoo.py | reiserbc/ML-StockAnalysisProject | train | 0 | |
e915b63d9cbecf2d79f0eee2cb37c09b9827f927 | [
"self.alert_category = alert_category\nself.alert_code = alert_code\nself.alert_document = alert_document\nself.alert_state = alert_state\nself.alert_type = alert_type\nself.alert_type_bucket = alert_type_bucket\nself.cluster_id = cluster_id\nself.cluster_name = cluster_name\nself.dedup_count = dedup_count\nself.de... | <|body_start_0|>
self.alert_category = alert_category
self.alert_code = alert_code
self.alert_document = alert_document
self.alert_state = alert_state
self.alert_type = alert_type
self.alert_type_bucket = alert_type_bucket
self.cluster_id = cluster_id
self... | Implementation of the 'Alert' model. Specifies information about an Alert such as the type, id assigned by the Cohesity Cluster, number of duplicates, severity, etc. Attributes: alert_category (AlertCategoryEnum): Specifies the category of an Alert. kDisk - Alert associated with the disk. kNode - Alert associated with ... | Alert | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Alert:
"""Implementation of the 'Alert' model. Specifies information about an Alert such as the type, id assigned by the Cohesity Cluster, number of duplicates, severity, etc. Attributes: alert_category (AlertCategoryEnum): Specifies the category of an Alert. kDisk - Alert associated with the dis... | stack_v2_sparse_classes_10k_train_007212 | 12,597 | permissive | [
{
"docstring": "Constructor for the Alert class",
"name": "__init__",
"signature": "def __init__(self, alert_category=None, alert_code=None, alert_document=None, alert_state=None, alert_type=None, alert_type_bucket=None, cluster_id=None, cluster_name=None, dedup_count=None, dedup_timestamps=None, event_... | 2 | null | Implement the Python class `Alert` described below.
Class description:
Implementation of the 'Alert' model. Specifies information about an Alert such as the type, id assigned by the Cohesity Cluster, number of duplicates, severity, etc. Attributes: alert_category (AlertCategoryEnum): Specifies the category of an Alert... | Implement the Python class `Alert` described below.
Class description:
Implementation of the 'Alert' model. Specifies information about an Alert such as the type, id assigned by the Cohesity Cluster, number of duplicates, severity, etc. Attributes: alert_category (AlertCategoryEnum): Specifies the category of an Alert... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Alert:
"""Implementation of the 'Alert' model. Specifies information about an Alert such as the type, id assigned by the Cohesity Cluster, number of duplicates, severity, etc. Attributes: alert_category (AlertCategoryEnum): Specifies the category of an Alert. kDisk - Alert associated with the dis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Alert:
"""Implementation of the 'Alert' model. Specifies information about an Alert such as the type, id assigned by the Cohesity Cluster, number of duplicates, severity, etc. Attributes: alert_category (AlertCategoryEnum): Specifies the category of an Alert. kDisk - Alert associated with the disk. kNode - Al... | the_stack_v2_python_sparse | cohesity_management_sdk/models/alert.py | cohesity/management-sdk-python | train | 24 |
7e31dccdfcf4efe2d5b4db6dd40fd8aa5d76a64e | [
"num_rows = self._parse_file_data_size(file_path)\npixels = zeros((num_rows, self.num_columns - 1), float32)\nnumbers = zeros((num_rows,), uint8)\nrow = 0\nfor sample_data in super(TrainingSetIO, self).parse(file_path):\n numbers[row] = uint8(sample_data[0])\n pixels[row] = uint8(sample_data[1:])\n row += ... | <|body_start_0|>
num_rows = self._parse_file_data_size(file_path)
pixels = zeros((num_rows, self.num_columns - 1), float32)
numbers = zeros((num_rows,), uint8)
row = 0
for sample_data in super(TrainingSetIO, self).parse(file_path):
numbers[row] = uint8(sample_data[0])... | Parses kaggle input training and test set data for processing For training data input is expected in the form: label, pixel0, pixel1, ... pixelN 1,22,33,...250 9,53,0,...125 ... Where the label column is absent for testing, the format is otherwise identical Pixels can range from 0 -> 255 Labels can range from 0 -> 9 | TrainingSetIO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingSetIO:
"""Parses kaggle input training and test set data for processing For training data input is expected in the form: label, pixel0, pixel1, ... pixelN 1,22,33,...250 9,53,0,...125 ... Where the label column is absent for testing, the format is otherwise identical Pixels can range from... | stack_v2_sparse_classes_10k_train_007213 | 2,146 | no_license | [
{
"docstring": "Parses the training set for labels (image numbers) and pixel values Generates tuples of integer labels and arrays of pixel values :param file_path: The path to be parsed :return: A tuple of (actual numbers, images). Where actual numbers is an array of the integer value of the associated image. I... | 2 | stack_v2_sparse_classes_30k_train_000156 | Implement the Python class `TrainingSetIO` described below.
Class description:
Parses kaggle input training and test set data for processing For training data input is expected in the form: label, pixel0, pixel1, ... pixelN 1,22,33,...250 9,53,0,...125 ... Where the label column is absent for testing, the format is ot... | Implement the Python class `TrainingSetIO` described below.
Class description:
Parses kaggle input training and test set data for processing For training data input is expected in the form: label, pixel0, pixel1, ... pixelN 1,22,33,...250 9,53,0,...125 ... Where the label column is absent for testing, the format is ot... | 164f8df98b82d6be55e01229feac7f09cd7b3be0 | <|skeleton|>
class TrainingSetIO:
"""Parses kaggle input training and test set data for processing For training data input is expected in the form: label, pixel0, pixel1, ... pixelN 1,22,33,...250 9,53,0,...125 ... Where the label column is absent for testing, the format is otherwise identical Pixels can range from... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrainingSetIO:
"""Parses kaggle input training and test set data for processing For training data input is expected in the form: label, pixel0, pixel1, ... pixelN 1,22,33,...250 9,53,0,...125 ... Where the label column is absent for testing, the format is otherwise identical Pixels can range from 0 -> 255 Lab... | the_stack_v2_python_sparse | formatted_io/training_set_io.py | barryhennessy/digit_classifier | train | 0 |
ff1d191f3fd8493ab554084a811247d7d83ce5d0 | [
"addresses = addresses or list(utils.generate_mac_addresses(count=count))\nports = []\n_port_addresses = {}\nfor address in addresses:\n port = self._client.port.create(address=address, node_uuid=node.uuid, **kwargs)\n _port_addresses[port.uuid] = address\n ports.append(port)\nif check:\n self.check_por... | <|body_start_0|>
addresses = addresses or list(utils.generate_mac_addresses(count=count))
ports = []
_port_addresses = {}
for address in addresses:
port = self._client.port.create(address=address, node_uuid=node.uuid, **kwargs)
_port_addresses[port.uuid] = address... | Ironic port steps. | IronicPortSteps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IronicPortSteps:
"""Ironic port steps."""
def create_ports(self, node, addresses=None, count=1, check=True, **kwargs):
"""Step to create ironic ports with kwargs dictionary of attributes. Args: addresses (list): MAC addresses for ports node (object): node of the ports should be assoc... | stack_v2_sparse_classes_10k_train_007214 | 4,813 | no_license | [
{
"docstring": "Step to create ironic ports with kwargs dictionary of attributes. Args: addresses (list): MAC addresses for ports node (object): node of the ports should be associated with count (int): count of created ports check (bool): For checking ports were created correct with correct addresses kwargs: Op... | 4 | null | Implement the Python class `IronicPortSteps` described below.
Class description:
Ironic port steps.
Method signatures and docstrings:
- def create_ports(self, node, addresses=None, count=1, check=True, **kwargs): Step to create ironic ports with kwargs dictionary of attributes. Args: addresses (list): MAC addresses f... | Implement the Python class `IronicPortSteps` described below.
Class description:
Ironic port steps.
Method signatures and docstrings:
- def create_ports(self, node, addresses=None, count=1, check=True, **kwargs): Step to create ironic ports with kwargs dictionary of attributes. Args: addresses (list): MAC addresses f... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class IronicPortSteps:
"""Ironic port steps."""
def create_ports(self, node, addresses=None, count=1, check=True, **kwargs):
"""Step to create ironic ports with kwargs dictionary of attributes. Args: addresses (list): MAC addresses for ports node (object): node of the ports should be assoc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IronicPortSteps:
"""Ironic port steps."""
def create_ports(self, node, addresses=None, count=1, check=True, **kwargs):
"""Step to create ironic ports with kwargs dictionary of attributes. Args: addresses (list): MAC addresses for ports node (object): node of the ports should be associated with co... | the_stack_v2_python_sparse | stepler/baremetal/steps/port.py | Mirantis/stepler | train | 16 |
129ca51a52d26887e85a1626eabee958aa38a6c5 | [
"x, y = (0, -1)\nn = len(array)\nfor i in range(n):\n for j in range(i, n):\n curr_sum = sum(array[i:j + 1])\n if curr_sum == 0 and j - i + 1 > y - x + 1:\n x, y = (i, j)\nreturn array[x:y + 1]",
"prev_sum = {0: -1}\nx, y = (0, -1)\ncurr = 0\nfor i, num in enumerate(array):\n curr +... | <|body_start_0|>
x, y = (0, -1)
n = len(array)
for i in range(n):
for j in range(i, n):
curr_sum = sum(array[i:j + 1])
if curr_sum == 0 and j - i + 1 > y - x + 1:
x, y = (i, j)
return array[x:y + 1]
<|end_body_0|>
<|body_st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_largest_brute(self, array):
"""Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array)."""
<|body_0|>
def find_largest(self, array):
"""Algorithm based on hashing already calculated sum. Time ... | stack_v2_sparse_classes_10k_train_007215 | 2,509 | no_license | [
{
"docstring": "Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array).",
"name": "find_largest_brute",
"signature": "def find_largest_brute(self, array)"
},
{
"docstring": "Algorithm based on hashing already calculated sum. Time complexit... | 3 | stack_v2_sparse_classes_30k_train_006651 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_largest_brute(self, array): Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array).
- def find_largest(self, arr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_largest_brute(self, array): Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array).
- def find_largest(self, arr... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def find_largest_brute(self, array):
"""Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array)."""
<|body_0|>
def find_largest(self, array):
"""Algorithm based on hashing already calculated sum. Time ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def find_largest_brute(self, array):
"""Brute force algorithm. Checks all subarrays. Time complexity: O(n ^ 3). Space complexity: O(n), n is len(array)."""
x, y = (0, -1)
n = len(array)
for i in range(n):
for j in range(i, n):
curr_sum = su... | the_stack_v2_python_sparse | Hashing/largest_zero_sum.py | vladn90/Algorithms | train | 0 | |
d7308318fedd81c1965f4266798b13219f3bd865 | [
"if len(nums) == 0 or nums is None:\n return 0\nif len(nums) <= 2:\n return max(nums[:])\nreturn max(self.robHelper(nums[1:]), self.robHelper(nums[:len(nums) - 1]))",
"pp = nums[0]\np = max(pp, nums[1])\nfor i in range(2, len(nums)):\n tmp = p\n p = max(pp + nums[i], p)\n pp = tmp\nreturn p"
] | <|body_start_0|>
if len(nums) == 0 or nums is None:
return 0
if len(nums) <= 2:
return max(nums[:])
return max(self.robHelper(nums[1:]), self.robHelper(nums[:len(nums) - 1]))
<|end_body_0|>
<|body_start_1|>
pp = nums[0]
p = max(pp, nums[1])
for i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def robHelper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0 or nums is None:
return 0... | stack_v2_sparse_classes_10k_train_007216 | 707 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "robHelper",
"signature": "def robHelper(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def robHelper(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 rob(self, nums): :type nums: List[int] :rtype: int
- def robHelper(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def robHelper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0 or nums is None:
return 0
if len(nums) <= 2:
return max(nums[:])
return max(self.robHelper(nums[1:]), self.robHelper(nums[:len(nums) - 1]))
def robHelper(self, ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/lc-all-solutions/213.house-robber-ii/house-robber-ii.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
68ad5214491d94b3cadddcb31441c3ba95632f6d | [
"self.sensor = gateway.api.sensors[sensor_id]\nself.gateway = gateway\nself.description = description\nself.async_add_entities = async_add_entities\nself.unsubscribe = self.sensor.subscribe(self.async_update_callback)",
"if self.description.update_key in self.sensor.changed_keys:\n self.unsubscribe()\n self... | <|body_start_0|>
self.sensor = gateway.api.sensors[sensor_id]
self.gateway = gateway
self.description = description
self.async_add_entities = async_add_entities
self.unsubscribe = self.sensor.subscribe(self.async_update_callback)
<|end_body_0|>
<|body_start_1|>
if self.d... | Track sensors without a battery state and add entity when battery state exist. | DeconzBatteryTracker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeconzBatteryTracker:
"""Track sensors without a battery state and add entity when battery state exist."""
def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None:
"""Set up tracker."""
... | stack_v2_sparse_classes_10k_train_007217 | 16,422 | permissive | [
{
"docstring": "Set up tracker.",
"name": "__init__",
"signature": "def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None"
},
{
"docstring": "Update the device's state.",
"name": "async_update_callbac... | 2 | null | Implement the Python class `DeconzBatteryTracker` described below.
Class description:
Track sensors without a battery state and add entity when battery state exist.
Method signatures and docstrings:
- def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: ... | Implement the Python class `DeconzBatteryTracker` described below.
Class description:
Track sensors without a battery state and add entity when battery state exist.
Method signatures and docstrings:
- def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DeconzBatteryTracker:
"""Track sensors without a battery state and add entity when battery state exist."""
def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None:
"""Set up tracker."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeconzBatteryTracker:
"""Track sensors without a battery state and add entity when battery state exist."""
def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None:
"""Set up tracker."""
self.sensor =... | the_stack_v2_python_sparse | homeassistant/components/deconz/sensor.py | home-assistant/core | train | 35,501 |
3a253428e137197d4133562d6e7deb2fff3f5c2f | [
"super().__init__(hass, LOGGER, name=name, update_interval=update_interval, update_method=update_method, always_update=False)\nself._rebooting = False\nself._signal_handler_unsubs: list[Callable[..., None]] = []\nself.config_entry = entry\nself.signal_reboot_completed = SIGNAL_REBOOT_COMPLETED.format(self.config_en... | <|body_start_0|>
super().__init__(hass, LOGGER, name=name, update_interval=update_interval, update_method=update_method, always_update=False)
self._rebooting = False
self._signal_handler_unsubs: list[Callable[..., None]] = []
self.config_entry = entry
self.signal_reboot_completed... | Define an extended DataUpdateCoordinator. | RainMachineDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainMachineDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None:
"""Initialize."""
<|bod... | stack_v2_sparse_classes_10k_train_007218 | 5,234 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None"
},
{
"docstring": "Initialize the coordinator.",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_006144 | Implement the Python class `RainMachineDataUpdateCoordinator` described below.
Class description:
Define an extended DataUpdateCoordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callab... | Implement the Python class `RainMachineDataUpdateCoordinator` described below.
Class description:
Define an extended DataUpdateCoordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callab... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RainMachineDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None:
"""Initialize."""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RainMachineDataUpdateCoordinator:
"""Define an extended DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry, name: str, api_category: str, update_interval: timedelta, update_method: Callable[..., Awaitable]) -> None:
"""Initialize."""
super().__init__(h... | the_stack_v2_python_sparse | homeassistant/components/rainmachine/util.py | home-assistant/core | train | 35,501 |
e944924f06776adce205340fdb95884385004029 | [
"template = PartParameterTemplate.objects.create(name='My Template', description='A template with choices', choices='red, blue, green')\npass_values = ['red', 'blue', 'green']\nfail_values = ['rod', 'bleu', 'grene']\npart = Part.objects.all().first()\nfor value in pass_values:\n param = PartParameter(part=part, ... | <|body_start_0|>
template = PartParameterTemplate.objects.create(name='My Template', description='A template with choices', choices='red, blue, green')
pass_values = ['red', 'blue', 'green']
fail_values = ['rod', 'bleu', 'grene']
part = Part.objects.all().first()
for value in pas... | Unit tests for parameter validation | ParameterTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterTests:
"""Unit tests for parameter validation"""
def test_choice_validation(self):
"""Test that parameter choices are correctly validated"""
<|body_0|>
def test_unit_validation(self):
"""Test validation of 'units' field for PartParameterTemplate"""
... | stack_v2_sparse_classes_10k_train_007219 | 12,864 | permissive | [
{
"docstring": "Test that parameter choices are correctly validated",
"name": "test_choice_validation",
"signature": "def test_choice_validation(self)"
},
{
"docstring": "Test validation of 'units' field for PartParameterTemplate",
"name": "test_unit_validation",
"signature": "def test_u... | 4 | stack_v2_sparse_classes_30k_train_002942 | Implement the Python class `ParameterTests` described below.
Class description:
Unit tests for parameter validation
Method signatures and docstrings:
- def test_choice_validation(self): Test that parameter choices are correctly validated
- def test_unit_validation(self): Test validation of 'units' field for PartParam... | Implement the Python class `ParameterTests` described below.
Class description:
Unit tests for parameter validation
Method signatures and docstrings:
- def test_choice_validation(self): Test that parameter choices are correctly validated
- def test_unit_validation(self): Test validation of 'units' field for PartParam... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class ParameterTests:
"""Unit tests for parameter validation"""
def test_choice_validation(self):
"""Test that parameter choices are correctly validated"""
<|body_0|>
def test_unit_validation(self):
"""Test validation of 'units' field for PartParameterTemplate"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParameterTests:
"""Unit tests for parameter validation"""
def test_choice_validation(self):
"""Test that parameter choices are correctly validated"""
template = PartParameterTemplate.objects.create(name='My Template', description='A template with choices', choices='red, blue, green')
... | the_stack_v2_python_sparse | InvenTree/part/test_param.py | inventree/InvenTree | train | 3,077 |
a330d62002b315707cc0ee83bc38f61aca9c6965 | [
"stack = []\nres = []\nrs = ''\nfor n in range(len(s)):\n if s[n] != ' ':\n stack.append(s[n])\n else:\n while len(stack) > 0:\n res.append(stack.pop())\n res.append(' ')\nwhile len(stack) > 0:\n res.append(stack.pop())\nreturn rs.join(res)",
"s = s.split(' ')\nfor i in ra... | <|body_start_0|>
stack = []
res = []
rs = ''
for n in range(len(s)):
if s[n] != ' ':
stack.append(s[n])
else:
while len(stack) > 0:
res.append(stack.pop())
res.append(' ')
while len(stack)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWords2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = []
res = []
rs = ''
for n in range... | stack_v2_sparse_classes_10k_train_007220 | 1,177 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords2",
"signature": "def reverseWords2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004015 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWords2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWords2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseWords(self, s):
"... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWords2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
stack = []
res = []
rs = ''
for n in range(len(s)):
if s[n] != ' ':
stack.append(s[n])
else:
while len(stack) > 0:
res.append(... | the_stack_v2_python_sparse | 11. STRING MANIP/reverse_words_in_A_string_III/solution.py | kimmyoo/python_leetcode | train | 1 | |
56b1da541bb8cca70306510fc8dafc9dd4a818b9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DelegatedAdminRelationshipRequest()",
"from .delegated_admin_relationship_request_action import DelegatedAdminRelationshipRequestAction\nfrom .delegated_admin_relationship_request_status import DelegatedAdminRelationshipRequestStatus\n... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DelegatedAdminRelationshipRequest()
<|end_body_0|>
<|body_start_1|>
from .delegated_admin_relationship_request_action import DelegatedAdminRelationshipRequestAction
from .delegated_admin... | DelegatedAdminRelationshipRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelegatedAdminRelationshipRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin... | stack_v2_sparse_classes_10k_train_007221 | 3,825 | 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: DelegatedAdminRelationshipRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from... | 3 | stack_v2_sparse_classes_30k_train_007307 | Implement the Python class `DelegatedAdminRelationshipRequest` described below.
Class description:
Implement the DelegatedAdminRelationshipRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest: Creates a new in... | Implement the Python class `DelegatedAdminRelationshipRequest` described below.
Class description:
Implement the DelegatedAdminRelationshipRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest: Creates a new in... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DelegatedAdminRelationshipRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DelegatedAdminRelationshipRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminRelationshipRequest:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/delegated_admin_relationship_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
667426322e8b20be95be8415c8b544312fa8f4f5 | [
"role = db.Role.get(id)\nif not role:\n return ({'msg': f'Role id={id} not found!'}, HTTPStatus.NOT_FOUND)\nauth_org = self.obtain_auth_organization()\nif not self.r.v_glo.can():\n if not (self.r.v_org.can() and auth_org == role.organization):\n return ({'msg': 'You lack permissions to do that'}, HTTPS... | <|body_start_0|>
role = db.Role.get(id)
if not role:
return ({'msg': f'Role id={id} not found!'}, HTTPStatus.NOT_FOUND)
auth_org = self.obtain_auth_organization()
if not self.r.v_glo.can():
if not (self.r.v_org.can() and auth_org == role.organization):
... | RoleRules | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleRules:
def get(self, id):
"""Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a ... | stack_v2_sparse_classes_10k_train_007222 | 26,260 | permissive | [
{
"docstring": "Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a role's rules| |Role|Organization|View|❌|❌... | 3 | stack_v2_sparse_classes_30k_train_001096 | Implement the Python class `RoleRules` described below.
Class description:
Implement the RoleRules class.
Method signatures and docstrings:
- def get(self, id): Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assi... | Implement the Python class `RoleRules` described below.
Class description:
Implement the RoleRules class.
Method signatures and docstrings:
- def get(self, id): Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assi... | b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca | <|skeleton|>
class RoleRules:
def get(self, id):
"""Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RoleRules:
def get(self, id):
"""Returns the rules for a specific role --- description: >- View the rules that belong to a specific role. ### Permission Table |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description| |--|--|--|--|--|--| |Role|Global|View|❌|❌|View a role's rules| ... | the_stack_v2_python_sparse | vantage6-server/vantage6/server/resource/role.py | vantage6/vantage6 | train | 15 | |
1a725a99c23d33a59e31935e37c031cb7f117502 | [
"status = ErrorCode.SUCCESS\ntry:\n tid = self.get_argument('tid')\nexcept Exception as e:\n status = ErrorCode.ILLEGAL_DATA_FORMAT\n logging.exception('[UWEB] Invalid data format. Exception: %s', e.args)\n self.write_ret(status)\n return\ntry:\n res = QueryHelper.get_bind_region(tid, self.db)\n ... | <|body_start_0|>
status = ErrorCode.SUCCESS
try:
tid = self.get_argument('tid')
except Exception as e:
status = ErrorCode.ILLEGAL_DATA_FORMAT
logging.exception('[UWEB] Invalid data format. Exception: %s', e.args)
self.write_ret(status)
... | Handle regions-bind for corp. :url /bindregion | BindRegionHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BindRegionHandler:
"""Handle regions-bind for corp. :url /bindregion"""
def get(self):
"""Get all regions binded by the terminal."""
<|body_0|>
def post(self):
"""Bind region bind for the terminals."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007223 | 2,434 | no_license | [
{
"docstring": "Get all regions binded by the terminal.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Bind region bind for the terminals.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `BindRegionHandler` described below.
Class description:
Handle regions-bind for corp. :url /bindregion
Method signatures and docstrings:
- def get(self): Get all regions binded by the terminal.
- def post(self): Bind region bind for the terminals. | Implement the Python class `BindRegionHandler` described below.
Class description:
Handle regions-bind for corp. :url /bindregion
Method signatures and docstrings:
- def get(self): Get all regions binded by the terminal.
- def post(self): Bind region bind for the terminals.
<|skeleton|>
class BindRegionHandler:
... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class BindRegionHandler:
"""Handle regions-bind for corp. :url /bindregion"""
def get(self):
"""Get all regions binded by the terminal."""
<|body_0|>
def post(self):
"""Bind region bind for the terminals."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BindRegionHandler:
"""Handle regions-bind for corp. :url /bindregion"""
def get(self):
"""Get all regions binded by the terminal."""
status = ErrorCode.SUCCESS
try:
tid = self.get_argument('tid')
except Exception as e:
status = ErrorCode.ILLEGAL_DAT... | the_stack_v2_python_sparse | apps/uweb/handlers/bindregion.py | jcsy521/ydws | train | 0 |
8bb8ed27b436ddf15f3a55a111cb4ed81ba57559 | [
"self.end_time_usecs = end_time_usecs\nself.is_incremental = is_incremental\nself.logical_bytes_transferred = logical_bytes_transferred\nself.logical_size_bytes = logical_size_bytes\nself.logical_transfer_rate_bps = logical_transfer_rate_bps\nself.physical_bytes_transferred = physical_bytes_transferred\nself.start_... | <|body_start_0|>
self.end_time_usecs = end_time_usecs
self.is_incremental = is_incremental
self.logical_bytes_transferred = logical_bytes_transferred
self.logical_size_bytes = logical_size_bytes
self.logical_transfer_rate_bps = logical_transfer_rate_bps
self.physical_byte... | Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental (bool): Specifies whether this archival... | CopyRunStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyRunStats:
"""Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental... | stack_v2_sparse_classes_10k_train_007224 | 3,966 | permissive | [
{
"docstring": "Constructor for the CopyRunStats class",
"name": "__init__",
"signature": "def __init__(self, end_time_usecs=None, is_incremental=None, logical_bytes_transferred=None, logical_size_bytes=None, logical_transfer_rate_bps=None, physical_bytes_transferred=None, start_time_usecs=None)"
},
... | 2 | null | Implement the Python class `CopyRunStats` described below.
Class description:
Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replic... | Implement the Python class `CopyRunStats` described below.
Class description:
Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replic... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CopyRunStats:
"""Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CopyRunStats:
"""Implementation of the 'CopyRunStats' model. Stats for one copy task or aggregated stats of a Copy Run in a Protection Job Run. Attributes: end_time_usecs (long|int): Specifies the time when this replication ended. If not set, then the replication has not ended yet. is_incremental (bool): Spec... | the_stack_v2_python_sparse | cohesity_management_sdk/models/copy_run_stats.py | cohesity/management-sdk-python | train | 24 |
bba969a7f96173f077a951082a3b50502f3aa406 | [
"self.text = text\nself.motive = motive\nself.replacement = replacement\nself.finite_state_machine = finite_state_machine",
"positions = self.finite_state_machine.look_for(self.text)\ndecal = 0\nresult = ''\nfor pos in range(len(self.text)):\n if pos + decal in positions:\n result += self.replacement\n ... | <|body_start_0|>
self.text = text
self.motive = motive
self.replacement = replacement
self.finite_state_machine = finite_state_machine
<|end_body_0|>
<|body_start_1|>
positions = self.finite_state_machine.look_for(self.text)
decal = 0
result = ''
for pos ... | define the replace methode for a Text | Text | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Text:
"""define the replace methode for a Text"""
def __init__(self, text, motive, replacement, finite_state_machine):
"""initiate the text text : str represent the text motive : str this is the motive we are looking for replacement : str this is the thing that replace the motive fin... | stack_v2_sparse_classes_10k_train_007225 | 1,007 | no_license | [
{
"docstring": "initiate the text text : str represent the text motive : str this is the motive we are looking for replacement : str this is the thing that replace the motive finite_state_machine : FiniteStateMachine is the machine designed for the motive we are looking for",
"name": "__init__",
"signat... | 2 | stack_v2_sparse_classes_30k_val_000231 | Implement the Python class `Text` described below.
Class description:
define the replace methode for a Text
Method signatures and docstrings:
- def __init__(self, text, motive, replacement, finite_state_machine): initiate the text text : str represent the text motive : str this is the motive we are looking for replac... | Implement the Python class `Text` described below.
Class description:
define the replace methode for a Text
Method signatures and docstrings:
- def __init__(self, text, motive, replacement, finite_state_machine): initiate the text text : str represent the text motive : str this is the motive we are looking for replac... | 147773cc8871d74f1ec1d6bd03e3cce95e9490d1 | <|skeleton|>
class Text:
"""define the replace methode for a Text"""
def __init__(self, text, motive, replacement, finite_state_machine):
"""initiate the text text : str represent the text motive : str this is the motive we are looking for replacement : str this is the thing that replace the motive fin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Text:
"""define the replace methode for a Text"""
def __init__(self, text, motive, replacement, finite_state_machine):
"""initiate the text text : str represent the text motive : str this is the motive we are looking for replacement : str this is the thing that replace the motive finite_state_mac... | the_stack_v2_python_sparse | theorie_des_graphes/TP2/Text.py | porigonop/code_v2 | train | 0 |
b1058e0e388171501c29fa6c189b7551ddde4d86 | [
"try:\n data = ExcelUtil(reportxlsx, Sheet_Name).dict_data()\n login_cookies = loggin_wx()\n cookie = requests.utils.dict_from_cookiejar(login_cookies.cookies)\n cookies = {'SERVERID': '%s' % cookie, 'SESSION': '%s' % wx_session}\n test_id = 0\n s = requests.session()\n res = send_requests(s, d... | <|body_start_0|>
try:
data = ExcelUtil(reportxlsx, Sheet_Name).dict_data()
login_cookies = loggin_wx()
cookie = requests.utils.dict_from_cookiejar(login_cookies.cookies)
cookies = {'SERVERID': '%s' % cookie, 'SESSION': '%s' % wx_session}
test_id = 0
... | member_openChildCard | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class member_openChildCard:
def test_openChildCard_1(self):
"""开通附属卡,附属卡已存在的情况"""
<|body_0|>
def test_openChildCard_2(self):
"""开通附属卡,主卡人ID错误"""
<|body_1|>
def test_openChildCard_3(self):
"""开通附属卡,主卡ID错误"""
<|body_2|>
def test_openChildCar... | stack_v2_sparse_classes_10k_train_007226 | 4,831 | permissive | [
{
"docstring": "开通附属卡,附属卡已存在的情况",
"name": "test_openChildCard_1",
"signature": "def test_openChildCard_1(self)"
},
{
"docstring": "开通附属卡,主卡人ID错误",
"name": "test_openChildCard_2",
"signature": "def test_openChildCard_2(self)"
},
{
"docstring": "开通附属卡,主卡ID错误",
"name": "test_ope... | 5 | stack_v2_sparse_classes_30k_train_004293 | Implement the Python class `member_openChildCard` described below.
Class description:
Implement the member_openChildCard class.
Method signatures and docstrings:
- def test_openChildCard_1(self): 开通附属卡,附属卡已存在的情况
- def test_openChildCard_2(self): 开通附属卡,主卡人ID错误
- def test_openChildCard_3(self): 开通附属卡,主卡ID错误
- def test_... | Implement the Python class `member_openChildCard` described below.
Class description:
Implement the member_openChildCard class.
Method signatures and docstrings:
- def test_openChildCard_1(self): 开通附属卡,附属卡已存在的情况
- def test_openChildCard_2(self): 开通附属卡,主卡人ID错误
- def test_openChildCard_3(self): 开通附属卡,主卡ID错误
- def test_... | 472f3f6d9bd407f1c4ed30a5557ec141e2434188 | <|skeleton|>
class member_openChildCard:
def test_openChildCard_1(self):
"""开通附属卡,附属卡已存在的情况"""
<|body_0|>
def test_openChildCard_2(self):
"""开通附属卡,主卡人ID错误"""
<|body_1|>
def test_openChildCard_3(self):
"""开通附属卡,主卡ID错误"""
<|body_2|>
def test_openChildCar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class member_openChildCard:
def test_openChildCard_1(self):
"""开通附属卡,附属卡已存在的情况"""
try:
data = ExcelUtil(reportxlsx, Sheet_Name).dict_data()
login_cookies = loggin_wx()
cookie = requests.utils.dict_from_cookiejar(login_cookies.cookies)
cookies = {'SERVE... | the_stack_v2_python_sparse | case/Test_Environment/Member/member_openChildCard.py | Four-sun/Requests_Load | train | 0 | |
0bbdaad3ff08e9ef65e16d6852f0e091cd5cd10e | [
"parser.add_argument('--device', '-d', help='Device to record video from', type=types.connected_android_device, default=defaults.connected_android_device()).completer = completion.android_devices\nparser.add_argument('--bitrate', '-b', help='Video bit rate, by default 8000000 (6Mbps)', type=int, default=8000000)\np... | <|body_start_0|>
parser.add_argument('--device', '-d', help='Device to record video from', type=types.connected_android_device, default=defaults.connected_android_device()).completer = completion.android_devices
parser.add_argument('--bitrate', '-b', help='Video bit rate, by default 8000000 (6Mbps)', ty... | Action for recording video. | RecordVideoAction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordVideoAction:
"""Action for recording video."""
def init_parser(parser):
"""Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments."""
<|body_0|>
def __call__(self, device, timeo... | stack_v2_sparse_classes_10k_train_007227 | 3,003 | permissive | [
{
"docstring": "Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments.",
"name": "init_parser",
"signature": "def init_parser(parser)"
},
{
"docstring": "Takes one or more screenshots from specified device. ... | 2 | stack_v2_sparse_classes_30k_train_004885 | Implement the Python class `RecordVideoAction` described below.
Class description:
Action for recording video.
Method signatures and docstrings:
- def init_parser(parser): Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments.
- ... | Implement the Python class `RecordVideoAction` described below.
Class description:
Action for recording video.
Method signatures and docstrings:
- def init_parser(parser): Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments.
- ... | 46dcb27b0ee25153b697d19c17801cee35e136ce | <|skeleton|>
class RecordVideoAction:
"""Action for recording video."""
def init_parser(parser):
"""Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments."""
<|body_0|>
def __call__(self, device, timeo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RecordVideoAction:
"""Action for recording video."""
def init_parser(parser):
"""Initializes argument parser with own arguments. :param parser: argparse.ArgumentParser, parser instance to initialize it with custom arguments."""
parser.add_argument('--device', '-d', help='Device to record ... | the_stack_v2_python_sparse | action/RecordVideoAction.py | maxim-filkov/mobile-test-helper | train | 1 |
58fef73df6ce18437f3c8ba1b52dd3afb7a29001 | [
"super(ConvDropoutNormNonlin2D, self).__init__()\nif nonlin_kwargs is None:\n nonlin_kwargs = {'alpha': 0.01, 'inplace': True}\nif dropout_op_kwargs is None:\n dropout_op_kwargs = {'p': 0.5, 'inplace': True}\nif norm_op_kwargs is None:\n norm_op_kwargs = {'eps': 1e-05, 'affine': True, 'momentum': 0.9}\nif ... | <|body_start_0|>
super(ConvDropoutNormNonlin2D, self).__init__()
if nonlin_kwargs is None:
nonlin_kwargs = {'alpha': 0.01, 'inplace': True}
if dropout_op_kwargs is None:
dropout_op_kwargs = {'p': 0.5, 'inplace': True}
if norm_op_kwargs is None:
norm_op... | fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad. | ConvDropoutNormNonlin2D | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvDropoutNormNonlin2D:
"""fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad."""
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=N... | stack_v2_sparse_classes_10k_train_007228 | 24,212 | permissive | [
{
"docstring": "init class",
"name": "__init__",
"signature": "def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=None, nonlin=nn.LeakyReLU, nonlin_kwargs=None)"
},
{
"docs... | 2 | null | Implement the Python class `ConvDropoutNormNonlin2D` described below.
Class description:
fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad.
Method signatures and docstrings:
- def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNor... | Implement the Python class `ConvDropoutNormNonlin2D` described below.
Class description:
fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad.
Method signatures and docstrings:
- def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNor... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class ConvDropoutNormNonlin2D:
"""fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad."""
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=N... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConvDropoutNormNonlin2D:
"""fixes a bug in ConvDropoutNormNonlin where lrelu was used regardless of nonlin. Bad."""
def __init__(self, input_channels, output_channels, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout, dropout_op_kwargs=None, nonlin=n... | the_stack_v2_python_sparse | research/cv/nnUNet/src/nnunet/network_architecture/generic_UNet.py | mindspore-ai/models | train | 301 |
f72afca769004d0f477b3ecff28d5c5d025e5c63 | [
"self._entity_component = self.hass.data[DATA_INSTANCES][self.domain]\nawait super().async_activate()\n\nasync def _async_update_listener(_hass: HomeAssistant, _entry: ConfigEntry) -> None:\n \"\"\"Handle options update.\"\"\"\n await self.inspect_debouncer.async_call()\nasync_dispatcher_connect(self.hass, SI... | <|body_start_0|>
self._entity_component = self.hass.data[DATA_INSTANCES][self.domain]
await super().async_activate()
async def _async_update_listener(_hass: HomeAssistant, _entry: ConfigEntry) -> None:
"""Handle options update."""
await self.inspect_debouncer.async_call(... | Spook repair tries to find unknown referenced entity in scripts. | SpookRepair | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpookRepair:
"""Spook repair tries to find unknown referenced entity in scripts."""
async def async_activate(self) -> None:
"""Handle the activating a repair."""
<|body_0|>
async def async_inspect(self) -> None:
"""Trigger a inspection."""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_007229 | 5,085 | permissive | [
{
"docstring": "Handle the activating a repair.",
"name": "async_activate",
"signature": "async def async_activate(self) -> None"
},
{
"docstring": "Trigger a inspection.",
"name": "async_inspect",
"signature": "async def async_inspect(self) -> None"
}
] | 2 | null | Implement the Python class `SpookRepair` described below.
Class description:
Spook repair tries to find unknown referenced entity in scripts.
Method signatures and docstrings:
- async def async_activate(self) -> None: Handle the activating a repair.
- async def async_inspect(self) -> None: Trigger a inspection. | Implement the Python class `SpookRepair` described below.
Class description:
Spook repair tries to find unknown referenced entity in scripts.
Method signatures and docstrings:
- async def async_activate(self) -> None: Handle the activating a repair.
- async def async_inspect(self) -> None: Trigger a inspection.
<|sk... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class SpookRepair:
"""Spook repair tries to find unknown referenced entity in scripts."""
async def async_activate(self) -> None:
"""Handle the activating a repair."""
<|body_0|>
async def async_inspect(self) -> None:
"""Trigger a inspection."""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpookRepair:
"""Spook repair tries to find unknown referenced entity in scripts."""
async def async_activate(self) -> None:
"""Handle the activating a repair."""
self._entity_component = self.hass.data[DATA_INSTANCES][self.domain]
await super().async_activate()
async def ... | the_stack_v2_python_sparse | custom_components/spook/ectoplasms/script/repairs/unknown_entity_references.py | bacco007/HomeAssistantConfig | train | 98 |
8ddae3bf5fe99f8205fa68ef0a40023f39467441 | [
"self.screen_width = 600\nself.screen_height = 400\nself.bg_color = (230, 30, 230)\nself.plane_limit = 3\nself.missle_width = 15\nself.missle_height = 3\nself.missle_color = (60, 60, 60)\nself.missles_allowed = 3\nself.fleet_drop_speed = 10\nself.speedup_scale = 2\nself.initialize_dynamic_settings()",
"self.plane... | <|body_start_0|>
self.screen_width = 600
self.screen_height = 400
self.bg_color = (230, 30, 230)
self.plane_limit = 3
self.missle_width = 15
self.missle_height = 3
self.missle_color = (60, 60, 60)
self.missles_allowed = 3
self.fleet_drop_speed = 10... | Класс для хранения всех настроек игры Alien Invasion | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует настройки игры"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры"""
<|body_1|>
def inc... | stack_v2_sparse_classes_10k_train_007230 | 1,225 | no_license | [
{
"docstring": "Инициализирует настройки игры",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Инициализирует настройки, изменяющиеся в ходе игры",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_003734 | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры
- def increas... | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры
- def increas... | 355d117ae48f78d331ef2cfc2f92551dc857cb58 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует настройки игры"""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры"""
<|body_1|>
def inc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Settings:
"""Класс для хранения всех настроек игры Alien Invasion"""
def __init__(self):
"""Инициализирует настройки игры"""
self.screen_width = 600
self.screen_height = 400
self.bg_color = (230, 30, 230)
self.plane_limit = 3
self.missle_width = 15
... | the_stack_v2_python_sparse | Eric_Matthes/chapter_2/games/vertical/settings.py | rvdmtr/python | train | 0 |
91eed0080f5cca573d230e119b5e17439170e4ff | [
"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... | Proto file describing the Customer service. Service to manage customers. | CustomerServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerServiceServicer:
"""Proto file describing the Customer service. Service to manage customers."""
def GetCustomer(self, request, context):
"""Returns the requested customer in full detail."""
<|body_0|>
def MutateCustomer(self, request, context):
"""Updates... | stack_v2_sparse_classes_10k_train_007231 | 9,513 | permissive | [
{
"docstring": "Returns the requested customer in full detail.",
"name": "GetCustomer",
"signature": "def GetCustomer(self, request, context)"
},
{
"docstring": "Updates a customer. Operation statuses are returned.",
"name": "MutateCustomer",
"signature": "def MutateCustomer(self, reques... | 4 | stack_v2_sparse_classes_30k_train_002382 | Implement the Python class `CustomerServiceServicer` described below.
Class description:
Proto file describing the Customer service. Service to manage customers.
Method signatures and docstrings:
- def GetCustomer(self, request, context): Returns the requested customer in full detail.
- def MutateCustomer(self, reque... | Implement the Python class `CustomerServiceServicer` described below.
Class description:
Proto file describing the Customer service. Service to manage customers.
Method signatures and docstrings:
- def GetCustomer(self, request, context): Returns the requested customer in full detail.
- def MutateCustomer(self, reque... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class CustomerServiceServicer:
"""Proto file describing the Customer service. Service to manage customers."""
def GetCustomer(self, request, context):
"""Returns the requested customer in full detail."""
<|body_0|>
def MutateCustomer(self, request, context):
"""Updates... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomerServiceServicer:
"""Proto file describing the Customer service. Service to manage customers."""
def GetCustomer(self, request, context):
"""Returns the requested customer in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imp... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/customer_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
a982c8780d821868cc20216307e8984210d86237 | [
"m = 0\nfor i in range(len(matrix)):\n for j in range(len(matrix[i])):\n matrix[i][j] = int(matrix[i][j])\n if i != 0 and matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\nfor row in matrix:\n m = max(m, self.largestRectangleArea(row))\nreturn m",
"stack = []\nheight.append(0)\... | <|body_start_0|>
m = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if i != 0 and matrix[i][j] == 1:
matrix[i][j] += matrix[i - 1][j]
for row in matrix:
m = max(m, self.la... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = 0
for... | stack_v2_sparse_classes_10k_train_007232 | 1,154 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class So... | cb70fc9ddc410923cc1dae6015a821d4e52c1c14 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
m = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if i != 0 and matrix[i][j] == 1:
... | the_stack_v2_python_sparse | 85Maximal Rectangle.py | zingzheng/LeetCode_py | train | 0 | |
27795b5319530924f8965bd153da6102a426834e | [
"self.driver.get(login_url)\nlogin_title = self.driver.find_element(Login_Locator.LOGIN_TITLE).text\ntt_check.assertEqual('手机快捷登录', login_title, '登录页面的title,期望是手机快捷登录,实际是%s' % login_title)",
"self.driver.get(login_url)\nself.driver.find_element(Login_Locator.LOGIN_PASSWORD_LOGIN).click()\nsleep(2)\nself.driver.fi... | <|body_start_0|>
self.driver.get(login_url)
login_title = self.driver.find_element(Login_Locator.LOGIN_TITLE).text
tt_check.assertEqual('手机快捷登录', login_title, '登录页面的title,期望是手机快捷登录,实际是%s' % login_title)
<|end_body_0|>
<|body_start_1|>
self.driver.get(login_url)
self.driver.find_... | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
def test_login_title(self):
"""测试登录页面的Title显示的是否正确@author:zhangyanli"""
<|body_0|>
def login(self):
"""手机号密码登录M站"""
<|body_1|>
def test_login_passwordlogin(self):
"""测试手机号密码登录@author:zhangyanli"""
<|body_2|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_10k_train_007233 | 2,174 | no_license | [
{
"docstring": "测试登录页面的Title显示的是否正确@author:zhangyanli",
"name": "test_login_title",
"signature": "def test_login_title(self)"
},
{
"docstring": "手机号密码登录M站",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "测试手机号密码登录@author:zhangyanli",
"name": "test_login_pa... | 3 | stack_v2_sparse_classes_30k_train_000374 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def test_login_title(self): 测试登录页面的Title显示的是否正确@author:zhangyanli
- def login(self): 手机号密码登录M站
- def test_login_passwordlogin(self): 测试手机号密码登录@author:zhangyanli | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def test_login_title(self): 测试登录页面的Title显示的是否正确@author:zhangyanli
- def login(self): 手机号密码登录M站
- def test_login_passwordlogin(self): 测试手机号密码登录@author:zhangyanli
<|skeleton|>
class Log... | 204856bd33c06d25f2970eba13799db75d4fd4fe | <|skeleton|>
class Login:
def test_login_title(self):
"""测试登录页面的Title显示的是否正确@author:zhangyanli"""
<|body_0|>
def login(self):
"""手机号密码登录M站"""
<|body_1|>
def test_login_passwordlogin(self):
"""测试手机号密码登录@author:zhangyanli"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Login:
def test_login_title(self):
"""测试登录页面的Title显示的是否正确@author:zhangyanli"""
self.driver.get(login_url)
login_title = self.driver.find_element(Login_Locator.LOGIN_TITLE).text
tt_check.assertEqual('手机快捷登录', login_title, '登录页面的title,期望是手机快捷登录,实际是%s' % login_title)
def logi... | the_stack_v2_python_sparse | mc/taocheM/test_login/test_login.py | boeai/mc | train | 0 | |
0b0a299a2615580e74bd93e29d8c0ffeefdc7cfd | [
"serial = ''\n\ndef helper(nd):\n if nd == None:\n return 'None,'\n return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)\nreturn helper(root)",
"lst = data.split(',')\n\ndef helper(lst):\n if lst[0] == 'None':\n lst.pop(0)\n return None\n root = TreeNode(lst[0])\n lst.... | <|body_start_0|>
serial = ''
def helper(nd):
if nd == None:
return 'None,'
return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)
return helper(root)
<|end_body_0|>
<|body_start_1|>
lst = data.split(',')
def helper(lst):
... | 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_10k_train_007234 | 1,477 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006748 | 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:... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
serial = ''
def helper(nd):
if nd == None:
return 'None,'
return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)
return he... | the_stack_v2_python_sparse | leetcode/297.py | liuweilin17/algorithm | train | 3 | |
344ec2bed37c4f8b21332c7078f4da2649f2c825 | [
"super(ConvGRU, self).__init__()\nself.input_size = input_size\nif type(hidden_sizes) != list:\n self.hidden_sizes = [hidden_sizes] * n_layers\nelse:\n assert len(hidden_sizes) == n_layers, '`hidden_sizes` must have the same length as n_layers'\n self.hidden_sizes = hidden_sizes\nif type(kernel_sizes) != l... | <|body_start_0|>
super(ConvGRU, self).__init__()
self.input_size = input_size
if type(hidden_sizes) != list:
self.hidden_sizes = [hidden_sizes] * n_layers
else:
assert len(hidden_sizes) == n_layers, '`hidden_sizes` must have the same length as n_layers'
... | ConvGRU | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvGRU:
def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):
"""Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : intege... | stack_v2_sparse_classes_10k_train_007235 | 4,783 | permissive | [
{
"docstring": "Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : integer or list. depth dimensions of hidden state. if integer, the same hidden size is used for ... | 2 | null | Implement the Python class `ConvGRU` described below.
Class description:
Implement the ConvGRU class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers): Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Par... | Implement the Python class `ConvGRU` described below.
Class description:
Implement the ConvGRU class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers): Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Par... | 3efa944031e65d4a9fc6dee27381e73e446bb16d | <|skeleton|>
class ConvGRU:
def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):
"""Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : intege... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConvGRU:
def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):
"""Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : integer or list. dep... | the_stack_v2_python_sparse | gen_models/convgru.py | KamyarGh/rl_swiss | train | 61 | |
cd709243eb68e48b2a763e4a73f99e6c0026f17b | [
"conf['angel.worker.matrix.transfer.request.timeout.ms'] = 60000\njconf = conf.dict_to_jconf()\nsuper(LinearRegRunner, self).train(conf, conf._jvm.com.tencent.angel.ml.regression.linear.LinearRegModel(jconf, None), 'com.tencent.angel.ml.regression.linear.LinearRegTrainTask')",
"conf['angel.worker.matrix.transfer.... | <|body_start_0|>
conf['angel.worker.matrix.transfer.request.timeout.ms'] = 60000
jconf = conf.dict_to_jconf()
super(LinearRegRunner, self).train(conf, conf._jvm.com.tencent.angel.ml.regression.linear.LinearRegModel(jconf, None), 'com.tencent.angel.ml.regression.linear.LinearRegTrainTask')
<|end_... | Run linear regression task on angel | LinearRegRunner | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegRunner:
"""Run linear regression task on angel"""
def train(self, conf):
"""Run linear regression train task :param conf: configuration of a algorithm and resource :return:"""
<|body_0|>
def predict(self, conf):
"""Run linear regression predict task :par... | stack_v2_sparse_classes_10k_train_007236 | 2,910 | permissive | [
{
"docstring": "Run linear regression train task :param conf: configuration of a algorithm and resource :return:",
"name": "train",
"signature": "def train(self, conf)"
},
{
"docstring": "Run linear regression predict task :param conf: configuration of algorithm and resource :return:",
"name... | 3 | stack_v2_sparse_classes_30k_train_001368 | Implement the Python class `LinearRegRunner` described below.
Class description:
Run linear regression task on angel
Method signatures and docstrings:
- def train(self, conf): Run linear regression train task :param conf: configuration of a algorithm and resource :return:
- def predict(self, conf): Run linear regress... | Implement the Python class `LinearRegRunner` described below.
Class description:
Run linear regression task on angel
Method signatures and docstrings:
- def train(self, conf): Run linear regression train task :param conf: configuration of a algorithm and resource :return:
- def predict(self, conf): Run linear regress... | cb015db12356ffbfbdde096e4ec112a2cd324ac3 | <|skeleton|>
class LinearRegRunner:
"""Run linear regression task on angel"""
def train(self, conf):
"""Run linear regression train task :param conf: configuration of a algorithm and resource :return:"""
<|body_0|>
def predict(self, conf):
"""Run linear regression predict task :par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearRegRunner:
"""Run linear regression task on angel"""
def train(self, conf):
"""Run linear regression train task :param conf: configuration of a algorithm and resource :return:"""
conf['angel.worker.matrix.transfer.request.timeout.ms'] = 60000
jconf = conf.dict_to_jconf()
... | the_stack_v2_python_sparse | angel-ps/python/pyangel/ml/regression/runner.py | haitwang-cloud/angel | train | 0 |
076f9b66354cf8d6be88c56dea6d576c8271042e | [
"self.stack = []\nself.l = nestedList\nself.i = 0",
"if self.hasNext():\n v = self.l[self.i]\n self.i += 1\n return v.getInteger()\nelse:\n return None",
"while True:\n while self.i == len(self.l):\n if self.stack:\n self.l, self.i = self.stack.pop()\n self.i += 1\n ... | <|body_start_0|>
self.stack = []
self.l = nestedList
self.i = 0
<|end_body_0|>
<|body_start_1|>
if self.hasNext():
v = self.l[self.i]
self.i += 1
return v.getInteger()
else:
return None
<|end_body_1|>
<|body_start_2|>
whil... | NestedIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k_train_007237 | 2,819 | no_license | [
{
"docstring": "Initialize your data structure here. :type nestedList: List[NestedInteger]",
"name": "__init__",
"signature": "def __init__(self, nestedList)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"nam... | 3 | null | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | d6b9f07e2d1437681fa77fee0687ea9b83cab135 | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
self.stack = []
self.l = nestedList
self.i = 0
def next(self):
""":rtype: int"""
if self.hasNext():
v = self.l[self.... | the_stack_v2_python_sparse | python/algorithm/leetcode/341.py | yanxurui/keepcoding | train | 1 | |
fee941112eda563154ec9e1ea07d7daf775ca48e | [
"\"\"\"\n string是一种不可变的数据类型\n O(n)的时间复杂度,还有各种类型转换\n \"\"\"\nx_s = list(str(x))\nif len(x_s) <= 1:\n return x\nsign = 1\nif x_s[0] == '-':\n sign = -1\n x_s = x_s[1:]\ni, j = (0, len(x_s) - 1)\nwhile i < j:\n x_s[i], x_s[j] = (x_s[j], x_s[i])\n i += 1\n j -= 1\nresult = sign * ... | <|body_start_0|>
"""
string是一种不可变的数据类型
O(n)的时间复杂度,还有各种类型转换
"""
x_s = list(str(x))
if len(x_s) <= 1:
return x
sign = 1
if x_s[0] == '-':
sign = -1
x_s = x_s[1:]
i, j = (0, len(x_s) - 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_2(self, x):
"""rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
string是一种不可变的数据... | stack_v2_sparse_classes_10k_train_007238 | 1,619 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": "rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:",
"name": "reverse_2",
"signature": "def reverse_2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004822 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_2(self, x): rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse_2(self, x): rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:
<|skeleton|>
class Solution:
def r... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse_2(self, x):
"""rev是返回结果,依次将x弹出最末尾的意味, 将其添加到rev的第一位。注意判断溢出 log(n)的时间复杂度 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
"""
string是一种不可变的数据类型
O(n)的时间复杂度,还有各种类型转换
"""
x_s = list(str(x))
if len(x_s) <= 1:
return x
sign = 1
if x_s[0] == '-':
sign = -... | the_stack_v2_python_sparse | tuter_start/7_int.py | cainingning/leetcode | train | 1 | |
6309dff27da1287bf9ee022f37a09445b542520c | [
"parameters = super().parameters()\nparameters['resize_type'].update_default_value('standard')\nparameters.update({'metadata': DictValue(description='Metadata for inference'), 'threshold': NumericalValue(description='Threshold used to classify anomaly')})\nreturn parameters",
"normalized = (targets - threshold) /... | <|body_start_0|>
parameters = super().parameters()
parameters['resize_type'].update_default_value('standard')
parameters.update({'metadata': DictValue(description='Metadata for inference'), 'threshold': NumericalValue(description='Threshold used to classify anomaly')})
return parameters
... | Wrapper for anomaly tasks. | AnomalyBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnomalyBase:
"""Wrapper for anomaly tasks."""
def parameters(cls):
"""Dictionary containing model parameters."""
<|body_0|>
def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarray, float], max_val: Union[np.nd... | stack_v2_sparse_classes_10k_train_007239 | 1,617 | permissive | [
{
"docstring": "Dictionary containing model parameters.",
"name": "parameters",
"signature": "def parameters(cls)"
},
{
"docstring": "Apply min-max normalization and shift the values such that the threshold value is centered at 0.5.",
"name": "_normalize",
"signature": "def _normalize(ta... | 2 | null | Implement the Python class `AnomalyBase` described below.
Class description:
Wrapper for anomaly tasks.
Method signatures and docstrings:
- def parameters(cls): Dictionary containing model parameters.
- def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarr... | Implement the Python class `AnomalyBase` described below.
Class description:
Wrapper for anomaly tasks.
Method signatures and docstrings:
- def parameters(cls): Dictionary containing model parameters.
- def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarr... | 80454808b38727e358e8b880043eeac0f18152fb | <|skeleton|>
class AnomalyBase:
"""Wrapper for anomaly tasks."""
def parameters(cls):
"""Dictionary containing model parameters."""
<|body_0|>
def _normalize(targets: Union[np.ndarray, np.float32], threshold: Union[np.ndarray, float], min_val: Union[np.ndarray, float], max_val: Union[np.nd... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AnomalyBase:
"""Wrapper for anomaly tasks."""
def parameters(cls):
"""Dictionary containing model parameters."""
parameters = super().parameters()
parameters['resize_type'].update_default_value('standard')
parameters.update({'metadata': DictValue(description='Metadata for ... | the_stack_v2_python_sparse | src/otx/algorithms/anomaly/adapters/anomalib/exportable_code/base.py | openvinotoolkit/training_extensions | train | 397 |
7611739327781b333d6475c253304e417f433892 | [
"if not root:\n return path\nif root.left is None and root.right is None:\n path.append(root.val)\nif root.left:\n self.helper(root.left, path)\nif root.right:\n self.helper(root.right, path)",
"path1, path2 = ([], [])\nself.helper(root1, path1)\nself.helper(root2, path2)\nif path1 == path2:\n retu... | <|body_start_0|>
if not root:
return path
if root.left is None and root.right is None:
path.append(root.val)
if root.left:
self.helper(root.left, path)
if root.right:
self.helper(root.right, path)
<|end_body_0|>
<|body_start_1|>
pa... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, root, path):
""":type path: list :type root: TreeNode"""
<|body_0|>
def leafSimilar(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not ro... | stack_v2_sparse_classes_10k_train_007240 | 927 | no_license | [
{
"docstring": ":type path: list :type root: TreeNode",
"name": "helper",
"signature": "def helper(self, root, path)"
},
{
"docstring": ":type root1: TreeNode :type root2: TreeNode :rtype: bool",
"name": "leafSimilar",
"signature": "def leafSimilar(self, root1, root2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003142 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, root, path): :type path: list :type root: TreeNode
- def leafSimilar(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, root, path): :type path: list :type root: TreeNode
- def leafSimilar(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
<|skeleton|>
... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def helper(self, root, path):
""":type path: list :type root: TreeNode"""
<|body_0|>
def leafSimilar(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def helper(self, root, path):
""":type path: list :type root: TreeNode"""
if not root:
return path
if root.left is None and root.right is None:
path.append(root.val)
if root.left:
self.helper(root.left, path)
if root.right:
... | the_stack_v2_python_sparse | leetcode/leafSimilar-872.py | pittcat/Algorithm_Practice | train | 0 | |
1068d2f4d8383c3aa6a1a9c5e0f7ea6c5bd14c99 | [
"super().__init__(context)\nself._beam_pipeline_args = []\nself._make_beam_pipeline_fn = None\nif context:\n if isinstance(context, BaseBeamExecutor.Context):\n self._beam_pipeline_args = context.beam_pipeline_args or []\n self._make_beam_pipeline_fn = context.make_beam_pipeline_fn\n else:\n ... | <|body_start_0|>
super().__init__(context)
self._beam_pipeline_args = []
self._make_beam_pipeline_fn = None
if context:
if isinstance(context, BaseBeamExecutor.Context):
self._beam_pipeline_args = context.beam_pipeline_args or []
self._make_bea... | Abstract TFX executor class for Beam powered components. | BaseBeamExecutor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseBeamExecutor:
"""Abstract TFX executor class for Beam powered components."""
def __init__(self, context: Optional[Context]=None):
"""Constructs a beam based executor."""
<|body_0|>
def _make_beam_pipeline(self) -> _BeamPipeline:
"""Makes beam pipeline."""
... | stack_v2_sparse_classes_10k_train_007241 | 5,166 | permissive | [
{
"docstring": "Constructs a beam based executor.",
"name": "__init__",
"signature": "def __init__(self, context: Optional[Context]=None)"
},
{
"docstring": "Makes beam pipeline.",
"name": "_make_beam_pipeline",
"signature": "def _make_beam_pipeline(self) -> _BeamPipeline"
}
] | 2 | null | Implement the Python class `BaseBeamExecutor` described below.
Class description:
Abstract TFX executor class for Beam powered components.
Method signatures and docstrings:
- def __init__(self, context: Optional[Context]=None): Constructs a beam based executor.
- def _make_beam_pipeline(self) -> _BeamPipeline: Makes ... | Implement the Python class `BaseBeamExecutor` described below.
Class description:
Abstract TFX executor class for Beam powered components.
Method signatures and docstrings:
- def __init__(self, context: Optional[Context]=None): Constructs a beam based executor.
- def _make_beam_pipeline(self) -> _BeamPipeline: Makes ... | 1b328504fa08a70388691e4072df76f143631325 | <|skeleton|>
class BaseBeamExecutor:
"""Abstract TFX executor class for Beam powered components."""
def __init__(self, context: Optional[Context]=None):
"""Constructs a beam based executor."""
<|body_0|>
def _make_beam_pipeline(self) -> _BeamPipeline:
"""Makes beam pipeline."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseBeamExecutor:
"""Abstract TFX executor class for Beam powered components."""
def __init__(self, context: Optional[Context]=None):
"""Constructs a beam based executor."""
super().__init__(context)
self._beam_pipeline_args = []
self._make_beam_pipeline_fn = None
... | the_stack_v2_python_sparse | tfx/dsl/components/base/base_beam_executor.py | tensorflow/tfx | train | 2,116 |
7e7b95a1aeebee239801632cfe9bedf2a848ed8c | [
"self.address = address\nself.is_cluster_auditing_enabled = is_cluster_auditing_enabled\nself.is_data_protection_enabled = is_data_protection_enabled\nself.is_filer_auditing_enabled = is_filer_auditing_enabled\nself.is_ssh_log_enabled = is_ssh_log_enabled\nself.name = name\nself.port = port\nself.protocol = protoco... | <|body_start_0|>
self.address = address
self.is_cluster_auditing_enabled = is_cluster_auditing_enabled
self.is_data_protection_enabled = is_data_protection_enabled
self.is_filer_auditing_enabled = is_filer_auditing_enabled
self.is_ssh_log_enabled = is_ssh_log_enabled
self... | Implementation of the 'SyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string): Specifies the IP address or hostname of the syslog server. is_cluster_auditing_enabled (bool): Specifies if Cluster audit logs should be sent to this sy... | SyslogServer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyslogServer:
"""Implementation of the 'SyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string): Specifies the IP address or hostname of the syslog server. is_cluster_auditing_enabled (bool): Specifies if Clus... | stack_v2_sparse_classes_10k_train_007242 | 4,641 | permissive | [
{
"docstring": "Constructor for the SyslogServer class",
"name": "__init__",
"signature": "def __init__(self, address=None, port=None, protocol=None, is_cluster_auditing_enabled=None, is_data_protection_enabled=None, is_filer_auditing_enabled=None, is_ssh_log_enabled=None, name=None)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_001056 | Implement the Python class `SyslogServer` described below.
Class description:
Implementation of the 'SyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string): Specifies the IP address or hostname of the syslog server. is_cluster_aud... | Implement the Python class `SyslogServer` described below.
Class description:
Implementation of the 'SyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string): Specifies the IP address or hostname of the syslog server. is_cluster_aud... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SyslogServer:
"""Implementation of the 'SyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string): Specifies the IP address or hostname of the syslog server. is_cluster_auditing_enabled (bool): Specifies if Clus... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyslogServer:
"""Implementation of the 'SyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string): Specifies the IP address or hostname of the syslog server. is_cluster_auditing_enabled (bool): Specifies if Cluster audit log... | the_stack_v2_python_sparse | cohesity_management_sdk/models/syslog_server.py | cohesity/management-sdk-python | train | 24 |
39e3829f7a19c9b559bbc89fec9d2da947ced615 | [
"if stones[1] != 1:\n return False\nstone_set, fail = (set(stones), set())\nstack = [(0, 0)]\nwhile stack:\n stone, jump = stack.pop()\n for jump_step in (jump - 1, jump, jump + 1):\n stone_next = stone + jump_step\n if jump_step > 0 and stone_next in stone_set and ((stone_next, jump_step) no... | <|body_start_0|>
if stones[1] != 1:
return False
stone_set, fail = (set(stones), set())
stack = [(0, 0)]
while stack:
stone, jump = stack.pop()
for jump_step in (jump - 1, jump, jump + 1):
stone_next = stone + jump_step
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCross(self, stones):
""":type stones: List[int] :rtype: bool beats 94.74%"""
<|body_0|>
def canCross1(self, stones):
""":type stones: List[int] :rtype: bool https://discuss.leetcode.com/topic/59570/python-documented-solution-that-is-easy-to-understan... | stack_v2_sparse_classes_10k_train_007243 | 2,969 | no_license | [
{
"docstring": ":type stones: List[int] :rtype: bool beats 94.74%",
"name": "canCross",
"signature": "def canCross(self, stones)"
},
{
"docstring": ":type stones: List[int] :rtype: bool https://discuss.leetcode.com/topic/59570/python-documented-solution-that-is-easy-to-understand beats 31.58%",
... | 3 | stack_v2_sparse_classes_30k_train_002556 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCross(self, stones): :type stones: List[int] :rtype: bool beats 94.74%
- def canCross1(self, stones): :type stones: List[int] :rtype: bool https://discuss.leetcode.com/top... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCross(self, stones): :type stones: List[int] :rtype: bool beats 94.74%
- def canCross1(self, stones): :type stones: List[int] :rtype: bool https://discuss.leetcode.com/top... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def canCross(self, stones):
""":type stones: List[int] :rtype: bool beats 94.74%"""
<|body_0|>
def canCross1(self, stones):
""":type stones: List[int] :rtype: bool https://discuss.leetcode.com/topic/59570/python-documented-solution-that-is-easy-to-understan... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canCross(self, stones):
""":type stones: List[int] :rtype: bool beats 94.74%"""
if stones[1] != 1:
return False
stone_set, fail = (set(stones), set())
stack = [(0, 0)]
while stack:
stone, jump = stack.pop()
for jump_step... | the_stack_v2_python_sparse | LeetCode/403_frog_jump.py | yao23/Machine_Learning_Playground | train | 12 | |
2dbfc183a5864f6724f23a69cc44bc9a53a2156b | [
"res = {}\nfor rec in self:\n reserv_bed = 0\n for bed_line in rec.room_id.bed_ids:\n if bed_line.employee_id and bed_line.employee_id.emp_country_id.id and (rec.nationality_id.id == bed_line.employee_id.emp_country_id.id):\n reserv_bed += 1\n res[rec.id] = rec.number_of_quota - reserv_be... | <|body_start_0|>
res = {}
for rec in self:
reserv_bed = 0
for bed_line in rec.room_id.bed_ids:
if bed_line.employee_id and bed_line.employee_id.emp_country_id.id and (rec.nationality_id.id == bed_line.employee_id.emp_country_id.id):
reserv_bed ... | visa_quota | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class visa_quota:
def get_quota_available(self):
"""This method used to get total calculate of quota available ------------------------------------------------------------- @param self : Records set @multi : The decorator of multi"""
<|body_0|>
def unlink(self):
"""This me... | stack_v2_sparse_classes_10k_train_007244 | 24,603 | no_license | [
{
"docstring": "This method used to get total calculate of quota available ------------------------------------------------------------- @param self : Records set @multi : The decorator of multi",
"name": "get_quota_available",
"signature": "def get_quota_available(self)"
},
{
"docstring": "This... | 3 | stack_v2_sparse_classes_30k_val_000295 | Implement the Python class `visa_quota` described below.
Class description:
Implement the visa_quota class.
Method signatures and docstrings:
- def get_quota_available(self): This method used to get total calculate of quota available ------------------------------------------------------------- @param self : Records ... | Implement the Python class `visa_quota` described below.
Class description:
Implement the visa_quota class.
Method signatures and docstrings:
- def get_quota_available(self): This method used to get total calculate of quota available ------------------------------------------------------------- @param self : Records ... | 46e15330b5d642053da61754247f3fbf9d02717e | <|skeleton|>
class visa_quota:
def get_quota_available(self):
"""This method used to get total calculate of quota available ------------------------------------------------------------- @param self : Records set @multi : The decorator of multi"""
<|body_0|>
def unlink(self):
"""This me... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class visa_quota:
def get_quota_available(self):
"""This method used to get total calculate of quota available ------------------------------------------------------------- @param self : Records set @multi : The decorator of multi"""
res = {}
for rec in self:
reserv_bed = 0
... | the_stack_v2_python_sparse | core/sg_accommodation/models/accommodation_agreement.py | Muhammad-SF/Test | train | 0 | |
59fb990cd7daafd55c010cf346c5c540891ce2ae | [
"pygame.init()\nwidth, height = Display_Config['BATTLE_SIZE']\nheight += Display_Config['LOG_SIZE'][1]\nheight += Display_Config['SELECT_SIZE'][1]\nif state['use_agent'] and Display_Config['VISUALIZE_AGENT_INFO']:\n width *= 2\nSCREEN_SIZE = (width, height)\nself.SCREEN = display.set_mode(scale(SCREEN_SIZE))\ndi... | <|body_start_0|>
pygame.init()
width, height = Display_Config['BATTLE_SIZE']
height += Display_Config['LOG_SIZE'][1]
height += Display_Config['SELECT_SIZE'][1]
if state['use_agent'] and Display_Config['VISUALIZE_AGENT_INFO']:
width *= 2
SCREEN_SIZE = (width, h... | Window | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Window:
def __init__(self, state):
"""Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: "Ally_0", "Ally_1", "Foe_0" and "Foe_1" with the corresponding pokemon as a value. Action: Create and execute a ... | stack_v2_sparse_classes_10k_train_007245 | 6,184 | no_license | [
{
"docstring": "Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: \"Ally_0\", \"Ally_1\", \"Foe_0\" and \"Foe_1\" with the corresponding pokemon as a value. Action: Create and execute a window where the 'state' of a battle i... | 6 | stack_v2_sparse_classes_30k_train_007184 | Implement the Python class `Window` described below.
Class description:
Implement the Window class.
Method signatures and docstrings:
- def __init__(self, state): Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: "Ally_0", "Ally_1... | Implement the Python class `Window` described below.
Class description:
Implement the Window class.
Method signatures and docstrings:
- def __init__(self, state): Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: "Ally_0", "Ally_1... | aa9defc6387788fc57d50dfdff7e4c43e8a1c358 | <|skeleton|>
class Window:
def __init__(self, state):
"""Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: "Ally_0", "Ally_1", "Foe_0" and "Foe_1" with the corresponding pokemon as a value. Action: Create and execute a ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Window:
def __init__(self, state):
"""Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: "Ally_0", "Ally_1", "Foe_0" and "Foe_1" with the corresponding pokemon as a value. Action: Create and execute a window where t... | the_stack_v2_python_sparse | Game/display/window.py | dieguigram/Pokemon-Python | train | 0 | |
6c952ce6ef498b3213542d60cb26c72a2df90e6d | [
"self.X = X_k\nself.fk = fk\nself.N = len(fk)\nself.K = self.X.shape[0]",
"x = np.zeros(self.N)\nfor n in range(self.N):\n for k in range(self.K):\n x[n] = x[n] + 1 / np.sqrt(self.N) * self.X[k, 0] * np.exp(1j * 2 * cmath.pi * self.X[k, 1] * n / self.N)\nreturn x"
] | <|body_start_0|>
self.X = X_k
self.fk = fk
self.N = len(fk)
self.K = self.X.shape[0]
<|end_body_0|>
<|body_start_1|>
x = np.zeros(self.N)
for n in range(self.N):
for k in range(self.K):
x[n] = x[n] + 1 / np.sqrt(self.N) * self.X[k, 0] * np.exp... | Signal reconstruction Question 1.7 | Sginal_Recon_K_q18 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sginal_Recon_K_q18:
"""Signal reconstruction Question 1.7"""
def __init__(self, X_k, fk):
""":param X: Input truncated DFT X_k :param fs: Input integer fs contains the sample frequency"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the iDFT with truncat... | stack_v2_sparse_classes_10k_train_007246 | 25,417 | no_license | [
{
"docstring": ":param X: Input truncated DFT X_k :param fs: Input integer fs contains the sample frequency",
"name": "__init__",
"signature": "def __init__(self, X_k, fk)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the iDFT with truncated K coefficients with largest energy",
"name": "s... | 2 | stack_v2_sparse_classes_30k_test_000182 | Implement the Python class `Sginal_Recon_K_q18` described below.
Class description:
Signal reconstruction Question 1.7
Method signatures and docstrings:
- def __init__(self, X_k, fk): :param X: Input truncated DFT X_k :param fs: Input integer fs contains the sample frequency
- def solve(self): \\\\\\ METHOD: Compute ... | Implement the Python class `Sginal_Recon_K_q18` described below.
Class description:
Signal reconstruction Question 1.7
Method signatures and docstrings:
- def __init__(self, X_k, fk): :param X: Input truncated DFT X_k :param fs: Input integer fs contains the sample frequency
- def solve(self): \\\\\\ METHOD: Compute ... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class Sginal_Recon_K_q18:
"""Signal reconstruction Question 1.7"""
def __init__(self, X_k, fk):
""":param X: Input truncated DFT X_k :param fs: Input integer fs contains the sample frequency"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the iDFT with truncat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Sginal_Recon_K_q18:
"""Signal reconstruction Question 1.7"""
def __init__(self, X_k, fk):
""":param X: Input truncated DFT X_k :param fs: Input integer fs contains the sample frequency"""
self.X = X_k
self.fk = fk
self.N = len(fk)
self.K = self.X.shape[0]
def ... | the_stack_v2_python_sparse | Inverse Discrete Fourier Transform/iDFT_main.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
bc4609361c3cf4afec0a8f65fa06c956c45e5ba2 | [
"self.x = array_check(x)\nself.y = array_check(y)\nself._coef = None\nself._intercept = None\nself._pvalues = None\nself._f_statistics = None\nself._r_squared = None\nself.__m = OLS(self.y, sm.add_constant(self.x))",
"result = self.__m.fit()\nself._intercept, *self._coef = result.params\nself._pvalues = result.f_... | <|body_start_0|>
self.x = array_check(x)
self.y = array_check(y)
self._coef = None
self._intercept = None
self._pvalues = None
self._f_statistics = None
self._r_squared = None
self.__m = OLS(self.y, sm.add_constant(self.x))
<|end_body_0|>
<|body_start_1|>... | Linear regression for single variable or multi-variable. | LinearRegression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegression:
"""Linear regression for single variable or multi-variable."""
def __init__(self, x: array_like, y: array_like) -> None:
""":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like"""
<|body_0|>
def fit(self) -> LinearRegressionPar... | stack_v2_sparse_classes_10k_train_007247 | 4,947 | no_license | [
{
"docstring": ":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like",
"name": "__init__",
"signature": "def __init__(self, x: array_like, y: array_like) -> None"
},
{
"docstring": "Fit the self.x and self.y, then get fitting params. :return: class LinearRegressionParam... | 4 | stack_v2_sparse_classes_30k_val_000383 | Implement the Python class `LinearRegression` described below.
Class description:
Linear regression for single variable or multi-variable.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like) -> None: :param x: array_like N-D array with (n-sample, n-feature) :param y: array_like
- def ... | Implement the Python class `LinearRegression` described below.
Class description:
Linear regression for single variable or multi-variable.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like) -> None: :param x: array_like N-D array with (n-sample, n-feature) :param y: array_like
- def ... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class LinearRegression:
"""Linear regression for single variable or multi-variable."""
def __init__(self, x: array_like, y: array_like) -> None:
""":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like"""
<|body_0|>
def fit(self) -> LinearRegressionPar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearRegression:
"""Linear regression for single variable or multi-variable."""
def __init__(self, x: array_like, y: array_like) -> None:
""":param x: array_like N-D array with (n-sample, n-feature) :param y: array_like"""
self.x = array_check(x)
self.y = array_check(y)
s... | the_stack_v2_python_sparse | statistics/regression.py | qliu0/PythonInAirSeaScience | train | 0 |
093a863cb41b3fbf75196ad2afac399a126f68c0 | [
"self._start = None\nself._end = None\nself._secs = None\nself._msecs = None\nself._running = False",
"self._start = time.time()\nself._running = True\nself._end = None\nself._secs = None\nself._msecs = None",
"self._start = time.time()\nself._end = None\nself._secs = None\nself._msecs = None",
"if self._runn... | <|body_start_0|>
self._start = None
self._end = None
self._secs = None
self._msecs = None
self._running = False
<|end_body_0|>
<|body_start_1|>
self._start = time.time()
self._running = True
self._end = None
self._secs = None
self._msecs =... | Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch. | Stopwatch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stopwatch:
"""Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch."""
def __init__(self):
"""Create and initialize a Stopwatch."""
<|body_0|>
def start(self):
"""Mark current time as the starting time.""... | stack_v2_sparse_classes_10k_train_007248 | 2,432 | permissive | [
{
"docstring": "Create and initialize a Stopwatch.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Mark current time as the starting time.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Reset the timer to zero. This doesn't stop th... | 6 | stack_v2_sparse_classes_30k_train_002038 | Implement the Python class `Stopwatch` described below.
Class description:
Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch.
Method signatures and docstrings:
- def __init__(self): Create and initialize a Stopwatch.
- def start(self): Mark current time as... | Implement the Python class `Stopwatch` described below.
Class description:
Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch.
Method signatures and docstrings:
- def __init__(self): Create and initialize a Stopwatch.
- def start(self): Mark current time as... | 9b5e355d79642e9b5998031872ec0ee2f1a6f08d | <|skeleton|>
class Stopwatch:
"""Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch."""
def __init__(self):
"""Create and initialize a Stopwatch."""
<|body_0|>
def start(self):
"""Mark current time as the starting time.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Stopwatch:
"""Provides stopwatch timing functionality. This class provides simple time keeping functionality like a stopwatch."""
def __init__(self):
"""Create and initialize a Stopwatch."""
self._start = None
self._end = None
self._secs = None
self._msecs = None
... | the_stack_v2_python_sparse | src/stopwatch.py | TechnoJays/robot2018 | train | 0 |
3db652421434a9492d7ef600bf495d59e618a25d | [
"if len(string) <= 3:\n return False\nstring = string[-3:]\nif not string.startswith('[') or not string.endswith(']'):\n return False\nstring = string[1]\nreturn DataType.parse(string) is not None",
"name: str = string\ndatatype: DataType = DataType.UNKNOWN\nif len(string) > 3 and string.endswith(']'):\n ... | <|body_start_0|>
if len(string) <= 3:
return False
string = string[-3:]
if not string.startswith('[') or not string.endswith(']'):
return False
string = string[1]
return DataType.parse(string) is not None
<|end_body_0|>
<|body_start_1|>
name: str ... | A single report field identifier. | Field | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Field:
"""A single report field identifier."""
def is_valid(string: str) -> bool:
"""Checks whether the field is valid. :param string: The string to check. :return: True if valid format"""
<|body_0|>
def parse_field(string: str) -> 'Field':
"""Parses the given st... | stack_v2_sparse_classes_10k_train_007249 | 1,778 | permissive | [
{
"docstring": "Checks whether the field is valid. :param string: The string to check. :return: True if valid format",
"name": "is_valid",
"signature": "def is_valid(string: str) -> bool"
},
{
"docstring": "Parses the given string and returns the field. The type of the field can be append with p... | 2 | stack_v2_sparse_classes_30k_train_006009 | Implement the Python class `Field` described below.
Class description:
A single report field identifier.
Method signatures and docstrings:
- def is_valid(string: str) -> bool: Checks whether the field is valid. :param string: The string to check. :return: True if valid format
- def parse_field(string: str) -> 'Field'... | Implement the Python class `Field` described below.
Class description:
A single report field identifier.
Method signatures and docstrings:
- def is_valid(string: str) -> bool: Checks whether the field is valid. :param string: The string to check. :return: True if valid format
- def parse_field(string: str) -> 'Field'... | 2cb5b21bc05932ff1f43c2ccb31d02a762c03c87 | <|skeleton|>
class Field:
"""A single report field identifier."""
def is_valid(string: str) -> bool:
"""Checks whether the field is valid. :param string: The string to check. :return: True if valid format"""
<|body_0|>
def parse_field(string: str) -> 'Field':
"""Parses the given st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Field:
"""A single report field identifier."""
def is_valid(string: str) -> bool:
"""Checks whether the field is valid. :param string: The string to check. :return: True if valid format"""
if len(string) <= 3:
return False
string = string[-3:]
if not string.sta... | the_stack_v2_python_sparse | src/wai/common/file/report/_Field.py | waikato-datamining/wai-common | train | 0 |
642b7921733b8fb0d4bed8b8f52e0d57d135ef9b | [
"n = len(arr)\ndp = [0] * n\ndp[0] = 1\nres = 1\nfor i in range(1, n):\n if dp[i - 1] == 1:\n if arr[i] != arr[i - 1]:\n dp[i] = dp[i - 1] + 1\n else:\n dp[i] = 1\n elif arr[i - 1] > arr[i] and arr[i - 2] < arr[i - 1] or (arr[i - 1] < arr[i] and arr[i - 2] > arr[i - 1]):\n ... | <|body_start_0|>
n = len(arr)
dp = [0] * n
dp[0] = 1
res = 1
for i in range(1, n):
if dp[i - 1] == 1:
if arr[i] != arr[i - 1]:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1
elif arr[i - 1] > a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def maxTurbulenceSizeO1Space(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def maxTurbulenceSizeO1SpaceFaster(self, arr):
""":type arr: ... | stack_v2_sparse_classes_10k_train_007250 | 3,331 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "maxTurbulenceSize",
"signature": "def maxTurbulenceSize(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "maxTurbulenceSizeO1Space",
"signature": "def maxTurbulenceSizeO1Space(self, arr)"
},
{
"d... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1Space(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1SpaceFaste... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1Space(self, arr): :type arr: List[int] :rtype: int
- def maxTurbulenceSizeO1SpaceFaste... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def maxTurbulenceSizeO1Space(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def maxTurbulenceSizeO1SpaceFaster(self, arr):
""":type arr: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxTurbulenceSize(self, arr):
""":type arr: List[int] :rtype: int"""
n = len(arr)
dp = [0] * n
dp[0] = 1
res = 1
for i in range(1, n):
if dp[i - 1] == 1:
if arr[i] != arr[i - 1]:
dp[i] = dp[i - 1] + 1... | the_stack_v2_python_sparse | L/LongestTurbulentSubarray.py | bssrdf/pyleet | train | 2 | |
4e52d4f0aa4670eac13826cab934920be18a5148 | [
"super(DecoderRNN, self).__init__()\nself.embed = nn.Embedding(vocab_size, embed_size)\nself.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)\nself.linear = nn.Linear(hidden_size, vocab_size)\nself.init_weights()",
"self.embed.weight.data.uniform_(-0.1, 0.1)\nself.linear.weight.data.uniform_(... | <|body_start_0|>
super(DecoderRNN, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
self.linear = nn.Linear(hidden_size, vocab_size)
self.init_weights()
<|end_body_0|>
<|body_start_1|>
... | DecoderRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderRNN:
def __init__(self, embed_size, hidden_size, vocab_size, num_layers):
"""Set the hyper-parameters and build the layers."""
<|body_0|>
def init_weights(self):
"""Initialize weights."""
<|body_1|>
def forward(self, features, captions, lengths):
... | stack_v2_sparse_classes_10k_train_007251 | 5,485 | no_license | [
{
"docstring": "Set the hyper-parameters and build the layers.",
"name": "__init__",
"signature": "def __init__(self, embed_size, hidden_size, vocab_size, num_layers)"
},
{
"docstring": "Initialize weights.",
"name": "init_weights",
"signature": "def init_weights(self)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_000033 | Implement the Python class `DecoderRNN` described below.
Class description:
Implement the DecoderRNN class.
Method signatures and docstrings:
- def __init__(self, embed_size, hidden_size, vocab_size, num_layers): Set the hyper-parameters and build the layers.
- def init_weights(self): Initialize weights.
- def forwar... | Implement the Python class `DecoderRNN` described below.
Class description:
Implement the DecoderRNN class.
Method signatures and docstrings:
- def __init__(self, embed_size, hidden_size, vocab_size, num_layers): Set the hyper-parameters and build the layers.
- def init_weights(self): Initialize weights.
- def forwar... | 80150803ebe291db2b63db01115029b86f36a802 | <|skeleton|>
class DecoderRNN:
def __init__(self, embed_size, hidden_size, vocab_size, num_layers):
"""Set the hyper-parameters and build the layers."""
<|body_0|>
def init_weights(self):
"""Initialize weights."""
<|body_1|>
def forward(self, features, captions, lengths):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DecoderRNN:
def __init__(self, embed_size, hidden_size, vocab_size, num_layers):
"""Set the hyper-parameters and build the layers."""
super(DecoderRNN, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, ba... | the_stack_v2_python_sparse | tag_walk/fachung/models/tagwalk_cnn_rnn.py | Antobiotics/tagWalk | train | 2 | |
ae8e8d2a59a255d7b3aa52264a2a0f95e87f3d57 | [
"self._registered = {}\nself._discovered = {}\nself._lock = threading.Lock()\nself._browser = None",
"with self._lock:\n if device.serial in self._discovered:\n callback(self._discovered[device.serial])\n else:\n self._registered[device.serial] = callback",
"if info.type == TYPE_DYSON_360_EY... | <|body_start_0|>
self._registered = {}
self._discovered = {}
self._lock = threading.Lock()
self._browser = None
<|end_body_0|>
<|body_start_1|>
with self._lock:
if device.serial in self._discovered:
callback(self._discovered[device.serial])
... | Dyson device discovery. | DysonDiscovery | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DysonDiscovery:
"""Dyson device discovery."""
def __init__(self):
"""Initialize the instance."""
<|body_0|>
def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None:
"""Register a device."""
<|body_1|>
def device_discov... | stack_v2_sparse_classes_10k_train_007252 | 2,876 | permissive | [
{
"docstring": "Initialize the instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Register a device.",
"name": "register_device",
"signature": "def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None"
},
{
"docstri... | 5 | null | Implement the Python class `DysonDiscovery` described below.
Class description:
Dyson device discovery.
Method signatures and docstrings:
- def __init__(self): Initialize the instance.
- def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None: Register a device.
- def device_discovered... | Implement the Python class `DysonDiscovery` described below.
Class description:
Dyson device discovery.
Method signatures and docstrings:
- def __init__(self): Initialize the instance.
- def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None: Register a device.
- def device_discovered... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class DysonDiscovery:
"""Dyson device discovery."""
def __init__(self):
"""Initialize the instance."""
<|body_0|>
def register_device(self, device: DysonDevice, callback: Callable[[str], None]) -> None:
"""Register a device."""
<|body_1|>
def device_discov... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DysonDiscovery:
"""Dyson device discovery."""
def __init__(self):
"""Initialize the instance."""
self._registered = {}
self._discovered = {}
self._lock = threading.Lock()
self._browser = None
def register_device(self, device: DysonDevice, callback: Callable[[s... | the_stack_v2_python_sparse | custom_components/dyson_local/vendor/libdyson/discovery.py | bacco007/HomeAssistantConfig | train | 98 |
7a062e386db7c9c878217eb5b8d7435c0ff28982 | [
"merged = None\nmerged_current = merged\ncurrent1 = pHead1\ncurrent2 = pHead2\nwhile current1 or current2:\n if self.less(current1, current2):\n less = current1\n current1 = current1.next\n else:\n less = current2\n current2 = current2.next\n if not merged_current:\n merg... | <|body_start_0|>
merged = None
merged_current = merged
current1 = pHead1
current2 = pHead2
while current1 or current2:
if self.less(current1, current2):
less = current1
current1 = current1.next
else:
less = c... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def Merge(self, pHead1, pHead2):
"""输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表... | stack_v2_sparse_classes_10k_train_007253 | 2,931 | permissive | [
{
"docstring": "输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表看做了整体,而没有拆分成一个一个元素看待。 算法2: 比较两个链表的当前节点,然后选择更小的节点添加到新的链... | 2 | stack_v2_sparse_classes_30k_train_000146 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Merge(self, pHead1, pHead2): 输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def Merge(self, pHead1, pHead2): 输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所... | 5fdd3a607ee3828e9b229cac8104fcccf1a2770d | <|skeleton|>
class Solution:
def Merge(self, pHead1, pHead2):
"""输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def Merge(self, pHead1, pHead2):
"""输入两个单调递增的链表,输出两个链表合成后的链表,要求合成的链表满足单调不减。 比如 [1, 3, 5, 7] 与 [2, 4, 6, 8],合并后为 [1, 2, 3, 4, 5, 6, 7, 8] 算法1: 将两个链表转换为数组,然后合并、排序,然后再将数组转换为链表。由于转换包含了所有节点(情况),所以证明通过。 复杂度分析: n 指两个链表的节点数之和。 时间复杂度:O(nlogn) 空间复杂度:O(n)。所有的元素都要储存到数组中。 这里的思考局限是将两个单调递增的列表看做了整体,而没有拆分成一个... | the_stack_v2_python_sparse | 017-合并两个排序的链表/merge.py | Jay54520/Learn-Algorithms-With-Python | train | 0 | |
183370fde921c6500c31865d9ff4823138b107f8 | [
"args = dict(is_add=True, vni=int(vni), reid=LispEid.create_eid(deid, deid_prefix if not is_mac else None), leid=LispEid.create_eid(seid, seid_prefix if not is_mac else None))\ncmd = u'lisp_add_del_adjacency'\nerr_msg = f\"Failed to add lisp adjacency on host {node[u'host']}\"\nwith PapiSocketExecutor(node) as papi... | <|body_start_0|>
args = dict(is_add=True, vni=int(vni), reid=LispEid.create_eid(deid, deid_prefix if not is_mac else None), leid=LispEid.create_eid(seid, seid_prefix if not is_mac else None))
cmd = u'lisp_add_del_adjacency'
err_msg = f"Failed to add lisp adjacency on host {node[u'host']}"
... | Class for lisp adjacency API. | LispAdjacency | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LispAdjacency:
"""Class for lisp adjacency API."""
def vpp_add_lisp_adjacency(node, vni, deid, deid_prefix, seid, seid_prefix, is_mac=False):
"""Add lisp adjacency on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination eid address. :param deid_p... | stack_v2_sparse_classes_10k_train_007254 | 14,690 | permissive | [
{
"docstring": "Add lisp adjacency on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination eid address. :param deid_prefix: Destination eid address prefix_len. :param seid: Source eid address. :param seid_prefix: Source eid address prefix_len. :param is_mac: Set to True if ... | 2 | stack_v2_sparse_classes_30k_train_001561 | Implement the Python class `LispAdjacency` described below.
Class description:
Class for lisp adjacency API.
Method signatures and docstrings:
- def vpp_add_lisp_adjacency(node, vni, deid, deid_prefix, seid, seid_prefix, is_mac=False): Add lisp adjacency on the VPP node in topology. :param node: VPP node. :param vni:... | Implement the Python class `LispAdjacency` described below.
Class description:
Class for lisp adjacency API.
Method signatures and docstrings:
- def vpp_add_lisp_adjacency(node, vni, deid, deid_prefix, seid, seid_prefix, is_mac=False): Add lisp adjacency on the VPP node in topology. :param node: VPP node. :param vni:... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class LispAdjacency:
"""Class for lisp adjacency API."""
def vpp_add_lisp_adjacency(node, vni, deid, deid_prefix, seid, seid_prefix, is_mac=False):
"""Add lisp adjacency on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination eid address. :param deid_p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LispAdjacency:
"""Class for lisp adjacency API."""
def vpp_add_lisp_adjacency(node, vni, deid, deid_prefix, seid, seid_prefix, is_mac=False):
"""Add lisp adjacency on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination eid address. :param deid_prefix: Destin... | the_stack_v2_python_sparse | resources/libraries/python/LispSetup.py | FDio/csit | train | 28 |
bb0b248bc5bd1af9506f636b0f6bbb6d076236b0 | [
"self.TimeOne = '15:15:00'\nself.TimeTwo = '15:15:12'\nself.output = 1\nreturn (self.TimeOne, self.TimeTwo, self.output)",
"TimeOne, TimeTwo, output = self.setUp()\noutput_method = solution(TimeOne, TimeTwo)\nself.assertEqual(output, output_method)"
] | <|body_start_0|>
self.TimeOne = '15:15:00'
self.TimeTwo = '15:15:12'
self.output = 1
return (self.TimeOne, self.TimeTwo, self.output)
<|end_body_0|>
<|body_start_1|>
TimeOne, TimeTwo, output = self.setUp()
output_method = solution(TimeOne, TimeTwo)
self.assertEqu... | Class with unittests for Codility_1_task.py | test_Codility_1_task | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_Codility_1_task:
"""Class with unittests for Codility_1_task.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.TimeOne ... | stack_v2_sparse_classes_10k_train_007255 | 882 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if method works properly.",
"name": "test_user_input",
"signature": "def test_user_input(self)"
}
] | 2 | null | Implement the Python class `test_Codility_1_task` described below.
Class description:
Class with unittests for Codility_1_task.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly. | Implement the Python class `test_Codility_1_task` described below.
Class description:
Class with unittests for Codility_1_task.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_user_input(self): Checks if method works properly.
<|skeleton|>
class test_Codility_1_task:
"""Class wit... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_Codility_1_task:
"""Class with unittests for Codility_1_task.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_user_input(self):
"""Checks if method works properly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class test_Codility_1_task:
"""Class with unittests for Codility_1_task.py"""
def setUp(self):
"""Sets up input."""
self.TimeOne = '15:15:00'
self.TimeTwo = '15:15:12'
self.output = 1
return (self.TimeOne, self.TimeTwo, self.output)
def test_user_input(self):
... | the_stack_v2_python_sparse | Codility_algorithms/test_Codility_1_task.py | JakubKazimierski/PythonPortfolio | train | 9 |
43d620fd34635c10dfc2e980a40286a8a47554ef | [
"m, n = (len(nums1), len(nums2))\nif m > n:\n return self.intersect(nums2, nums1)\nc1 = Counter(nums1)\nres = []\nfor num in nums2:\n if num in c1:\n res.append(num)\n c1[num] -= 1\n if c1[num] == 0:\n c1.pop(num)\nreturn res",
"nums1.sort()\nnums2.sort()\nres = []\np1, p2 = ... | <|body_start_0|>
m, n = (len(nums1), len(nums2))
if m > n:
return self.intersect(nums2, nums1)
c1 = Counter(nums1)
res = []
for num in nums2:
if num in c1:
res.append(num)
c1[num] -= 1
if c1[num] == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect_hashtable(self, nums1, nums2):
"""hash table solution. Put nums1 in a hash table and check if each element in nums2 is in the hash table. Time: O(m+n) Space: O(m)"""
<|body_0|>
def intersect_two_pointer(self, nums1, nums2):
"""Assume both arra... | stack_v2_sparse_classes_10k_train_007256 | 3,670 | no_license | [
{
"docstring": "hash table solution. Put nums1 in a hash table and check if each element in nums2 is in the hash table. Time: O(m+n) Space: O(m)",
"name": "intersect_hashtable",
"signature": "def intersect_hashtable(self, nums1, nums2)"
},
{
"docstring": "Assume both arrays are sorted Time: O(m+... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect_hashtable(self, nums1, nums2): hash table solution. Put nums1 in a hash table and check if each element in nums2 is in the hash table. Time: O(m+n) Space: O(m)
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect_hashtable(self, nums1, nums2): hash table solution. Put nums1 in a hash table and check if each element in nums2 is in the hash table. Time: O(m+n) Space: O(m)
- de... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def intersect_hashtable(self, nums1, nums2):
"""hash table solution. Put nums1 in a hash table and check if each element in nums2 is in the hash table. Time: O(m+n) Space: O(m)"""
<|body_0|>
def intersect_two_pointer(self, nums1, nums2):
"""Assume both arra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect_hashtable(self, nums1, nums2):
"""hash table solution. Put nums1 in a hash table and check if each element in nums2 is in the hash table. Time: O(m+n) Space: O(m)"""
m, n = (len(nums1), len(nums2))
if m > n:
return self.intersect(nums2, nums1)
... | the_stack_v2_python_sparse | algo/hashtable/intersection_of_two_arrays_II.py | xys234/coding-problems | train | 0 | |
119b74f71b3c5ea6cb08394e9f0a39f645977335 | [
"self.__host = host\nself.__port = port\nurl = create_product_url(protocol, host, port, uri)\nself.transport = None\ntry:\n self.transport = THttpClient.THttpClient(url)\nexcept ValueError:\n pass\nself._validate_proxy_format()\nself.protocol = TJSONProtocol.TJSONProtocol(self.transport)\nself.client = None\n... | <|body_start_0|>
self.__host = host
self.__port = port
url = create_product_url(protocol, host, port, uri)
self.transport = None
try:
self.transport = THttpClient.THttpClient(url)
except ValueError:
pass
self._validate_proxy_format()
... | BaseClientHelper | [
"LLVM-exception",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseClientHelper:
def __init__(self, protocol, host, port, uri, session_token=None, get_new_token=None):
"""@param get_new_token: a function which can generate a new token."""
<|body_0|>
def _validate_proxy_format(self):
"""Validate the proxy settings. If the proxy s... | stack_v2_sparse_classes_10k_train_007257 | 3,017 | permissive | [
{
"docstring": "@param get_new_token: a function which can generate a new token.",
"name": "__init__",
"signature": "def __init__(self, protocol, host, port, uri, session_token=None, get_new_token=None)"
},
{
"docstring": "Validate the proxy settings. If the proxy settings are invalid, it will p... | 4 | stack_v2_sparse_classes_30k_train_006200 | Implement the Python class `BaseClientHelper` described below.
Class description:
Implement the BaseClientHelper class.
Method signatures and docstrings:
- def __init__(self, protocol, host, port, uri, session_token=None, get_new_token=None): @param get_new_token: a function which can generate a new token.
- def _val... | Implement the Python class `BaseClientHelper` described below.
Class description:
Implement the BaseClientHelper class.
Method signatures and docstrings:
- def __init__(self, protocol, host, port, uri, session_token=None, get_new_token=None): @param get_new_token: a function which can generate a new token.
- def _val... | f912cf0ccc7059240ae389823faf35225e6cabc8 | <|skeleton|>
class BaseClientHelper:
def __init__(self, protocol, host, port, uri, session_token=None, get_new_token=None):
"""@param get_new_token: a function which can generate a new token."""
<|body_0|>
def _validate_proxy_format(self):
"""Validate the proxy settings. If the proxy s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseClientHelper:
def __init__(self, protocol, host, port, uri, session_token=None, get_new_token=None):
"""@param get_new_token: a function which can generate a new token."""
self.__host = host
self.__port = port
url = create_product_url(protocol, host, port, uri)
self... | the_stack_v2_python_sparse | web/client/codechecker_client/helpers/base.py | Ericsson/codechecker | train | 2,028 | |
47ab5ac4fc8f1707236e4b7c785c21d539943c9c | [
"self.user = kwargs.pop('user', None)\nsuper(BaseCaseForm, self).__init__(*args, **kwargs)\nself.fields['add_tags'].widget.attrs['data-allow-new'] = 'true' if self.user and self.user.has_perm('tags.manage_tags') else 'false'",
"if self.data.get('tag-newtag') and (not (self.user and self.user.has_perm('tags.manage... | <|body_start_0|>
self.user = kwargs.pop('user', None)
super(BaseCaseForm, self).__init__(*args, **kwargs)
self.fields['add_tags'].widget.attrs['data-allow-new'] = 'true' if self.user and self.user.has_perm('tags.manage_tags') else 'false'
<|end_body_0|>
<|body_start_1|>
if self.data.get... | Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin. | BaseCaseForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseCaseForm:
"""Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin."""
def __init__(self, *args, **kwargs):
"""Initialize form; pull out user from kwargs, set up data-allow-new."""
<|body_0|>
def clean... | stack_v2_sparse_classes_10k_train_007258 | 16,711 | permissive | [
{
"docstring": "Initialize form; pull out user from kwargs, set up data-allow-new.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Can't create new tags without appropriate permissions.",
"name": "clean",
"signature": "def clean(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_002639 | Implement the Python class `BaseCaseForm` described below.
Class description:
Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form; pull out user from kwargs, se... | Implement the Python class `BaseCaseForm` described below.
Class description:
Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form; pull out user from kwargs, se... | ee54db2fe8ffbf2216d359b7a093b51f2574878e | <|skeleton|>
class BaseCaseForm:
"""Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin."""
def __init__(self, *args, **kwargs):
"""Initialize form; pull out user from kwargs, set up data-allow-new."""
<|body_0|>
def clean... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseCaseForm:
"""Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin."""
def __init__(self, *args, **kwargs):
"""Initialize form; pull out user from kwargs, set up data-allow-new."""
self.user = kwargs.pop('user', None)
... | the_stack_v2_python_sparse | moztrap/view/manage/cases/forms.py | isakib/moztrap | train | 1 |
ee544876b8cc667ea4be09384f3a8058bef3930b | [
"ret = BaseUtils()\ntry:\n queryset = models.Course.objects.all()\n ser = CourseSerializer(instance=queryset, many=True)\n ret.data = ser.data\n ret.code = 1000\nexcept Exception as e:\n ret.code = 1001\n ret.error = '获取课程失败'\nreturn Response(ret.dict)",
"ret = {'code': 1000, 'data': None}\nset ... | <|body_start_0|>
ret = BaseUtils()
try:
queryset = models.Course.objects.all()
ser = CourseSerializer(instance=queryset, many=True)
ret.data = ser.data
ret.code = 1000
except Exception as e:
ret.code = 1001
ret.error = '获取课程... | CourseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseView:
def list(self, request, *args, **kwargs):
"""课程列表 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建课程 :param request: :param args: :param kwargs: :return:"""
<|body_1|>
def retr... | stack_v2_sparse_classes_10k_train_007259 | 2,869 | no_license | [
{
"docstring": "课程列表 :param request: :param args: :param kwargs: :return:",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "创建课程 :param request: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, request, *args, ... | 4 | stack_v2_sparse_classes_30k_train_000115 | Implement the Python class `CourseView` described below.
Class description:
Implement the CourseView class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 课程列表 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建课程 :param request: :param ar... | Implement the Python class `CourseView` described below.
Class description:
Implement the CourseView class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 课程列表 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建课程 :param request: :param ar... | 306ce096537ac3e71ee7530ee58b43a9c3f25489 | <|skeleton|>
class CourseView:
def list(self, request, *args, **kwargs):
"""课程列表 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建课程 :param request: :param args: :param kwargs: :return:"""
<|body_1|>
def retr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CourseView:
def list(self, request, *args, **kwargs):
"""课程列表 :param request: :param args: :param kwargs: :return:"""
ret = BaseUtils()
try:
queryset = models.Course.objects.all()
ser = CourseSerializer(instance=queryset, many=True)
ret.data = ser.da... | the_stack_v2_python_sparse | luffapi/views/course.py | xxt123456/luffcity | train | 0 | |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super(Elish, self).__init__()\nself.hard = hard\nif hard is not False:\n self.a = torch.tensor(0.0)\n self.b = torch.tensor(1.0)",
"if self.hard is False:\n return (input >= 0).float() * swish_function(input, False, False, None, None) + (input < 0).float() * (torch.exp(input) - 1) * torch.sigmoid(input)... | <|body_start_0|>
super(Elish, self).__init__()
self.hard = hard
if hard is not False:
self.a = torch.tensor(0.0)
self.b = torch.tensor(1.0)
<|end_body_0|>
<|body_start_1|>
if self.hard is False:
return (input >= 0).float() * swish_function(input, Fals... | Elish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Elish:
def __init__(self, hard=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Elish, self).__init__()
self.hard = hard
if hard is... | stack_v2_sparse_classes_10k_train_007260 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, hard=False)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003056 | Implement the Python class `Elish` described below.
Class description:
Implement the Elish class.
Method signatures and docstrings:
- def __init__(self, hard=False): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `Elish` described below.
Class description:
Implement the Elish class.
Method signatures and docstrings:
- def __init__(self, hard=False): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class Elish:
def __init__(self, hard=False):
"""Init m... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Elish:
def __init__(self, hard=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Elish:
def __init__(self, hard=False):
"""Init method."""
super(Elish, self).__init__()
self.hard = hard
if hard is not False:
self.a = torch.tensor(0.0)
self.b = torch.tensor(1.0)
def forward(self, input):
"""Forward pass of the function.""... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
031d8fa3af0b4fe49a3f09f41d414480858b05f6 | [
"writer.write(indent + '<' + self.tagName)\nattrs = self._get_attributes()\nfor a_name in attrs.keys():\n writer.write(' %s=\"' % a_name)\n self.write_data(writer, attrs[a_name].value)\n writer.write('\"')\nif self.childNodes:\n writer.write('>')\n if len(self.childNodes) == 1 and self.childNodes[0].... | <|body_start_0|>
writer.write(indent + '<' + self.tagName)
attrs = self._get_attributes()
for a_name in attrs.keys():
writer.write(' %s="' % a_name)
self.write_data(writer, attrs[a_name].value)
writer.write('"')
if self.childNodes:
writer.w... | NElement | [
"MIT",
"GPL-3.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NElement:
def writexml(self, writer, indent='', add_indent='', new_line=''):
"""Overridden specifically for neutrino for more correct [' -> optional] xml attrs generation."""
<|body_0|>
def write_data(writer, data):
"""Writes data chars to writer."""
<|b... | stack_v2_sparse_classes_10k_train_007261 | 4,467 | permissive | [
{
"docstring": "Overridden specifically for neutrino for more correct [' -> optional] xml attrs generation.",
"name": "writexml",
"signature": "def writexml(self, writer, indent='', add_indent='', new_line='')"
},
{
"docstring": "Writes data chars to writer.",
"name": "write_data",
... | 2 | stack_v2_sparse_classes_30k_train_005985 | Implement the Python class `NElement` described below.
Class description:
Implement the NElement class.
Method signatures and docstrings:
- def writexml(self, writer, indent='', add_indent='', new_line=''): Overridden specifically for neutrino for more correct [' -> optional] xml attrs generation.
- def write_da... | Implement the Python class `NElement` described below.
Class description:
Implement the NElement class.
Method signatures and docstrings:
- def writexml(self, writer, indent='', add_indent='', new_line=''): Overridden specifically for neutrino for more correct [' -> optional] xml attrs generation.
- def write_da... | 917e184486ff212b4a19b36ab726343f900da8b7 | <|skeleton|>
class NElement:
def writexml(self, writer, indent='', add_indent='', new_line=''):
"""Overridden specifically for neutrino for more correct [' -> optional] xml attrs generation."""
<|body_0|>
def write_data(writer, data):
"""Writes data chars to writer."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NElement:
def writexml(self, writer, indent='', add_indent='', new_line=''):
"""Overridden specifically for neutrino for more correct [' -> optional] xml attrs generation."""
writer.write(indent + '<' + self.tagName)
attrs = self._get_attributes()
for a_name in attrs.keys(... | the_stack_v2_python_sparse | app/eparser/neutrino/nxml.py | DYefremov/DemonEditor | train | 105 | |
704007c62d247197840ceb0eb0c6f73d33e193dc | [
"dt1 = '2021-02-01:2,3,4,5;'\nself.assertEqual(turn_first_datetime_string_into_time_format(dt1), datetime(2021, 2, 1, 1, 0))\ndt2 = '2021-02-03:0;'\nself.assertEqual(turn_first_datetime_string_into_time_format(dt2), datetime(2021, 2, 3, 0, 0))\ndt3 = '2021-02-01:47'\nself.assertEqual(turn_first_datetime_string_into... | <|body_start_0|>
dt1 = '2021-02-01:2,3,4,5;'
self.assertEqual(turn_first_datetime_string_into_time_format(dt1), datetime(2021, 2, 1, 1, 0))
dt2 = '2021-02-03:0;'
self.assertEqual(turn_first_datetime_string_into_time_format(dt2), datetime(2021, 2, 3, 0, 0))
dt3 = '2021-02-01:47'
... | TEST_HANDY | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TEST_HANDY:
def test_turn_first_datetime_string_into_time_format(self):
"""檢查是否可以將字串化的日期區間轉為datetime格式"""
<|body_0|>
def test_turn_picture_into_jpeg_format_change_size(self):
"""測試Image的一些性質"""
<|body_1|>
def test_turn_picture_into_jpeg_format_change_siz... | stack_v2_sparse_classes_10k_train_007262 | 3,391 | no_license | [
{
"docstring": "檢查是否可以將字串化的日期區間轉為datetime格式",
"name": "test_turn_first_datetime_string_into_time_format",
"signature": "def test_turn_first_datetime_string_into_time_format(self)"
},
{
"docstring": "測試Image的一些性質",
"name": "test_turn_picture_into_jpeg_format_change_size",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_test_000347 | Implement the Python class `TEST_HANDY` described below.
Class description:
Implement the TEST_HANDY class.
Method signatures and docstrings:
- def test_turn_first_datetime_string_into_time_format(self): 檢查是否可以將字串化的日期區間轉為datetime格式
- def test_turn_picture_into_jpeg_format_change_size(self): 測試Image的一些性質
- def test_tu... | Implement the Python class `TEST_HANDY` described below.
Class description:
Implement the TEST_HANDY class.
Method signatures and docstrings:
- def test_turn_first_datetime_string_into_time_format(self): 檢查是否可以將字串化的日期區間轉為datetime格式
- def test_turn_picture_into_jpeg_format_change_size(self): 測試Image的一些性質
- def test_tu... | 7a292671a355ae58f3889036d8da199b3801d321 | <|skeleton|>
class TEST_HANDY:
def test_turn_first_datetime_string_into_time_format(self):
"""檢查是否可以將字串化的日期區間轉為datetime格式"""
<|body_0|>
def test_turn_picture_into_jpeg_format_change_size(self):
"""測試Image的一些性質"""
<|body_1|>
def test_turn_picture_into_jpeg_format_change_siz... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TEST_HANDY:
def test_turn_first_datetime_string_into_time_format(self):
"""檢查是否可以將字串化的日期區間轉為datetime格式"""
dt1 = '2021-02-01:2,3,4,5;'
self.assertEqual(turn_first_datetime_string_into_time_format(dt1), datetime(2021, 2, 1, 1, 0))
dt2 = '2021-02-03:0;'
self.assertEqual(tu... | the_stack_v2_python_sparse | Quikok/website_assets/handy_functions_tests.py | chikuku/QUIKOK | train | 0 | |
a9085eaf7a446c54f2a7226b5c8e7ae9a6661930 | [
"super(StreamPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.tmp = torch.tensor(0.0).expand(1, max_len)\nself.extend_pe(self.tmp.size(1), self.tmp.device, self.tmp.dtype)\nself._register_load_s... | <|body_start_0|>
super(StreamPositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.tmp = torch.tensor(0.0).expand(1, max_len)
self.extend_pe(self.tmp.si... | Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | StreamPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamPositionalEncoding:
"""Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length."""
def __init__(self, d_model, dropout_rate, max_len=5000):
"""Construct an PositionalEncoding object."""
... | stack_v2_sparse_classes_10k_train_007263 | 12,758 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, length, device, dtype)"
},
... | 3 | stack_v2_sparse_classes_30k_train_004372 | Implement the Python class `StreamPositionalEncoding` described below.
Class description:
Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model, dropout_rate, max_... | Implement the Python class `StreamPositionalEncoding` described below.
Class description:
Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model, dropout_rate, max_... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class StreamPositionalEncoding:
"""Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length."""
def __init__(self, d_model, dropout_rate, max_len=5000):
"""Construct an PositionalEncoding object."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StreamPositionalEncoding:
"""Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length."""
def __init__(self, d_model, dropout_rate, max_len=5000):
"""Construct an PositionalEncoding object."""
super(St... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
e50d4668751b33b8d5505a300d5236347070edc0 | [
"if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration']:\n return type.__new__(cls, classname, bases, classdict)\nif ElementDeclaration in bases:\n if not 'schema' in classdict or not 'literal' in classdict:\n raise AttributeError('ElementDeclaration must define schema and ... | <|body_start_0|>
if classname in ['ElementDeclaration', 'TypeDefinition', 'LocalElementDeclaration']:
return type.__new__(cls, classname, bases, classdict)
if ElementDeclaration in bases:
if not 'schema' in classdict or not 'literal' in classdict:
raise AttributeE... | Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- dict of typecode classes representing global el... | SchemaInstanceType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- d... | stack_v2_sparse_classes_10k_train_007264 | 14,557 | permissive | [
{
"docstring": "If classdict has literal and schema register it as a element declaration, else if has type and schema register it as a type definition.",
"name": "__new__",
"signature": "def __new__(cls, classname, bases, classdict)"
},
{
"docstring": "Grab a type definition, returns a typecode ... | 3 | stack_v2_sparse_classes_30k_train_000309 | Implement the Python class `SchemaInstanceType` described below.
Class description:
Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing... | Implement the Python class `SchemaInstanceType` described below.
Class description:
Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing... | 9b890e6a25471037b7485e4999b480de7c86b656 | <|skeleton|>
class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SchemaInstanceType:
"""Register all types/elements, when hit already defined class dont create a new one just give back reference. Thus import order determines which class is loaded. class variables: types -- dict of typecode classes definitions representing global type definitions. elements -- dict of typeco... | the_stack_v2_python_sparse | Libraries/DUTs/Community/di_vsphere/pysphere/pysphere/ZSI/schema.py | Spirent/iTest-assets | train | 10 |
7e4848c4087951dc6e0c0ff5892aa17670f8ae04 | [
"log.info('Starting Infrastructure Layer...')\nself.topology = None\nsuper(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)",
"log.debug('Initializing Infrastructure Layer...')\nCONFIG.set_layer_loaded(self._core_name)\nmn_opts = CONFIG.get_mn_network_opts()\noptional_topo = getattr(self, '_topo', Non... | <|body_start_0|>
log.info('Starting Infrastructure Layer...')
self.topology = None
super(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)
<|end_body_0|>
<|body_start_1|>
log.debug('Initializing Infrastructure Layer...')
CONFIG.set_layer_loaded(self._core_name)
... | Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point. | InfrastructureLayerAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_10k_train_007265 | 4,843 | no_license | [
{
"docstring": ".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractAPI.__init__>`",
"name": "__init__",
"signature": "def __init__(self, standalone=False, **kwargs)"
},
{
"docstring": ".. seealso:: :func:`AbstractAPI.initialize() <escape.util.api.AbstractAPI.initialize>`",
"... | 5 | stack_v2_sparse_classes_30k_train_007289 | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | 30a220b4042b74ea5cccec725eddd4e7f95ba97d | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractA... | the_stack_v2_python_sparse | escape/escape/infr/il_API.py | hsnlab/fero | train | 3 |
659eb6fadc32229d48a9e1f09215e699ca037b36 | [
"if layer_specs is None:\n layer_specs = [[3, 128, 1, 1], [3, 128, 1, 1], [3, 96, 1, 1], [3, 64, 1, 1], [3, 32, 1, 1], [3, 2, 1, 1]]\nsuper().__init__(name=name, layer_specs=layer_specs, activation_fn=activation_fn, last_activation_fn=None, regularizer=regularizer, padding='SAME', dense_net=dense_net)\nself.sear... | <|body_start_0|>
if layer_specs is None:
layer_specs = [[3, 128, 1, 1], [3, 128, 1, 1], [3, 96, 1, 1], [3, 64, 1, 1], [3, 32, 1, 1], [3, 2, 1, 1]]
super().__init__(name=name, layer_specs=layer_specs, activation_fn=activation_fn, last_activation_fn=None, regularizer=regularizer, padding='SAME... | EstimatorNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EstimatorNetwork:
def __init__(self, name='estimator_network', layer_specs=None, activation_fn=leaky_relu, regularizer=None, search_range=4, dense_net=True, cost_volume_activation=True):
""":param name: Str. For variable scoping. :param layer_specs: See parent class. :param activation_fn... | stack_v2_sparse_classes_10k_train_007266 | 4,188 | no_license | [
{
"docstring": ":param name: Str. For variable scoping. :param layer_specs: See parent class. :param activation_fn: Tensorflow activation function. :param regularizer: Tf regularizer such as tf.contrib.layers.l2_regularizer. :param dense_net: Bool. Default for PWC-Net is true. :param cost_volume_activation: Boo... | 2 | stack_v2_sparse_classes_30k_train_003140 | Implement the Python class `EstimatorNetwork` described below.
Class description:
Implement the EstimatorNetwork class.
Method signatures and docstrings:
- def __init__(self, name='estimator_network', layer_specs=None, activation_fn=leaky_relu, regularizer=None, search_range=4, dense_net=True, cost_volume_activation=... | Implement the Python class `EstimatorNetwork` described below.
Class description:
Implement the EstimatorNetwork class.
Method signatures and docstrings:
- def __init__(self, name='estimator_network', layer_specs=None, activation_fn=leaky_relu, regularizer=None, search_range=4, dense_net=True, cost_volume_activation=... | 494d503c729ba018614fc742f1aee1e48d37127e | <|skeleton|>
class EstimatorNetwork:
def __init__(self, name='estimator_network', layer_specs=None, activation_fn=leaky_relu, regularizer=None, search_range=4, dense_net=True, cost_volume_activation=True):
""":param name: Str. For variable scoping. :param layer_specs: See parent class. :param activation_fn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EstimatorNetwork:
def __init__(self, name='estimator_network', layer_specs=None, activation_fn=leaky_relu, regularizer=None, search_range=4, dense_net=True, cost_volume_activation=True):
""":param name: Str. For variable scoping. :param layer_specs: See parent class. :param activation_fn: Tensorflow a... | the_stack_v2_python_sparse | pwcnet/estimator_network/model.py | NeedsMorePie/interpolator | train | 2 | |
4cdf730789dce91dd23c144d249ad62a4a3d4444 | [
"question = 'Какой был ваш первый язык? '\nmy_survey = AnonymusSurvey(question)\nmy_survey.store_response('Русский')\nself.assertIn('Русский', my_survey.responses)",
"question = 'Какой был ваш первый язык? '\nmy_survey = AnonymusSurvey(question)\nresponses = ['Русский', 'Английский', 'Итальянский']\nfor response ... | <|body_start_0|>
question = 'Какой был ваш первый язык? '
my_survey = AnonymusSurvey(question)
my_survey.store_response('Русский')
self.assertIn('Русский', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
question = 'Какой был ваш первый язык? '
my_survey = AnonymusS... | Тесты для класса AnonymusSurvey | TestAnonymusSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymusSurvey:
"""Тесты для класса AnonymusSurvey"""
def test_store_single_response(self):
"""Проверяет что один ответ сохранен правильно."""
<|body_0|>
def test_store_three_responses(self):
"""Проверяет, что три ответа были сохранены правильно."""
<... | stack_v2_sparse_classes_10k_train_007267 | 1,187 | no_license | [
{
"docstring": "Проверяет что один ответ сохранен правильно.",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "Проверяет, что три ответа были сохранены правильно.",
"name": "test_store_three_responses",
"signature": "def test_s... | 2 | null | Implement the Python class `TestAnonymusSurvey` described below.
Class description:
Тесты для класса AnonymusSurvey
Method signatures and docstrings:
- def test_store_single_response(self): Проверяет что один ответ сохранен правильно.
- def test_store_three_responses(self): Проверяет, что три ответа были сохранены пр... | Implement the Python class `TestAnonymusSurvey` described below.
Class description:
Тесты для класса AnonymusSurvey
Method signatures and docstrings:
- def test_store_single_response(self): Проверяет что один ответ сохранен правильно.
- def test_store_three_responses(self): Проверяет, что три ответа были сохранены пр... | 8afde60aa2bddd6858a5f7a7189169a82bde4322 | <|skeleton|>
class TestAnonymusSurvey:
"""Тесты для класса AnonymusSurvey"""
def test_store_single_response(self):
"""Проверяет что один ответ сохранен правильно."""
<|body_0|>
def test_store_three_responses(self):
"""Проверяет, что три ответа были сохранены правильно."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAnonymusSurvey:
"""Тесты для класса AnonymusSurvey"""
def test_store_single_response(self):
"""Проверяет что один ответ сохранен правильно."""
question = 'Какой был ваш первый язык? '
my_survey = AnonymusSurvey(question)
my_survey.store_response('Русский')
self... | the_stack_v2_python_sparse | chapter_11/02_test_class/test_survey.py | MaximZolotukhin/erik_metiz | train | 0 |
9f44765518ce70b7b0adc98269f254e02d652436 | [
"try:\n group_type = TeamType.objects.get(pk=pk)\nexcept ObjectDoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\nif request.user.has_perm(VIEW_TEAMTYPE):\n serializer = TeamTypeDetailsSerializer(group_type)\n return Response(serializer.data)\nreturn Response(status=status.HTTP_401_UNAUT... | <|body_start_0|>
try:
group_type = TeamType.objects.get(pk=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.user.has_perm(VIEW_TEAMTYPE):
serializer = TeamTypeDetailsSerializer(group_type)
return Response(... | # Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type with the data on the request or if the data i... | TeamTypesDetail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamTypesDetail:
"""# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type wi... | stack_v2_sparse_classes_10k_train_007268 | 6,650 | permissive | [
{
"docstring": "docstring.",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "docstrings.",
"name": "put",
"signature": "def put(self, request, pk)"
},
{
"docstring": "docstrings.",
"name": "delete",
"signature": "def delete(self, request, pk)"
... | 3 | stack_v2_sparse_classes_30k_train_003514 | Implement the Python class `TeamTypesDetail` described below.
Class description:
# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data... | Implement the Python class `TeamTypesDetail` described below.
Class description:
# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class TeamTypesDetail:
"""# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type wi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeamTypesDetail:
"""# Retrieve, update or delete a team type. Parameters : request (HttpRequest) : the request coming from the front-end pk (int) : the id of the team type Return : response (Response) : the response. GET request : return the team type's data. PUT request : change the team type with the data o... | the_stack_v2_python_sparse | usersmanagement/views/views_teamtypes.py | Open-CMMS/openCMMS_backend | train | 4 |
9f6f39051d4921b8da5ffd18516fb1662c7334ba | [
"parser = (Literal('abc') > 'name') ** make_error('msg')\nparser.config.no_full_first_match()\nnode = parser.parse('abc')[0]\nassert isinstance(node, Error)\nassert node[0] == 'msg', node[0]\nassert str(node).startswith('msg ('), str(node)\nassert isinstance(node, Exception), type(node)",
"parser = (Literal('abc'... | <|body_start_0|>
parser = (Literal('abc') > 'name') ** make_error('msg')
parser.config.no_full_first_match()
node = parser.parse('abc')[0]
assert isinstance(node, Error)
assert node[0] == 'msg', node[0]
assert str(node).startswith('msg ('), str(node)
assert isinst... | Check generation of Error nodes. | MessageTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageTest:
"""Check generation of Error nodes."""
def test_simple(self):
"""Test a message with no fmtting."""
<|body_0|>
def test_fmtted(self):
"""Test a message with fmtting."""
<|body_1|>
def test_bad_fmt(self):
"""Test a message with ba... | stack_v2_sparse_classes_10k_train_007269 | 3,681 | no_license | [
{
"docstring": "Test a message with no fmtting.",
"name": "test_simple",
"signature": "def test_simple(self)"
},
{
"docstring": "Test a message with fmtting.",
"name": "test_fmtted",
"signature": "def test_fmtted(self)"
},
{
"docstring": "Test a message with bad fmtting.",
"n... | 4 | stack_v2_sparse_classes_30k_val_000183 | Implement the Python class `MessageTest` described below.
Class description:
Check generation of Error nodes.
Method signatures and docstrings:
- def test_simple(self): Test a message with no fmtting.
- def test_fmtted(self): Test a message with fmtting.
- def test_bad_fmt(self): Test a message with bad fmtting.
- de... | Implement the Python class `MessageTest` described below.
Class description:
Check generation of Error nodes.
Method signatures and docstrings:
- def test_simple(self): Test a message with no fmtting.
- def test_fmtted(self): Test a message with fmtting.
- def test_bad_fmt(self): Test a message with bad fmtting.
- de... | 0603505f187acc3c7da2e1a6083833a201f8b061 | <|skeleton|>
class MessageTest:
"""Check generation of Error nodes."""
def test_simple(self):
"""Test a message with no fmtting."""
<|body_0|>
def test_fmtted(self):
"""Test a message with fmtting."""
<|body_1|>
def test_bad_fmt(self):
"""Test a message with ba... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MessageTest:
"""Check generation of Error nodes."""
def test_simple(self):
"""Test a message with no fmtting."""
parser = (Literal('abc') > 'name') ** make_error('msg')
parser.config.no_full_first_match()
node = parser.parse('abc')[0]
assert isinstance(node, Error)... | the_stack_v2_python_sparse | src/lepl/matchers/_test/error.py | nyimbi/LEPL | train | 2 |
95091c6b7c4e772633dcd655caf80e274042fdfe | [
"super(HumiditySensorEmulatorTask, self).__init__(sensorName=ConfigConst.HUMIDITY_SENSOR_NAME, sensorType=SensorData.HUMIDITY_SENSOR_TYPE, minVal=SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY, maxVal=SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)\nself.configUtil = ConfigUtil()\nif self.configUtil.getBoolean(self, Confi... | <|body_start_0|>
super(HumiditySensorEmulatorTask, self).__init__(sensorName=ConfigConst.HUMIDITY_SENSOR_NAME, sensorType=SensorData.HUMIDITY_SENSOR_TYPE, minVal=SensorDataGenerator.LOW_NORMAL_ENV_HUMIDITY, maxVal=SensorDataGenerator.HI_NORMAL_ENV_HUMIDITY)
self.configUtil = ConfigUtil()
if self... | Shell representation of class for student implementation. | HumiditySensorEmulatorTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumiditySensorEmulatorTask:
"""Shell representation of class for student implementation."""
def __init__(self, dataSet=None):
"""Constructor: determine if emulator is used dataSet: DataSet"""
<|body_0|>
def generateTelemetry(self) -> SensorData:
"""Get humidity d... | stack_v2_sparse_classes_10k_train_007270 | 2,165 | permissive | [
{
"docstring": "Constructor: determine if emulator is used dataSet: DataSet",
"name": "__init__",
"signature": "def __init__(self, dataSet=None)"
},
{
"docstring": "Get humidity data from emulator return SensorData",
"name": "generateTelemetry",
"signature": "def generateTelemetry(self) ... | 2 | stack_v2_sparse_classes_30k_train_003517 | Implement the Python class `HumiditySensorEmulatorTask` described below.
Class description:
Shell representation of class for student implementation.
Method signatures and docstrings:
- def __init__(self, dataSet=None): Constructor: determine if emulator is used dataSet: DataSet
- def generateTelemetry(self) -> Senso... | Implement the Python class `HumiditySensorEmulatorTask` described below.
Class description:
Shell representation of class for student implementation.
Method signatures and docstrings:
- def __init__(self, dataSet=None): Constructor: determine if emulator is used dataSet: DataSet
- def generateTelemetry(self) -> Senso... | 26db6375a21ee9bdccba3d137e30d2e63ad6395c | <|skeleton|>
class HumiditySensorEmulatorTask:
"""Shell representation of class for student implementation."""
def __init__(self, dataSet=None):
"""Constructor: determine if emulator is used dataSet: DataSet"""
<|body_0|>
def generateTelemetry(self) -> SensorData:
"""Get humidity d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HumiditySensorEmulatorTask:
"""Shell representation of class for student implementation."""
def __init__(self, dataSet=None):
"""Constructor: determine if emulator is used dataSet: DataSet"""
super(HumiditySensorEmulatorTask, self).__init__(sensorName=ConfigConst.HUMIDITY_SENSOR_NAME, sen... | the_stack_v2_python_sparse | src/main/python/programmingtheiot/cda/emulated/HumiditySensorEmulatorTask.py | Zhengrui-Liu/FireAlarmingSysCDA | train | 0 |
7cdf23278627b02ade640e880f7d7d53818f3bed | [
"self._fixed_length_left = fixed_length_left\nself._fixed_length_right = fixed_length_right\nself._pad_word_value = pad_word_value\nself._pad_word_mode = pad_word_mode\nself._with_ngram = with_ngram\nself._fixed_ngram_length = fixed_ngram_length\nself._pad_ngram_value = pad_ngram_value\nself._pad_ngram_mode = pad_n... | <|body_start_0|>
self._fixed_length_left = fixed_length_left
self._fixed_length_right = fixed_length_right
self._pad_word_value = pad_word_value
self._pad_word_mode = pad_word_mode
self._with_ngram = with_ngram
self._fixed_ngram_length = fixed_ngram_length
self._p... | Pad data for basic preprocessor. :param fixed_length_left: Integer. If set, `text_left` will be padded to this length. :param fixed_length_right: Integer. If set, `text_right` will be padded to this length. :param pad_word_value: the value to fill text. :param pad_word_mode: String, `pre` or `post`: pad either before o... | BasicPadding | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicPadding:
"""Pad data for basic preprocessor. :param fixed_length_left: Integer. If set, `text_left` will be padded to this length. :param fixed_length_right: Integer. If set, `text_right` will be padded to this length. :param pad_word_value: the value to fill text. :param pad_word_mode: Stri... | stack_v2_sparse_classes_10k_train_007271 | 10,301 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, fixed_length_left: int=None, fixed_length_right: int=None, pad_word_value: typing.Union[int, str]=0, pad_word_mode: str='pre', with_ngram: bool=False, fixed_ngram_length: int=None, pad_ngram_value: typing.Union[int, str]=0, pad... | 2 | stack_v2_sparse_classes_30k_train_005189 | Implement the Python class `BasicPadding` described below.
Class description:
Pad data for basic preprocessor. :param fixed_length_left: Integer. If set, `text_left` will be padded to this length. :param fixed_length_right: Integer. If set, `text_right` will be padded to this length. :param pad_word_value: the value t... | Implement the Python class `BasicPadding` described below.
Class description:
Pad data for basic preprocessor. :param fixed_length_left: Integer. If set, `text_left` will be padded to this length. :param fixed_length_right: Integer. If set, `text_right` will be padded to this length. :param pad_word_value: the value t... | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | <|skeleton|>
class BasicPadding:
"""Pad data for basic preprocessor. :param fixed_length_left: Integer. If set, `text_left` will be padded to this length. :param fixed_length_right: Integer. If set, `text_right` will be padded to this length. :param pad_word_value: the value to fill text. :param pad_word_mode: Stri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasicPadding:
"""Pad data for basic preprocessor. :param fixed_length_left: Integer. If set, `text_left` will be padded to this length. :param fixed_length_right: Integer. If set, `text_right` will be padded to this length. :param pad_word_value: the value to fill text. :param pad_word_mode: String, `pre` or ... | the_stack_v2_python_sparse | poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/dataloader/callbacks/padding.py | microsoft/ContextualSP | train | 332 |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(Spectrogram, self).__init__()\nself.n_fft = n_fft\nself.hop = hop\nself.mels = mels\nself.sr = sr\nself.window = nn.Parameter(torch.hann_window(n_fft), requires_grad=False)\nstft_size = n_fft // 2 + 1\nself.mel_transform = nn.Conv1d(stft_size, mels, kernel_size=1, stride=1, padding=0, bias=True)\nself.mean =... | <|body_start_0|>
super(Spectrogram, self).__init__()
self.n_fft = n_fft
self.hop = hop
self.mels = mels
self.sr = sr
self.window = nn.Parameter(torch.hann_window(n_fft), requires_grad=False)
stft_size = n_fft // 2 + 1
self.mel_transform = nn.Conv1d(stft_si... | Calculate the mel spectrogram as an additional input for the encoder | Spectrogram | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spectrogram:
"""Calculate the mel spectrogram as an additional input for the encoder"""
def __init__(self, n_fft, hop, mels, sr):
"""Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate... | stack_v2_sparse_classes_10k_train_007272 | 37,269 | no_license | [
{
"docstring": "Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate of the signal",
"name": "__init__",
"signature": "def __init__(self, n_fft, hop, mels, sr)"
},
{
"docstring": "Arguments: audio_... | 4 | stack_v2_sparse_classes_30k_train_003552 | Implement the Python class `Spectrogram` described below.
Class description:
Calculate the mel spectrogram as an additional input for the encoder
Method signatures and docstrings:
- def __init__(self, n_fft, hop, mels, sr): Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {in... | Implement the Python class `Spectrogram` described below.
Class description:
Calculate the mel spectrogram as an additional input for the encoder
Method signatures and docstrings:
- def __init__(self, n_fft, hop, mels, sr): Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {in... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Spectrogram:
"""Calculate the mel spectrogram as an additional input for the encoder"""
def __init__(self, n_fft, hop, mels, sr):
"""Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Spectrogram:
"""Calculate the mel spectrogram as an additional input for the encoder"""
def __init__(self, n_fft, hop, mels, sr):
"""Arguments: n_fft {int} -- The number fo frequency bins hop {int} -- Hop size (stride) mels {int} -- The number of mel filters sr {int} -- Sampling rate of the signa... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
2e31d4668d6585438bb138dcb7487535291e8345 | [
"if not data:\n return None\nattribute_name = data['attribute_name']\nparameter_name = data['parameter_name']\nhelp_text = data['help']\ncompletion_id_field = data.get('completion_id_field', None)\ncompletion_request_params_list = data.get('completion_request_params', [])\ncompletion_request_params = {param.get(... | <|body_start_0|>
if not data:
return None
attribute_name = data['attribute_name']
parameter_name = data['parameter_name']
help_text = data['help']
completion_id_field = data.get('completion_id_field', None)
completion_request_params_list = data.get('completion... | Configuration used to create attributes from resource parameters. | ResourceParameterAttributeConfig | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceParameterAttributeConfig:
"""Configuration used to create attributes from resource parameters."""
def FromData(cls, data):
"""Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Retu... | stack_v2_sparse_classes_10k_train_007273 | 31,588 | permissive | [
{
"docstring": "Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Returns: ResourceParameterAttributeConfig",
"name": "FromData",
"signature": "def FromData(cls, data)"
},
{
"docstring": "Create a res... | 2 | stack_v2_sparse_classes_30k_train_005033 | Implement the Python class `ResourceParameterAttributeConfig` described below.
Class description:
Configuration used to create attributes from resource parameters.
Method signatures and docstrings:
- def FromData(cls, data): Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict o... | Implement the Python class `ResourceParameterAttributeConfig` described below.
Class description:
Configuration used to create attributes from resource parameters.
Method signatures and docstrings:
- def FromData(cls, data): Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict o... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class ResourceParameterAttributeConfig:
"""Configuration used to create attributes from resource parameters."""
def FromData(cls, data):
"""Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResourceParameterAttributeConfig:
"""Configuration used to create attributes from resource parameters."""
def FromData(cls, data):
"""Constructs an attribute config from data defined in the yaml file. Args: data: {}, the dict of data from the YAML file for this single attribute. Returns: Resource... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/calliope/concepts/concepts.py | bopopescu/socialliteapp | train | 0 |
b2ad93f0905da508645267ccf5add55ba4f2e391 | [
"if num <= 0:\n return self.isUgly(-1 * num)\nwhile num > 1:\n if num % 2 == 0:\n num /= 2\n elif num % 3 == 0:\n num /= 3\n elif num % 5 == 0:\n num /= 5\n else:\n return False\nreturn True",
"size = len(primes)\nnums = [1]\nindices = [0] * size\nlocal_num = [0] * size\... | <|body_start_0|>
if num <= 0:
return self.isUgly(-1 * num)
while num > 1:
if num % 2 == 0:
num /= 2
elif num % 3 == 0:
num /= 3
elif num % 5 == 0:
num /= 5
else:
return False
... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
... | stack_v2_sparse_classes_10k_train_007274 | 1,800 | permissive | [
{
"docstring": ":type num: int :rtype: bool",
"name": "isUgly",
"signature": "def isUgly(self, num)"
},
{
"docstring": ":type n: int :type primes: List[int] :rtype: int",
"name": "nthSuperUglyNumber",
"signature": "def nthSuperUglyNumber(self, n, primes)"
},
{
"docstring": ":type... | 3 | stack_v2_sparse_classes_30k_train_001060 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
- def nthUglyNumber(self, n): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
- def nthUglyNumber(self, n): :type... | 8221d10f201d001abcb15b27c9cf4b8cd5060f1f | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
if num <= 0:
return self.isUgly(-1 * num)
while num > 1:
if num % 2 == 0:
num /= 2
elif num % 3 == 0:
num /= 3
elif num % 5 == 0:
... | the_stack_v2_python_sparse | python/ugly_nums.py | shub0/algorithm-data-structure | train | 0 | |
7387d1184e2af209b64de27c7b1ae1e1ed6378bc | [
"for i in range(1, len(w)):\n w[i] += w[i - 1]\nself.w = w",
"rand = random.randint(1, self.w[-1])\ns, e = (0, len(self.w) - 1)\nwhile s + 1 < e:\n m = s + (e - s) // 2\n if self.w[m] > rand:\n e = m\n else:\n s = m\nif self.w[s] >= rand:\n return s\nreturn e"
] | <|body_start_0|>
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
<|end_body_0|>
<|body_start_1|>
rand = random.randint(1, self.w[-1])
s, e = (0, len(self.w) - 1)
while s + 1 < e:
m = s + (e - s) // 2
if self.w[m] > rand:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
<|end_body_0|>
<|bod... | stack_v2_sparse_classes_10k_train_007275 | 679 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 542c99e038d21429853515f62af51a77deaa4d9c | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
def pickIndex(self):
""":rtype: int"""
rand = random.randint(1, self.w[-1])
s, e = (0, len(self.w) - 1)
while s + 1 < e:
... | the_stack_v2_python_sparse | random-pick-with-weight/random-pick-with-weight.py | niufenjujuexianhua/Leetcode | train | 0 | |
cb28f6331ad7bdb320ebea55fd4badfc276c63cc | [
"data = json.load(f) or []\nnow = time.time()\nfor cookie in map(go_to_py_cookie, data):\n if not ignore_expires and cookie.is_expired(now):\n continue\n self.set_cookie(cookie)",
"if filename is None:\n if self.filename is not None:\n filename = self.filename\n else:\n raise Valu... | <|body_start_0|>
data = json.load(f) or []
now = time.time()
for cookie in map(go_to_py_cookie, data):
if not ignore_expires and cookie.is_expired(now):
continue
self.set_cookie(cookie)
<|end_body_0|>
<|body_start_1|>
if filename is None:
... | A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar. | GoCookieJar | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoCookieJar:
"""A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar."""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
"""Implement the _really_load method called b... | stack_v2_sparse_classes_10k_train_007276 | 3,755 | permissive | [
{
"docstring": "Implement the _really_load method called by FileCookieJar to implement the actual cookie loading",
"name": "_really_load",
"signature": "def _really_load(self, f, filename, ignore_discard, ignore_expires)"
},
{
"docstring": "Implement the FileCookieJar abstract method.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_006387 | Implement the Python class `GoCookieJar` described below.
Class description:
A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar.
Method signatures and docstrings:
- def _really_load(self, f, filename, ignore_discard, ig... | Implement the Python class `GoCookieJar` described below.
Class description:
A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar.
Method signatures and docstrings:
- def _really_load(self, f, filename, ignore_discard, ig... | f21bc426952579efb980439f6a07d59bcb4cce0b | <|skeleton|>
class GoCookieJar:
"""A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar."""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
"""Implement the _really_load method called b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoCookieJar:
"""A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar."""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
"""Implement the _really_load method called by FileCookieJ... | the_stack_v2_python_sparse | juju/client/gocookies.py | juju/python-libjuju | train | 63 |
ae599ab2276eb4f0f40c7ce7dd745fc3b0b2527f | [
"self.sprite = pygame.image.load(spritepath)\ncw, ch = charsize\nsw, sh = (self.sprite.get_width() / cw, self.sprite.get_height() / ch)\nspacewidth = spacewidth if spacewidth is not None else cw * 0.4\nself.height = ch\nself.chars = {}\nfor y in range(sh):\n for x in range(sw):\n char = chr(x + y * sw)\n ... | <|body_start_0|>
self.sprite = pygame.image.load(spritepath)
cw, ch = charsize
sw, sh = (self.sprite.get_width() / cw, self.sprite.get_height() / ch)
spacewidth = spacewidth if spacewidth is not None else cw * 0.4
self.height = ch
self.chars = {}
for y in range(sh... | Font | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Font:
def __init__(self, spritepath, charsize, mono=False, spacewidth=None):
"""Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0."""
<|body_0|>
def re... | stack_v2_sparse_classes_10k_train_007277 | 3,921 | no_license | [
{
"docstring": "Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0.",
"name": "__init__",
"signature": "def __init__(self, spritepath, charsize, mono=False, spacewidth=None)"
},
... | 4 | stack_v2_sparse_classes_30k_train_006255 | Implement the Python class `Font` described below.
Class description:
Implement the Font class.
Method signatures and docstrings:
- def __init__(self, spritepath, charsize, mono=False, spacewidth=None): Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces... | Implement the Python class `Font` described below.
Class description:
Implement the Font class.
Method signatures and docstrings:
- def __init__(self, spritepath, charsize, mono=False, spacewidth=None): Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces... | 6c769822a65ee0be48922da88f9910068ad58a4f | <|skeleton|>
class Font:
def __init__(self, spritepath, charsize, mono=False, spacewidth=None):
"""Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0."""
<|body_0|>
def re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Font:
def __init__(self, spritepath, charsize, mono=False, spacewidth=None):
"""Given a sprite that is a grid of characters, and the dimensions of each character, slice it into a dict of surfaces mapped to each character in ASCII sequence, starting at 0."""
self.sprite = pygame.image.load(spri... | the_stack_v2_python_sparse | pyg/font.py | saltire/roverchip-tdd | train | 0 | |
a27d12c4a81e6ba65fd390657ca38f2b7ee02065 | [
"loc_inactive = mixer.blend(Location, manager=None, active=False)\nurl = '/api/locations/'\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\nself.assertNotContains(response, loc_inactive.name)",
"url = '/api/locations/?location_id={}'.format(self.loc1.pk)\nresponse = self.client.get(u... | <|body_start_0|>
loc_inactive = mixer.blend(Location, manager=None, active=False)
url = '/api/locations/'
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, loc_inactive.name)
<|end_body_0|>
<|body_start_1|>
url =... | LocationResourceTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationResourceTestCase:
def test_list(self):
"""Test the LocationResource list response"""
<|body_0|>
def test_filter(self):
"""Test the LocationResource filtered response"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
loc_inactive = mixer.blend(... | stack_v2_sparse_classes_10k_train_007278 | 18,653 | permissive | [
{
"docstring": "Test the LocationResource list response",
"name": "test_list",
"signature": "def test_list(self)"
},
{
"docstring": "Test the LocationResource filtered response",
"name": "test_filter",
"signature": "def test_filter(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006432 | Implement the Python class `LocationResourceTestCase` described below.
Class description:
Implement the LocationResourceTestCase class.
Method signatures and docstrings:
- def test_list(self): Test the LocationResource list response
- def test_filter(self): Test the LocationResource filtered response | Implement the Python class `LocationResourceTestCase` described below.
Class description:
Implement the LocationResourceTestCase class.
Method signatures and docstrings:
- def test_list(self): Test the LocationResource list response
- def test_filter(self): Test the LocationResource filtered response
<|skeleton|>
cl... | 4d5caceba69cac7f59b63745a0f52322004df2eb | <|skeleton|>
class LocationResourceTestCase:
def test_list(self):
"""Test the LocationResource list response"""
<|body_0|>
def test_filter(self):
"""Test the LocationResource filtered response"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LocationResourceTestCase:
def test_list(self):
"""Test the LocationResource list response"""
loc_inactive = mixer.blend(Location, manager=None, active=False)
url = '/api/locations/'
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self... | the_stack_v2_python_sparse | organisation/test_api.py | bryceprince0/it-assets | train | 0 | |
db7b07be21d0ad1b19a0a9acc7e5c95e4cd821cf | [
"tree = etree.parse(file)\nroot = tree.getroot()\nif not etree.iselement(root):\n sys.exit(\"Error while parsing '\" + file + \"' file.\\n\")\nfor node in root.findall('node'):\n self.parse_node(node)\nfor way in root.findall('way'):\n self.parse_way(way)\nfor relation in root.findall('relation'):\n sel... | <|body_start_0|>
tree = etree.parse(file)
root = tree.getroot()
if not etree.iselement(root):
sys.exit("Error while parsing '" + file + "' file.\n")
for node in root.findall('node'):
self.parse_node(node)
for way in root.findall('way'):
self.pa... | Parser of the OSM file. | Parser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser of the OSM file."""
def parse_file(self, file, disableMultipolygonBuildings=False):
"""Parse the OSM file."""
<|body_0|>
def get_tags(self, element):
"""Return a dictionnary of tags belonging to this element."""
<|body_1|>
def parse... | stack_v2_sparse_classes_10k_train_007279 | 6,805 | permissive | [
{
"docstring": "Parse the OSM file.",
"name": "parse_file",
"signature": "def parse_file(self, file, disableMultipolygonBuildings=False)"
},
{
"docstring": "Return a dictionnary of tags belonging to this element.",
"name": "get_tags",
"signature": "def get_tags(self, element)"
},
{
... | 6 | null | Implement the Python class `Parser` described below.
Class description:
Parser of the OSM file.
Method signatures and docstrings:
- def parse_file(self, file, disableMultipolygonBuildings=False): Parse the OSM file.
- def get_tags(self, element): Return a dictionnary of tags belonging to this element.
- def parse_nod... | Implement the Python class `Parser` described below.
Class description:
Parser of the OSM file.
Method signatures and docstrings:
- def parse_file(self, file, disableMultipolygonBuildings=False): Parse the OSM file.
- def get_tags(self, element): Return a dictionnary of tags belonging to this element.
- def parse_nod... | 8aba6eaae76989facf3442305c8089d3cc366bcf | <|skeleton|>
class Parser:
"""Parser of the OSM file."""
def parse_file(self, file, disableMultipolygonBuildings=False):
"""Parse the OSM file."""
<|body_0|>
def get_tags(self, element):
"""Return a dictionnary of tags belonging to this element."""
<|body_1|>
def parse... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser of the OSM file."""
def parse_file(self, file, disableMultipolygonBuildings=False):
"""Parse the OSM file."""
tree = etree.parse(file)
root = tree.getroot()
if not etree.iselement(root):
sys.exit("Error while parsing '" + file + "' file.\n")
... | the_stack_v2_python_sparse | resources/osm_importer/parser_objects.py | cyberbotics/webots | train | 2,495 |
b2e672df28e20bae58e436d87c4e8fa4647d551f | [
"super(mp_conv_residual, self).__init__()\nself.conv1 = torch.nn.Sequential(torch.nn.Conv2d(nin, nmed, 1), SyncBatchNorm(nmed), torch.nn.ReLU(inplace=True))\nself.mp_conv = mp_conv_v2(nmed, nmed, netype, extension=extension)\nself.conv2 = torch.nn.Sequential(torch.nn.Conv2d(nmed, nin, 1), SyncBatchNorm(nin), torch.... | <|body_start_0|>
super(mp_conv_residual, self).__init__()
self.conv1 = torch.nn.Sequential(torch.nn.Conv2d(nin, nmed, 1), SyncBatchNorm(nmed), torch.nn.ReLU(inplace=True))
self.mp_conv = mp_conv_v2(nmed, nmed, netype, extension=extension)
self.conv2 = torch.nn.Sequential(torch.nn.Conv2d(... | mp_conv_residual | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mp_conv_residual:
def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False):
"""Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of ed... | stack_v2_sparse_classes_10k_train_007280 | 1,915 | permissive | [
{
"docstring": "Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of edge types :param extension: organization type of edge features :param with_residual: use residual link or not",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_001297 | Implement the Python class `mp_conv_residual` described below.
Class description:
Implement the mp_conv_residual class.
Method signatures and docstrings:
- def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False): Residual block for graph conv network. :param ni... | Implement the Python class `mp_conv_residual` described below.
Class description:
Implement the mp_conv_residual class.
Method signatures and docstrings:
- def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False): Residual block for graph conv network. :param ni... | d7d480aa63d1e69cb94128610ec72938cc7873e8 | <|skeleton|>
class mp_conv_residual:
def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False):
"""Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of ed... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class mp_conv_residual:
def __init__(self, nin, nmed, netype, extension=mp_conv_type.ORIG_WITH_DIFF, with_residual=True, with_hop=False):
"""Residual block for graph conv network. :param nin: number of input units :param nmed: number of units in the graph conv layer :param netype: number of edge types :para... | the_stack_v2_python_sparse | lib/mpnn/mp_nn_residual.py | richardodliu/Factor-Graph-Neural-Network | train | 0 | |
c1d5c9cd4b2c84248d98e8f59c62dc63ef57f65a | [
"super().__init__()\nself._lock: RLock = RLock()\nself._last: int = 0\nself._count: int = 0\nself._urn: Optional[str] = urn",
"with self._lock:\n now: int = int(time())\n if now == self._last:\n self._count += 1\n else:\n self._count = 0\n self._last = now\n if self._urn is not No... | <|body_start_0|>
super().__init__()
self._lock: RLock = RLock()
self._last: int = 0
self._count: int = 0
self._urn: Optional[str] = urn
<|end_body_0|>
<|body_start_1|>
with self._lock:
now: int = int(time())
if now == self._last:
s... | An event ID generator that always generates a unique, non-repeating ID. | BoboGenEventIDUnique | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoboGenEventIDUnique:
"""An event ID generator that always generates a unique, non-repeating ID."""
def __init__(self, urn: Optional[str]=None):
""":param urn: A URN to prefix before the generated event ID (optional)."""
<|body_0|>
def generate(self) -> str:
""":... | stack_v2_sparse_classes_10k_train_007281 | 1,403 | permissive | [
{
"docstring": ":param urn: A URN to prefix before the generated event ID (optional).",
"name": "__init__",
"signature": "def __init__(self, urn: Optional[str]=None)"
},
{
"docstring": ":return: A generated event ID.",
"name": "generate",
"signature": "def generate(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_006262 | Implement the Python class `BoboGenEventIDUnique` described below.
Class description:
An event ID generator that always generates a unique, non-repeating ID.
Method signatures and docstrings:
- def __init__(self, urn: Optional[str]=None): :param urn: A URN to prefix before the generated event ID (optional).
- def gen... | Implement the Python class `BoboGenEventIDUnique` described below.
Class description:
An event ID generator that always generates a unique, non-repeating ID.
Method signatures and docstrings:
- def __init__(self, urn: Optional[str]=None): :param urn: A URN to prefix before the generated event ID (optional).
- def gen... | 7035feece42ae3494d4471e90f8ce818ed5ab670 | <|skeleton|>
class BoboGenEventIDUnique:
"""An event ID generator that always generates a unique, non-repeating ID."""
def __init__(self, urn: Optional[str]=None):
""":param urn: A URN to prefix before the generated event ID (optional)."""
<|body_0|>
def generate(self) -> str:
""":... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BoboGenEventIDUnique:
"""An event ID generator that always generates a unique, non-repeating ID."""
def __init__(self, urn: Optional[str]=None):
""":param urn: A URN to prefix before the generated event ID (optional)."""
super().__init__()
self._lock: RLock = RLock()
self.... | the_stack_v2_python_sparse | bobocep/cep/gen/event_id.py | r3w0p/bobocep | train | 10 |
f03a710f13bc9958348156d49e4af302f43d947f | [
"self.f = False\n\ndef help(nums, i, subsum, t):\n if t == subsum:\n self.f = True\n return\n if i < len(nums) and (not self.f):\n help(nums, i + 1, subsum + nums[i], t)\n help(nums, i + 1, subsum, t)\ns = sum(nums)\nif s % 2 == 1:\n return self.f\nelse:\n help(nums, 0, 0, s ... | <|body_start_0|>
self.f = False
def help(nums, i, subsum, t):
if t == subsum:
self.f = True
return
if i < len(nums) and (not self.f):
help(nums, i + 1, subsum + nums[i], t)
help(nums, i + 1, subsum, t)
s = s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.f = False
def help(nums, i... | stack_v2_sparse_classes_10k_train_007282 | 1,237 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition1",
"signature": "def canPartition1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition",
"signature": "def canPartition(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition1(self, nums): :type nums: List[int] :rtype: bool
- def canPartition(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition1(self, nums): :type nums: List[int] :rtype: bool
- def canPartition(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def canPar... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def canPartition1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canPartition1(self, nums):
""":type nums: List[int] :rtype: bool"""
self.f = False
def help(nums, i, subsum, t):
if t == subsum:
self.f = True
return
if i < len(nums) and (not self.f):
help(nums, i +... | the_stack_v2_python_sparse | py/leetcode/416.py | wfeng1991/learnpy | train | 0 | |
5aec9db14569e309175b32a02b06b72e3c1c92b4 | [
"if warmup_type is not None:\n if not isinstance(warmup_iters, int) or warmup_iters <= 0:\n raise ValueError('\"warmup_iters\" must be a positive integer')\n if not isinstance(warmup_ratio, float) or warmup_ratio <= 0 or warmup_ratio > 1.0:\n raise ValueError('\"warmup_ratio\" must be in range (... | <|body_start_0|>
if warmup_type is not None:
if not isinstance(warmup_iters, int) or warmup_iters <= 0:
raise ValueError('"warmup_iters" must be a positive integer')
if not isinstance(warmup_ratio, float) or warmup_ratio <= 0 or warmup_ratio > 1.0:
raise V... | Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch :type epoch_steps: int | WarmupScheduler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarmupScheduler:
"""Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch ... | stack_v2_sparse_classes_10k_train_007283 | 3,827 | permissive | [
{
"docstring": "Init WarmupScheduler.",
"name": "__init__",
"signature": "def __init__(self, optimizer, warmup_type='linear', warmup_iters=0, warmup_ratio=0.1, after_scheduler_config=None, **kwargs)"
},
{
"docstring": "Get lr.",
"name": "get_lr",
"signature": "def get_lr(self)"
},
{
... | 3 | null | Implement the Python class `WarmupScheduler` described below.
Class description:
Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool ... | Implement the Python class `WarmupScheduler` described below.
Class description:
Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool ... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class WarmupScheduler:
"""Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WarmupScheduler:
"""Multiple Step learning rate with warm up. :param milestones: list of decay epochs :type milestones: list of int :param decay_rates: list of decay rates :type decay_rates: list of float :param warmup: whether to warm up :type warmup: bool :param epoch_steps: steps in one epoch :type epoch_s... | the_stack_v2_python_sparse | zeus/trainer/modules/lr_schedulers/warmup_scheduler_torch.py | huawei-noah/xingtian | train | 308 |
02edb7c26824676ea5b66b895a23663d45a7531a | [
"logging.info('Validando os dados para criação da questão.')\nif 'alternatives' not in data.keys():\n raise ParseError('As alternativas são obrigatórias.')\nif not data['alternatives']:\n raise ParseError('Alternativas vazias.')\nif data['question'] != TypeSet.V_OR_F.value:\n counter = 0\n for alternati... | <|body_start_0|>
logging.info('Validando os dados para criação da questão.')
if 'alternatives' not in data.keys():
raise ParseError('As alternativas são obrigatórias.')
if not data['alternatives']:
raise ParseError('Alternativas vazias.')
if data['question'] != Ty... | Serializado de dados dos grupos da disciplina. | QuestionSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def validate_creation(self, data):
"""Valida se somente uma alternativa está como True."""
<|body_0|>
def create_alternatives(self, alternatives, question):
"""Cria as alternativas passadas.... | stack_v2_sparse_classes_10k_train_007284 | 2,522 | no_license | [
{
"docstring": "Valida se somente uma alternativa está como True.",
"name": "validate_creation",
"signature": "def validate_creation(self, data)"
},
{
"docstring": "Cria as alternativas passadas.",
"name": "create_alternatives",
"signature": "def create_alternatives(self, alternatives, q... | 3 | stack_v2_sparse_classes_30k_train_006336 | Implement the Python class `QuestionSerializer` described below.
Class description:
Serializado de dados dos grupos da disciplina.
Method signatures and docstrings:
- def validate_creation(self, data): Valida se somente uma alternativa está como True.
- def create_alternatives(self, alternatives, question): Cria as a... | Implement the Python class `QuestionSerializer` described below.
Class description:
Serializado de dados dos grupos da disciplina.
Method signatures and docstrings:
- def validate_creation(self, data): Valida se somente uma alternativa está como True.
- def create_alternatives(self, alternatives, question): Cria as a... | 3a8009b17518384c269dfee3c8fe44cbe2567cc0 | <|skeleton|>
class QuestionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def validate_creation(self, data):
"""Valida se somente uma alternativa está como True."""
<|body_0|>
def create_alternatives(self, alternatives, question):
"""Cria as alternativas passadas.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuestionSerializer:
"""Serializado de dados dos grupos da disciplina."""
def validate_creation(self, data):
"""Valida se somente uma alternativa está como True."""
logging.info('Validando os dados para criação da questão.')
if 'alternatives' not in data.keys():
raise P... | the_stack_v2_python_sparse | project/alma/questions/serializers.py | VWApplications/VWAlmaAPI | train | 1 |
8bd438f3818dbdc9294e1390abca1626e5e615dc | [
"storages = Session.query(CloudStorage).all()\nfor storage in storages:\n users = Session.query(CloudStorageUser).filter(CloudStorageUser.storage_name == storage.storage_name)\n setattr(storage, 'users', list(users))\nreturn storages",
"input_dict = get_input_as_dict(request)\nif 'storage_name' not in input... | <|body_start_0|>
storages = Session.query(CloudStorage).all()
for storage in storages:
users = Session.query(CloudStorageUser).filter(CloudStorageUser.storage_name == storage.storage_name)
setattr(storage, 'users', list(users))
return storages
<|end_body_0|>
<|body_start... | Configuration of cloud storages | CloudConfigController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudConfigController:
"""Configuration of cloud storages"""
def get_cloud_storages(self):
"""Get a list of cloud storages registered"""
<|body_0|>
def set_cloud_storage(self, start_response):
"""Add or modify a cloud storage entry"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_007285 | 6,616 | permissive | [
{
"docstring": "Get a list of cloud storages registered",
"name": "get_cloud_storages",
"signature": "def get_cloud_storages(self)"
},
{
"docstring": "Add or modify a cloud storage entry",
"name": "set_cloud_storage",
"signature": "def set_cloud_storage(self, start_response)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_006235 | Implement the Python class `CloudConfigController` described below.
Class description:
Configuration of cloud storages
Method signatures and docstrings:
- def get_cloud_storages(self): Get a list of cloud storages registered
- def set_cloud_storage(self, start_response): Add or modify a cloud storage entry
- def get_... | Implement the Python class `CloudConfigController` described below.
Class description:
Configuration of cloud storages
Method signatures and docstrings:
- def get_cloud_storages(self): Get a list of cloud storages registered
- def set_cloud_storage(self, start_response): Add or modify a cloud storage entry
- def get_... | 12a763986e1a0b6245e7adef044a2d4179e34734 | <|skeleton|>
class CloudConfigController:
"""Configuration of cloud storages"""
def get_cloud_storages(self):
"""Get a list of cloud storages registered"""
<|body_0|>
def set_cloud_storage(self, start_response):
"""Add or modify a cloud storage entry"""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CloudConfigController:
"""Configuration of cloud storages"""
def get_cloud_storages(self):
"""Get a list of cloud storages registered"""
storages = Session.query(CloudStorage).all()
for storage in storages:
users = Session.query(CloudStorageUser).filter(CloudStorageUse... | the_stack_v2_python_sparse | src/fts3rest/fts3rest/controllers/config/cloud.py | cern-fts/fts-rest | train | 2 |
9900dc120c93a8f245c2be866bca42c710bb7cd4 | [
"self.data_source = data_source\nself.skew_thresholds = skew_thresholds\nself.attribute_skew_thresholds = attribute_skew_thresholds\nself.data_format = data_format\nself.target_field = target_field",
"skew_thresholds_mapping = {}\nattribution_score_skew_thresholds_mapping = {}\ndefault_skew_threshold = None\nif s... | <|body_start_0|>
self.data_source = data_source
self.skew_thresholds = skew_thresholds
self.attribute_skew_thresholds = attribute_skew_thresholds
self.data_format = data_format
self.target_field = target_field
<|end_body_0|>
<|body_start_1|>
skew_thresholds_mapping = {}
... | _SkewDetectionConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SkewDetectionConfig:
def __init__(self, data_source: Optional[str]=None, skew_thresholds: Union[Dict[str, float], float, None]=None, target_field: Optional[str]=None, attribute_skew_thresholds: Optional[Dict[str, float]]=None, data_format: Optional[str]=None):
"""Base class for training... | stack_v2_sparse_classes_10k_train_007286 | 17,467 | permissive | [
{
"docstring": "Base class for training-serving skew detection. Args: data_source (str): Optional. Path to training dataset. skew_thresholds: Union[Dict[str, float], float, None]: Optional. Key is the feature name and value is the threshold. If a feature needs to be monitored for skew, a value threshold must be... | 2 | stack_v2_sparse_classes_30k_train_001715 | Implement the Python class `_SkewDetectionConfig` described below.
Class description:
Implement the _SkewDetectionConfig class.
Method signatures and docstrings:
- def __init__(self, data_source: Optional[str]=None, skew_thresholds: Union[Dict[str, float], float, None]=None, target_field: Optional[str]=None, attribut... | Implement the Python class `_SkewDetectionConfig` described below.
Class description:
Implement the _SkewDetectionConfig class.
Method signatures and docstrings:
- def __init__(self, data_source: Optional[str]=None, skew_thresholds: Union[Dict[str, float], float, None]=None, target_field: Optional[str]=None, attribut... | 76b95b92c1d3b87c72d754d8c02b1bca652b9a27 | <|skeleton|>
class _SkewDetectionConfig:
def __init__(self, data_source: Optional[str]=None, skew_thresholds: Union[Dict[str, float], float, None]=None, target_field: Optional[str]=None, attribute_skew_thresholds: Optional[Dict[str, float]]=None, data_format: Optional[str]=None):
"""Base class for training... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _SkewDetectionConfig:
def __init__(self, data_source: Optional[str]=None, skew_thresholds: Union[Dict[str, float], float, None]=None, target_field: Optional[str]=None, attribute_skew_thresholds: Optional[Dict[str, float]]=None, data_format: Optional[str]=None):
"""Base class for training-serving skew ... | the_stack_v2_python_sparse | google/cloud/aiplatform/model_monitoring/objective.py | googleapis/python-aiplatform | train | 418 | |
bc3284ac40cf09e87b862269e1b78523f6f64e0e | [
"self.search_expansion = search_expansion\nself.min_search_wh = min_search_wh\nself.pad_pixels = pad_pixels",
"for i, _track in enumerate(in_box):\n bbox_w = _track.bbox[:, 2] - _track.bbox[:, 0] + 1\n bbox_h = _track.bbox[:, 3] - _track.bbox[:, 1] + 1\n w_ext = bbox_w * (self.search_expansion / 2.0)\n ... | <|body_start_0|>
self.search_expansion = search_expansion
self.min_search_wh = min_search_wh
self.pad_pixels = pad_pixels
<|end_body_0|>
<|body_start_1|>
for i, _track in enumerate(in_box):
bbox_w = _track.bbox[:, 2] - _track.bbox[:, 0] + 1
bbox_h = _track.bbox[:... | A class that includes utility functions unique to track branch | TrackUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrackUtils:
"""A class that includes utility functions unique to track branch"""
def __init__(self, search_expansion=1.0, min_search_wh=128, pad_pixels=256):
""":param search_expansion: expansion ratio (of the search region) w.r.t the size of tracking targets :param min_search_wh: mi... | stack_v2_sparse_classes_10k_train_007287 | 22,017 | permissive | [
{
"docstring": ":param search_expansion: expansion ratio (of the search region) w.r.t the size of tracking targets :param min_search_wh: minimal size (width and height) of the search region :param pad_pixels: the padding pixels that are neccessary to keep the feature map pf search region and that of template ta... | 3 | null | Implement the Python class `TrackUtils` described below.
Class description:
A class that includes utility functions unique to track branch
Method signatures and docstrings:
- def __init__(self, search_expansion=1.0, min_search_wh=128, pad_pixels=256): :param search_expansion: expansion ratio (of the search region) w.... | Implement the Python class `TrackUtils` described below.
Class description:
A class that includes utility functions unique to track branch
Method signatures and docstrings:
- def __init__(self, search_expansion=1.0, min_search_wh=128, pad_pixels=256): :param search_expansion: expansion ratio (of the search region) w.... | da1c277b602606586cd83943ef6b23eb705ec604 | <|skeleton|>
class TrackUtils:
"""A class that includes utility functions unique to track branch"""
def __init__(self, search_expansion=1.0, min_search_wh=128, pad_pixels=256):
""":param search_expansion: expansion ratio (of the search region) w.r.t the size of tracking targets :param min_search_wh: mi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrackUtils:
"""A class that includes utility functions unique to track branch"""
def __init__(self, search_expansion=1.0, min_search_wh=128, pad_pixels=256):
""":param search_expansion: expansion ratio (of the search region) w.r.t the size of tracking targets :param min_search_wh: minimal size (w... | the_stack_v2_python_sparse | object_tracking/siam-mot/track_utils.py | axinc-ai/ailia-models | train | 1,554 |
555a63e5f144891b5bae20501841a74ac1937e8c | [
"self.name = name\nself.age = age\nself.favourite_food = food\nself.mood = 'Happy'",
"if self.favourite_food == food:\n self.mood = 'ecstatic'\n print('Ah, this is my favourite!')"
] | <|body_start_0|>
self.name = name
self.age = age
self.favourite_food = food
self.mood = 'Happy'
<|end_body_0|>
<|body_start_1|>
if self.favourite_food == food:
self.mood = 'ecstatic'
print('Ah, this is my favourite!')
<|end_body_1|>
| Person | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Person:
def __init__(self, name, age, food):
"""(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood."""
<|body_0|>
def eat(self, food):
"""Person, string) -> NoneType Make this person eat the food. Change the ... | stack_v2_sparse_classes_10k_train_007288 | 678 | permissive | [
{
"docstring": "(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.",
"name": "__init__",
"signature": "def __init__(self, name, age, food)"
},
{
"docstring": "Person, string) -> NoneType Make this person eat the food. Change the mood of... | 2 | stack_v2_sparse_classes_30k_train_003703 | Implement the Python class `Person` described below.
Class description:
Implement the Person class.
Method signatures and docstrings:
- def __init__(self, name, age, food): (Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.
- def eat(self, food): Person, str... | Implement the Python class `Person` described below.
Class description:
Implement the Person class.
Method signatures and docstrings:
- def __init__(self, name, age, food): (Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.
- def eat(self, food): Person, str... | 37009dfdbef9a15c2851bcca2a4e029267e6a02d | <|skeleton|>
class Person:
def __init__(self, name, age, food):
"""(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood."""
<|body_0|>
def eat(self, food):
"""Person, string) -> NoneType Make this person eat the food. Change the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Person:
def __init__(self, name, age, food):
"""(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood."""
self.name = name
self.age = age
self.favourite_food = food
self.mood = 'Happy'
def eat(self, food):
... | the_stack_v2_python_sparse | uoft/CSC148H1F Intro to Comp Sci/@week1_object_oriented/@@playground/class.py | Reginald-Lee/biji-ben | train | 0 | |
f0fa262e96ddae6b6d882a564768e2f3114d6b09 | [
"assert entity_type in BlueprintEntity.entity_classification, 'Unknown entity type {}'.format(entity_type)\nclass_list_sorted = sorted(BlueprintEntity.entity_classification[entity_type].keys())\nreturn class_list_sorted[0]",
"assert entity_type in BlueprintEntity.entity_classification\nif entity_classification is... | <|body_start_0|>
assert entity_type in BlueprintEntity.entity_classification, 'Unknown entity type {}'.format(entity_type)
class_list_sorted = sorted(BlueprintEntity.entity_classification[entity_type].keys())
return class_list_sorted[0]
<|end_body_0|>
<|body_start_1|>
assert entity_type... | @type entity_classification: dict[int, dict[int, str]] | BlueprintEntity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlueprintEntity:
"""@type entity_classification: dict[int, dict[int, str]]"""
def get_entity_classification_default(entity_type):
"""Return name of entity classification @param entity_type: @type entity_type: int @rtype: str"""
<|body_0|>
def get_entity_classification_na... | stack_v2_sparse_classes_10k_train_007289 | 2,637 | no_license | [
{
"docstring": "Return name of entity classification @param entity_type: @type entity_type: int @rtype: str",
"name": "get_entity_classification_default",
"signature": "def get_entity_classification_default(entity_type)"
},
{
"docstring": "Return name of entity classification @param entity_type:... | 2 | stack_v2_sparse_classes_30k_train_000038 | Implement the Python class `BlueprintEntity` described below.
Class description:
@type entity_classification: dict[int, dict[int, str]]
Method signatures and docstrings:
- def get_entity_classification_default(entity_type): Return name of entity classification @param entity_type: @type entity_type: int @rtype: str
- ... | Implement the Python class `BlueprintEntity` described below.
Class description:
@type entity_classification: dict[int, dict[int, str]]
Method signatures and docstrings:
- def get_entity_classification_default(entity_type): Return name of entity classification @param entity_type: @type entity_type: int @rtype: str
- ... | 12fe1b39513cf0d1ca8edd9adb6c11269c58fbb5 | <|skeleton|>
class BlueprintEntity:
"""@type entity_classification: dict[int, dict[int, str]]"""
def get_entity_classification_default(entity_type):
"""Return name of entity classification @param entity_type: @type entity_type: int @rtype: str"""
<|body_0|>
def get_entity_classification_na... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BlueprintEntity:
"""@type entity_classification: dict[int, dict[int, str]]"""
def get_entity_classification_default(entity_type):
"""Return name of entity classification @param entity_type: @type entity_type: int @rtype: str"""
assert entity_type in BlueprintEntity.entity_classification, ... | the_stack_v2_python_sparse | smlib/utils/blueprintentity.py | p-hofmann/SMBEdit | train | 6 |
578e53d4cb013ec851e991cbba692698cbeb54fc | [
"if not student.is_active:\n return False\nif semester.records_closing is not None and time > semester.records_closing:\n return False\nt0_record = None\ntry:\n t0_record = cls.objects.get(student=student, semester=semester)\nexcept cls.DoesNotExist:\n return False\nif time < t0_record.time:\n return... | <|body_start_0|>
if not student.is_active:
return False
if semester.records_closing is not None and time > semester.records_closing:
return False
t0_record = None
try:
t0_record = cls.objects.get(student=student, semester=semester)
except cls.D... | This model stores a T0 for a student. T0 is a time when they can enroll into each groups (except of those that are still closed). | T0Times | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class T0Times:
"""This model stores a T0 for a student. T0 is a time when they can enroll into each groups (except of those that are still closed)."""
def is_after_t0(cls, student: Student, semester: Semester, time: datetime) -> bool:
"""Checks whether the T0 for student has passed. The fu... | stack_v2_sparse_classes_10k_train_007290 | 12,426 | no_license | [
{
"docstring": "Checks whether the T0 for student has passed. The function will return False if student is inactive, his T0 is not in the database, the enrollment is closed in the semester or has not yet started.",
"name": "is_after_t0",
"signature": "def is_after_t0(cls, student: Student, semester: Sem... | 2 | null | Implement the Python class `T0Times` described below.
Class description:
This model stores a T0 for a student. T0 is a time when they can enroll into each groups (except of those that are still closed).
Method signatures and docstrings:
- def is_after_t0(cls, student: Student, semester: Semester, time: datetime) -> b... | Implement the Python class `T0Times` described below.
Class description:
This model stores a T0 for a student. T0 is a time when they can enroll into each groups (except of those that are still closed).
Method signatures and docstrings:
- def is_after_t0(cls, student: Student, semester: Semester, time: datetime) -> b... | 2299f5f57d67efb3ad8b661e9a22709d9eeec922 | <|skeleton|>
class T0Times:
"""This model stores a T0 for a student. T0 is a time when they can enroll into each groups (except of those that are still closed)."""
def is_after_t0(cls, student: Student, semester: Semester, time: datetime) -> bool:
"""Checks whether the T0 for student has passed. The fu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class T0Times:
"""This model stores a T0 for a student. T0 is a time when they can enroll into each groups (except of those that are still closed)."""
def is_after_t0(cls, student: Student, semester: Semester, time: datetime) -> bool:
"""Checks whether the T0 for student has passed. The function will r... | the_stack_v2_python_sparse | zapisy/apps/enrollment/records/models/opening_times.py | iiuni/projektzapisy | train | 34 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.enc = enc\nself.dec = dec\nself.timestep = timestep\nself.seq_len = seq_len\nself.decoder_start = 0 if timestep == seq_len else timestep",
"_, (hn, cn) = self.enc(*args)\ndevice = hn.device\nseq_cont_data = args[1]\nseq_cat_data = args[0]\nbatch_size = seq_cont_data.shape[0]\ndecoder_inp... | <|body_start_0|>
super().__init__()
self.enc = enc
self.dec = dec
self.timestep = timestep
self.seq_len = seq_len
self.decoder_start = 0 if timestep == seq_len else timestep
<|end_body_0|>
<|body_start_1|>
_, (hn, cn) = self.enc(*args)
device = hn.device
... | Teacher Training based autoencoder. | AutoencoderTeacherTraining | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoencoderTeacherTraining:
"""Teacher Training based autoencoder."""
def __init__(self, enc, dec, timestep=15, seq_len=15):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1... | stack_v2_sparse_classes_10k_train_007291 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, enc, dec, timestep=15, seq_len=15)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring": "R... | 3 | stack_v2_sparse_classes_30k_train_005197 | Implement the Python class `AutoencoderTeacherTraining` described below.
Class description:
Teacher Training based autoencoder.
Method signatures and docstrings:
- def __init__(self, enc, dec, timestep=15, seq_len=15): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data... | Implement the Python class `AutoencoderTeacherTraining` described below.
Class description:
Teacher Training based autoencoder.
Method signatures and docstrings:
- def __init__(self, enc, dec, timestep=15, seq_len=15): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class AutoencoderTeacherTraining:
"""Teacher Training based autoencoder."""
def __init__(self, enc, dec, timestep=15, seq_len=15):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AutoencoderTeacherTraining:
"""Teacher Training based autoencoder."""
def __init__(self, enc, dec, timestep=15, seq_len=15):
"""Initialize model with params."""
super().__init__()
self.enc = enc
self.dec = dec
self.timestep = timestep
self.seq_len = seq_len... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 |
7020c10ae6df9a131d61ab910d907159c820a7ff | [
"if Ices.objects.filter(type=value.lower()):\n raise serializers.ValidationError('There already exist such type')\nreturn value",
"ret = super().to_representation(instance)\nret['type'] = ret['type'].lower()\nreturn ret"
] | <|body_start_0|>
if Ices.objects.filter(type=value.lower()):
raise serializers.ValidationError('There already exist such type')
return value
<|end_body_0|>
<|body_start_1|>
ret = super().to_representation(instance)
ret['type'] = ret['type'].lower()
return ret
<|end_b... | AddIcesSerializers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddIcesSerializers:
def validate_type(self, value):
"""Check the duplicate"""
<|body_0|>
def to_representation(self, instance):
"""Convert `type` to lowercase."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Ices.objects.filter(type=value.lower()... | stack_v2_sparse_classes_10k_train_007292 | 4,598 | permissive | [
{
"docstring": "Check the duplicate",
"name": "validate_type",
"signature": "def validate_type(self, value)"
},
{
"docstring": "Convert `type` to lowercase.",
"name": "to_representation",
"signature": "def to_representation(self, instance)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002567 | Implement the Python class `AddIcesSerializers` described below.
Class description:
Implement the AddIcesSerializers class.
Method signatures and docstrings:
- def validate_type(self, value): Check the duplicate
- def to_representation(self, instance): Convert `type` to lowercase. | Implement the Python class `AddIcesSerializers` described below.
Class description:
Implement the AddIcesSerializers class.
Method signatures and docstrings:
- def validate_type(self, value): Check the duplicate
- def to_representation(self, instance): Convert `type` to lowercase.
<|skeleton|>
class AddIcesSerialize... | 6a935bb77db3996dcf14b71deed8d7ca5c8f0fa3 | <|skeleton|>
class AddIcesSerializers:
def validate_type(self, value):
"""Check the duplicate"""
<|body_0|>
def to_representation(self, instance):
"""Convert `type` to lowercase."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddIcesSerializers:
def validate_type(self, value):
"""Check the duplicate"""
if Ices.objects.filter(type=value.lower()):
raise serializers.ValidationError('There already exist such type')
return value
def to_representation(self, instance):
"""Convert `type` to... | the_stack_v2_python_sparse | drf_api/serializers.py | destro6984/LynxWasp | train | 0 | |
5a1e23cc95062a28064aa862cfa32faf0e31e156 | [
"self.loginpage.openLoginPage()\nself.log('PO-gjs 뵽Ŀҳ ')\nself.loginpage.login_gjs_pro(self.readusername(1), self.readpassword(1))\nself.log('PO-gjs ȷû ')\nself.assertEqual(self.loginpage.get_assertText(), self.exceptText(1))\nself.log('PO-gjs ¼ɹȡϢж ')\nSaveImage(self.dr, 'login_success.png')\nself.log('PO-gjs ¼ɹȡͼ... | <|body_start_0|>
self.loginpage.openLoginPage()
self.log('PO-gjs 뵽Ŀҳ ')
self.loginpage.login_gjs_pro(self.readusername(1), self.readpassword(1))
self.log('PO-gjs ȷû ')
self.assertEqual(self.loginpage.get_assertText(), self.exceptText(1))
self.log('PO-gjs ¼ɹȡϢж ')
... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def testlogin(self):
"""ȷû"""
<|body_0|>
def test_user_null(self):
"""Ϊ"""
<|body_1|>
def test_username_null(self):
"""ûΪ"""
<|body_2|>
def test_user_passwd_null(self):
"""û / Ϊ"""
<|body_3|>
<|end_skeleto... | stack_v2_sparse_classes_10k_train_007293 | 2,841 | no_license | [
{
"docstring": "ȷû",
"name": "testlogin",
"signature": "def testlogin(self)"
},
{
"docstring": "Ϊ",
"name": "test_user_null",
"signature": "def test_user_null(self)"
},
{
"docstring": "ûΪ",
"name": "test_username_null",
"signature": "def test_username_null(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_001448 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def testlogin(self): ȷû
- def test_user_null(self): Ϊ
- def test_username_null(self): ûΪ
- def test_user_passwd_null(self): û / Ϊ | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def testlogin(self): ȷû
- def test_user_null(self): Ϊ
- def test_username_null(self): ûΪ
- def test_user_passwd_null(self): û / Ϊ
<|skeleton|>
class TestLogin:
def testlo... | 910bcf91dacb8ef699c700709b42dec771b504d0 | <|skeleton|>
class TestLogin:
def testlogin(self):
"""ȷû"""
<|body_0|>
def test_user_null(self):
"""Ϊ"""
<|body_1|>
def test_username_null(self):
"""ûΪ"""
<|body_2|>
def test_user_passwd_null(self):
"""û / Ϊ"""
<|body_3|>
<|end_skeleto... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestLogin:
def testlogin(self):
"""ȷû"""
self.loginpage.openLoginPage()
self.log('PO-gjs 뵽Ŀҳ ')
self.loginpage.login_gjs_pro(self.readusername(1), self.readpassword(1))
self.log('PO-gjs ȷû ')
self.assertEqual(self.loginpage.get_assertText(), self.exceptText(1))
... | the_stack_v2_python_sparse | 2.15章节源码/testCases/test_Login.py | luruifeng/myBookCode | train | 3 | |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(QRDQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activatio... | <|body_start_0|>
super(QRDQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = F... | QRDQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: ... | stack_v2_sparse_classes_10k_train_007294 | 30,380 | permissive | [
{
"docstring": "Overview: Init the QRDQN Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation's space. - action_shape (:obj:`Union[int, SequenceType]`): Action's space. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pass to... | 2 | null | Implement the Python class `QRDQN` described below.
Class description:
Implement the QRDQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=N... | Implement the Python class `QRDQN` described below.
Class description:
Implement the QRDQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=N... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 | |
04cbe688ff1a5ebf5e8deb7e3e1e989715926f78 | [
"try:\n tinc = value.first()\nexcept AttributeError:\n tinc = value\nif tinc is None:\n return None\nreturn TincHostSerializer(tinc).to_native(tinc)",
"if data:\n tinc_host = TincHost(pubkey=data.get('pubkey'))\n tinc_host.full_clean(exclude=['content_type', 'object_id', 'name'])\n return [tinc_... | <|body_start_0|>
try:
tinc = value.first()
except AttributeError:
tinc = value
if tinc is None:
return None
return TincHostSerializer(tinc).to_native(tinc)
<|end_body_0|>
<|body_start_1|>
if data:
tinc_host = TincHost(pubkey=data.g... | TincHost writable serializer | TincHostRelatedField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TincHostRelatedField:
"""TincHost writable serializer"""
def to_native(self, value):
"""Convert to serialized fields"""
<|body_0|>
def from_native(self, data):
"""Return a list of tinc configuration objects"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_007295 | 2,992 | no_license | [
{
"docstring": "Convert to serialized fields",
"name": "to_native",
"signature": "def to_native(self, value)"
},
{
"docstring": "Return a list of tinc configuration objects",
"name": "from_native",
"signature": "def from_native(self, data)"
}
] | 2 | null | Implement the Python class `TincHostRelatedField` described below.
Class description:
TincHost writable serializer
Method signatures and docstrings:
- def to_native(self, value): Convert to serialized fields
- def from_native(self, data): Return a list of tinc configuration objects | Implement the Python class `TincHostRelatedField` described below.
Class description:
TincHost writable serializer
Method signatures and docstrings:
- def to_native(self, value): Convert to serialized fields
- def from_native(self, data): Return a list of tinc configuration objects
<|skeleton|>
class TincHostRelated... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class TincHostRelatedField:
"""TincHost writable serializer"""
def to_native(self, value):
"""Convert to serialized fields"""
<|body_0|>
def from_native(self, data):
"""Return a list of tinc configuration objects"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TincHostRelatedField:
"""TincHost writable serializer"""
def to_native(self, value):
"""Convert to serialized fields"""
try:
tinc = value.first()
except AttributeError:
tinc = value
if tinc is None:
return None
return TincHostSer... | the_stack_v2_python_sparse | controller/apps/tinc/serializers.py | m00dy/vct-controller | train | 2 |
7bcfaf280485922d37acc7737d336136f5e00350 | [
"assert avg_degree >= 1, 'Average degree should be greater than 0'\nself.min_nodes = min_nodes\nself.max_nodes = max_nodes\nself.avg_degree = avg_degree\nself.n_node_features = n_node_features\nself.n_edge_features = n_edge_features\nself.n_classes = n_classes\nself.task = task\nself.kwargs = kwargs",
"graphs, la... | <|body_start_0|>
assert avg_degree >= 1, 'Average degree should be greater than 0'
self.min_nodes = min_nodes
self.max_nodes = max_nodes
self.avg_degree = avg_degree
self.n_node_features = n_node_features
self.n_edge_features = n_edge_features
self.n_classes = n_c... | Generates a random graphs which can be used for testing or other purposes. The generated graph supports both node-level and graph-level labels. Example ------- >>> from deepchem.utils.fake_data_generator import FakeGraphGenerator >>> fgg = FakeGraphGenerator(min_nodes=8, max_nodes=10, n_node_features=5, avg_degree=8, n... | FakeGraphGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FakeGraphGenerator:
"""Generates a random graphs which can be used for testing or other purposes. The generated graph supports both node-level and graph-level labels. Example ------- >>> from deepchem.utils.fake_data_generator import FakeGraphGenerator >>> fgg = FakeGraphGenerator(min_nodes=8, ma... | stack_v2_sparse_classes_10k_train_007296 | 6,134 | permissive | [
{
"docstring": "Parameters ---------- min_nodes: int, default 10 Minimum number of permissible nodes in a graph max_nodes: int, default 10 Maximum number of permissible nodes in a graph n_node_features: int, default 5 Average number of node features in a graph avg_degree: int, default 4 Average degree of the gr... | 2 | stack_v2_sparse_classes_30k_train_003994 | Implement the Python class `FakeGraphGenerator` described below.
Class description:
Generates a random graphs which can be used for testing or other purposes. The generated graph supports both node-level and graph-level labels. Example ------- >>> from deepchem.utils.fake_data_generator import FakeGraphGenerator >>> f... | Implement the Python class `FakeGraphGenerator` described below.
Class description:
Generates a random graphs which can be used for testing or other purposes. The generated graph supports both node-level and graph-level labels. Example ------- >>> from deepchem.utils.fake_data_generator import FakeGraphGenerator >>> f... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class FakeGraphGenerator:
"""Generates a random graphs which can be used for testing or other purposes. The generated graph supports both node-level and graph-level labels. Example ------- >>> from deepchem.utils.fake_data_generator import FakeGraphGenerator >>> fgg = FakeGraphGenerator(min_nodes=8, ma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FakeGraphGenerator:
"""Generates a random graphs which can be used for testing or other purposes. The generated graph supports both node-level and graph-level labels. Example ------- >>> from deepchem.utils.fake_data_generator import FakeGraphGenerator >>> fgg = FakeGraphGenerator(min_nodes=8, max_nodes=10, n... | the_stack_v2_python_sparse | deepchem/utils/fake_data_generator.py | deepchem/deepchem | train | 4,876 |
67fe38b17dbd876a0b4f42ac6af03fcb3f2144fc | [
"self.status_list.append(status)\nif len(self.status_list) >= 500:\n if not push_to_bigquery(self.status_list):\n print('Failed to send to bigquery', file=sys.stderr)\n return False\n self.num_imported += len(self.status_list)\n self.status_list = []\n print('Imported {0} rows'.format(self... | <|body_start_0|>
self.status_list.append(status)
if len(self.status_list) >= 500:
if not push_to_bigquery(self.status_list):
print('Failed to send to bigquery', file=sys.stderr)
return False
self.num_imported += len(self.status_list)
se... | Streaming API로 추출한 트윗을 처리하기 위한 클래스 | MyStreamListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyStreamListener:
"""Streaming API로 추출한 트윗을 처리하기 위한 클래스"""
def on_status(self, status):
"""트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체"""
<|body_0|>
def push_to_bigquery(status_list):
"""트윗 리스트를 BigQuery에 임포트하는 메서드입니다."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_007297 | 4,338 | no_license | [
{
"docstring": "트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체",
"name": "on_status",
"signature": "def on_status(self, status)"
},
{
"docstring": "트윗 리스트를 BigQuery에 임포트하는 메서드입니다.",
"name": "push_to_bigquery",
"signature": "def push_to_bigquery(status_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000662 | Implement the Python class `MyStreamListener` described below.
Class description:
Streaming API로 추출한 트윗을 처리하기 위한 클래스
Method signatures and docstrings:
- def on_status(self, status): 트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체
- def push_to_bigquery(status_list): 트윗 리스트를 BigQuery에 임포트하는 메서드입니다. | Implement the Python class `MyStreamListener` described below.
Class description:
Streaming API로 추출한 트윗을 처리하기 위한 클래스
Method signatures and docstrings:
- def on_status(self, status): 트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체
- def push_to_bigquery(status_list): 트윗 리스트를 BigQuery에 임포트하는 메서드입니다.
<|skeleton|>
class... | b64956e1250cc5d867b3d6d62e0b7d9506344993 | <|skeleton|>
class MyStreamListener:
"""Streaming API로 추출한 트윗을 처리하기 위한 클래스"""
def on_status(self, status):
"""트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체"""
<|body_0|>
def push_to_bigquery(status_list):
"""트윗 리스트를 BigQuery에 임포트하는 메서드입니다."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyStreamListener:
"""Streaming API로 추출한 트윗을 처리하기 위한 클래스"""
def on_status(self, status):
"""트윗을 추출할 때 호출되는 메서드입니다. 매개변수: 트윗을 나타내는 Status 객체"""
self.status_list.append(status)
if len(self.status_list) >= 500:
if not push_to_bigquery(self.status_list):
pri... | the_stack_v2_python_sparse | chapter_5/import_from_stream_api_to_bigquery.py | innerrace/crawl_images.py | train | 0 |
851a53927a9567eb93bfcd3652bb98e4d6f9042b | [
"super(ParameterGenerator, self).__init__(*args, **kwargs)\nself.parameters = parameters\nself._tree = None\nreturn",
"if self._tree is None:\n self._tree = ParameterTree(self.parameters)\nreturn self._tree",
"for parameters in self.tree.paths:\n yield parameters\nreturn"
] | <|body_start_0|>
super(ParameterGenerator, self).__init__(*args, **kwargs)
self.parameters = parameters
self._tree = None
return
<|end_body_0|>
<|body_start_1|>
if self._tree is None:
self._tree = ParameterTree(self.parameters)
return self._tree
<|end_body_1|... | A ParameterGenerator is an iterator that generates test-parameters. | ParameterGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterGenerator:
"""A ParameterGenerator is an iterator that generates test-parameters."""
def __init__(self, parameters, *args, **kwargs):
""":param: - `parameters`: A list of parameter (namedtuple) lists"""
<|body_0|>
def tree(self):
""":return: parameter-tr... | stack_v2_sparse_classes_10k_train_007298 | 1,730 | permissive | [
{
"docstring": ":param: - `parameters`: A list of parameter (namedtuple) lists",
"name": "__init__",
"signature": "def __init__(self, parameters, *args, **kwargs)"
},
{
"docstring": ":return: parameter-tree populated with parameters (possibly)",
"name": "tree",
"signature": "def tree(sel... | 3 | null | Implement the Python class `ParameterGenerator` described below.
Class description:
A ParameterGenerator is an iterator that generates test-parameters.
Method signatures and docstrings:
- def __init__(self, parameters, *args, **kwargs): :param: - `parameters`: A list of parameter (namedtuple) lists
- def tree(self): ... | Implement the Python class `ParameterGenerator` described below.
Class description:
A ParameterGenerator is an iterator that generates test-parameters.
Method signatures and docstrings:
- def __init__(self, parameters, *args, **kwargs): :param: - `parameters`: A list of parameter (namedtuple) lists
- def tree(self): ... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class ParameterGenerator:
"""A ParameterGenerator is an iterator that generates test-parameters."""
def __init__(self, parameters, *args, **kwargs):
""":param: - `parameters`: A list of parameter (namedtuple) lists"""
<|body_0|>
def tree(self):
""":return: parameter-tr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParameterGenerator:
"""A ParameterGenerator is an iterator that generates test-parameters."""
def __init__(self, parameters, *args, **kwargs):
""":param: - `parameters`: A list of parameter (namedtuple) lists"""
super(ParameterGenerator, self).__init__(*args, **kwargs)
self.parame... | the_stack_v2_python_sparse | apetools/lexicographers/parametergenerator.py | russell-n/oldape | train | 0 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.unified_encoder = unified_encoder\nself.mlp = mlp",
"enc_src, _, _ = self.unified_encoder(*args)\nenc_src = enc_src.view(enc_src.shape[0], -1)\ny_pred = self.mlp(enc_src)\nreturn y_pred",
"data = (seq_cat_data, seq_cont_data, non_seq_cat_data, non_seq_cont_data)\nnonempty_tensors, none... | <|body_start_0|>
super().__init__()
self.unified_encoder = unified_encoder
self.mlp = mlp
<|end_body_0|>
<|body_start_1|>
enc_src, _, _ = self.unified_encoder(*args)
enc_src = enc_src.view(enc_src.shape[0], -1)
y_pred = self.mlp(enc_src)
return y_pred
<|end_body_... | TransformerChurnModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerChurnModel:
def __init__(self, unified_encoder, mlp):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_cont_data, non_seq_ca... | stack_v2_sparse_classes_10k_train_007299 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, unified_encoder, mlp)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring": "Run model on d... | 3 | stack_v2_sparse_classes_30k_train_001477 | Implement the Python class `TransformerChurnModel` described below.
Class description:
Implement the TransformerChurnModel class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, mlp): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data.
- def run... | Implement the Python class `TransformerChurnModel` described below.
Class description:
Implement the TransformerChurnModel class.
Method signatures and docstrings:
- def __init__(self, unified_encoder, mlp): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data.
- def run... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class TransformerChurnModel:
def __init__(self, unified_encoder, mlp):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cat_data, seq_cont_data, non_seq_ca... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformerChurnModel:
def __init__(self, unified_encoder, mlp):
"""Initialize model with params."""
super().__init__()
self.unified_encoder = unified_encoder
self.mlp = mlp
def forward(self, *args):
"""Run a forward pass of model over the data."""
enc_src,... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.