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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6364968a8d0c1cb2c18f1c467261b272386e1e38 | [
"user = get_authentication(self.request)\nqueryset = Histories.objects.filter(user=user, is_used=True)\nreturn queryset",
"if self.request.method in ['GET', 'POST']:\n serializer_class = SearchSerialzer\nelif self.action == 'destroy':\n serializer_class = SearchNotRequiredSerializer\nelif self.action == 'de... | <|body_start_0|>
user = get_authentication(self.request)
queryset = Histories.objects.filter(user=user, is_used=True)
return queryset
<|end_body_0|>
<|body_start_1|>
if self.request.method in ['GET', 'POST']:
serializer_class = SearchSerialzer
elif self.action == 'de... | History view. | HistoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistoryView:
"""History view."""
def get_queryset(self):
"""Get the history of the user."""
<|body_0|>
def get_serializer_class(self, *args, **kwargs):
"""Get the serializer class depending of the request method."""
<|body_1|>
def get(self, request, ... | stack_v2_sparse_classes_10k_train_005700 | 12,742 | no_license | [
{
"docstring": "Get the history of the user.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Get the serializer class depending of the request method.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self, *args, **kwargs)"
},
... | 6 | stack_v2_sparse_classes_30k_train_002061 | Implement the Python class `HistoryView` described below.
Class description:
History view.
Method signatures and docstrings:
- def get_queryset(self): Get the history of the user.
- def get_serializer_class(self, *args, **kwargs): Get the serializer class depending of the request method.
- def get(self, request, *arg... | Implement the Python class `HistoryView` described below.
Class description:
History view.
Method signatures and docstrings:
- def get_queryset(self): Get the history of the user.
- def get_serializer_class(self, *args, **kwargs): Get the serializer class depending of the request method.
- def get(self, request, *arg... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class HistoryView:
"""History view."""
def get_queryset(self):
"""Get the history of the user."""
<|body_0|>
def get_serializer_class(self, *args, **kwargs):
"""Get the serializer class depending of the request method."""
<|body_1|>
def get(self, request, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HistoryView:
"""History view."""
def get_queryset(self):
"""Get the history of the user."""
user = get_authentication(self.request)
queryset = Histories.objects.filter(user=user, is_used=True)
return queryset
def get_serializer_class(self, *args, **kwargs):
""... | the_stack_v2_python_sparse | api/services/views.py | ignite7/backproject | train | 0 |
d70e88bce02d3642024077d5865fd3e72a2a3c1b | [
"if n == 1:\n return [0]\nout = [[] for i in range(n)]\nfor edge in edges:\n out[edge[0]].append(edge[1])\n out[edge[1]].append(edge[0])\ncurrent = []\nfor i in range(n):\n if len(out[i]) == 1:\n current.append(i)\nwhile current:\n next = []\n for node in current:\n for i in range(le... | <|body_start_0|>
if n == 1:
return [0]
out = [[] for i in range(n)]
for edge in edges:
out[edge[0]].append(edge[1])
out[edge[1]].append(edge[0])
current = []
for i in range(n):
if len(out[i]) == 1:
current.append(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:"""
<|body_0|>
def _findMinHeightTrees(self, n: ... | stack_v2_sparse_classes_10k_train_005701 | 2,371 | no_license | [
{
"docstring": "从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:",
"name": "findMinHeightTrees",
"signature": "def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_test_000073 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为... | 9ab35dbffed7865e41b437b026f2268d133357be | <|skeleton|>
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:"""
<|body_0|>
def _findMinHeightTrees(self, n: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""从树的叶子节点bfs遍历整棵树 1.枚举所有的边 2.找到入度为0的边 3.以这些点为基础枚举他们的出度,然后减去相对应入度 4.找到当前入度为1的点,进入队列(入度为1相当于当前的最外层),找到最后入度为1的点 :param n: :param edges: :return:"""
if n == 1:
return [0]
out = [[] for i in ra... | the_stack_v2_python_sparse | leetcode/310. 最小高度树.py | Cjz-Y/shuati | train | 0 | |
3f67d9d72ce564d2b1e35bbbe28fdb22ef5b5b69 | [
"f = False\nif x < 0:\n f = True\nx2 = list(reversed(str(abs(x))))\nif f:\n x2.insert(0, '-')\nlast = int(''.join(x2))\nif abs(last) > 2147483647:\n return 0\nelse:\n return last",
"sum = 0\nif x < 0:\n y = -x\nelse:\n y = x\nwhile y > 0:\n sum = sum * 10 + y % 10\n y = y // 10\nprint(sum)... | <|body_start_0|>
f = False
if x < 0:
f = True
x2 = list(reversed(str(abs(x))))
if f:
x2.insert(0, '-')
last = int(''.join(x2))
if abs(last) > 2147483647:
return 0
else:
return last
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f = False
if x < 0:
f = True
x2 = list(reversed(... | stack_v2_sparse_classes_10k_train_005702 | 1,545 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | null | 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 reverse2(self, x): :type x: int :rtype: int | 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 reverse2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int ... | b0f498ebe84e46b7e17e94759dd462891dcc8f85 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|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"""
f = False
if x < 0:
f = True
x2 = list(reversed(str(abs(x))))
if f:
x2.insert(0, '-')
last = int(''.join(x2))
if abs(last) > 2147483647:
return 0
e... | the_stack_v2_python_sparse | 初级算法/string_2.py | wulinlw/leetcode_cn | train | 0 | |
58fbe93a10bcc00e2ad447d3b43ca662c1492758 | [
"count = 0\nresult = 0\n\ndef dfs(node):\n nonlocal count, result\n if node.left:\n dfs(node.left)\n if count >= k:\n return\n count += 1\n result = node.val\n if node.right:\n dfs(node.right)\ndfs(root)\nreturn result",
"def helper(node, stack):\n while node:\n st... | <|body_start_0|>
count = 0
result = 0
def dfs(node):
nonlocal count, result
if node.left:
dfs(node.left)
if count >= k:
return
count += 1
result = node.val
if node.right:
dfs(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_0|>
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_1... | stack_v2_sparse_classes_10k_train_005703 | 1,262 | no_license | [
{
"docstring": "Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: TreeNode, k: int) -> int"
},
{
"docstring": "Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)",
"name": "kthSmallest",
"signature": "def kthSmal... | 2 | stack_v2_sparse_classes_30k_train_001024 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)
- def kthSmallest(self, root: TreeNode, k: int) -> int: Iterative Ino... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)
- def kthSmallest(self, root: TreeNode, k: int) -> int: Iterative Ino... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_0|>
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_1... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
count = 0
result = 0
def dfs(node):
nonlocal count, result
if node.left:
dfs(node.left)
if count >= ... | the_stack_v2_python_sparse | python/230-Kth Smallest Element in a BST.py | cwza/leetcode | train | 0 | |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"try:\n db.show_by_id(show_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('show with ID %s not found' % show_id)\ntry:\n db.episode_by_id(ep_id, session)\nexcept NoResultFound:\n raise NotFoundError('episode with ID %s not found' % ep_id)\ntry:\n release = db.episode_release_by_id(... | <|body_start_0|>
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
db.episode_by_id(ep_id, session)
except NoResultFound:
raise NotFoundError('episode with ID ... | SeriesEpisodeReleaseAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesEpisodeReleaseAPI:
def get(self, show_id, ep_id, rel_id, session):
"""Get episode release by show ID, episode ID and release ID"""
<|body_0|>
def delete(self, show_id, ep_id, rel_id, session):
"""Delete episode release by show ID, episode ID and release ID"""
... | stack_v2_sparse_classes_10k_train_005704 | 47,001 | permissive | [
{
"docstring": "Get episode release by show ID, episode ID and release ID",
"name": "get",
"signature": "def get(self, show_id, ep_id, rel_id, session)"
},
{
"docstring": "Delete episode release by show ID, episode ID and release ID",
"name": "delete",
"signature": "def delete(self, show... | 3 | stack_v2_sparse_classes_30k_train_000189 | Implement the Python class `SeriesEpisodeReleaseAPI` described below.
Class description:
Implement the SeriesEpisodeReleaseAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, rel_id, session): Get episode release by show ID, episode ID and release ID
- def delete(self, show_id, ep_id, rel_id,... | Implement the Python class `SeriesEpisodeReleaseAPI` described below.
Class description:
Implement the SeriesEpisodeReleaseAPI class.
Method signatures and docstrings:
- def get(self, show_id, ep_id, rel_id, session): Get episode release by show ID, episode ID and release ID
- def delete(self, show_id, ep_id, rel_id,... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesEpisodeReleaseAPI:
def get(self, show_id, ep_id, rel_id, session):
"""Get episode release by show ID, episode ID and release ID"""
<|body_0|>
def delete(self, show_id, ep_id, rel_id, session):
"""Delete episode release by show ID, episode ID and release ID"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeriesEpisodeReleaseAPI:
def get(self, show_id, ep_id, rel_id, session):
"""Get episode release by show ID, episode ID and release ID"""
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
479a6a3becb493d0dd7a917cbd86fc15e763947a | [
"m = len(x)\ncost = 1 / (2 * m) * np.power(np.dot(x, theta.T) - y.T, 2).sum() + l / (2 * m) * np.power(theta, 2).sum()\ntheta_temp = np.mat([0] + theta.tolist()[1:])\ngrad = 1 / m * np.dot(x.T, np.dot(x, theta.T) - y.T) + l / m * theta_temp.T\nreturn (cost, grad)",
"alpha, lam, times, theta = (settings['alpha'], ... | <|body_start_0|>
m = len(x)
cost = 1 / (2 * m) * np.power(np.dot(x, theta.T) - y.T, 2).sum() + l / (2 * m) * np.power(theta, 2).sum()
theta_temp = np.mat([0] + theta.tolist()[1:])
grad = 1 / m * np.dot(x.T, np.dot(x, theta.T) - y.T) + l / m * theta_temp.T
return (cost, grad)
<|en... | GradientDescent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientDescent:
def __get_cost_and_grad(x, theta, l, y):
"""获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值"""
<|body_0|>
def optimize_param(... | stack_v2_sparse_classes_10k_train_005705 | 6,270 | no_license | [
{
"docstring": "获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值",
"name": "__get_cost_and_grad",
"signature": "def __get_cost_and_grad(x, theta, l, y)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_005822 | Implement the Python class `GradientDescent` described below.
Class description:
Implement the GradientDescent class.
Method signatures and docstrings:
- def __get_cost_and_grad(x, theta, l, y): 获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: num... | Implement the Python class `GradientDescent` described below.
Class description:
Implement the GradientDescent class.
Method signatures and docstrings:
- def __get_cost_and_grad(x, theta, l, y): 获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: num... | 4d6c45a07ea9456a635793006b13cc3d62fc7419 | <|skeleton|>
class GradientDescent:
def __get_cost_and_grad(x, theta, l, y):
"""获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值"""
<|body_0|>
def optimize_param(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GradientDescent:
def __get_cost_and_grad(x, theta, l, y):
"""获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值"""
m = len(x)
cost = 1 / (2 * m) * np.power(... | the_stack_v2_python_sparse | app/admin/algorithm.py | llf-970310/expression-api | train | 0 | |
534c4bd071961026b8b0922fdd3741cf27fc9872 | [
"self.location = os.getenv('SLAM_LOCATION')\nself.username = os.getenv('SLAM_USERNAME')\nself.password = os.getenv('SLAM_PASSWORD')\nif os.getenv('SLAM_SSL_VERIFY') is not None and (not strtobool(os.getenv('SLAM_SSL_VERIFY'))):\n self.verify = False\nelse:\n self.verify = True\nif self.location is None:\n ... | <|body_start_0|>
self.location = os.getenv('SLAM_LOCATION')
self.username = os.getenv('SLAM_USERNAME')
self.password = os.getenv('SLAM_PASSWORD')
if os.getenv('SLAM_SSL_VERIFY') is not None and (not strtobool(os.getenv('SLAM_SSL_VERIFY'))):
self.verify = False
else:
... | Class config provide specific installation information | SlamAPIController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlamAPIController:
"""Class config provide specific installation information"""
def __init__(self):
"""Define some default value"""
<|body_0|>
def login(self):
"""This method is used to signin slam-v2 REST api."""
<|body_1|>
def get(self, plugin, ite... | stack_v2_sparse_classes_10k_train_005706 | 6,947 | no_license | [
{
"docstring": "Define some default value",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method is used to signin slam-v2 REST api.",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "A standard way to retrieve all element into a ... | 6 | stack_v2_sparse_classes_30k_train_001370 | Implement the Python class `SlamAPIController` described below.
Class description:
Class config provide specific installation information
Method signatures and docstrings:
- def __init__(self): Define some default value
- def login(self): This method is used to signin slam-v2 REST api.
- def get(self, plugin, item=No... | Implement the Python class `SlamAPIController` described below.
Class description:
Class config provide specific installation information
Method signatures and docstrings:
- def __init__(self): Define some default value
- def login(self): This method is used to signin slam-v2 REST api.
- def get(self, plugin, item=No... | 4ddf6c603fd8e4d555d8e69203ae8e9837d85896 | <|skeleton|>
class SlamAPIController:
"""Class config provide specific installation information"""
def __init__(self):
"""Define some default value"""
<|body_0|>
def login(self):
"""This method is used to signin slam-v2 REST api."""
<|body_1|>
def get(self, plugin, ite... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SlamAPIController:
"""Class config provide specific installation information"""
def __init__(self):
"""Define some default value"""
self.location = os.getenv('SLAM_LOCATION')
self.username = os.getenv('SLAM_USERNAME')
self.password = os.getenv('SLAM_PASSWORD')
if o... | the_stack_v2_python_sparse | core/api.py | guillaume-philippon/slam-v2-cli | train | 0 |
18f9804985f0694eb89489807b9a58078230f602 | [
"sequence = ['1']\nfor i in range(2, n + 1):\n prev = sequence[-1]\n curr_number = prev[0]\n curr_count = 1\n result = []\n for j in range(1, len(prev)):\n if prev[j] == curr_number:\n curr_count += 1\n else:\n result.append(str(curr_count))\n result.app... | <|body_start_0|>
sequence = ['1']
for i in range(2, n + 1):
prev = sequence[-1]
curr_number = prev[0]
curr_count = 1
result = []
for j in range(1, len(prev)):
if prev[j] == curr_number:
curr_count += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def count_and_say_1(self, n):
"""Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string.... | stack_v2_sparse_classes_10k_train_005707 | 3,147 | no_license | [
{
"docstring": "Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string. 3) Repeat till the end of current term. Time compl... | 2 | stack_v2_sparse_classes_30k_val_000368 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_and_say_1(self, n): Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_and_say_1(self, n): Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term t... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def count_and_say_1(self, n):
"""Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def count_and_say_1(self, n):
"""Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string. 3) Repeat til... | the_stack_v2_python_sparse | Strings/count_and_say.py | vladn90/Algorithms | train | 0 | |
2f3cfdb42e8b799e315dd81404ce551af905f8a8 | [
"for i in range(len(haystack) - len(needle) + 1):\n if haystack[i:i + len(needle)] == needle:\n return i\nreturn -1",
"if not needle:\n return 0\nif len(haystack) < len(needle):\n return -1\nfor i in range(len(haystack) - len(needle) + 1):\n if haystack[i:i + len(needle)] == needle:\n re... | <|body_start_0|>
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
return -1
<|end_body_0|>
<|body_start_1|>
if not needle:
return 0
if len(haystack) < len(needle):
return -1
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
"""查找第一次出现needle的位置"""
<|body_0|>
def strStr2(self, haystack: str, needle: str) -> int:
"""查找第一次出现needle的位置"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(len(haystack) -... | stack_v2_sparse_classes_10k_train_005708 | 2,130 | no_license | [
{
"docstring": "查找第一次出现needle的位置",
"name": "strStr",
"signature": "def strStr(self, haystack: str, needle: str) -> int"
},
{
"docstring": "查找第一次出现needle的位置",
"name": "strStr2",
"signature": "def strStr2(self, haystack: str, needle: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_003688 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置
- def strStr2(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置
- def strStr2(self, haystack: str, needle: str) -> int: 查找第一次出现needle的位置
<|skeleton|>
class Solution:
... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
"""查找第一次出现needle的位置"""
<|body_0|>
def strStr2(self, haystack: str, needle: str) -> int:
"""查找第一次出现needle的位置"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
"""查找第一次出现needle的位置"""
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
return -1
def strStr2(self, haystack: str, needle: str) -> int:
... | the_stack_v2_python_sparse | str/028 Implement strStr().py | mofei952/leetcode_python | train | 0 | |
2456f608b19a6f936dcf23c816ba5679b2cf48fb | [
"super().__init__()\nself.query_emb = nn.Linear(args['target_agent_enc_size'], args['emb_size'])\nself.key_emb = nn.Linear(args['context_enc_size'], args['emb_size'])\nself.val_emb = nn.Linear(args['context_enc_size'], args['emb_size'])\nself.mha = nn.MultiheadAttention(args['emb_size'], args['num_heads'])",
"tar... | <|body_start_0|>
super().__init__()
self.query_emb = nn.Linear(args['target_agent_enc_size'], args['emb_size'])
self.key_emb = nn.Linear(args['context_enc_size'], args['emb_size'])
self.val_emb = nn.Linear(args['context_enc_size'], args['emb_size'])
self.mha = nn.MultiheadAttenti... | Aggregate context encoding using scaled dot product attention. Query obtained using target agent encoding, Keys and values obtained using map and surrounding agent encodings. | GlobalAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalAttention:
"""Aggregate context encoding using scaled dot product attention. Query obtained using target agent encoding, Keys and values obtained using map and surrounding agent encodings."""
def __init__(self, args: Dict):
"""args to include enc_size: int Dimension of encoding... | stack_v2_sparse_classes_10k_train_005709 | 2,711 | permissive | [
{
"docstring": "args to include enc_size: int Dimension of encodings generated by encoder emb_size: int Size of embeddings used for queries, keys and values num_heads: int Number of attention heads",
"name": "__init__",
"signature": "def __init__(self, args: Dict)"
},
{
"docstring": "Forward pas... | 3 | stack_v2_sparse_classes_30k_train_004267 | Implement the Python class `GlobalAttention` described below.
Class description:
Aggregate context encoding using scaled dot product attention. Query obtained using target agent encoding, Keys and values obtained using map and surrounding agent encodings.
Method signatures and docstrings:
- def __init__(self, args: D... | Implement the Python class `GlobalAttention` described below.
Class description:
Aggregate context encoding using scaled dot product attention. Query obtained using target agent encoding, Keys and values obtained using map and surrounding agent encodings.
Method signatures and docstrings:
- def __init__(self, args: D... | 6419894aa040adb9570b14493952a98c0a52f803 | <|skeleton|>
class GlobalAttention:
"""Aggregate context encoding using scaled dot product attention. Query obtained using target agent encoding, Keys and values obtained using map and surrounding agent encodings."""
def __init__(self, args: Dict):
"""args to include enc_size: int Dimension of encoding... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GlobalAttention:
"""Aggregate context encoding using scaled dot product attention. Query obtained using target agent encoding, Keys and values obtained using map and surrounding agent encodings."""
def __init__(self, args: Dict):
"""args to include enc_size: int Dimension of encodings generated b... | the_stack_v2_python_sparse | models/aggregators/global_attention.py | sancarlim/Explainable-MP | train | 17 |
c6155b355152d4d1086fb83a5604c3b17cf973b4 | [
"pressure = self.getPressure(target)\nif self.parent.currPowerPoints > 0:\n self.parent.currPowerPoints -= pressure\nreturn []",
"if isinstance(self.parent.hitDelegate, HitSelfDelegate):\n return 1\nelse:\n return target.getAbility().powerPointsPressure()"
] | <|body_start_0|>
pressure = self.getPressure(target)
if self.parent.currPowerPoints > 0:
self.parent.currPowerPoints -= pressure
return []
<|end_body_0|>
<|body_start_1|>
if isinstance(self.parent.hitDelegate, HitSelfDelegate):
return 1
else:
... | Represents the Remove PP Step in the Attack Process | RemovePPStep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemovePPStep:
"""Represents the Remove PP Step in the Attack Process"""
def perform(self, user, target, environment):
"""Perform this step"""
<|body_0|>
def getPressure(self, target):
"""Return the Pressure exerted when using the attack"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_005710 | 769 | no_license | [
{
"docstring": "Perform this step",
"name": "perform",
"signature": "def perform(self, user, target, environment)"
},
{
"docstring": "Return the Pressure exerted when using the attack",
"name": "getPressure",
"signature": "def getPressure(self, target)"
}
] | 2 | null | Implement the Python class `RemovePPStep` described below.
Class description:
Represents the Remove PP Step in the Attack Process
Method signatures and docstrings:
- def perform(self, user, target, environment): Perform this step
- def getPressure(self, target): Return the Pressure exerted when using the attack | Implement the Python class `RemovePPStep` described below.
Class description:
Represents the Remove PP Step in the Attack Process
Method signatures and docstrings:
- def perform(self, user, target, environment): Perform this step
- def getPressure(self, target): Return the Pressure exerted when using the attack
<|sk... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class RemovePPStep:
"""Represents the Remove PP Step in the Attack Process"""
def perform(self, user, target, environment):
"""Perform this step"""
<|body_0|>
def getPressure(self, target):
"""Return the Pressure exerted when using the attack"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RemovePPStep:
"""Represents the Remove PP Step in the Attack Process"""
def perform(self, user, target, environment):
"""Perform this step"""
pressure = self.getPressure(target)
if self.parent.currPowerPoints > 0:
self.parent.currPowerPoints -= pressure
return ... | the_stack_v2_python_sparse | src/Battle/Attack/Steps/remove_pp_step.py | sgtnourry/Pokemon-Project | train | 0 |
967e54d85e510846849f361498527a3ba9d17e28 | [
"result = root.val\nwhile root:\n result = min((root.val, result), key=lambda x: abs(target - x))\n root = root.left if target < root.val else root.right\nreturn result",
"child = root.left if root.val > target else root.right\nif not child:\n return root.val\nchild_val = self.closestValue(child, target)... | <|body_start_0|>
result = root.val
while root:
result = min((root.val, result), key=lambda x: abs(target - x))
root = root.left if target < root.val else root.right
return result
<|end_body_0|>
<|body_start_1|>
child = root.left if root.val > target else root.rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_0|>
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_005711 | 947 | no_license | [
{
"docstring": ":type root: TreeNode :type target: float :rtype: int",
"name": "closestValue",
"signature": "def closestValue(self, root, target)"
},
{
"docstring": ":type root: TreeNode :type target: float :rtype: int",
"name": "closestValue",
"signature": "def closestValue(self, root, ... | 2 | stack_v2_sparse_classes_30k_train_002975 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype: int
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype: int
- def closestValue(self, root, target): :type root: TreeNode :type target: float :rtype... | 9513e215d40145a5f2f40095b459693c79c4b560 | <|skeleton|>
class Solution:
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_0|>
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def closestValue(self, root, target):
""":type root: TreeNode :type target: float :rtype: int"""
result = root.val
while root:
result = min((root.val, result), key=lambda x: abs(target - x))
root = root.left if target < root.val else root.right
... | the_stack_v2_python_sparse | 270.py | huangyingw/Leetcode-Python | train | 1 | |
9fa382ea5c91e94bfce3b32a402049b790148741 | [
"size, header = FormatSMVADSCSN.get_smv_header(image_file)\nif int(header['DETECTOR_SN']) not in [926, 907]:\n return False\nreturn True",
"distance = float(self._header_dictionary['DISTANCE'])\nif 'DENZO_X_BEAM' in self._header_dictionary:\n beam_x = float(self._header_dictionary['DENZO_X_BEAM'])\n beam... | <|body_start_0|>
size, header = FormatSMVADSCSN.get_smv_header(image_file)
if int(header['DETECTOR_SN']) not in [926, 907]:
return False
return True
<|end_body_0|>
<|body_start_1|>
distance = float(self._header_dictionary['DISTANCE'])
if 'DENZO_X_BEAM' in self._heade... | A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926. | FormatSMVADSCSN926 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormatSMVADSCSN926:
"""A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926."""
def understand(image_file):
"""Check to see if this is ADSC SN 926."""
<|body_0|>
def _detector(self):
... | stack_v2_sparse_classes_10k_train_005712 | 2,464 | permissive | [
{
"docstring": "Check to see if this is ADSC SN 926.",
"name": "understand",
"signature": "def understand(image_file)"
},
{
"docstring": "Return a model for a simple detector, allowing for the installation on on a two-theta stage. Assert that the beam centre is provided in the Mosflm coordinate ... | 2 | null | Implement the Python class `FormatSMVADSCSN926` described below.
Class description:
A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926.
Method signatures and docstrings:
- def understand(image_file): Check to see if this is ADSC SN 92... | Implement the Python class `FormatSMVADSCSN926` described below.
Class description:
A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926.
Method signatures and docstrings:
- def understand(image_file): Check to see if this is ADSC SN 92... | 2fc8ffadbf67d0611e2d7affcf50d0f23abfc16f | <|skeleton|>
class FormatSMVADSCSN926:
"""A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926."""
def understand(image_file):
"""Check to see if this is ADSC SN 926."""
<|body_0|>
def _detector(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FormatSMVADSCSN926:
"""A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926."""
def understand(image_file):
"""Check to see if this is ADSC SN 926."""
size, header = FormatSMVADSCSN.get_smv_header(image_file... | the_stack_v2_python_sparse | src/dxtbx/format/FormatSMVADSCSN926.py | cctbx/dxtbx | train | 2 |
b6b65782dabc3ff499cfb958e6a1250c852f90b1 | [
"self.SetStartDate(2013, 10, 7)\nself.SetEndDate(2013, 10, 11)\nspy = self.AddEquity('SPY')\nibm = self.AddEquity('IBM')\nself._symbols = [spy.Symbol, ibm.Symbol]\nself._trin = self.TRIN(self._symbols, Resolution.Minute)\nself._trin2 = None",
"if self._trin.IsReady:\n self._trin.Reset()\n self.UnregisterInd... | <|body_start_0|>
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 11)
spy = self.AddEquity('SPY')
ibm = self.AddEquity('IBM')
self._symbols = [spy.Symbol, ibm.Symbol]
self._trin = self.TRIN(self._symbols, Resolution.Minute)
self._trin2 = None
<|end_body_0|... | UnregisterIndicatorRegressionAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnregisterIndicatorRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnData event is the pri... | stack_v2_sparse_classes_10k_train_005713 | 2,225 | permissive | [
{
"docstring": "Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.",
"name": "Initialize",
"signature": "def Initialize(self)"
},
{
"docstring": "OnData event is the primary entry point for your algorithm. Eac... | 2 | null | Implement the Python class `UnregisterIndicatorRegressionAlgorithm` described below.
Class description:
Implement the UnregisterIndicatorRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and start-end dates for your al... | Implement the Python class `UnregisterIndicatorRegressionAlgorithm` described below.
Class description:
Implement the UnregisterIndicatorRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and start-end dates for your al... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class UnregisterIndicatorRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnData event is the pri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnregisterIndicatorRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 11)
spy = self.... | the_stack_v2_python_sparse | Algorithm.Python/UnregisterIndicatorRegressionAlgorithm.py | Capnode/Algoloop | train | 87 | |
9f20acdf38992d8a639986af8b5202072131f0b1 | [
"tuples = self.fscd_tester.machine.read_sensors(self.fscd_tester.sensors, None)\ncount = len(tuples['slot1'])\nself.assertEqual(count, 41, 'Incorrect sensor tupple count')",
"tuples = self.fscd_tester.machine.read_fans(self.fscd_tester.fans)\ncount = len(tuples)\nself.assertEqual(count, 3, 'Incorrect fan tupple c... | <|body_start_0|>
tuples = self.fscd_tester.machine.read_sensors(self.fscd_tester.sensors, None)
count = len(tuples['slot1'])
self.assertEqual(count, 41, 'Incorrect sensor tupple count')
<|end_body_0|>
<|body_start_1|>
tuples = self.fscd_tester.machine.read_fans(self.fscd_tester.fans)
... | FscdBmcMachineUnitTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FscdBmcMachineUnitTest:
def test_sensor_read(self):
"""Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform."""
<|body_0|>
def test_fan_read(self):
"""Test if fan tuples are getting built. 'fan 2' has... | stack_v2_sparse_classes_10k_train_005714 | 4,109 | no_license | [
{
"docstring": "Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform.",
"name": "test_sensor_read",
"signature": "def test_sensor_read(self)"
},
{
"docstring": "Test if fan tuples are getting built. 'fan 2' has a source that read... | 2 | stack_v2_sparse_classes_30k_train_003239 | Implement the Python class `FscdBmcMachineUnitTest` described below.
Class description:
Implement the FscdBmcMachineUnitTest class.
Method signatures and docstrings:
- def test_sensor_read(self): Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform.
-... | Implement the Python class `FscdBmcMachineUnitTest` described below.
Class description:
Implement the FscdBmcMachineUnitTest class.
Method signatures and docstrings:
- def test_sensor_read(self): Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform.
-... | 32777c66a8410d767eae15baabf71c61a0bef13c | <|skeleton|>
class FscdBmcMachineUnitTest:
def test_sensor_read(self):
"""Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform."""
<|body_0|>
def test_fan_read(self):
"""Test if fan tuples are getting built. 'fan 2' has... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FscdBmcMachineUnitTest:
def test_sensor_read(self):
"""Test if sensor tuples are getting built. 'linear_dimm' has a source that reads a file and dumps data like from platform."""
tuples = self.fscd_tester.machine.read_sensors(self.fscd_tester.sensors, None)
count = len(tuples['slot1'])... | the_stack_v2_python_sparse | common/recipes-core/fscd3/fscd/fscd_test/fsc_bmc_machine_tester.py | facebook/openbmc | train | 684 | |
77954a077f38705c155e2227989ef72a48571399 | [
"try:\n if isinstance(number, float) and (not number.is_integer()):\n raise ValueError\n number = int(number)\nexcept (TypeError, ValueError):\n raise PageNotAnInteger(_('That page number is not an integer'))\nif number < 1:\n raise EmptyPage(_('That page number is less than 1'))\nreturn number",... | <|body_start_0|>
try:
if isinstance(number, float) and (not number.is_integer()):
raise ValueError
number = int(number)
except (TypeError, ValueError):
raise PageNotAnInteger(_('That page number is not an integer'))
if number < 1:
r... | Paginator for `SumoSearch` classes. Inherits from the default django paginator with a few adjustments. The default paginator attempts to call len() on the `object_list` first, and then query for an individual page. However, since elasticsearch returns the total number of results at the same time as querying for a singl... | SumoSearchPaginator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumoSearchPaginator:
"""Paginator for `SumoSearch` classes. Inherits from the default django paginator with a few adjustments. The default paginator attempts to call len() on the `object_list` first, and then query for an individual page. However, since elasticsearch returns the total number of r... | stack_v2_sparse_classes_10k_train_005715 | 16,315 | permissive | [
{
"docstring": "Validate the given 1-based page number, without checking if the number is greater than the total number of pages.",
"name": "pre_validate_number",
"signature": "def pre_validate_number(self, number)"
},
{
"docstring": "Return a Page object for the given 1-based page number.",
... | 2 | null | Implement the Python class `SumoSearchPaginator` described below.
Class description:
Paginator for `SumoSearch` classes. Inherits from the default django paginator with a few adjustments. The default paginator attempts to call len() on the `object_list` first, and then query for an individual page. However, since elas... | Implement the Python class `SumoSearchPaginator` described below.
Class description:
Paginator for `SumoSearch` classes. Inherits from the default django paginator with a few adjustments. The default paginator attempts to call len() on the `object_list` first, and then query for an individual page. However, since elas... | 67ec527bfc32c715bf9f29d5e01362c4903aebd2 | <|skeleton|>
class SumoSearchPaginator:
"""Paginator for `SumoSearch` classes. Inherits from the default django paginator with a few adjustments. The default paginator attempts to call len() on the `object_list` first, and then query for an individual page. However, since elasticsearch returns the total number of r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SumoSearchPaginator:
"""Paginator for `SumoSearch` classes. Inherits from the default django paginator with a few adjustments. The default paginator attempts to call len() on the `object_list` first, and then query for an individual page. However, since elasticsearch returns the total number of results at the... | the_stack_v2_python_sparse | kitsune/search/base.py | mozilla/kitsune | train | 1,218 |
2956ee1bc27eeae31538da7430d17b310a6bb29d | [
"super().__init__(session, _id, name, server, options)\nmtu = self.session.options.get_int('mtu')\nself.mtu: int = mtu if mtu > 0 else DEFAULT_MTU\nself.brname: Optional[str] = None\nself.linked: dict[CoreInterface, dict[CoreInterface, bool]] = {}\nself.linked_lock: threading.Lock = threading.Lock()",
"iface_id =... | <|body_start_0|>
super().__init__(session, _id, name, server, options)
mtu = self.session.options.get_int('mtu')
self.mtu: int = mtu if mtu > 0 else DEFAULT_MTU
self.brname: Optional[str] = None
self.linked: dict[CoreInterface, dict[CoreInterface, bool]] = {}
self.linked_... | Base class for networks | CoreNetworkBase | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoreNetworkBase:
"""Base class for networks"""
def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None:
"""Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: obj... | stack_v2_sparse_classes_10k_train_005716 | 32,238 | permissive | [
{
"docstring": "Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: object name :param server: remote server node will run on, default is None for localhost :param options: options to create node with",
"name": "__init__",
"signature": "def __init__(self,... | 3 | stack_v2_sparse_classes_30k_train_004959 | Implement the Python class `CoreNetworkBase` described below.
Class description:
Base class for networks
Method signatures and docstrings:
- def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None: Create a CoreNetworkBase instance. :param sessi... | Implement the Python class `CoreNetworkBase` described below.
Class description:
Base class for networks
Method signatures and docstrings:
- def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None: Create a CoreNetworkBase instance. :param sessi... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class CoreNetworkBase:
"""Base class for networks"""
def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None:
"""Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: obj... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CoreNetworkBase:
"""Base class for networks"""
def __init__(self, session: 'Session', _id: int, name: str, server: 'DistributedServer'=None, options: NodeOptions=None) -> None:
"""Create a CoreNetworkBase instance. :param session: session object :param _id: object id :param name: object name :par... | the_stack_v2_python_sparse | daemon/core/nodes/base.py | coreemu/core | train | 606 |
9087909750cc8636253d4ff98b575fa19a189210 | [
"rides.sort(key=lambda e: (e[1], e[0], e[2]))\ndp = [0]\nendtimes = [e for _, e, _ in rides]\nfor s, e, t in rides:\n i = bisect.bisect_right(endtimes, s)\n dp.append(max(dp[-1], dp[i] + e - s + t))\nreturn dp[-1]",
"rides.sort(key=lambda e: (e[1], e[0], e[2]))\ndp = [0 for _ in range(n + 1)]\nfor i in rang... | <|body_start_0|>
rides.sort(key=lambda e: (e[1], e[0], e[2]))
dp = [0]
endtimes = [e for _, e, _ in rides]
for s, e, t in rides:
i = bisect.bisect_right(endtimes, s)
dp.append(max(dp[-1], dp[i] + e - s + t))
return dp[-1]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
"""DP + binary search."""
<|body_0|>
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
"""DP + sort"""
<|body_1|>
def maxTaxiEarnings1(self, n: int, rides: List[L... | stack_v2_sparse_classes_10k_train_005717 | 1,412 | no_license | [
{
"docstring": "DP + binary search.",
"name": "maxTaxiEarnings",
"signature": "def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int"
},
{
"docstring": "DP + sort",
"name": "maxTaxiEarnings",
"signature": "def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int"
},
... | 3 | stack_v2_sparse_classes_30k_train_002191 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: DP + binary search.
- def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: DP + sort
- def maxTaxiE... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: DP + binary search.
- def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: DP + sort
- def maxTaxiE... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
"""DP + binary search."""
<|body_0|>
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
"""DP + sort"""
<|body_1|>
def maxTaxiEarnings1(self, n: int, rides: List[L... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
"""DP + binary search."""
rides.sort(key=lambda e: (e[1], e[0], e[2]))
dp = [0]
endtimes = [e for _, e, _ in rides]
for s, e, t in rides:
i = bisect.bisect_right(endtimes, s)
... | the_stack_v2_python_sparse | Leetcode/2008.py | hanwgyu/algorithm_problem_solving | train | 5 | |
82ac0b0fe823ed8269f806e9fb09ed1f9bc2f7e8 | [
"if len(word) <= 1:\n return True\nstart_with_cap = word[0] == word[0].upper()\nis_cap = word[1] == word[1].upper()\nif not start_with_cap and is_cap:\n return False\ni = 2\nwhile i < len(word):\n cap = word[i] == word[i].upper()\n if is_cap ^ cap:\n return False\n i += 1\nreturn True",
"if ... | <|body_start_0|>
if len(word) <= 1:
return True
start_with_cap = word[0] == word[0].upper()
is_cap = word[1] == word[1].upper()
if not start_with_cap and is_cap:
return False
i = 2
while i < len(word):
cap = word[i] == word[i].upper()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCapitalUse(self, word: str) -> bool:
"""Feb 08, 2022 12:57"""
<|body_0|>
def detectCapitalUse(self, word: str) -> bool:
"""Mar 04, 2023 20:17"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(word) <= 1:
return T... | stack_v2_sparse_classes_10k_train_005718 | 1,912 | no_license | [
{
"docstring": "Feb 08, 2022 12:57",
"name": "detectCapitalUse",
"signature": "def detectCapitalUse(self, word: str) -> bool"
},
{
"docstring": "Mar 04, 2023 20:17",
"name": "detectCapitalUse",
"signature": "def detectCapitalUse(self, word: str) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_002386 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCapitalUse(self, word: str) -> bool: Feb 08, 2022 12:57
- def detectCapitalUse(self, word: str) -> bool: Mar 04, 2023 20:17 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCapitalUse(self, word: str) -> bool: Feb 08, 2022 12:57
- def detectCapitalUse(self, word: str) -> bool: Mar 04, 2023 20:17
<|skeleton|>
class Solution:
def detec... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def detectCapitalUse(self, word: str) -> bool:
"""Feb 08, 2022 12:57"""
<|body_0|>
def detectCapitalUse(self, word: str) -> bool:
"""Mar 04, 2023 20:17"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def detectCapitalUse(self, word: str) -> bool:
"""Feb 08, 2022 12:57"""
if len(word) <= 1:
return True
start_with_cap = word[0] == word[0].upper()
is_cap = word[1] == word[1].upper()
if not start_with_cap and is_cap:
return False
... | the_stack_v2_python_sparse | leetcode/solved/520_Detect_Capital/solution.py | sungminoh/algorithms | train | 0 | |
3cdfdf40f3c526c20256a645b08f0a15b337929e | [
"self.enter_mtz()\nself.swipe_to_up(1)\nself.enter_collect()\nself.myClick(self.find_element('第一个商品', *self.by_first_collected_goods_id))\nself.assertTrue(self.is_collected('普通团'))\nself.myClick(self.find_element('收藏', *self.by_collect_id))\nself.assertTrue(not self.is_collected('普通团'))",
"self.enter_mtz()\nself.... | <|body_start_0|>
self.enter_mtz()
self.swipe_to_up(1)
self.enter_collect()
self.myClick(self.find_element('第一个商品', *self.by_first_collected_goods_id))
self.assertTrue(self.is_collected('普通团'))
self.myClick(self.find_element('收藏', *self.by_collect_id))
self.assertT... | MyCollect | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyCollect:
def test_buy_collect(self):
"""萌团长_购买商品_收藏切换"""
<|body_0|>
def test_distribution_collect(self):
"""萌团长_分销商品_收藏切换"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.enter_mtz()
self.swipe_to_up(1)
self.enter_collect()
... | stack_v2_sparse_classes_10k_train_005719 | 1,433 | no_license | [
{
"docstring": "萌团长_购买商品_收藏切换",
"name": "test_buy_collect",
"signature": "def test_buy_collect(self)"
},
{
"docstring": "萌团长_分销商品_收藏切换",
"name": "test_distribution_collect",
"signature": "def test_distribution_collect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005349 | Implement the Python class `MyCollect` described below.
Class description:
Implement the MyCollect class.
Method signatures and docstrings:
- def test_buy_collect(self): 萌团长_购买商品_收藏切换
- def test_distribution_collect(self): 萌团长_分销商品_收藏切换 | Implement the Python class `MyCollect` described below.
Class description:
Implement the MyCollect class.
Method signatures and docstrings:
- def test_buy_collect(self): 萌团长_购买商品_收藏切换
- def test_distribution_collect(self): 萌团长_分销商品_收藏切换
<|skeleton|>
class MyCollect:
def test_buy_collect(self):
"""萌团长_购买... | b2066139eb0723eff69d971589b283b4b776c84c | <|skeleton|>
class MyCollect:
def test_buy_collect(self):
"""萌团长_购买商品_收藏切换"""
<|body_0|>
def test_distribution_collect(self):
"""萌团长_分销商品_收藏切换"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyCollect:
def test_buy_collect(self):
"""萌团长_购买商品_收藏切换"""
self.enter_mtz()
self.swipe_to_up(1)
self.enter_collect()
self.myClick(self.find_element('第一个商品', *self.by_first_collected_goods_id))
self.assertTrue(self.is_collected('普通团'))
self.myClick(self.f... | the_stack_v2_python_sparse | TestCase/4_5/TC_Meng_TZ/test_collect_goods.py | testerSunshine/auto_md | train | 4 | |
e5d62b559d6e309344d0247a1420de4adffcd386 | [
"super(SpatialTransformer, self).__init__()\nvectors = [torch.arange(0, s) for s in size]\ngrids = torch.meshgrid(vectors)\ngrid = torch.stack(grids)\ngrid = torch.unsqueeze(grid, 0)\ngrid = grid.type(torch.FloatTensor)\nself.register_buffer('grid', grid)\nself.mode = mode",
"try:\n new_locs = self.grid + flow... | <|body_start_0|>
super(SpatialTransformer, self).__init__()
vectors = [torch.arange(0, s) for s in size]
grids = torch.meshgrid(vectors)
grid = torch.stack(grids)
grid = torch.unsqueeze(grid, 0)
grid = grid.type(torch.FloatTensor)
self.register_buffer('grid', grid... | [SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample | SpatialTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, size, mode='bilinear'):
"""Instiatiate the block :... | stack_v2_sparse_classes_10k_train_005720 | 8,888 | permissive | [
{
"docstring": "Instiatiate the block :param size: size of input to the spatial transformer block :param mode: method of interpolation for grid_sampler",
"name": "__init__",
"signature": "def __init__(self, size, mode='bilinear')"
},
{
"docstring": "Push the src and flow through the spatial tran... | 2 | stack_v2_sparse_classes_30k_train_002595 | Implement the Python class `SpatialTransformer` described below.
Class description:
[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample
Method signatures and docstrings:
- def __ini... | Implement the Python class `SpatialTransformer` described below.
Class description:
[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample
Method signatures and docstrings:
- def __ini... | 730f7dff2239ef716841390311b5b9250149acaf | <|skeleton|>
class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, size, mode='bilinear'):
"""Instiatiate the block :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpatialTransformer:
"""[SpatialTransformer] represesents a spatial transformation block that uses the output from the UNet to preform an grid_sample https://pytorch.org/docs/stable/nn.functional.html#grid-sample"""
def __init__(self, size, mode='bilinear'):
"""Instiatiate the block :param size: s... | the_stack_v2_python_sparse | annolid/motion/deformation.py | healthonrails/annolid | train | 25 |
0c1e793257ac820523adc3dbe0b649d972f5bf0b | [
"BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder)\nself.fault_frame = StructuralFrame(f'{fault_frame.name}_displacementframe', [fault_frame[0].copy(), fault_frame[1].copy(), fault_frame[2].copy()])\nself.displacement = displacement",
"fault_suface = self.fault_frame.features[0].... | <|body_start_0|>
BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder)
self.fault_frame = StructuralFrame(f'{fault_frame.name}_displacementframe', [fault_frame[0].copy(), fault_frame[1].copy(), fault_frame[2].copy()])
self.displacement = displacement
<|end_body_0|>
... | FaultDisplacementFeature | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaultDisplacementFeature:
def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None):
"""Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function... | stack_v2_sparse_classes_10k_train_005721 | 2,390 | permissive | [
{
"docstring": "Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function defining fault displacement",
"name": "__init__",
"signature": "def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, fa... | 4 | stack_v2_sparse_classes_30k_train_002568 | Implement the Python class `FaultDisplacementFeature` described below.
Class description:
Implement the FaultDisplacementFeature class.
Method signatures and docstrings:
- def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None): Geological feature repr... | Implement the Python class `FaultDisplacementFeature` described below.
Class description:
Implement the FaultDisplacementFeature class.
Method signatures and docstrings:
- def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None): Geological feature repr... | c6175623450dbc79ed06ed8d8bbff21b63fc8b4c | <|skeleton|>
class FaultDisplacementFeature:
def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None):
"""Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FaultDisplacementFeature:
def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None):
"""Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function defining faul... | the_stack_v2_python_sparse | LoopStructural/modelling/features/fault/_fault_function_feature.py | Loop3D/LoopStructural | train | 123 | |
3dc01d0aea014a13affd7c161978a87343a9ac3b | [
"matrix.reverse()\nfor i in range(len(matrix)):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])",
"for i in range(len(matrix)):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nmatrix.reverse()"
] | <|body_start_0|>
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
<|end_body_0|>
<|body_start_1|>
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matri... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3"""
<|body_0|>
def anti_rotate(self, matrix: List[List[int]]) -> None:
... | stack_v2_sparse_classes_10k_train_005722 | 1,189 | no_license | [
{
"docstring": "clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3",
"name": "rotate",
"signature": "def rotate(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "anti-clockwise rotate * first swap the sym... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3... | 73654b6567fdb282af84a868608929be234075c5 | <|skeleton|>
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3"""
<|body_0|>
def anti_rotate(self, matrix: List[List[int]]) -> None:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3"""
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
... | the_stack_v2_python_sparse | LeetCode/0048-Rotate image/main.py | PRKKILLER/Algorithm_Practice | train | 0 | |
44eb4f972be21afe0fea55ea0494c28252f1053d | [
"w = self.out.write\nif o.labels:\n w('# ')\n if o.labels:\n w(o.labels[0])\nw('\\n')\nself.visit_doc(o)\nself.visit_iHdlStatement(o.body)",
"self.visit_doc(o)\nw = self.out.write\nfor is_last, i in iter_with_last(o.body):\n self.visit_iHdlStatement(i)\n if not is_last:\n w(',\\n')",
"... | <|body_start_0|>
w = self.out.write
if o.labels:
w('# ')
if o.labels:
w(o.labels[0])
w('\n')
self.visit_doc(o)
self.visit_iHdlStatement(o.body)
<|end_body_0|>
<|body_start_1|>
self.visit_doc(o)
w = self.out.write
fo... | ToHwtStm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToHwtStm:
def visit_HdlStmProcess(self, o):
""":type o: HdlStmProcess"""
<|body_0|>
def visit_HdlStmBlock(self, o):
""":type o: HdlStmBlock"""
<|body_1|>
def visit_HdlStmIf(self, o):
""":type stm: HdlStmIf if cond: ... else: ... will become c, cV... | stack_v2_sparse_classes_10k_train_005723 | 3,549 | permissive | [
{
"docstring": ":type o: HdlStmProcess",
"name": "visit_HdlStmProcess",
"signature": "def visit_HdlStmProcess(self, o)"
},
{
"docstring": ":type o: HdlStmBlock",
"name": "visit_HdlStmBlock",
"signature": "def visit_HdlStmBlock(self, o)"
},
{
"docstring": ":type stm: HdlStmIf if c... | 5 | stack_v2_sparse_classes_30k_train_002814 | Implement the Python class `ToHwtStm` described below.
Class description:
Implement the ToHwtStm class.
Method signatures and docstrings:
- def visit_HdlStmProcess(self, o): :type o: HdlStmProcess
- def visit_HdlStmBlock(self, o): :type o: HdlStmBlock
- def visit_HdlStmIf(self, o): :type stm: HdlStmIf if cond: ... el... | Implement the Python class `ToHwtStm` described below.
Class description:
Implement the ToHwtStm class.
Method signatures and docstrings:
- def visit_HdlStmProcess(self, o): :type o: HdlStmProcess
- def visit_HdlStmBlock(self, o): :type o: HdlStmBlock
- def visit_HdlStmIf(self, o): :type stm: HdlStmIf if cond: ... el... | 64c8c1deee923ffae17e70e0fb1ad763cb69608c | <|skeleton|>
class ToHwtStm:
def visit_HdlStmProcess(self, o):
""":type o: HdlStmProcess"""
<|body_0|>
def visit_HdlStmBlock(self, o):
""":type o: HdlStmBlock"""
<|body_1|>
def visit_HdlStmIf(self, o):
""":type stm: HdlStmIf if cond: ... else: ... will become c, cV... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ToHwtStm:
def visit_HdlStmProcess(self, o):
""":type o: HdlStmProcess"""
w = self.out.write
if o.labels:
w('# ')
if o.labels:
w(o.labels[0])
w('\n')
self.visit_doc(o)
self.visit_iHdlStatement(o.body)
def visit_HdlStmB... | the_stack_v2_python_sparse | hdlConvertorAst/to/hwt/stm.py | mewais/hdlConvertorAst | train | 0 | |
3cdf5ddd7311079b2f7727992b7d3d16e6b3c8ef | [
"square1 = PolybiusSquare(alphabet, key[0])\nsquare2 = PolybiusSquare(alphabet, key[1])\nsquare3 = PolybiusSquare(alphabet, key[2])\nres = []\nit = iter(text)\nrows = square1.get_rows()\ncols = square2.get_columns()\nwhile True:\n try:\n t = next(it)\n except StopIteration:\n break\n row1, co... | <|body_start_0|>
square1 = PolybiusSquare(alphabet, key[0])
square2 = PolybiusSquare(alphabet, key[1])
square3 = PolybiusSquare(alphabet, key[2])
res = []
it = iter(text)
rows = square1.get_rows()
cols = square2.get_columns()
while True:
try:
... | The Three Square Cipher | ThreeSquare | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: strin... | stack_v2_sparse_classes_10k_train_005724 | 2,590 | permissive | [
{
"docstring": "Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: string :type key: tuple of 3 strings :type alphabet: string :return: text :rtype: string",
"name": "encrypt",
"signa... | 2 | stack_v2_sparse_classes_30k_train_001327 | Implement the Python class `ThreeSquare` described below.
Class description:
The Three Square Cipher
Method signatures and docstrings:
- def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ): Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, ... | Implement the Python class `ThreeSquare` described below.
Class description:
The Three Square Cipher
Method signatures and docstrings:
- def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ): Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, ... | e464f998e5540f52e269fe360ec9d3a08e976b2e | <|skeleton|>
class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: strin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: string :type key: ... | the_stack_v2_python_sparse | secretpy/ciphers/three_square.py | tigertv/secretpy | train | 65 |
0d2c7d1937b75d563c46e0a2d30389a588a45c18 | [
"if len(colors) < 2:\n raise BetseSequenceException('Colormap scheme defines less than two colors: {!r}'.format(colors))\nfor color in colors:\n sequences.die_unless_length(sequence=color, length=3)\n ints.die_unless_byte(*color)\nself._name = name\nself._colors = colors\nself._gamma = gamma",
"colors_no... | <|body_start_0|>
if len(colors) < 2:
raise BetseSequenceException('Colormap scheme defines less than two colors: {!r}'.format(colors))
for color in colors:
sequences.die_unless_length(sequence=color, length=3)
ints.die_unless_byte(*color)
self._name = name
... | Matplotlib-specific **colormap scheme** (i.e., collection of parameters sufficient to subsequently define a standard linear-segmented colormap). Instances of this class are typically passed to the :func:`add_colormap` function, which both creates and registers a new colormap from the passed colormap scheme. Attributes ... | MplColormapScheme | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MplColormapScheme:
"""Matplotlib-specific **colormap scheme** (i.e., collection of parameters sufficient to subsequently define a standard linear-segmented colormap). Instances of this class are typically passed to the :func:`add_colormap` function, which both creates and registers a new colormap... | stack_v2_sparse_classes_10k_train_005725 | 13,291 | no_license | [
{
"docstring": "Initialize this colormap scheme. Parameters ----------- name : str Name of the colormap to be created. colors : SequenceTypes Two-dimensional sequence whose: * First dimension indexes each color defining this colormap's gradient. This dimension *must* be a sequence containing two or more colors.... | 2 | stack_v2_sparse_classes_30k_train_000648 | Implement the Python class `MplColormapScheme` described below.
Class description:
Matplotlib-specific **colormap scheme** (i.e., collection of parameters sufficient to subsequently define a standard linear-segmented colormap). Instances of this class are typically passed to the :func:`add_colormap` function, which bo... | Implement the Python class `MplColormapScheme` described below.
Class description:
Matplotlib-specific **colormap scheme** (i.e., collection of parameters sufficient to subsequently define a standard linear-segmented colormap). Instances of this class are typically passed to the :func:`add_colormap` function, which bo... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class MplColormapScheme:
"""Matplotlib-specific **colormap scheme** (i.e., collection of parameters sufficient to subsequently define a standard linear-segmented colormap). Instances of this class are typically passed to the :func:`add_colormap` function, which both creates and registers a new colormap... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MplColormapScheme:
"""Matplotlib-specific **colormap scheme** (i.e., collection of parameters sufficient to subsequently define a standard linear-segmented colormap). Instances of this class are typically passed to the :func:`add_colormap` function, which both creates and registers a new colormap from the pas... | the_stack_v2_python_sparse | betse/lib/matplotlib/mplcolormap.py | R-Stefano/betse-ml | train | 0 |
e688e235226bef00ac82b0e5806b081bbf580c3e | [
"index1 = self._select_index(population=population)\nindex2 = index1\nwhile index2 == index1:\n index2 = self._select_index(population=population)\nreturn (population.get(index1), population.get(index2))",
"total_fitness = 0\nfor solution in population.solutions:\n total_fitness += solution.fitness\nwheel_p... | <|body_start_0|>
index1 = self._select_index(population=population)
index2 = index1
while index2 == index1:
index2 = self._select_index(population=population)
return (population.get(index1), population.get(index2))
<|end_body_0|>
<|body_start_1|>
total_fitness = 0
... | Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does not consider minimization problem | RouletteWheelSelection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does no... | stack_v2_sparse_classes_10k_train_005726 | 10,268 | no_license | [
{
"docstring": "select two different parents using roulette wheel",
"name": "select",
"signature": "def select(self, population, objective, params)"
},
{
"docstring": "This is the roullete wheel itself",
"name": "_select_index",
"signature": "def _select_index(self, population)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000584 | Implement the Python class `RouletteWheelSelection` described below.
Class description:
Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individu... | Implement the Python class `RouletteWheelSelection` described below.
Class description:
Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individu... | 4dd77d5d72186f446fead55371c9941c4020f431 | <|skeleton|>
class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does no... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does not consider mi... | the_stack_v2_python_sparse | Customer Segmentation for Insurance Dataset/Extra Code/GA for ML/algorithm/ga_operators.py | apanchot/Projects | train | 1 |
b7094885839d34430b25400fa5d96a0e9c221107 | [
"super().setUp()\nself.n_batch = 4\nself.x_dims = 5\nself.z_dims = 2\nself.x = tf.ones([self.n_batch, self.x_dims])\nself.inputs = {'test_data': self.x}\nself.gin_config_kwarg_modules = f\"\\n import ddsp\\n\\n ### Modules\\n ConfigurableDAGLayer.dag = [\\n ('encoder', ['inputs/test_data'], ['z']),\... | <|body_start_0|>
super().setUp()
self.n_batch = 4
self.x_dims = 5
self.z_dims = 2
self.x = tf.ones([self.n_batch, self.x_dims])
self.inputs = {'test_data': self.x}
self.gin_config_kwarg_modules = f"\n import ddsp\n\n ### Modules\n ConfigurableDAGLayer.dag... | DAGLayerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAGLayerTest:
def setUp(self):
"""Create some dummy input data for the chain."""
<|body_0|>
def test_build_layer(self, kwarg_modules):
"""Tests if layer builds properly and produces outputs of correct shape."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005727 | 3,744 | permissive | [
{
"docstring": "Create some dummy input data for the chain.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests if layer builds properly and produces outputs of correct shape.",
"name": "test_build_layer",
"signature": "def test_build_layer(self, kwarg_modules)"
... | 2 | stack_v2_sparse_classes_30k_train_003315 | Implement the Python class `DAGLayerTest` described below.
Class description:
Implement the DAGLayerTest class.
Method signatures and docstrings:
- def setUp(self): Create some dummy input data for the chain.
- def test_build_layer(self, kwarg_modules): Tests if layer builds properly and produces outputs of correct s... | Implement the Python class `DAGLayerTest` described below.
Class description:
Implement the DAGLayerTest class.
Method signatures and docstrings:
- def setUp(self): Create some dummy input data for the chain.
- def test_build_layer(self, kwarg_modules): Tests if layer builds properly and produces outputs of correct s... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class DAGLayerTest:
def setUp(self):
"""Create some dummy input data for the chain."""
<|body_0|>
def test_build_layer(self, kwarg_modules):
"""Tests if layer builds properly and produces outputs of correct shape."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DAGLayerTest:
def setUp(self):
"""Create some dummy input data for the chain."""
super().setUp()
self.n_batch = 4
self.x_dims = 5
self.z_dims = 2
self.x = tf.ones([self.n_batch, self.x_dims])
self.inputs = {'test_data': self.x}
self.gin_config_kw... | the_stack_v2_python_sparse | ddsp/dags_test.py | magenta/ddsp | train | 2,666 | |
fccee119f790eb0e2de214de35bb39aefe689935 | [
"if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
"max_depth = 0\nstack = deque([(root, 0)])\nwhile stack:\n node, depth = stack.pop()\n max_depth = max(max_depth, depth)\n if node:\n stack.append((node.left, depth + 1))\n stack.append((node.... | <|body_start_0|>
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
<|end_body_0|>
<|body_start_1|>
max_depth = 0
stack = deque([(root, 0)])
while stack:
node, depth = stack.pop()
max_depth = max(max_dept... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Recursive DFS Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int:
"""Iterative DFS Time complexity: O(n) Space complexity: O(n)""... | stack_v2_sparse_classes_10k_train_005728 | 1,684 | permissive | [
{
"docstring": "Recursive DFS Time complexity: O(n) Space complexity: O(n)",
"name": "maxDepth",
"signature": "def maxDepth(self, root: Optional[TreeNode]) -> int"
},
{
"docstring": "Iterative DFS Time complexity: O(n) Space complexity: O(n)",
"name": "maxDepthIterativeDFS",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_004682 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: Optional[TreeNode]) -> int: Recursive DFS Time complexity: O(n) Space complexity: O(n)
- def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root: Optional[TreeNode]) -> int: Recursive DFS Time complexity: O(n) Space complexity: O(n)
- def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int:... | 32b0878f63e5edd19a1fbe13bfa4c518a4261e23 | <|skeleton|>
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Recursive DFS Time complexity: O(n) Space complexity: O(n)"""
<|body_0|>
def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int:
"""Iterative DFS Time complexity: O(n) Space complexity: O(n)""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""Recursive DFS Time complexity: O(n) Space complexity: O(n)"""
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepthIterativeDFS(self, root: Optional[TreeN... | the_stack_v2_python_sparse | leetcode/Trees/104. Maximum Depth of Binary Tree.py | danielfsousa/algorithms-solutions | train | 2 | |
fcb0ca9a957d88b00c8b1c42f3cb1488b4255b3f | [
"if not isinstance(value, QuantDescriptor):\n raise ValueError('{} is not an instance of QuantDescriptor!')\ncls.default_quant_desc_input = copy.deepcopy(value)",
"if not isinstance(value, QuantDescriptor):\n raise ValueError('{} is not an instance of QuantDescriptor!')\ncls.default_quant_desc_kernel = copy... | <|body_start_0|>
if not isinstance(value, QuantDescriptor):
raise ValueError('{} is not an instance of QuantDescriptor!')
cls.default_quant_desc_input = copy.deepcopy(value)
<|end_body_0|>
<|body_start_1|>
if not isinstance(value, QuantDescriptor):
raise ValueError('{} i... | Mixin class for adding basic quantization logic to quantized modules | QuantMixin | [
"Apache-2.0",
"CAL-1.0-Combined-Work-Exception",
"CAL-1.0",
"MIT",
"CC-BY-SA-4.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuantMixin:
"""Mixin class for adding basic quantization logic to quantized modules"""
def set_default_quant_desc_input(cls, value):
"""Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescriptor>`"""
<|body_0|>
def set_default_quant_desc_kernel(cls,... | stack_v2_sparse_classes_10k_train_005729 | 2,612 | permissive | [
{
"docstring": "Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescriptor>`",
"name": "set_default_quant_desc_input",
"signature": "def set_default_quant_desc_input(cls, value)"
},
{
"docstring": "Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescri... | 2 | null | Implement the Python class `QuantMixin` described below.
Class description:
Mixin class for adding basic quantization logic to quantized modules
Method signatures and docstrings:
- def set_default_quant_desc_input(cls, value): Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescriptor>`
- def se... | Implement the Python class `QuantMixin` described below.
Class description:
Mixin class for adding basic quantization logic to quantized modules
Method signatures and docstrings:
- def set_default_quant_desc_input(cls, value): Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescriptor>`
- def se... | c50cd2b9154c83c3db5e4a11b9e8874f7fb8afa2 | <|skeleton|>
class QuantMixin:
"""Mixin class for adding basic quantization logic to quantized modules"""
def set_default_quant_desc_input(cls, value):
"""Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescriptor>`"""
<|body_0|>
def set_default_quant_desc_kernel(cls,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuantMixin:
"""Mixin class for adding basic quantization logic to quantized modules"""
def set_default_quant_desc_input(cls, value):
"""Args: value: An instance of :func:`QuantDescriptor <quantization.QuantDescriptor>`"""
if not isinstance(value, QuantDescriptor):
raise ValueE... | the_stack_v2_python_sparse | developer/lab/tools/NVIDIA/FasterTransformer/bert-quantization/bert-tf-quantization/ft-tensorflow-quantization/ft-tensorflow-quantization/python/layers/utils.py | arXiv-research/DevLab-III-1 | train | 2 |
fed6a92acea62f9d42c2d89245118f36812705d4 | [
"MobileText = self.find_element(*self.MobileTextElement)\nMobileText.send_keys(mobilevalue)\nVerifyCodeText = self.find_element(*self.VerifyCodeTextElement)\nVerifyCodeText.send_keys('111222')\nLoginBtn = self.find_element(*self.LoginBtnElement)\nLoginBtn.click()\nlogger.info('LoginBtn is click!')",
"deskBtn = se... | <|body_start_0|>
MobileText = self.find_element(*self.MobileTextElement)
MobileText.send_keys(mobilevalue)
VerifyCodeText = self.find_element(*self.VerifyCodeTextElement)
VerifyCodeText.send_keys('111222')
LoginBtn = self.find_element(*self.LoginBtnElement)
LoginBtn.click... | notice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class notice:
def LoginBtnObj(self, mobilevalue):
"""登录测试账号"""
<|body_0|>
def intoObj(self):
"""进入班级通知"""
<|body_1|>
def addObj(self, text):
"""添加班级通知"""
<|body_2|>
def addvideoObj(self):
"""添加视频"""
<|body_3|>
<|end_skelet... | stack_v2_sparse_classes_10k_train_005730 | 4,142 | no_license | [
{
"docstring": "登录测试账号",
"name": "LoginBtnObj",
"signature": "def LoginBtnObj(self, mobilevalue)"
},
{
"docstring": "进入班级通知",
"name": "intoObj",
"signature": "def intoObj(self)"
},
{
"docstring": "添加班级通知",
"name": "addObj",
"signature": "def addObj(self, text)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_005171 | Implement the Python class `notice` described below.
Class description:
Implement the notice class.
Method signatures and docstrings:
- def LoginBtnObj(self, mobilevalue): 登录测试账号
- def intoObj(self): 进入班级通知
- def addObj(self, text): 添加班级通知
- def addvideoObj(self): 添加视频 | Implement the Python class `notice` described below.
Class description:
Implement the notice class.
Method signatures and docstrings:
- def LoginBtnObj(self, mobilevalue): 登录测试账号
- def intoObj(self): 进入班级通知
- def addObj(self, text): 添加班级通知
- def addvideoObj(self): 添加视频
<|skeleton|>
class notice:
def LoginBtnObj... | c4e11c8aa67306111ca2831a18af4363831af939 | <|skeleton|>
class notice:
def LoginBtnObj(self, mobilevalue):
"""登录测试账号"""
<|body_0|>
def intoObj(self):
"""进入班级通知"""
<|body_1|>
def addObj(self, text):
"""添加班级通知"""
<|body_2|>
def addvideoObj(self):
"""添加视频"""
<|body_3|>
<|end_skelet... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class notice:
def LoginBtnObj(self, mobilevalue):
"""登录测试账号"""
MobileText = self.find_element(*self.MobileTextElement)
MobileText.send_keys(mobilevalue)
VerifyCodeText = self.find_element(*self.VerifyCodeTextElement)
VerifyCodeText.send_keys('111222')
LoginBtn = self.... | the_stack_v2_python_sparse | Public/Pages/Notice.py | alexzeger/android_teacher | train | 0 | |
58d8c2271fb423f8309143ccf3d44b10f145e02b | [
"print(data)\nmin_date = timezone.now() + timedelta(minutes=10)\nif data <= min_date:\n raise serializers.ValidationError('Departure time must be at least pass the next 20 minutes window')\nreturn data",
"if self.context['request'].user != data['offered_by']:\n raise serializer.ValidationError('Ride offered... | <|body_start_0|>
print(data)
min_date = timezone.now() + timedelta(minutes=10)
if data <= min_date:
raise serializers.ValidationError('Departure time must be at least pass the next 20 minutes window')
return data
<|end_body_0|>
<|body_start_1|>
if self.context['reque... | Create ride serializer | CreateRideSerialier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateRideSerialier:
"""Create ride serializer"""
def validate_departure_date(self, data):
"""Verify date is not in the past"""
<|body_0|>
def validate(self, data):
"""Validate Verify that the person who offers the ride is member and also the same user making the... | stack_v2_sparse_classes_10k_train_005731 | 7,953 | no_license | [
{
"docstring": "Verify date is not in the past",
"name": "validate_departure_date",
"signature": "def validate_departure_date(self, data)"
},
{
"docstring": "Validate Verify that the person who offers the ride is member and also the same user making the request",
"name": "validate",
"sig... | 3 | stack_v2_sparse_classes_30k_train_003455 | Implement the Python class `CreateRideSerialier` described below.
Class description:
Create ride serializer
Method signatures and docstrings:
- def validate_departure_date(self, data): Verify date is not in the past
- def validate(self, data): Validate Verify that the person who offers the ride is member and also the... | Implement the Python class `CreateRideSerialier` described below.
Class description:
Create ride serializer
Method signatures and docstrings:
- def validate_departure_date(self, data): Verify date is not in the past
- def validate(self, data): Validate Verify that the person who offers the ride is member and also the... | 0cede53169041667bd40bbce3c4774af84ffc2fa | <|skeleton|>
class CreateRideSerialier:
"""Create ride serializer"""
def validate_departure_date(self, data):
"""Verify date is not in the past"""
<|body_0|>
def validate(self, data):
"""Validate Verify that the person who offers the ride is member and also the same user making the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreateRideSerialier:
"""Create ride serializer"""
def validate_departure_date(self, data):
"""Verify date is not in the past"""
print(data)
min_date = timezone.now() + timedelta(minutes=10)
if data <= min_date:
raise serializers.ValidationError('Departure time ... | the_stack_v2_python_sparse | rides/serializers/rides.py | KrystellCR/DjangoRF | train | 0 |
3e3ecd5339ce3e3cc9d3d282129d02238c83a655 | [
"num.sort()\nresset = set()\nfor i in range(len(num) - 2):\n if i > 0 and num[i] == num[i - 1]:\n continue\n j = i + 1\n k = len(num) - 1\n while j < k:\n x = num[i] + num[j] + num[k]\n if x == 0:\n resset.add((num[i], num[j], num[k]))\n j += 1\n k -... | <|body_start_0|>
num.sort()
resset = set()
for i in range(len(num) - 2):
if i > 0 and num[i] == num[i - 1]:
continue
j = i + 1
k = len(num) - 1
while j < k:
x = num[i] + num[j] + num[k]
if x == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, num):
"""Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solut... | stack_v2_sparse_classes_10k_train_005732 | 2,612 | no_license | [
{
"docstring": "Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. F... | 2 | stack_v2_sparse_classes_30k_train_002763 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, num): Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zer... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, num): Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zer... | d16e4724ee34a0046cb2a8b0b13139b43d284e83 | <|skeleton|>
class Solution:
def threeSum(self, num):
"""Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solut... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, num):
"""Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must n... | the_stack_v2_python_sparse | 3Sum.py | KnightChan/LeetCode-Python | train | 0 | |
f11a0afe24f19099e5b33366d1722047b217899e | [
"super(DecodingAlgorithm, self).__init__(train_state_spec=decoder.state_spec, name=name)\nself._decoder = decoder\nself._loss = loss\nself._loss_weight = loss_weight",
"input, target = inputs\npred, state = self._decoder(input, state=state)\nassert pred.shape == target.shape\nloss = self._loss(pred, target)\nasse... | <|body_start_0|>
super(DecodingAlgorithm, self).__init__(train_state_spec=decoder.state_spec, name=name)
self._decoder = decoder
self._loss = loss
self._loss_weight = loss_weight
<|end_body_0|>
<|body_start_1|>
input, target = inputs
pred, state = self._decoder(input, st... | Generic decoding algorithm. | DecodingAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodingAlgorithm:
"""Generic decoding algorithm."""
def __init__(self, decoder: Network, loss=torch.nn.MSELoss(reduction='none'), loss_weight=1.0, name='DecodingAlgorithm'):
"""Args: decoder (Network): network for decoding target from input. loss (Callable): loss function with signa... | stack_v2_sparse_classes_10k_train_005733 | 2,571 | permissive | [
{
"docstring": "Args: decoder (Network): network for decoding target from input. loss (Callable): loss function with signature ``loss(y_pred, y_true)``. Note that it should not reduce to a scalar. It should at least keep the batch dimension in the returned loss. loss_weight (float): weight for the loss.",
"... | 2 | stack_v2_sparse_classes_30k_val_000053 | Implement the Python class `DecodingAlgorithm` described below.
Class description:
Generic decoding algorithm.
Method signatures and docstrings:
- def __init__(self, decoder: Network, loss=torch.nn.MSELoss(reduction='none'), loss_weight=1.0, name='DecodingAlgorithm'): Args: decoder (Network): network for decoding tar... | Implement the Python class `DecodingAlgorithm` described below.
Class description:
Generic decoding algorithm.
Method signatures and docstrings:
- def __init__(self, decoder: Network, loss=torch.nn.MSELoss(reduction='none'), loss_weight=1.0, name='DecodingAlgorithm'): Args: decoder (Network): network for decoding tar... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class DecodingAlgorithm:
"""Generic decoding algorithm."""
def __init__(self, decoder: Network, loss=torch.nn.MSELoss(reduction='none'), loss_weight=1.0, name='DecodingAlgorithm'):
"""Args: decoder (Network): network for decoding target from input. loss (Callable): loss function with signa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DecodingAlgorithm:
"""Generic decoding algorithm."""
def __init__(self, decoder: Network, loss=torch.nn.MSELoss(reduction='none'), loss_weight=1.0, name='DecodingAlgorithm'):
"""Args: decoder (Network): network for decoding target from input. loss (Callable): loss function with signature ``loss(y... | the_stack_v2_python_sparse | alf/algorithms/decoding_algorithm.py | HorizonRobotics/alf | train | 288 |
c1ceafabbcaff4ef3a603106b9fb1d47d4c2d58b | [
"self.a = [0]\nfor i in range(len(rects) - 1):\n self.a.append(self.a[-1] + (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1))\n rects[i] = [rects[i][0], rects[i][1], rects[i][2] - rects[i][0] + 1]\nself.b, self.k = (rects, self.a[-1] + (rects[-1][2] - rects[-1][0] + 1) * (rects[-1][3] - rects... | <|body_start_0|>
self.a = [0]
for i in range(len(rects) - 1):
self.a.append(self.a[-1] + (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1))
rects[i] = [rects[i][0], rects[i][1], rects[i][2] - rects[i][0] + 1]
self.b, self.k = (rects, self.a[-1] + (rects[-1... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def __init__(self, rects):
""":type rects: List[List[int]] 256ms"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.a = [0]
for i in range(len(rects) - 1):
self.a.a... | stack_v2_sparse_classes_10k_train_005734 | 2,805 | no_license | [
{
"docstring": ":type rects: List[List[int]] 256ms",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001372 | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]] 256ms
- def pick(self): :rtype: List[int] | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]] 256ms
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution_1:
def __init__(self, rects):
""":... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution_1:
def __init__(self, rects):
""":type rects: List[List[int]] 256ms"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution_1:
def __init__(self, rects):
""":type rects: List[List[int]] 256ms"""
self.a = [0]
for i in range(len(rects) - 1):
self.a.append(self.a[-1] + (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1))
rects[i] = [rects[i][0], rects[i][1], rects... | the_stack_v2_python_sparse | RandomPointInNonoverlappingRectangles_MID_882.py | 953250587/leetcode-python | train | 2 | |
be76ad3d413e402df7e6ac137d0d26a444ef98f9 | [
"super().__init__(max_number=max_number, min_number=min_number, seed=seed)\nself.stamp_size = stamp_size\nself.mag_name = mag_name\nif min_number < 1:\n raise ValueError('At least 1 bright galaxy will be added, so need min_number >=1.')",
"if self.mag_name not in table.colnames:\n raise ValueError(f\"Catalo... | <|body_start_0|>
super().__init__(max_number=max_number, min_number=min_number, seed=seed)
self.stamp_size = stamp_size
self.mag_name = mag_name
if min_number < 1:
raise ValueError('At least 1 bright galaxy will be added, so need min_number >=1.')
<|end_body_0|>
<|body_start... | Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization. | BasicSampling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicSampling:
"""Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization."""
def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_name: str='i_ab', seed: int=DEFAULT_SEED):
"""Initializes the ... | stack_v2_sparse_classes_10k_train_005735 | 12,943 | permissive | [
{
"docstring": "Initializes the basic sampling function. Args: max_number: Defined in parent class. min_number: Defined in parent class. stamp_size: Size of the desired stamp. seed: Seed to initialize randomness for reproducibility. mag_name: Name of the magnitude column in the catalog for cuts.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_001186 | Implement the Python class `BasicSampling` described below.
Class description:
Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization.
Method signatures and docstrings:
- def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_na... | Implement the Python class `BasicSampling` described below.
Class description:
Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization.
Method signatures and docstrings:
- def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_na... | f5b716a373f130238100db8980aa0d282822983a | <|skeleton|>
class BasicSampling:
"""Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization."""
def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_name: str='i_ab', seed: int=DEFAULT_SEED):
"""Initializes the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasicSampling:
"""Example of basic sampling function features. Includes magnitude cut, restriction on the shape, shift randomization."""
def __init__(self, max_number: int=4, min_number: int=1, stamp_size: float=24.0, mag_name: str='i_ab', seed: int=DEFAULT_SEED):
"""Initializes the basic samplin... | the_stack_v2_python_sparse | btk/sampling_functions.py | LSSTDESC/BlendingToolKit | train | 22 |
e66b5edf7e64a9edcebe7126be3999a2a283beee | [
"assert isinstance(output_size, (int, tuple, list))\nif isinstance(output_size, int):\n output_size = (output_size, output_size)\nself.output_size = output_size",
"h, w = image.shape[:2]\ntarget_h, target_w = (self.output_size[0], self.output_size[1])\n(new_h, new_w), (left, right, top, bottom) = get_rescale_s... | <|body_start_0|>
assert isinstance(output_size, (int, tuple, list))
if isinstance(output_size, int):
output_size = (output_size, output_size)
self.output_size = output_size
<|end_body_0|>
<|body_start_1|>
h, w = image.shape[:2]
target_h, target_w = (self.output_size[... | Rescale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rescale:
def __init__(self, output_size: typing.Union[int, tuple, list]):
"""将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸"""
<|body_0|>
def __call__(self, image: np.ndarray) -> np.ndarray:
"""对cv2读取的单张BGR图像进行图像等比例伸缩,空余部分pad 0 :param image: cv2读取的bgr格式图像, ... | stack_v2_sparse_classes_10k_train_005736 | 1,407 | no_license | [
{
"docstring": "将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸",
"name": "__init__",
"signature": "def __init__(self, output_size: typing.Union[int, tuple, list])"
},
{
"docstring": "对cv2读取的单张BGR图像进行图像等比例伸缩,空余部分pad 0 :param image: cv2读取的bgr格式图像, (h, w, 3) :return: 等比例伸缩后的图像, (h, w, 3)"... | 2 | stack_v2_sparse_classes_30k_train_006354 | Implement the Python class `Rescale` described below.
Class description:
Implement the Rescale class.
Method signatures and docstrings:
- def __init__(self, output_size: typing.Union[int, tuple, list]): 将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸
- def __call__(self, image: np.ndarray) -> np.ndarray: 对cv... | Implement the Python class `Rescale` described below.
Class description:
Implement the Rescale class.
Method signatures and docstrings:
- def __init__(self, output_size: typing.Union[int, tuple, list]): 将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸
- def __call__(self, image: np.ndarray) -> np.ndarray: 对cv... | 13030bd157a499b80d1860b8b654a66224eaf475 | <|skeleton|>
class Rescale:
def __init__(self, output_size: typing.Union[int, tuple, list]):
"""将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸"""
<|body_0|>
def __call__(self, image: np.ndarray) -> np.ndarray:
"""对cv2读取的单张BGR图像进行图像等比例伸缩,空余部分pad 0 :param image: cv2读取的bgr格式图像, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Rescale:
def __init__(self, output_size: typing.Union[int, tuple, list]):
"""将图像等比例伸缩到指定尺寸,空余部分pad 0 :param output_size: 指定的等比例伸缩后的尺寸"""
assert isinstance(output_size, (int, tuple, list))
if isinstance(output_size, int):
output_size = (output_size, output_size)
self... | the_stack_v2_python_sparse | dataloader/enhancement/rescale.py | zheng-yuwei/PyTorch-Image-Classification | train | 63 | |
8ed236b3786393e0614b3e3b51ebed760f928cfb | [
"self._model = dict()\nself._ngram = 1\nself._epsilon = sppasPerplexity.DEFAULT_EPSILON\nself.set_model(model)\nself.set_ngram(ngram)",
"eps = float(eps)\nif eps < 0.0 or eps > 0.1:\n raise InsideIntervalError(eps, 0.0, 0.1)\nif self._model is not None:\n p_min = round(min((proba for proba in self._model.va... | <|body_start_0|>
self._model = dict()
self._ngram = 1
self._epsilon = sppasPerplexity.DEFAULT_EPSILON
self.set_model(model)
self.set_ngram(ngram)
<|end_body_0|>
<|body_start_1|>
eps = float(eps)
if eps < 0.0 or eps > 0.1:
raise InsideIntervalError(eps... | Perplexity estimator. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Perplexity is a measurement of how well a probability distribution or probability model predicts a sample. Th... | sppasPerplexity | [
"MIT",
"GFDL-1.1-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasPerplexity:
"""Perplexity estimator. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Perplexity is a measurement of how well a probability distribution... | stack_v2_sparse_classes_10k_train_005737 | 6,620 | permissive | [
{
"docstring": "Create a Perplexity instance with a list of symbols. :param model: (dict) a dictionary with key=item, value=probability :param ngram: (int) the n value, in the range 1..8",
"name": "__init__",
"signature": "def __init__(self, model, ngram=1)"
},
{
"docstring": "Set a value for ep... | 5 | null | Implement the Python class `sppasPerplexity` described below.
Class description:
Perplexity estimator. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Perplexity is a measurement... | Implement the Python class `sppasPerplexity` described below.
Class description:
Perplexity estimator. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Perplexity is a measurement... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasPerplexity:
"""Perplexity estimator. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Perplexity is a measurement of how well a probability distribution... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class sppasPerplexity:
"""Perplexity estimator. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi Perplexity is a measurement of how well a probability distribution or probabili... | the_stack_v2_python_sparse | sppas/sppas/src/calculus/infotheory/perplexity.py | mirfan899/MTTS | train | 0 |
3400dbab0f9a3edb08d4b4528b4c878bc68bf906 | [
"out_file = open(file_path, 'w')\njson.dump(data, out_file, indent=4)\nout_file.close()",
"try:\n with open(file_path) as f:\n return json.load(f)\nexcept IOError as e:\n print('could not read ' + file_path)"
] | <|body_start_0|>
out_file = open(file_path, 'w')
json.dump(data, out_file, indent=4)
out_file.close()
<|end_body_0|>
<|body_start_1|>
try:
with open(file_path) as f:
return json.load(f)
except IOError as e:
print('could not read ' + file_p... | This class handles writing data objects to files and loading in data objects | MyJsonHandler | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyJsonHandler:
"""This class handles writing data objects to files and loading in data objects"""
def save_data_to_json_file(data, file_path):
"""Store data as json in designated file_path"""
<|body_0|>
def get_data_from_json_file(file_path):
"""get data as json ... | stack_v2_sparse_classes_10k_train_005738 | 704 | permissive | [
{
"docstring": "Store data as json in designated file_path",
"name": "save_data_to_json_file",
"signature": "def save_data_to_json_file(data, file_path)"
},
{
"docstring": "get data as json in designated file_path and returns the loaded json",
"name": "get_data_from_json_file",
"signatur... | 2 | null | Implement the Python class `MyJsonHandler` described below.
Class description:
This class handles writing data objects to files and loading in data objects
Method signatures and docstrings:
- def save_data_to_json_file(data, file_path): Store data as json in designated file_path
- def get_data_from_json_file(file_pat... | Implement the Python class `MyJsonHandler` described below.
Class description:
This class handles writing data objects to files and loading in data objects
Method signatures and docstrings:
- def save_data_to_json_file(data, file_path): Store data as json in designated file_path
- def get_data_from_json_file(file_pat... | 20d8df6172906337f81583dabb841d66b8f31857 | <|skeleton|>
class MyJsonHandler:
"""This class handles writing data objects to files and loading in data objects"""
def save_data_to_json_file(data, file_path):
"""Store data as json in designated file_path"""
<|body_0|>
def get_data_from_json_file(file_path):
"""get data as json ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyJsonHandler:
"""This class handles writing data objects to files and loading in data objects"""
def save_data_to_json_file(data, file_path):
"""Store data as json in designated file_path"""
out_file = open(file_path, 'w')
json.dump(data, out_file, indent=4)
out_file.clos... | the_stack_v2_python_sparse | new_algs/Number+theoretic+algorithms/Euclidean+algorithm/myjsonhandler.py | coolsnake/JupyterNotebook | train | 0 |
144e8bc464940711e49ac8ebb9f2c70f375f85c3 | [
"n = len(nums)\nk = k % n\nnums[:] = nums[n - k:] + nums[:n - k]\nreturn nums",
"if len(nums) <= k:\n nums.reverse()\n return nums\nnums.reverse()\nnumk, nume = (nums[:k], nums[k:])\nnumk.reverse()\nnume.reverse()\nnums[:k] = numk\nnums[k:] = nume\nreturn nums"
] | <|body_start_0|>
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + nums[:n - k]
return nums
<|end_body_0|>
<|body_start_1|>
if len(nums) <= k:
nums.reverse()
return nums
nums.reverse()
numk, nume = (nums[:k], nums[k:])
numk.reverse(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""国外大神 几行代码解决,果然是大神,但是没看懂"""
<|body_0|>
def rotate1(self, nums, k):
"""反转更好理解一点点,但是代码有问题,执行不成功"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + num... | stack_v2_sparse_classes_10k_train_005739 | 2,277 | no_license | [
{
"docstring": "国外大神 几行代码解决,果然是大神,但是没看懂",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": "反转更好理解一点点,但是代码有问题,执行不成功",
"name": "rotate1",
"signature": "def rotate1(self, nums, k)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000036 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): 国外大神 几行代码解决,果然是大神,但是没看懂
- def rotate1(self, nums, k): 反转更好理解一点点,但是代码有问题,执行不成功 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): 国外大神 几行代码解决,果然是大神,但是没看懂
- def rotate1(self, nums, k): 反转更好理解一点点,但是代码有问题,执行不成功
<|skeleton|>
class Solution:
def rotate(self, nums, k):
"""... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""国外大神 几行代码解决,果然是大神,但是没看懂"""
<|body_0|>
def rotate1(self, nums, k):
"""反转更好理解一点点,但是代码有问题,执行不成功"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
"""国外大神 几行代码解决,果然是大神,但是没看懂"""
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + nums[:n - k]
return nums
def rotate1(self, nums, k):
"""反转更好理解一点点,但是代码有问题,执行不成功"""
if len(nums) <= k:
nums.reverse()
... | the_stack_v2_python_sparse | 算法/Week_01/189. 旋转数组.py | RichieSong/algorithm | train | 0 | |
21ecfb83d98b8776b4e4f74d627a0c6d078bcfcd | [
"job_kwargs = {'trigger': self._create_trigger(trigger, trigger_args), 'executor': executor, 'func': func, 'args': tuple(args) if args is not None else (), 'kwargs': dict(kwargs) if kwargs is not None else {}, 'id': id, 'name': name, 'misfire_grace_time': misfire_grace_time, 'coalesce': coalesce, 'max_instances': m... | <|body_start_0|>
job_kwargs = {'trigger': self._create_trigger(trigger, trigger_args), 'executor': executor, 'func': func, 'args': tuple(args) if args is not None else (), 'kwargs': dict(kwargs) if kwargs is not None else {}, 'id': id, 'name': name, 'misfire_grace_time': misfire_grace_time, 'coalesce': coalesce... | MySQLScheduler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLScheduler:
def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', status=0, description='', replace_existing=False, cron_typ... | stack_v2_sparse_classes_10k_train_005740 | 2,914 | permissive | [
{
"docstring": "新增了两个属性: :param status: 任务状态 :param description: 任务描述 :return: str callback msg",
"name": "add_job",
"signature": "def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=un... | 2 | stack_v2_sparse_classes_30k_train_003121 | Implement the Python class `MySQLScheduler` described below.
Class description:
Implement the MySQLScheduler class.
Method signatures and docstrings:
- def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_... | Implement the Python class `MySQLScheduler` described below.
Class description:
Implement the MySQLScheduler class.
Method signatures and docstrings:
- def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_... | ff4d003cd0825247db4efe62db95f9245c0a303c | <|skeleton|>
class MySQLScheduler:
def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', status=0, description='', replace_existing=False, cron_typ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MySQLScheduler:
def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', status=0, description='', replace_existing=False, cron_type='operation',... | the_stack_v2_python_sparse | bspider/bcron/scheduler.py | littlebai3618/bspider | train | 2 | |
cfd404458c4ae82b964b91e6ca78123fba158d5b | [
"super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs)\nself.endpoint = 'reports'\nself.campaign_id = None\nself.report_id = None",
"self.campaign_id = campaign_id\nself.report_id = None\nreturn self._mc_client._get(url=self._build_path(campaign_id, 'abuse-reports'), **queryparams)",
"self.campaign_... | <|body_start_0|>
super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs)
self.endpoint = 'reports'
self.campaign_id = None
self.report_id = None
<|end_body_0|>
<|body_start_1|>
self.campaign_id = campaign_id
self.report_id = None
return self._mc_client.... | Get information about campaign abuse complaints. | ReportCampaignAbuseReports | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportCampaignAbuseReports:
"""Get information about campaign abuse complaints."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, campaign_id, **queryparams):
"""Get a list of abuse complaints for a specific campaign. ... | stack_v2_sparse_classes_10k_train_005741 | 1,850 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get a list of abuse complaints for a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param queryparams: T... | 3 | stack_v2_sparse_classes_30k_train_005883 | Implement the Python class `ReportCampaignAbuseReports` described below.
Class description:
Get information about campaign abuse complaints.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, campaign_id, **queryparams): Get a list of abuse complaints for ... | Implement the Python class `ReportCampaignAbuseReports` described below.
Class description:
Get information about campaign abuse complaints.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, campaign_id, **queryparams): Get a list of abuse complaints for ... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class ReportCampaignAbuseReports:
"""Get information about campaign abuse complaints."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, campaign_id, **queryparams):
"""Get a list of abuse complaints for a specific campaign. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReportCampaignAbuseReports:
"""Get information about campaign abuse complaints."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(ReportCampaignAbuseReports, self).__init__(*args, **kwargs)
self.endpoint = 'reports'
self.campaign_id = None
... | the_stack_v2_python_sparse | mailchimp3/entities/reportcampaignabusereports.py | VingtCinq/python-mailchimp | train | 190 |
8eb79998d207f97000902786ea60215a1f5151bd | [
"super().__init__(enc_dim, dec_dim, att_dim, dirac_at_first_step, discreteness)\nself.chunk_size = chunk_size\nself.chunk_energy = Energy(enc_dim, dec_dim, att_dim)\nself.unfold = nn.Unfold(kernel_size=(self.chunk_size, 1))\nself.softmax = nn.Softmax(dim=1)",
"batch_size, _ = emit_probs.size()\nframed_chunk_energ... | <|body_start_0|>
super().__init__(enc_dim, dec_dim, att_dim, dirac_at_first_step, discreteness)
self.chunk_size = chunk_size
self.chunk_energy = Energy(enc_dim, dec_dim, att_dim)
self.unfold = nn.Unfold(kernel_size=(self.chunk_size, 1))
self.softmax = nn.Softmax(dim=1)
<|end_body... | MoChA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoChA:
def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None:
"""[Monotonic Chunkwise Attention] from "Monotonic Chunkwise Attention" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW"""
... | stack_v2_sparse_classes_10k_train_005742 | 23,577 | no_license | [
{
"docstring": "[Monotonic Chunkwise Attention] from \"Monotonic Chunkwise Attention\" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW",
"name": "__init__",
"signature": "def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: fl... | 6 | stack_v2_sparse_classes_30k_train_003661 | Implement the Python class `MoChA` described below.
Class description:
Implement the MoChA class.
Method signatures and docstrings:
- def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None: [Monotonic Chunkwise Attention] from "M... | Implement the Python class `MoChA` described below.
Class description:
Implement the MoChA class.
Method signatures and docstrings:
- def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None: [Monotonic Chunkwise Attention] from "M... | 9f9a55f8020ac05b7bb84746a62a83950fe833a2 | <|skeleton|>
class MoChA:
def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None:
"""[Monotonic Chunkwise Attention] from "Monotonic Chunkwise Attention" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MoChA:
def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None:
"""[Monotonic Chunkwise Attention] from "Monotonic Chunkwise Attention" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW"""
super().__ini... | the_stack_v2_python_sparse | stt/modules/attention.py | Chung-I/tsm-rnnt | train | 4 | |
7c1440a4cbdc37ccaabbeca0341e91cbccb3b2a0 | [
"self.parser = parser\ncommand_parser.add_argument('-n', '--noprint', dest='doprint', default=True, action='store_false', help=_(\" Don't attempt to pretty print the object. This is useful if there\\n is some problem with the object and you just want to get an\\n unpickled represen... | <|body_start_0|>
self.parser = parser
command_parser.add_argument('-n', '--noprint', dest='doprint', default=True, action='store_false', help=_(" Don't attempt to pretty print the object. This is useful if there\n is some problem with the object and you just want to get an\n ... | Get information out of a queue file. | QFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QFile:
"""Get information out of a queue file."""
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
<|body_0|>
def process(self, args):
"""See `ICLISubCommand`."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = parse... | stack_v2_sparse_classes_10k_train_005743 | 3,206 | no_license | [
{
"docstring": "See `ICLISubCommand`.",
"name": "add",
"signature": "def add(self, parser, command_parser)"
},
{
"docstring": "See `ICLISubCommand`.",
"name": "process",
"signature": "def process(self, args)"
}
] | 2 | null | Implement the Python class `QFile` described below.
Class description:
Get information out of a queue file.
Method signatures and docstrings:
- def add(self, parser, command_parser): See `ICLISubCommand`.
- def process(self, args): See `ICLISubCommand`. | Implement the Python class `QFile` described below.
Class description:
Get information out of a queue file.
Method signatures and docstrings:
- def add(self, parser, command_parser): See `ICLISubCommand`.
- def process(self, args): See `ICLISubCommand`.
<|skeleton|>
class QFile:
"""Get information out of a queue... | 7edf8148e34b9f73ca6433ceb43a1770f4fa32c1 | <|skeleton|>
class QFile:
"""Get information out of a queue file."""
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
<|body_0|>
def process(self, args):
"""See `ICLISubCommand`."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QFile:
"""Get information out of a queue file."""
def add(self, parser, command_parser):
"""See `ICLISubCommand`."""
self.parser = parser
command_parser.add_argument('-n', '--noprint', dest='doprint', default=True, action='store_false', help=_(" Don't attempt to pretty ... | the_stack_v2_python_sparse | libs/Mailman/mailman/commands/cli_qfile.py | masomel/py-import-analysis | train | 1 |
580e085599250ae6ff6db02070968b11dde6bf7b | [
"self.mirror = mirror\nself.cleanLine = cleanLine\nself.Busnum = cleanLine[1]\nself.Busnam = cleanLine[2]\nself.baseKv = cleanLine[3]\nself.Id = cleanLine[4]\nself.mwCap = float(cleanLine[6].split('=')[1])\nself.droop = cleanLine[7]\nself.Gen = ltd.find.findGenOnBus(mirror, self.Busnum, self.Id)\nif self.Gen:\n ... | <|body_start_0|>
self.mirror = mirror
self.cleanLine = cleanLine
self.Busnum = cleanLine[1]
self.Busnam = cleanLine[2]
self.baseKv = cleanLine[3]
self.Id = cleanLine[4]
self.mwCap = float(cleanLine[6].split('=')[1])
self.droop = cleanLine[7]
self.G... | Agent to perform proportional governor action (droop) | pgov1Agent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pgov1Agent:
"""Agent to perform proportional governor action (droop)"""
def __init__(self, mirror, cleanLine):
"""Objects created from parseDyd, cleanLine is list of parameters"""
<|body_0|>
def stepDynamics(self):
"""Perform droop control"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_005744 | 1,524 | permissive | [
{
"docstring": "Objects created from parseDyd, cleanLine is list of parameters",
"name": "__init__",
"signature": "def __init__(self, mirror, cleanLine)"
},
{
"docstring": "Perform droop control",
"name": "stepDynamics",
"signature": "def stepDynamics(self)"
},
{
"docstring": "On... | 3 | stack_v2_sparse_classes_30k_train_006328 | Implement the Python class `pgov1Agent` described below.
Class description:
Agent to perform proportional governor action (droop)
Method signatures and docstrings:
- def __init__(self, mirror, cleanLine): Objects created from parseDyd, cleanLine is list of parameters
- def stepDynamics(self): Perform droop control
- ... | Implement the Python class `pgov1Agent` described below.
Class description:
Agent to perform proportional governor action (droop)
Method signatures and docstrings:
- def __init__(self, mirror, cleanLine): Objects created from parseDyd, cleanLine is list of parameters
- def stepDynamics(self): Perform droop control
- ... | 1bc598f3733c1369c164f54249e5f7757e6bf466 | <|skeleton|>
class pgov1Agent:
"""Agent to perform proportional governor action (droop)"""
def __init__(self, mirror, cleanLine):
"""Objects created from parseDyd, cleanLine is list of parameters"""
<|body_0|>
def stepDynamics(self):
"""Perform droop control"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class pgov1Agent:
"""Agent to perform proportional governor action (droop)"""
def __init__(self, mirror, cleanLine):
"""Objects created from parseDyd, cleanLine is list of parameters"""
self.mirror = mirror
self.cleanLine = cleanLine
self.Busnum = cleanLine[1]
self.Busna... | the_stack_v2_python_sparse | psltdsim/dynamicAgents/pgov1Agent.py | thadhaines/PSLTDSim | train | 0 |
97ba2c8dbb90199871ebead20570ddb79ccca4d5 | [
"try:\n movie_list = db.get_list_by_id(list_id=list_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('list_id %d does not exist' % list_id)\nreturn jsonify(movie_list.to_dict())",
"try:\n movie_list = db.get_list_by_id(list_id=list_id, session=session)\nexcept NoResultFound:\n raise N... | <|body_start_0|>
try:
movie_list = db.get_list_by_id(list_id=list_id, session=session)
except NoResultFound:
raise NotFoundError('list_id %d does not exist' % list_id)
return jsonify(movie_list.to_dict())
<|end_body_0|>
<|body_start_1|>
try:
movie_lis... | MovieListListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieListListAPI:
def get(self, list_id, session=None):
"""Get list by ID"""
<|body_0|>
def delete(self, list_id, session=None):
"""Delete list by ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
movie_list = db.get_list_by_id(lis... | stack_v2_sparse_classes_10k_train_005745 | 12,846 | permissive | [
{
"docstring": "Get list by ID",
"name": "get",
"signature": "def get(self, list_id, session=None)"
},
{
"docstring": "Delete list by ID",
"name": "delete",
"signature": "def delete(self, list_id, session=None)"
}
] | 2 | null | Implement the Python class `MovieListListAPI` described below.
Class description:
Implement the MovieListListAPI class.
Method signatures and docstrings:
- def get(self, list_id, session=None): Get list by ID
- def delete(self, list_id, session=None): Delete list by ID | Implement the Python class `MovieListListAPI` described below.
Class description:
Implement the MovieListListAPI class.
Method signatures and docstrings:
- def get(self, list_id, session=None): Get list by ID
- def delete(self, list_id, session=None): Delete list by ID
<|skeleton|>
class MovieListListAPI:
def g... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class MovieListListAPI:
def get(self, list_id, session=None):
"""Get list by ID"""
<|body_0|>
def delete(self, list_id, session=None):
"""Delete list by ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovieListListAPI:
def get(self, list_id, session=None):
"""Get list by ID"""
try:
movie_list = db.get_list_by_id(list_id=list_id, session=session)
except NoResultFound:
raise NotFoundError('list_id %d does not exist' % list_id)
return jsonify(movie_list.... | the_stack_v2_python_sparse | flexget/components/managed_lists/lists/movie_list/api.py | BrutuZ/Flexget | train | 1 | |
5cb1a65ccee4c54377a7f9807db036cb8486e8dc | [
"if 'n_drop' in args:\n self.n_drop = args['n_drop']\nelse:\n self.n_drop = 10\nsuper(MarginSamplingDropout, self).__init__(X, Y, unlabeled_x, net, handler, nclasses, args)",
"probs = self.predict_prob_dropout(self.unlabeled_x, self.n_drop)\nprobs_sorted, idxs = probs.sort(descending=True)\nU = probs_sorted... | <|body_start_0|>
if 'n_drop' in args:
self.n_drop = args['n_drop']
else:
self.n_drop = 10
super(MarginSamplingDropout, self).__init__(X, Y, unlabeled_x, net, handler, nclasses, args)
<|end_body_0|>
<|body_start_1|>
probs = self.predict_prob_dropout(self.unlabeled... | Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the confidence of first and the second most probable ... | MarginSamplingDropout | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarginSamplingDropout:
"""Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the ... | stack_v2_sparse_classes_10k_train_005746 | 3,247 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, X, Y, unlabeled_x, net, handler, nclasses, args={})"
},
{
"docstring": "Select next set of points Parameters ---------- budget: int Number of indexes to be returned for next set Returns ---------- U_idx: li... | 2 | stack_v2_sparse_classes_30k_val_000052 | Implement the Python class `MarginSamplingDropout` described below.
Class description:
Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin samplin... | Implement the Python class `MarginSamplingDropout` described below.
Class description:
Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin samplin... | c8c3489920a24537a849eb8446efc9c2e19ab193 | <|skeleton|>
class MarginSamplingDropout:
"""Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MarginSamplingDropout:
"""Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the confidence of... | the_stack_v2_python_sparse | distil/active_learning_strategies/margin_sampling_dropout.py | chipsh/distil | train | 1 |
86606bc769437f84b37de8eb1be2a52e0111826a | [
"for key in inparsers:\n if not key.startswith('text search parser '):\n raise KeyError('Unrecognized object type: %s' % key)\n tsp = key[19:]\n self[schema.name, tsp] = parser = TSParser(schema=schema.name, name=tsp)\n inparser = inparsers[key]\n if inparser:\n for attr, val in list(in... | <|body_start_0|>
for key in inparsers:
if not key.startswith('text search parser '):
raise KeyError('Unrecognized object type: %s' % key)
tsp = key[19:]
self[schema.name, tsp] = parser = TSParser(schema=schema.name, name=tsp)
inparser = inparsers[k... | The collection of text search parsers in a database | TSParserDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSParserDict:
"""The collection of text search parsers in a database"""
def from_map(self, schema, inparsers):
"""Initialize the dictionary of parsers by examining the input map :param schema: schema owning the parsers :param inparsers: input YAML map defining the parsers"""
... | stack_v2_sparse_classes_10k_train_005747 | 15,925 | permissive | [
{
"docstring": "Initialize the dictionary of parsers by examining the input map :param schema: schema owning the parsers :param inparsers: input YAML map defining the parsers",
"name": "from_map",
"signature": "def from_map(self, schema, inparsers)"
},
{
"docstring": "Generate SQL to transform e... | 2 | stack_v2_sparse_classes_30k_train_006892 | Implement the Python class `TSParserDict` described below.
Class description:
The collection of text search parsers in a database
Method signatures and docstrings:
- def from_map(self, schema, inparsers): Initialize the dictionary of parsers by examining the input map :param schema: schema owning the parsers :param i... | Implement the Python class `TSParserDict` described below.
Class description:
The collection of text search parsers in a database
Method signatures and docstrings:
- def from_map(self, schema, inparsers): Initialize the dictionary of parsers by examining the input map :param schema: schema owning the parsers :param i... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class TSParserDict:
"""The collection of text search parsers in a database"""
def from_map(self, schema, inparsers):
"""Initialize the dictionary of parsers by examining the input map :param schema: schema owning the parsers :param inparsers: input YAML map defining the parsers"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TSParserDict:
"""The collection of text search parsers in a database"""
def from_map(self, schema, inparsers):
"""Initialize the dictionary of parsers by examining the input map :param schema: schema owning the parsers :param inparsers: input YAML map defining the parsers"""
for key in in... | the_stack_v2_python_sparse | pyrseas/dbobject/textsearch.py | vayerx/Pyrseas | train | 1 |
5e9255ca5c4a452f1eac94b1a78829925f5f5318 | [
"super().__init__(*args, **kwargs)\nself.job_name = job_name\nself.step_name = step_name\nself.catalogue = catalogue\nself.collection = collection\nself.optional = optional or {}\nself.connection = Connection()",
"message = context['task_instance'].xcom_pull(key=context['dag_run'].run_id)\nif message is None:\n ... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.job_name = job_name
self.step_name = step_name
self.catalogue = catalogue
self.collection = collection
self.optional = optional or {}
self.connection = Connection()
<|end_body_0|>
<|body_start_1|>
me... | GOBOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GOBOperator:
def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs):
"""Initializes the GOB operator for the specific workflow"""
<|body_0|>
def execute(self, context):
"""Execute the workflow step Any messa... | stack_v2_sparse_classes_10k_train_005748 | 2,281 | no_license | [
{
"docstring": "Initializes the GOB operator for the specific workflow",
"name": "__init__",
"signature": "def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs)"
},
{
"docstring": "Execute the workflow step Any message that is the resu... | 2 | stack_v2_sparse_classes_30k_train_002331 | Implement the Python class `GOBOperator` described below.
Class description:
Implement the GOBOperator class.
Method signatures and docstrings:
- def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs): Initializes the GOB operator for the specific workflow
-... | Implement the Python class `GOBOperator` described below.
Class description:
Implement the GOBOperator class.
Method signatures and docstrings:
- def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs): Initializes the GOB operator for the specific workflow
-... | ae3bca2827a63b6c447d7117d2fb4d84fdfc6cef | <|skeleton|>
class GOBOperator:
def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs):
"""Initializes the GOB operator for the specific workflow"""
<|body_0|>
def execute(self, context):
"""Execute the workflow step Any messa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GOBOperator:
def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs):
"""Initializes the GOB operator for the specific workflow"""
super().__init__(*args, **kwargs)
self.job_name = job_name
self.step_name = step_name
... | the_stack_v2_python_sparse | src/plugins/operators/gob_operator.py | Amsterdam/GOB-Airflow | train | 0 | |
65363130424ad565487f772538a11a377156418c | [
"self.head = MyLinkedListNode()\nself.tail = MyLinkedListNode()\nself.head.next = self.tail\nself.tail.prev = self.head\nself.size = 0",
"def getFromHead(m):\n p = self.head\n while m > 0:\n m -= 1\n p = p.next\n return p.next.val\n\ndef getFromTail(m):\n p = self.tail\n while m > 0:\... | <|body_start_0|>
self.head = MyLinkedListNode()
self.tail = MyLinkedListNode()
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
<|end_body_0|>
<|body_start_1|>
def getFromHead(m):
p = self.head
while m > 0:
m -= ... | MyLinkedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyLinkedList:
def __init__(self):
"""Initialize your data structure here. Running Time: O(1)"""
<|body_0|>
def get(self, index: int) -> int:
"""Get the value of the index-th node in the linked list. If the index is invalid, return -1. Running Time: O(size of list)"""... | stack_v2_sparse_classes_10k_train_005749 | 3,989 | permissive | [
{
"docstring": "Initialize your data structure here. Running Time: O(1)",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1. Running Time: O(size of list)",
"name": "get",
"si... | 6 | stack_v2_sparse_classes_30k_train_001429 | Implement the Python class `MyLinkedList` described below.
Class description:
Implement the MyLinkedList class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here. Running Time: O(1)
- def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If ... | Implement the Python class `MyLinkedList` described below.
Class description:
Implement the MyLinkedList class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here. Running Time: O(1)
- def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If ... | 4a508a982b125a3a90ea893ae70863df7c99cc70 | <|skeleton|>
class MyLinkedList:
def __init__(self):
"""Initialize your data structure here. Running Time: O(1)"""
<|body_0|>
def get(self, index: int) -> int:
"""Get the value of the index-th node in the linked list. If the index is invalid, return -1. Running Time: O(size of list)"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyLinkedList:
def __init__(self):
"""Initialize your data structure here. Running Time: O(1)"""
self.head = MyLinkedListNode()
self.tail = MyLinkedListNode()
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def get(self, index: int) -> in... | the_stack_v2_python_sparse | solutions/707_design_linked_list.py | YiqunPeng/leetcode_pro | train | 0 | |
4afee0b10b982e669613e4a8b4a2fb402612665f | [
"actionlist = [1, 2, 3, 4, 5]\nfor action in actionlist:\n if action == 1:\n val = getColumnSelection(action)\n self.assertEqual(val, 'bookID')\n if action == 2:\n val = getColumnSelection(action)\n self.assertEqual(val, 'bookAuthor')\n if action == 3:\n val = getColumnSe... | <|body_start_0|>
actionlist = [1, 2, 3, 4, 5]
for action in actionlist:
if action == 1:
val = getColumnSelection(action)
self.assertEqual(val, 'bookID')
if action == 2:
val = getColumnSelection(action)
self.assertEqu... | Test for getting action solution | TestgetColumnSelection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestgetColumnSelection:
"""Test for getting action solution"""
def testGetColumnSolution(self):
"""This a True test to see if the column is selected"""
<|body_0|>
def testBadGetColumnSolution(self):
"""This a False test to see if the column is selected"""
... | stack_v2_sparse_classes_10k_train_005750 | 1,495 | no_license | [
{
"docstring": "This a True test to see if the column is selected",
"name": "testGetColumnSolution",
"signature": "def testGetColumnSolution(self)"
},
{
"docstring": "This a False test to see if the column is selected",
"name": "testBadGetColumnSolution",
"signature": "def testBadGetColu... | 2 | stack_v2_sparse_classes_30k_train_004410 | Implement the Python class `TestgetColumnSelection` described below.
Class description:
Test for getting action solution
Method signatures and docstrings:
- def testGetColumnSolution(self): This a True test to see if the column is selected
- def testBadGetColumnSolution(self): This a False test to see if the column i... | Implement the Python class `TestgetColumnSelection` described below.
Class description:
Test for getting action solution
Method signatures and docstrings:
- def testGetColumnSolution(self): This a True test to see if the column is selected
- def testBadGetColumnSolution(self): This a False test to see if the column i... | c9fc7f312f9d73fef6af6d13459ea4a69b16cdca | <|skeleton|>
class TestgetColumnSelection:
"""Test for getting action solution"""
def testGetColumnSolution(self):
"""This a True test to see if the column is selected"""
<|body_0|>
def testBadGetColumnSolution(self):
"""This a False test to see if the column is selected"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestgetColumnSelection:
"""Test for getting action solution"""
def testGetColumnSolution(self):
"""This a True test to see if the column is selected"""
actionlist = [1, 2, 3, 4, 5]
for action in actionlist:
if action == 1:
val = getColumnSelection(actio... | the_stack_v2_python_sparse | IT - 412/databaseAssignment/testcases/testGetColumnSelection.py | vifezue/PythonWork | train | 0 |
bdf01644535cb33f6ae5cf04df4b49544cf874b0 | [
"length = len(nums)\nif length <= 1:\n return\nk = k % length\nif k > 0:\n nums[:-k], nums[-k:] = (nums[-k:], nums[:-k])",
"if not nums:\n return\nfor _ in range(k):\n nums.insert(0, nums.pop())"
] | <|body_start_0|>
length = len(nums)
if length <= 1:
return
k = k % length
if k > 0:
nums[:-k], nums[-k:] = (nums[-k:], nums[:-k])
<|end_body_0|>
<|body_start_1|>
if not nums:
return
for _ in range(k):
nums.insert(0, nums.po... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_10k_train_005751 | 1,248 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste... | 2 | stack_v2_sparse_classes_30k_train_005317 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate1(self, nums, k): :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate1(self, nums, k): :type nums: List[in... | 3ded7bd0f046e8f87c9b9b9bce81e52ab1bdcdac | <|skeleton|>
class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify n... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
length = len(nums)
if length <= 1:
return
k = k % length
if k > 0:
nums[:-k], nums[-k:] = (nums[-k:],... | the_stack_v2_python_sparse | leetcode/arrays/rotate.py | JeanChrist/Algorithms | train | 0 | |
7e60399ac0ee75fbbbd27e7ef442eaaed5ef7a20 | [
"video_uuid = uuid.uuid1()\nsession_uuid = uuid.uuid1()\ntry:\n serializer = VideoSerializer(data=request.data, partial=True)\n serializer.is_valid(raise_exception=True)\n serializer.save(video_id=video_uuid, session_id=session_uuid)\n return Response({'status': 'success', 'code': 1}, status.HTTP_200_OK... | <|body_start_0|>
video_uuid = uuid.uuid1()
session_uuid = uuid.uuid1()
try:
serializer = VideoSerializer(data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save(video_id=video_uuid, session_id=session_uuid)
return... | Add notifications details and save in DB | Videos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Videos:
"""Add notifications details and save in DB"""
def post(request):
"""Add appointment to DB"""
<|body_0|>
def put(request):
"""This has been used for ratings"""
<|body_1|>
def notify_staff(all_tokens, message):
"""Send notification to ... | stack_v2_sparse_classes_10k_train_005752 | 20,501 | no_license | [
{
"docstring": "Add appointment to DB",
"name": "post",
"signature": "def post(request)"
},
{
"docstring": "This has been used for ratings",
"name": "put",
"signature": "def put(request)"
},
{
"docstring": "Send notification to the doctor",
"name": "notify_staff",
"signat... | 3 | stack_v2_sparse_classes_30k_train_005323 | Implement the Python class `Videos` described below.
Class description:
Add notifications details and save in DB
Method signatures and docstrings:
- def post(request): Add appointment to DB
- def put(request): This has been used for ratings
- def notify_staff(all_tokens, message): Send notification to the doctor | Implement the Python class `Videos` described below.
Class description:
Add notifications details and save in DB
Method signatures and docstrings:
- def post(request): Add appointment to DB
- def put(request): This has been used for ratings
- def notify_staff(all_tokens, message): Send notification to the doctor
<|s... | cb811523f0867a2824a39f1e70e30ed63c57f857 | <|skeleton|>
class Videos:
"""Add notifications details and save in DB"""
def post(request):
"""Add appointment to DB"""
<|body_0|>
def put(request):
"""This has been used for ratings"""
<|body_1|>
def notify_staff(all_tokens, message):
"""Send notification to ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Videos:
"""Add notifications details and save in DB"""
def post(request):
"""Add appointment to DB"""
video_uuid = uuid.uuid1()
session_uuid = uuid.uuid1()
try:
serializer = VideoSerializer(data=request.data, partial=True)
serializer.is_valid(raise_... | the_stack_v2_python_sparse | south_fitness_server/apps/videos/views.py | GransonO/south-fitness | train | 1 |
59c06aa50a5ab697676be284b760258ba33eca33 | [
"super(Encoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(input_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",... | <|body_start_0|>
super(Encoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(input_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [EncoderBlock(dm, h, hidden, drop_rate) for _ in range(N... | [summary] Args: tf ([type]): [description] | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type... | stack_v2_sparse_classes_10k_train_005753 | 1,989 | no_license | [
{
"docstring": "[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type]): [description] max_seq_len ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signat... | 2 | stack_v2_sparse_classes_30k_train_005808 | Implement the Python class `Encoder` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): [summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [descr... | Implement the Python class `Encoder` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1): [summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [descr... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class Encoder:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, N, dm, h, hidden, input_vocab, max_seq_len, drop_rate=0.1):
"""[summary] Args: N ([type]): [description] dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] input_vocab ([type]): [descript... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/9-transformer_encoder.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
5bd95bcc51b394f57115924fdfd730e0f6226a53 | [
"self.classifier = classifier\nself.regressor = regressor\nself.classFields = classFields\nself.regFields = regFields",
"y = np.ravel(y)\nposYInd = y > 0\nbinaryY = copy(y)\nbinaryY[posYInd] = 1\nx_classify = X[:, self.classFields]\ny_classify = binaryY\nif sample_weight is not None and 'sample_weight' in self.cl... | <|body_start_0|>
self.classifier = classifier
self.regressor = regressor
self.classFields = classFields
self.regFields = regFields
<|end_body_0|>
<|body_start_1|>
y = np.ravel(y)
posYInd = y > 0
binaryY = copy(y)
binaryY[posYInd] = 1
x_classify = ... | First use classification to figure out which y's are positive. Then use regression to figure out the actual values of the positive y's. | ClassifyThenRegress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifyThenRegress:
"""First use classification to figure out which y's are positive. Then use regression to figure out the actual values of the positive y's."""
def __init__(self, classifier, regressor, classFields, regFields):
""":param classifier: :param regressor: :param classFi... | stack_v2_sparse_classes_10k_train_005754 | 2,216 | no_license | [
{
"docstring": ":param classifier: :param regressor: :param classFields: array of column indicators used for classification :param regFields: array of column indicators used for regression :return:",
"name": "__init__",
"signature": "def __init__(self, classifier, regressor, classFields, regFields)"
}... | 3 | stack_v2_sparse_classes_30k_train_004725 | Implement the Python class `ClassifyThenRegress` described below.
Class description:
First use classification to figure out which y's are positive. Then use regression to figure out the actual values of the positive y's.
Method signatures and docstrings:
- def __init__(self, classifier, regressor, classFields, regFie... | Implement the Python class `ClassifyThenRegress` described below.
Class description:
First use classification to figure out which y's are positive. Then use regression to figure out the actual values of the positive y's.
Method signatures and docstrings:
- def __init__(self, classifier, regressor, classFields, regFie... | 35d20eeef168f69586b49bd87db30cbf2839beb4 | <|skeleton|>
class ClassifyThenRegress:
"""First use classification to figure out which y's are positive. Then use regression to figure out the actual values of the positive y's."""
def __init__(self, classifier, regressor, classFields, regFields):
""":param classifier: :param regressor: :param classFi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClassifyThenRegress:
"""First use classification to figure out which y's are positive. Then use regression to figure out the actual values of the positive y's."""
def __init__(self, classifier, regressor, classFields, regFields):
""":param classifier: :param regressor: :param classFields: array o... | the_stack_v2_python_sparse | Fire/ClassifyThenRegress.py | j-planet/Kaggle | train | 0 |
96e610726135a19eb6f822ee8ce941396166ac3a | [
"if not isinstance(process_num, int):\n raise ValueError('AKG kernel compiling process number must be of type int, but got {} with type {}'.format(process_num, type(wait_time)))\nif not isinstance(wait_time, int):\n raise ValueError('AKG kernel compiling wait time must be of type int, but got {} with type {}'... | <|body_start_0|>
if not isinstance(process_num, int):
raise ValueError('AKG kernel compiling process number must be of type int, but got {} with type {}'.format(process_num, type(wait_time)))
if not isinstance(wait_time, int):
raise ValueError('AKG kernel compiling wait time must... | akg kernel parallel process | AkgProcess | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AkgProcess:
"""akg kernel parallel process"""
def __init__(self, process_num, wait_time, platform):
"""Args: process_num: int. processes number wait_time: int. max time the function blocked"""
<|body_0|>
def compile(self, attrs=None):
"""compile kernel by multi p... | stack_v2_sparse_classes_10k_train_005755 | 7,760 | permissive | [
{
"docstring": "Args: process_num: int. processes number wait_time: int. max time the function blocked",
"name": "__init__",
"signature": "def __init__(self, process_num, wait_time, platform)"
},
{
"docstring": "compile kernel by multi processes Return: True for all compile success, False for so... | 3 | stack_v2_sparse_classes_30k_train_001629 | Implement the Python class `AkgProcess` described below.
Class description:
akg kernel parallel process
Method signatures and docstrings:
- def __init__(self, process_num, wait_time, platform): Args: process_num: int. processes number wait_time: int. max time the function blocked
- def compile(self, attrs=None): comp... | Implement the Python class `AkgProcess` described below.
Class description:
akg kernel parallel process
Method signatures and docstrings:
- def __init__(self, process_num, wait_time, platform): Args: process_num: int. processes number wait_time: int. max time the function blocked
- def compile(self, attrs=None): comp... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class AkgProcess:
"""akg kernel parallel process"""
def __init__(self, process_num, wait_time, platform):
"""Args: process_num: int. processes number wait_time: int. max time the function blocked"""
<|body_0|>
def compile(self, attrs=None):
"""compile kernel by multi p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AkgProcess:
"""akg kernel parallel process"""
def __init__(self, process_num, wait_time, platform):
"""Args: process_num: int. processes number wait_time: int. max time the function blocked"""
if not isinstance(process_num, int):
raise ValueError('AKG kernel compiling process ... | the_stack_v2_python_sparse | mindspore/python/mindspore/_extends/parallel_compile/akg_compiler/akg_process.py | mindspore-ai/mindspore | train | 4,178 |
d166f0e62667805b2c28b3eabb466e23329e3dde | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Campaign Budget service. Service to manage campaign budgets. | CampaignBudgetServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignBudgetServiceServicer:
"""Proto file describing the Campaign Budget service. Service to manage campaign budgets."""
def GetCampaignBudget(self, request, context):
"""Returns the requested Campaign Budget in full detail."""
<|body_0|>
def MutateCampaignBudgets(sel... | stack_v2_sparse_classes_10k_train_005756 | 5,659 | permissive | [
{
"docstring": "Returns the requested Campaign Budget in full detail.",
"name": "GetCampaignBudget",
"signature": "def GetCampaignBudget(self, request, context)"
},
{
"docstring": "Creates, updates, or removes campaign budgets. Operation statuses are returned.",
"name": "MutateCampaignBudget... | 2 | stack_v2_sparse_classes_30k_train_006156 | Implement the Python class `CampaignBudgetServiceServicer` described below.
Class description:
Proto file describing the Campaign Budget service. Service to manage campaign budgets.
Method signatures and docstrings:
- def GetCampaignBudget(self, request, context): Returns the requested Campaign Budget in full detail.... | Implement the Python class `CampaignBudgetServiceServicer` described below.
Class description:
Proto file describing the Campaign Budget service. Service to manage campaign budgets.
Method signatures and docstrings:
- def GetCampaignBudget(self, request, context): Returns the requested Campaign Budget in full detail.... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class CampaignBudgetServiceServicer:
"""Proto file describing the Campaign Budget service. Service to manage campaign budgets."""
def GetCampaignBudget(self, request, context):
"""Returns the requested Campaign Budget in full detail."""
<|body_0|>
def MutateCampaignBudgets(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CampaignBudgetServiceServicer:
"""Proto file describing the Campaign Budget service. Service to manage campaign budgets."""
def GetCampaignBudget(self, request, context):
"""Returns the requested Campaign Budget in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
co... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/campaign_budget_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
473e183c39784c3ac836b2fac5488650bb56e1c6 | [
"self.set_sys()\nself.fig = fig\nfrom wigner_normalize import WignerNormalize, WignerSymLogNorm\nimg_params = dict(extent=[self.hybrid_sys.X.min(), self.hybrid_sys.X.max(), self.hybrid_sys.P.min(), self.hybrid_sys.P.max()], origin='lower', cmap='seismic', norm=WignerSymLogNorm(linthresh=1e-07, vmin=-0.01, vmax=0.1)... | <|body_start_0|>
self.set_sys()
self.fig = fig
from wigner_normalize import WignerNormalize, WignerSymLogNorm
img_params = dict(extent=[self.hybrid_sys.X.min(), self.hybrid_sys.X.max(), self.hybrid_sys.P.min(), self.hybrid_sys.P.max()], origin='lower', cmap='seismic', norm=WignerSymLogNo... | Class to visualize the phase space dynamics in phase space. | VisualizeHybrid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualizeHybrid:
"""Class to visualize the phase space dynamics in phase space."""
def __init__(self, fig):
"""Initialize all propagators and frame :param fig: matplotlib figure object"""
<|body_0|>
def set_sys(self):
"""Initialize quantum propagator :param self:... | stack_v2_sparse_classes_10k_train_005757 | 7,316 | no_license | [
{
"docstring": "Initialize all propagators and frame :param fig: matplotlib figure object",
"name": "__init__",
"signature": "def __init__(self, fig)"
},
{
"docstring": "Initialize quantum propagator :param self: :return:",
"name": "set_sys",
"signature": "def set_sys(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_007028 | Implement the Python class `VisualizeHybrid` described below.
Class description:
Class to visualize the phase space dynamics in phase space.
Method signatures and docstrings:
- def __init__(self, fig): Initialize all propagators and frame :param fig: matplotlib figure object
- def set_sys(self): Initialize quantum pr... | Implement the Python class `VisualizeHybrid` described below.
Class description:
Class to visualize the phase space dynamics in phase space.
Method signatures and docstrings:
- def __init__(self, fig): Initialize all propagators and frame :param fig: matplotlib figure object
- def set_sys(self): Initialize quantum pr... | c247a8dc47d38435191f14bc4d71fa64ad98e008 | <|skeleton|>
class VisualizeHybrid:
"""Class to visualize the phase space dynamics in phase space."""
def __init__(self, fig):
"""Initialize all propagators and frame :param fig: matplotlib figure object"""
<|body_0|>
def set_sys(self):
"""Initialize quantum propagator :param self:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VisualizeHybrid:
"""Class to visualize the phase space dynamics in phase space."""
def __init__(self, fig):
"""Initialize all propagators and frame :param fig: matplotlib figure object"""
self.set_sys()
self.fig = fig
from wigner_normalize import WignerNormalize, WignerSym... | the_stack_v2_python_sparse | hybrid_vs_pauli.py | gharib85/QCHybrid | train | 0 |
6387e46ef6c393a7ed2a6c5f2cddf7a8efa98793 | [
"self.count = count\nself.minimum = minimum\nself.maximum = maximum\nself.character = character",
"exploded = [c for c in str]\nfor count in range(self.count):\n size = random.randint(self.minimum, self.maximum)\n position = random.randint(0, len(str) - size)\n for iIter in range(size):\n exploded... | <|body_start_0|>
self.count = count
self.minimum = minimum
self.maximum = maximum
self.character = character
<|end_body_0|>
<|body_start_1|>
exploded = [c for c in str]
for count in range(self.count):
size = random.randint(self.minimum, self.maximum)
... | Class to implement a simple fuzzer | cFuzzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cFuzzer:
"""Class to implement a simple fuzzer"""
def __init__(self, count=10, minimum=1, maximum=10, character='A'):
"""class instantiation arguments: count is the number of fuzzed sequences (i.e. overwritten bytes) produced by the fuzzer; default 10 minimum is the minimum length of... | stack_v2_sparse_classes_10k_train_005758 | 25,658 | no_license | [
{
"docstring": "class instantiation arguments: count is the number of fuzzed sequences (i.e. overwritten bytes) produced by the fuzzer; default 10 minimum is the minimum length of a fuzzed sequence; default 1 maximum is the maximum length of a fuzzed sequence; default 10 character is the character used to gener... | 2 | stack_v2_sparse_classes_30k_train_002876 | Implement the Python class `cFuzzer` described below.
Class description:
Class to implement a simple fuzzer
Method signatures and docstrings:
- def __init__(self, count=10, minimum=1, maximum=10, character='A'): class instantiation arguments: count is the number of fuzzed sequences (i.e. overwritten bytes) produced b... | Implement the Python class `cFuzzer` described below.
Class description:
Class to implement a simple fuzzer
Method signatures and docstrings:
- def __init__(self, count=10, minimum=1, maximum=10, character='A'): class instantiation arguments: count is the number of fuzzed sequences (i.e. overwritten bytes) produced b... | 8190354314d6f42c9ddc477a795029dc446176c5 | <|skeleton|>
class cFuzzer:
"""Class to implement a simple fuzzer"""
def __init__(self, count=10, minimum=1, maximum=10, character='A'):
"""class instantiation arguments: count is the number of fuzzed sequences (i.e. overwritten bytes) produced by the fuzzer; default 10 minimum is the minimum length of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class cFuzzer:
"""Class to implement a simple fuzzer"""
def __init__(self, count=10, minimum=1, maximum=10, character='A'):
"""class instantiation arguments: count is the number of fuzzed sequences (i.e. overwritten bytes) produced by the fuzzer; default 10 minimum is the minimum length of a fuzzed seq... | the_stack_v2_python_sparse | mPDF.py | DidierStevens/DidierStevensSuite | train | 1,670 |
b558a76131e8bcbc35b033bb3809cea087f2641b | [
"if model._meta.app_label == 'orion_flash':\n return 'orion_aux_db'\nreturn None",
"if model._meta.app_label == 'orion_flash':\n return 'orion_aux_db'\nreturn None",
"if obj1._state.db == 'orion_aux_db' and obj2._state.db == 'orion_aux_db':\n return True\nreturn None",
"if app_label == 'orion_flash':... | <|body_start_0|>
if model._meta.app_label == 'orion_flash':
return 'orion_aux_db'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'orion_flash':
return 'orion_aux_db'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._state.db =... | database router class for the orion auxiliary database | OrionAuxRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrionAuxRouter:
"""database router class for the orion auxiliary database"""
def db_for_read(self, model, **hints):
"""all models in orion_flash will read from the orion auxiliary database"""
<|body_0|>
def db_for_write(self, model, **hints):
"""all models in ori... | stack_v2_sparse_classes_10k_train_005759 | 1,525 | no_license | [
{
"docstring": "all models in orion_flash will read from the orion auxiliary database",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "all models in orion_flash will write to the orion auxiliary database",
"name": "db_for_write",
"signature... | 4 | null | Implement the Python class `OrionAuxRouter` described below.
Class description:
database router class for the orion auxiliary database
Method signatures and docstrings:
- def db_for_read(self, model, **hints): all models in orion_flash will read from the orion auxiliary database
- def db_for_write(self, model, **hint... | Implement the Python class `OrionAuxRouter` described below.
Class description:
database router class for the orion auxiliary database
Method signatures and docstrings:
- def db_for_read(self, model, **hints): all models in orion_flash will read from the orion auxiliary database
- def db_for_write(self, model, **hint... | 08bf0cc90e4d63a84fcd4e35bf5d196430c43319 | <|skeleton|>
class OrionAuxRouter:
"""database router class for the orion auxiliary database"""
def db_for_read(self, model, **hints):
"""all models in orion_flash will read from the orion auxiliary database"""
<|body_0|>
def db_for_write(self, model, **hints):
"""all models in ori... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrionAuxRouter:
"""database router class for the orion auxiliary database"""
def db_for_read(self, model, **hints):
"""all models in orion_flash will read from the orion auxiliary database"""
if model._meta.app_label == 'orion_flash':
return 'orion_aux_db'
return None
... | the_stack_v2_python_sparse | orion_flash/router.py | PHSAServiceOperationsCenter/PHSA-SOC | train | 0 |
087fb15d89b20082e4aadd1a7d01c3f173f25b07 | [
"res = requests.get(url=self.url, params=self.para, headers=self.headers)\nresult = res.json()\nself.assertEqual(res.status_code, 200)\nif len(result) == 1:\n self.assertIn('b-2', result[0]['name'])\n self.assertEqual(1, result[0]['language_type'])\nelif len(result) > 1:\n self.assertIn('work_id', result[0... | <|body_start_0|>
res = requests.get(url=self.url, params=self.para, headers=self.headers)
result = res.json()
self.assertEqual(res.status_code, 200)
if len(result) == 1:
self.assertIn('b-2', result[0]['name'])
self.assertEqual(1, result[0]['language_type'])
... | 搜索云端作品 | Search_file | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Search_file:
"""搜索云端作品"""
def test_06_search_file01(self):
"""登录态正常--进行作品搜索"""
<|body_0|>
def test_07_search_file02(self):
"""登录态失效--进行作品搜搜"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = requests.get(url=self.url, params=self.para, header... | stack_v2_sparse_classes_10k_train_005760 | 1,854 | no_license | [
{
"docstring": "登录态正常--进行作品搜索",
"name": "test_06_search_file01",
"signature": "def test_06_search_file01(self)"
},
{
"docstring": "登录态失效--进行作品搜搜",
"name": "test_07_search_file02",
"signature": "def test_07_search_file02(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003373 | Implement the Python class `Search_file` described below.
Class description:
搜索云端作品
Method signatures and docstrings:
- def test_06_search_file01(self): 登录态正常--进行作品搜索
- def test_07_search_file02(self): 登录态失效--进行作品搜搜 | Implement the Python class `Search_file` described below.
Class description:
搜索云端作品
Method signatures and docstrings:
- def test_06_search_file01(self): 登录态正常--进行作品搜索
- def test_07_search_file02(self): 登录态失效--进行作品搜搜
<|skeleton|>
class Search_file:
"""搜索云端作品"""
def test_06_search_file01(self):
"""登录态... | e75039fcd2361977a2a5dc7ea95b7fb2fbc96bb0 | <|skeleton|>
class Search_file:
"""搜索云端作品"""
def test_06_search_file01(self):
"""登录态正常--进行作品搜索"""
<|body_0|>
def test_07_search_file02(self):
"""登录态失效--进行作品搜搜"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Search_file:
"""搜索云端作品"""
def test_06_search_file01(self):
"""登录态正常--进行作品搜索"""
res = requests.get(url=self.url, params=self.para, headers=self.headers)
result = res.json()
self.assertEqual(res.status_code, 200)
if len(result) == 1:
self.assertIn('b-2', ... | the_stack_v2_python_sparse | API_study/Wood/C_Search_file.py | JmeterChen/api_wood | train | 1 |
b837c1414ace1a5cc77be7187b5b71198cc56783 | [
"self.images_path = images_path\nself.masks_path = masks_path\nself.sort_flag = sort_flag",
"masks_path = self.masks_path\nif self.sort_flag:\n masks_path = sorted(masks_path)\nmasks_pixes_num = list()\nfor index, mask_path in enumerate(masks_path):\n mask_pixes_num = self.cal_mask_pixes(mask_path)\n mas... | <|body_start_0|>
self.images_path = images_path
self.masks_path = masks_path
self.sort_flag = sort_flag
<|end_body_0|>
<|body_start_1|>
masks_path = self.masks_path
if self.sort_flag:
masks_path = sorted(masks_path)
masks_pixes_num = list()
for index,... | DatasetsStatic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetsStatic:
def __init__(self, images_path, masks_path, sort_flag=False):
"""Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序"""
<|body_0|>
def mask_static_level(self, level=16):
"""依照掩膜的大小,按照指定的等级数对各样本包含的掩膜进行分级"""
... | stack_v2_sparse_classes_10k_train_005761 | 20,672 | no_license | [
{
"docstring": "Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序",
"name": "__init__",
"signature": "def __init__(self, images_path, masks_path, sort_flag=False)"
},
{
"docstring": "依照掩膜的大小,按照指定的等级数对各样本包含的掩膜进行分级",
"name": "mask_static_level",
... | 6 | stack_v2_sparse_classes_30k_train_000162 | Implement the Python class `DatasetsStatic` described below.
Class description:
Implement the DatasetsStatic class.
Method signatures and docstrings:
- def __init__(self, images_path, masks_path, sort_flag=False): Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序
- def mask... | Implement the Python class `DatasetsStatic` described below.
Class description:
Implement the DatasetsStatic class.
Method signatures and docstrings:
- def __init__(self, images_path, masks_path, sort_flag=False): Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序
- def mask... | 7ff0bbcc223b16d63cf1c74ef7f20cd2025f1608 | <|skeleton|>
class DatasetsStatic:
def __init__(self, images_path, masks_path, sort_flag=False):
"""Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序"""
<|body_0|>
def mask_static_level(self, level=16):
"""依照掩膜的大小,按照指定的等级数对各样本包含的掩膜进行分级"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DatasetsStatic:
def __init__(self, images_path, masks_path, sort_flag=False):
"""Args: data_root: 数据集的根目录 image_folder: 样本文件夹名 mask_folder: 掩膜文件夹名 sort_flag: bool,是否对样本路径进行排序"""
self.images_path = images_path
self.masks_path = masks_path
self.sort_flag = sort_flag
def mask... | the_stack_v2_python_sparse | dataset.py | jiudawn/hualu_segmentation_jiuda | train | 0 | |
ce0e00663ad3f0a622b5112d516c0316df177f2f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PrincipalResourceMembershipsScope()",
"from .access_review_scope import AccessReviewScope\nfrom .access_review_scope import AccessReviewScope\nfields: Dict[str, Callable[[Any], None]] = {'principalScopes': lambda n: setattr(self, 'prin... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PrincipalResourceMembershipsScope()
<|end_body_0|>
<|body_start_1|>
from .access_review_scope import AccessReviewScope
from .access_review_scope import AccessReviewScope
fields: ... | PrincipalResourceMembershipsScope | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrincipalResourceMembershipsScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrincipalResourceMembershipsScope:
"""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_005762 | 2,713 | 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: PrincipalResourceMembershipsScope",
"name": "create_from_discriminator_value",
"signature": "def create_from... | 3 | stack_v2_sparse_classes_30k_train_002819 | Implement the Python class `PrincipalResourceMembershipsScope` described below.
Class description:
Implement the PrincipalResourceMembershipsScope class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrincipalResourceMembershipsScope: Creates a new in... | Implement the Python class `PrincipalResourceMembershipsScope` described below.
Class description:
Implement the PrincipalResourceMembershipsScope class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrincipalResourceMembershipsScope: Creates a new in... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PrincipalResourceMembershipsScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrincipalResourceMembershipsScope:
"""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 PrincipalResourceMembershipsScope:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PrincipalResourceMembershipsScope:
"""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/principal_resource_memberships_scope.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
587d070a75f5f7c30eb435099c134272250066ab | [
"super().__init__(input_name=input_name, output_names=[output_name])\nself.min_value = min_value\nself.max_value = max_value",
"with tf.name_scope('Clip'):\n input = input[self.input_name]\n result = tf.clip_by_value(input, self.min_value, self.max_value)\n return ([result], self.output_names)"
] | <|body_start_0|>
super().__init__(input_name=input_name, output_names=[output_name])
self.min_value = min_value
self.max_value = max_value
<|end_body_0|>
<|body_start_1|>
with tf.name_scope('Clip'):
input = input[self.input_name]
result = tf.clip_by_value(input, ... | The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset. | ClipByValue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClipByValue:
"""The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset."""
def __init__(self, min_value=0.0, max_value=1.0, input_name='image', output_name='image'):
... | stack_v2_sparse_classes_10k_train_005763 | 1,509 | permissive | [
{
"docstring": "Constructor, initialize member variables. :param max_value : The allowed min_value. :param max_value : The allowed max_value. :param input_name: (String) The name of the input to apply this operation. \"image\" by default. :param output_name: (String) The name of the output where this operation ... | 2 | stack_v2_sparse_classes_30k_train_005949 | Implement the Python class `ClipByValue` described below.
Class description:
The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset.
Method signatures and docstrings:
- def __init__(self, min_value=0.... | Implement the Python class `ClipByValue` described below.
Class description:
The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset.
Method signatures and docstrings:
- def __init__(self, min_value=0.... | 6907ae5781765f56a8492bfba594bfb3b9987f29 | <|skeleton|>
class ClipByValue:
"""The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset."""
def __init__(self, min_value=0.0, max_value=1.0, input_name='image', output_name='image'):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClipByValue:
"""The ClipByValue clips the input values to the given range. :Attributes: min_value: (Integer) The min_value of the dataset. max_value: (Integer) The max_value of the dataset."""
def __init__(self, min_value=0.0, max_value=1.0, input_name='image', output_name='image'):
"""Constructo... | the_stack_v2_python_sparse | Preprocessing_Component/Preprocessing/ClipByValue.py | BonifazStuhr/OFM | train | 0 |
97271746905bc2279b8bb3cb5d5cccbec4fa5093 | [
"def construct(start, end):\n if start > end:\n return None\n if start == end:\n return Node(None, None, start, start, end, nums[start])\n mid = (start + end) // 2\n l, r = (construct(start, mid), construct(mid + 1, end))\n return Node(l, r, start, mid, end, l.val + r.val)\nself.root = ... | <|body_start_0|>
def construct(start, end):
if start > end:
return None
if start == end:
return Node(None, None, start, start, end, nums[start])
mid = (start + end) // 2
l, r = (construct(start, mid), construct(mid + 1, end))
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k_train_005764 | 4,459 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 36d7f9e967a62db77622e0888f61999d7f37579a | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
def construct(start, end):
if start > end:
return None
if start == end:
return Node(None, None, start, start, end, nums[start])
mid = (start + end) // 2
... | the_stack_v2_python_sparse | P0307.py | westgate458/LeetCode | train | 0 | |
ca3e6c50ee6c12dfed3588318923f3633bf9dc9a | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | ObservacionCyTGList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservacionCyTGList:
def get(self):
"""To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (CyTG (resultados))."""
<|body_1... | stack_v2_sparse_classes_10k_train_005765 | 18,120 | no_license | [
{
"docstring": "To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "To create an observation (CyTG (resultados)).",
"name": "post",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_004590 | Implement the Python class `ObservacionCyTGList` described below.
Class description:
Implement the ObservacionCyTGList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(... | Implement the Python class `ObservacionCyTGList` described below.
Class description:
Implement the ObservacionCyTGList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ObservacionCyTGList:
def get(self):
"""To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (CyTG (resultados))."""
<|body_1... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObservacionCyTGList:
def get(self):
"""To fetch several observations (CyTG (resultados)). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/observaciones_ires_cytg.py | Telematica/knight-rider | train | 1 | |
bd39b9c0fc423a30003a5ff0ff5555f01e9e8a6d | [
"self.length = len(nums)\nself.Map = dict()\nfor i in range(self.length):\n if nums[i] != 0:\n self.Map[i] = nums[i]",
"res = 0\nfor i in range(self.length):\n if i in self.Map and i in vec.Map:\n res += self.Map[i] * vec.Map[i]\nreturn res"
] | <|body_start_0|>
self.length = len(nums)
self.Map = dict()
for i in range(self.length):
if nums[i] != 0:
self.Map[i] = nums[i]
<|end_body_0|>
<|body_start_1|>
res = 0
for i in range(self.length):
if i in self.Map and i in vec.Map:
... | SparseVector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.length = len(nums)
self.Map = dict()
... | stack_v2_sparse_classes_10k_train_005766 | 741 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type vec: 'SparseVector' :rtype: int",
"name": "dotProduct",
"signature": "def dotProduct(self, vec)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002951 | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int | Implement the Python class `SparseVector` described below.
Class description:
Implement the SparseVector class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def dotProduct(self, vec): :type vec: 'SparseVector' :rtype: int
<|skeleton|>
class SparseVector:
def __init__(sel... | 8a82905d40b882b20a9b6f862942f8f3e4bebcf0 | <|skeleton|>
class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SparseVector:
def __init__(self, nums):
""":type nums: List[int]"""
self.length = len(nums)
self.Map = dict()
for i in range(self.length):
if nums[i] != 0:
self.Map[i] = nums[i]
def dotProduct(self, vec):
""":type vec: 'SparseVector' :rt... | the_stack_v2_python_sparse | ByTags/Others/1570. Dot Product of Two Sparse Vectors.py | lynkeib/LeetCode | train | 0 | |
d8fc6ba514bf61adc45fe99f0f337681653d729f | [
"uri = 'http://'\nresource = f'{uri}{host}{ENDPOINT}'\nself._request = requests.Request('GET', resource).prepare()\nself.raw_data = None\nself.conditions = conditions\nself.data = {ATTR_CURRENT_VERSION: None, ATTR_NEW_VERSION: None, ATTR_UPTIME: None, ATTR_LAST_RESTART: None, ATTR_LOCAL_IP: None, ATTR_STATUS: None}... | <|body_start_0|>
uri = 'http://'
resource = f'{uri}{host}{ENDPOINT}'
self._request = requests.Request('GET', resource).prepare()
self.raw_data = None
self.conditions = conditions
self.data = {ATTR_CURRENT_VERSION: None, ATTR_NEW_VERSION: None, ATTR_UPTIME: None, ATTR_LAST... | Get the latest data and update the states. | GoogleWifiAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleWifiAPI:
"""Get the latest data and update the states."""
def __init__(self, host, conditions):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from the router."""
<|body_1|>
def data_format(self):
... | stack_v2_sparse_classes_10k_train_005767 | 7,466 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, host, conditions)"
},
{
"docstring": "Get the latest data from the router.",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Format raw data into easily accessi... | 3 | stack_v2_sparse_classes_30k_train_002957 | Implement the Python class `GoogleWifiAPI` described below.
Class description:
Get the latest data and update the states.
Method signatures and docstrings:
- def __init__(self, host, conditions): Initialize the data object.
- def update(self): Get the latest data from the router.
- def data_format(self): Format raw d... | Implement the Python class `GoogleWifiAPI` described below.
Class description:
Get the latest data and update the states.
Method signatures and docstrings:
- def __init__(self, host, conditions): Initialize the data object.
- def update(self): Get the latest data from the router.
- def data_format(self): Format raw d... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class GoogleWifiAPI:
"""Get the latest data and update the states."""
def __init__(self, host, conditions):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from the router."""
<|body_1|>
def data_format(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoogleWifiAPI:
"""Get the latest data and update the states."""
def __init__(self, host, conditions):
"""Initialize the data object."""
uri = 'http://'
resource = f'{uri}{host}{ENDPOINT}'
self._request = requests.Request('GET', resource).prepare()
self.raw_data = N... | the_stack_v2_python_sparse | homeassistant/components/google_wifi/sensor.py | home-assistant/core | train | 35,501 |
5f91f428235bb57d6fb884366cacf1365c6a02ca | [
"self.dst_site_name = dst_site_name\nself.dst_site_uuid = dst_site_uuid\nself.dst_site_web_url = dst_site_web_url\nself.parent_source_sharepoint_domain_name = parent_source_sharepoint_domain_name\nself.restore_template = restore_template\nself.restore_to_original = restore_to_original\nself.site_owner_vec = site_ow... | <|body_start_0|>
self.dst_site_name = dst_site_name
self.dst_site_uuid = dst_site_uuid
self.dst_site_web_url = dst_site_web_url
self.parent_source_sharepoint_domain_name = parent_source_sharepoint_domain_name
self.restore_template = restore_template
self.restore_to_origin... | Implementation of the 'RestoreSiteParams' model. TODO: type description here. Attributes: dst_site_name (string): Entity name of target site in case of sharepoint restore. dst_site_uuid (string): Entity uuid of target site in case of sharepoint restore. dst_site_web_url (string): Entity web url of target site in case o... | RestoreSiteParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreSiteParams:
"""Implementation of the 'RestoreSiteParams' model. TODO: type description here. Attributes: dst_site_name (string): Entity name of target site in case of sharepoint restore. dst_site_uuid (string): Entity uuid of target site in case of sharepoint restore. dst_site_web_url (str... | stack_v2_sparse_classes_10k_train_005768 | 9,050 | permissive | [
{
"docstring": "Constructor for the RestoreSiteParams class",
"name": "__init__",
"signature": "def __init__(self, dst_site_name=None, dst_site_uuid=None, dst_site_web_url=None, parent_source_sharepoint_domain_name=None, restore_template=None, restore_to_original=None, site_owner_vec=None, site_result=N... | 2 | stack_v2_sparse_classes_30k_train_002128 | Implement the Python class `RestoreSiteParams` described below.
Class description:
Implementation of the 'RestoreSiteParams' model. TODO: type description here. Attributes: dst_site_name (string): Entity name of target site in case of sharepoint restore. dst_site_uuid (string): Entity uuid of target site in case of sh... | Implement the Python class `RestoreSiteParams` described below.
Class description:
Implementation of the 'RestoreSiteParams' model. TODO: type description here. Attributes: dst_site_name (string): Entity name of target site in case of sharepoint restore. dst_site_uuid (string): Entity uuid of target site in case of sh... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreSiteParams:
"""Implementation of the 'RestoreSiteParams' model. TODO: type description here. Attributes: dst_site_name (string): Entity name of target site in case of sharepoint restore. dst_site_uuid (string): Entity uuid of target site in case of sharepoint restore. dst_site_web_url (str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreSiteParams:
"""Implementation of the 'RestoreSiteParams' model. TODO: type description here. Attributes: dst_site_name (string): Entity name of target site in case of sharepoint restore. dst_site_uuid (string): Entity uuid of target site in case of sharepoint restore. dst_site_web_url (string): Entity ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_site_params.py | cohesity/management-sdk-python | train | 24 |
e81e18aa13fb0357b03757d63f0797c3406be96d | [
"self.config = {} if config is None else config\nray_ctx = OrcaRayContext.get()\nif 'batch_size' in self.config:\n from bigdl.dllib.utils.log4Error import invalidInputError\n invalidInputError(False, 'Please do not specify batch_size in config. Input batch_size in the fit/evaluate function of the estimator in... | <|body_start_0|>
self.config = {} if config is None else config
ray_ctx = OrcaRayContext.get()
if 'batch_size' in self.config:
from bigdl.dllib.utils.log4Error import invalidInputError
invalidInputError(False, 'Please do not specify batch_size in config. Input batch_size ... | TFEstimator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFEstimator:
def __init__(self, model_fn: Callable, model_dir: Optional[str]=None, config: Optional[Dict[str, Any]]=None, params: Optional[Dict[str, Any]]=None, warm_start_from: Optional[str]=None, workers_per_node: int=1, cpu_binding: bool=False) -> None:
""":param model_fn: Model funct... | stack_v2_sparse_classes_10k_train_005769 | 7,121 | permissive | [
{
"docstring": ":param model_fn: Model function. Follows the signature: * Args: * `features`: This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single `tf.Tensor` or `dict` of same. * `labels`: This is the second item returned from the `input_fn` ... | 2 | stack_v2_sparse_classes_30k_train_002741 | Implement the Python class `TFEstimator` described below.
Class description:
Implement the TFEstimator class.
Method signatures and docstrings:
- def __init__(self, model_fn: Callable, model_dir: Optional[str]=None, config: Optional[Dict[str, Any]]=None, params: Optional[Dict[str, Any]]=None, warm_start_from: Optiona... | Implement the Python class `TFEstimator` described below.
Class description:
Implement the TFEstimator class.
Method signatures and docstrings:
- def __init__(self, model_fn: Callable, model_dir: Optional[str]=None, config: Optional[Dict[str, Any]]=None, params: Optional[Dict[str, Any]]=None, warm_start_from: Optiona... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class TFEstimator:
def __init__(self, model_fn: Callable, model_dir: Optional[str]=None, config: Optional[Dict[str, Any]]=None, params: Optional[Dict[str, Any]]=None, warm_start_from: Optional[str]=None, workers_per_node: int=1, cpu_binding: bool=False) -> None:
""":param model_fn: Model funct... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TFEstimator:
def __init__(self, model_fn: Callable, model_dir: Optional[str]=None, config: Optional[Dict[str, Any]]=None, params: Optional[Dict[str, Any]]=None, warm_start_from: Optional[str]=None, workers_per_node: int=1, cpu_binding: bool=False) -> None:
""":param model_fn: Model function. Follows t... | the_stack_v2_python_sparse | python/orca/src/bigdl/orca/learn/tf/tf_estimator.py | intel-analytics/BigDL | train | 4,913 | |
3d253f2c18f28956acc91f103fa970ccf1a9e4b8 | [
"self.sess = tf.Session()\nvocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)\nself.vocab, self.rev_vocab = data_utils.initialize_vocabulary(vocab_path)\nself.model = model_utils.create_model(self.sess, True)\nself.model.batch_size = 1",
"token_ids = data_utils.sentence_to_token_ids(sentenc... | <|body_start_0|>
self.sess = tf.Session()
vocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)
self.vocab, self.rev_vocab = data_utils.initialize_vocabulary(vocab_path)
self.model = model_utils.create_model(self.sess, True)
self.model.batch_size = 1
<|end_bod... | ChatBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
<|body_0|>
def respond(self, sentence):
"""Talk with the chatbot! Args: sentence... | stack_v2_sparse_classes_10k_train_005770 | 2,435 | no_license | [
{
"docstring": "Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Talk with the chatbot! Args: sentence: Sentence to be... | 2 | stack_v2_sparse_classes_30k_train_003685 | Implement the Python class `ChatBot` described below.
Class description:
Implement the ChatBot class.
Method signatures and docstrings:
- def __init__(self): Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.
- def re... | Implement the Python class `ChatBot` described below.
Class description:
Implement the ChatBot class.
Method signatures and docstrings:
- def __init__(self): Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.
- def re... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
<|body_0|>
def respond(self, sentence):
"""Talk with the chatbot! Args: sentence... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
self.sess = tf.Session()
vocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)
... | the_stack_v2_python_sparse | python/gelsto_SpeakEasy-AI/SpeakEasy-AI-master/model/chat_bot.py | LiuFang816/SALSTM_py_data | train | 10 | |
b5371f51b07fe45358efd0dc8ef11e3cf917c67c | [
"bpm = env.job_generator.buffer_processing_matrix\nassert np.all(np.sum(np.where(bpm < 0, -1, 0), axis=0) >= -1), f'Buffer processing matrix not allowed: {bpm}.Current version only works for networks where each activity drains exactly one buffer (i.e., only works for scheduling and/or routing).'\nif weight_per_buff... | <|body_start_0|>
bpm = env.job_generator.buffer_processing_matrix
assert np.all(np.sum(np.where(bpm < 0, -1, 0), axis=0) >= -1), f'Buffer processing matrix not allowed: {bpm}.Current version only works for networks where each activity drains exactly one buffer (i.e., only works for scheduling and/or rou... | MaxWeightAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxWeightAgent:
def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None:
"""MaxWeight policy based on Chapter 6.4 (CTCN book online ... | stack_v2_sparse_classes_10k_train_005771 | 7,371 | permissive | [
{
"docstring": "MaxWeight policy based on Chapter 6.4 (CTCN book online edition). This only works for scheduling and routing problems, where each activity drains only one buffer. NOTE: in case of a buffer managed by multiple resources, the job_conservation_flag has to be True otherwise the buffer may have negat... | 3 | stack_v2_sparse_classes_30k_train_006967 | Implement the Python class `MaxWeightAgent` described below.
Class description:
Implement the MaxWeightAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int... | Implement the Python class `MaxWeightAgent` described below.
Class description:
Implement the MaxWeightAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int... | b067eebaa5b57a96efdaed5796aca9f157d32214 | <|skeleton|>
class MaxWeightAgent:
def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None:
"""MaxWeight policy based on Chapter 6.4 (CTCN book online ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MaxWeightAgent:
def __init__(self, env: crw.ControlledRandomWalk, weight_per_buffer: Optional[Union[str, types.StateSpace]]=None, name: str='MaxWeightAgent', agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None:
"""MaxWeight policy based on Chapter 6.4 (CTCN book online edition). This... | the_stack_v2_python_sparse | src/snc/agents/maxweight_variants/maxweight_agent.py | stochasticnetworkcontrol/snc | train | 9 | |
fffed213ed11b43a5328b06caca1320208cf87be | [
"queryset = self.get_queryset()\nslug = self.kwargs.get(self.slug_url_kwarg)\nif slug is not None:\n slug_field = self.get_slug_field()\n queryset = queryset.filter(**{slug_field: slug})\n try:\n part = queryset.get()\n return part\n except queryset.model.MultipleObjectsReturned:\n ... | <|body_start_0|>
queryset = self.get_queryset()
slug = self.kwargs.get(self.slug_url_kwarg)
if slug is not None:
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
try:
part = queryset.get()
retu... | Part detail view using the IPN (internal part number) of the Part as the lookup field | PartDetailFromIPN | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartDetailFromIPN:
"""Part detail view using the IPN (internal part number) of the Part as the lookup field"""
def get_object(self):
"""Return Part object which IPN field matches the slug value."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Attempt to... | stack_v2_sparse_classes_10k_train_005772 | 28,283 | permissive | [
{
"docstring": "Return Part object which IPN field matches the slug value.",
"name": "get_object",
"signature": "def get_object(self)"
},
{
"docstring": "Attempt to match slug to a Part, else redirect to PartIndex view.",
"name": "get",
"signature": "def get(self, request, *args, **kwarg... | 2 | stack_v2_sparse_classes_30k_train_005159 | Implement the Python class `PartDetailFromIPN` described below.
Class description:
Part detail view using the IPN (internal part number) of the Part as the lookup field
Method signatures and docstrings:
- def get_object(self): Return Part object which IPN field matches the slug value.
- def get(self, request, *args, ... | Implement the Python class `PartDetailFromIPN` described below.
Class description:
Part detail view using the IPN (internal part number) of the Part as the lookup field
Method signatures and docstrings:
- def get_object(self): Return Part object which IPN field matches the slug value.
- def get(self, request, *args, ... | 5a08ef908dd5344b4433436a4679d122f7f99e41 | <|skeleton|>
class PartDetailFromIPN:
"""Part detail view using the IPN (internal part number) of the Part as the lookup field"""
def get_object(self):
"""Return Part object which IPN field matches the slug value."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Attempt to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PartDetailFromIPN:
"""Part detail view using the IPN (internal part number) of the Part as the lookup field"""
def get_object(self):
"""Return Part object which IPN field matches the slug value."""
queryset = self.get_queryset()
slug = self.kwargs.get(self.slug_url_kwarg)
... | the_stack_v2_python_sparse | InvenTree/part/views.py | onurtatli/InvenTree | train | 0 |
075efe6c69f40c5e570dcf58922baac64df2a62c | [
"Layer.__init__(self)\nself.units_per_cell = units_per_cell\nself.is_sequence_output = is_sequence_output\nself.return_states = return_states\nself.with_prev_output = with_prev_output\nself.n_cells = time_steps\nself.n_output = n_output\nself.f_out = f_out\nself.input_keep_prob = 0.8\nself.state_keep_prob = 0.8\nse... | <|body_start_0|>
Layer.__init__(self)
self.units_per_cell = units_per_cell
self.is_sequence_output = is_sequence_output
self.return_states = return_states
self.with_prev_output = with_prev_output
self.n_cells = time_steps
self.n_output = n_output
self.f_ou... | RNNLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNLayer:
def __init__(self, units_per_cell, is_sequence_output=True, return_states=False, with_prev_output=True, time_steps=1, n_output=1, f_out='identity', seed=42):
"""Initialization of RNN layer Args: units_per_cell: the number of units per RNN Cell is_sequence_output: whether the mo... | stack_v2_sparse_classes_10k_train_005773 | 3,650 | no_license | [
{
"docstring": "Initialization of RNN layer Args: units_per_cell: the number of units per RNN Cell is_sequence_output: whether the model outputs a sequence return_states: whether to return the states with_prev_output: whether the model uses the previous cell output n_output: the output dimension f_out: the acti... | 2 | stack_v2_sparse_classes_30k_train_005906 | Implement the Python class `RNNLayer` described below.
Class description:
Implement the RNNLayer class.
Method signatures and docstrings:
- def __init__(self, units_per_cell, is_sequence_output=True, return_states=False, with_prev_output=True, time_steps=1, n_output=1, f_out='identity', seed=42): Initialization of RN... | Implement the Python class `RNNLayer` described below.
Class description:
Implement the RNNLayer class.
Method signatures and docstrings:
- def __init__(self, units_per_cell, is_sequence_output=True, return_states=False, with_prev_output=True, time_steps=1, n_output=1, f_out='identity', seed=42): Initialization of RN... | 6d4bf69dc8d7524f966a3e28affc5d9f845e50e6 | <|skeleton|>
class RNNLayer:
def __init__(self, units_per_cell, is_sequence_output=True, return_states=False, with_prev_output=True, time_steps=1, n_output=1, f_out='identity', seed=42):
"""Initialization of RNN layer Args: units_per_cell: the number of units per RNN Cell is_sequence_output: whether the mo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNNLayer:
def __init__(self, units_per_cell, is_sequence_output=True, return_states=False, with_prev_output=True, time_steps=1, n_output=1, f_out='identity', seed=42):
"""Initialization of RNN layer Args: units_per_cell: the number of units per RNN Cell is_sequence_output: whether the model outputs a ... | the_stack_v2_python_sparse | src/model/sequence_model/classRNNLayer.py | dorianb/ML_toolkit | train | 0 | |
2328ea021016837fb5391277e2d0e8bc9a646ad8 | [
"import heapq\ndummy = ListNode(0)\np = dummy\nhead = []\nfor i in range(len(lists)):\n if lists[i]:\n heapq.heappush(head, (lists[i].val, i))\n lists[i] = lists[i].next\nwhile head:\n val, idx = heapq.heappop(head)\n p.next = ListNode(val)\n p = p.next\n if lists[idx]:\n heapq.h... | <|body_start_0|>
import heapq
dummy = ListNode(0)
p = dummy
head = []
for i in range(len(lists)):
if lists[i]:
heapq.heappush(head, (lists[i].val, i))
lists[i] = lists[i].next
while head:
val, idx = heapq.heappop(hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""官网解法,使用基于堆的优先级队列 :param lists: :return:"""
<|body_0|>
def showNode(self, node: ListNode) -> list:
"""show all value of ListNode :param node: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_005774 | 3,032 | no_license | [
{
"docstring": "官网解法,使用基于堆的优先级队列 :param lists: :return:",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists: [ListNode]) -> ListNode"
},
{
"docstring": "show all value of ListNode :param node: :return:",
"name": "showNode",
"signature": "def showNode(self, node: ListNode) ... | 2 | stack_v2_sparse_classes_30k_train_006872 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: [ListNode]) -> ListNode: 官网解法,使用基于堆的优先级队列 :param lists: :return:
- def showNode(self, node: ListNode) -> list: show all value of ListNode :param node... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: [ListNode]) -> ListNode: 官网解法,使用基于堆的优先级队列 :param lists: :return:
- def showNode(self, node: ListNode) -> list: show all value of ListNode :param node... | fa45cd44c3d4e7b0205833efcdc708d1638cbbe4 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""官网解法,使用基于堆的优先级队列 :param lists: :return:"""
<|body_0|>
def showNode(self, node: ListNode) -> list:
"""show all value of ListNode :param node: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists: [ListNode]) -> ListNode:
"""官网解法,使用基于堆的优先级队列 :param lists: :return:"""
import heapq
dummy = ListNode(0)
p = dummy
head = []
for i in range(len(lists)):
if lists[i]:
heapq.heappush(head, (lists[i]... | the_stack_v2_python_sparse | Python/t23.py | g-lyc/LeetCode | train | 15 | |
ac731eae7f0e4b87ee7e659db0c648d6a4e5020a | [
"group = {}\nfor s in strs:\n k = ''.join(sorted(s))\n if k not in group:\n group[k] = []\n group[k].append(s)\nreturn list(group.values())",
"mapping = {}\nans = []\nfor s in strs:\n k = ''.join(sorted(s))\n if k not in mapping:\n mapping[k] = len(mapping)\n ans.append([s])\n ... | <|body_start_0|>
group = {}
for s in strs:
k = ''.join(sorted(s))
if k not in group:
group[k] = []
group[k].append(s)
return list(group.values())
<|end_body_0|>
<|body_start_1|>
mapping = {}
ans = []
for s in strs:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams2(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
group = {}
... | stack_v2_sparse_classes_10k_train_005775 | 1,291 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams2",
"signature": "def groupAnagrams2(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001765 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams2(self, strs): :type strs: List[str] :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams2(self, strs): :type strs: List[str] :rtype: List[List[str]]
<|skeleton|>
class S... | f2c4f727689567e00ee06560132fca55a6fd9286 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams2(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
group = {}
for s in strs:
k = ''.join(sorted(s))
if k not in group:
group[k] = []
group[k].append(s)
return list(group.values())
... | the_stack_v2_python_sparse | leetcode/49_Group_Anagrams.py | JianxiangWang/python-journey | train | 1 | |
4106684f650b3c3ce5898640242e238f27937e56 | [
"if exog is None:\n exog = np.zeros_like(endog)\nsuper(_CensoredPoisson, self).__init__(endog, exog, **kwds)\nself.data.xnames = ['x1']",
"lambda_ = params[0]\nll_output = self._LL(self.endog, rate=lambda_)\nreturn -np.log(ll_output)",
"if start_params is None:\n lambda_start = self.endog[:, 0].mean()\n ... | <|body_start_0|>
if exog is None:
exog = np.zeros_like(endog)
super(_CensoredPoisson, self).__init__(endog, exog, **kwds)
self.data.xnames = ['x1']
<|end_body_0|>
<|body_start_1|>
lambda_ = params[0]
ll_output = self._LL(self.endog, rate=lambda_)
return -np.l... | Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent. | _CensoredPoisson | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CensoredPoisson:
"""Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent."""
def __init__(self, endog, exog=None, **kwds):
"""Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: ot... | stack_v2_sparse_classes_10k_train_005776 | 25,038 | permissive | [
{
"docstring": "Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: other kwds.",
"name": "__init__",
"signature": "def __init__(self, endog, exog=None, **kwds)"
},
{
"docstring": "Return the negative loglikelihood of endog given t... | 4 | stack_v2_sparse_classes_30k_train_000491 | Implement the Python class `_CensoredPoisson` described below.
Class description:
Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent.
Method signatures and docstrings:
- def __init__(self, endog, exog=None, **kwds): Initializes the model. Args: endog : array-like dependent vari... | Implement the Python class `_CensoredPoisson` described below.
Class description:
Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent.
Method signatures and docstrings:
- def __init__(self, endog, exog=None, **kwds): Initializes the model. Args: endog : array-like dependent vari... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class _CensoredPoisson:
"""Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent."""
def __init__(self, endog, exog=None, **kwds):
"""Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: ot... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _CensoredPoisson:
"""Class modeling a censored poisson likelihood model. For use by MLEProbabilityMatchingAgent."""
def __init__(self, endog, exog=None, **kwds):
"""Initializes the model. Args: endog : array-like dependent variable. exog : array-like independent variables. **kwds: other kwds."""
... | the_stack_v2_python_sparse | agents/allocation_agents.py | google/ml-fairness-gym | train | 310 |
7c0ab126e91e2070d3083d35d923c24aa5d4a667 | [
"atmos_var = list(AtmosphericCoefficients)\nfmap = {Workflow.STANDARD: atmos_var, Workflow.NBAR: atmos_var[0:8], Workflow.SBT: atmos_var[8:]}\nreturn fmap.get(self)",
"albs = list(Albedos)\namap = {Workflow.STANDARD: albs, Workflow.NBAR: albs[0:-1], Workflow.SBT: [albs[-1]]}\nreturn amap.get(self)",
"products =... | <|body_start_0|>
atmos_var = list(AtmosphericCoefficients)
fmap = {Workflow.STANDARD: atmos_var, Workflow.NBAR: atmos_var[0:8], Workflow.SBT: atmos_var[8:]}
return fmap.get(self)
<|end_body_0|>
<|body_start_1|>
albs = list(Albedos)
amap = {Workflow.STANDARD: albs, Workflow.NBAR:... | Represents the different workflow that wagl can run. *standard* Indicates both NBAR and SBT workflows will run *nbar* Indicates NBAR only *sbt* Indicates SBT only | Workflow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workflow:
"""Represents the different workflow that wagl can run. *standard* Indicates both NBAR and SBT workflows will run *nbar* Indicates NBAR only *sbt* Indicates SBT only"""
def atmos_coefficients(self):
"""Returns the atmospheric coefficients names used for interpolation for a ... | stack_v2_sparse_classes_10k_train_005777 | 16,541 | permissive | [
{
"docstring": "Returns the atmospheric coefficients names used for interpolation for a given Workflow.<option>.",
"name": "atmos_coefficients",
"signature": "def atmos_coefficients(self)"
},
{
"docstring": "Returns the albedo names used for specific Atmospheric evaluations for a given Workflow.... | 3 | stack_v2_sparse_classes_30k_train_001338 | Implement the Python class `Workflow` described below.
Class description:
Represents the different workflow that wagl can run. *standard* Indicates both NBAR and SBT workflows will run *nbar* Indicates NBAR only *sbt* Indicates SBT only
Method signatures and docstrings:
- def atmos_coefficients(self): Returns the atm... | Implement the Python class `Workflow` described below.
Class description:
Represents the different workflow that wagl can run. *standard* Indicates both NBAR and SBT workflows will run *nbar* Indicates NBAR only *sbt* Indicates SBT only
Method signatures and docstrings:
- def atmos_coefficients(self): Returns the atm... | 4ae3670681b872530f59c57ab537a45d1b09c009 | <|skeleton|>
class Workflow:
"""Represents the different workflow that wagl can run. *standard* Indicates both NBAR and SBT workflows will run *nbar* Indicates NBAR only *sbt* Indicates SBT only"""
def atmos_coefficients(self):
"""Returns the atmospheric coefficients names used for interpolation for a ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Workflow:
"""Represents the different workflow that wagl can run. *standard* Indicates both NBAR and SBT workflows will run *nbar* Indicates NBAR only *sbt* Indicates SBT only"""
def atmos_coefficients(self):
"""Returns the atmospheric coefficients names used for interpolation for a given Workflo... | the_stack_v2_python_sparse | wagl/constants.py | GeoscienceAustralia/wagl | train | 25 |
54c42f02e6eab9ed664a9a7e4d7cf6de7c08a7b3 | [
"c: dict[str, Any] = {}\nfor field in cls.__fields__:\n if field in ['name']:\n continue\n c[field] = getattr(Defaults, f'DEFAULT_{field.upper()}')\n if defaults and getattr(defaults, field, None) is not None:\n c[field] = getattr(defaults, field)\n if config and getattr(config, field, Non... | <|body_start_0|>
c: dict[str, Any] = {}
for field in cls.__fields__:
if field in ['name']:
continue
c[field] = getattr(Defaults, f'DEFAULT_{field.upper()}')
if defaults and getattr(defaults, field, None) is not None:
c[field] = getattr(... | Skupper config (skupper-site configmap). | SkupperConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkupperConfig:
"""Skupper config (skupper-site configmap)."""
def init(cls, name: str, defaults: Optional[SkupperSiteConfigDefaultsV1]=None, config: Optional[SkupperSiteConfigV1]=None) -> SkupperConfig:
"""Create a SkupperConfig instance by merging skupper network defaults, site conf... | stack_v2_sparse_classes_10k_train_005778 | 11,403 | permissive | [
{
"docstring": "Create a SkupperConfig instance by merging skupper network defaults, site configs and integration defaults.",
"name": "init",
"signature": "def init(cls, name: str, defaults: Optional[SkupperSiteConfigDefaultsV1]=None, config: Optional[SkupperSiteConfigV1]=None) -> SkupperConfig"
},
... | 2 | stack_v2_sparse_classes_30k_val_000241 | Implement the Python class `SkupperConfig` described below.
Class description:
Skupper config (skupper-site configmap).
Method signatures and docstrings:
- def init(cls, name: str, defaults: Optional[SkupperSiteConfigDefaultsV1]=None, config: Optional[SkupperSiteConfigV1]=None) -> SkupperConfig: Create a SkupperConfi... | Implement the Python class `SkupperConfig` described below.
Class description:
Skupper config (skupper-site configmap).
Method signatures and docstrings:
- def init(cls, name: str, defaults: Optional[SkupperSiteConfigDefaultsV1]=None, config: Optional[SkupperSiteConfigV1]=None) -> SkupperConfig: Create a SkupperConfi... | 1f496d87a5b631ac3e9b9c4a08edb4ca788fa2d9 | <|skeleton|>
class SkupperConfig:
"""Skupper config (skupper-site configmap)."""
def init(cls, name: str, defaults: Optional[SkupperSiteConfigDefaultsV1]=None, config: Optional[SkupperSiteConfigV1]=None) -> SkupperConfig:
"""Create a SkupperConfig instance by merging skupper network defaults, site conf... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SkupperConfig:
"""Skupper config (skupper-site configmap)."""
def init(cls, name: str, defaults: Optional[SkupperSiteConfigDefaultsV1]=None, config: Optional[SkupperSiteConfigV1]=None) -> SkupperConfig:
"""Create a SkupperConfig instance by merging skupper network defaults, site configs and integ... | the_stack_v2_python_sparse | reconcile/skupper_network/models.py | jfchevrette/qontract-reconcile | train | 0 |
518865fc0081d6d4bfdf911ec34b5a2614b8cd1e | [
"if len(num1) == 0 or len(num2) == 0:\n return ''\nans = ''\nif len(num1) > len(num2):\n num1, num2 = (num2, num1)\nfor digit in num1:\n temp = self.single_mul(digit, num2)\n ans = self.add(ans + '0', temp)\nreturn ans",
"if digit == '0':\n return '0'\nif digit == '1':\n return num\ndigit = ord(... | <|body_start_0|>
if len(num1) == 0 or len(num2) == 0:
return ''
ans = ''
if len(num1) > len(num2):
num1, num2 = (num2, num1)
for digit in num1:
temp = self.single_mul(digit, num2)
ans = self.add(ans + '0', temp)
return ans
<|end_bod... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def single_mul(self, digit, num):
"""digit: a single digit string num: a str of number of any length"""
<|body_1|>
def add(self, num1, num2):
... | stack_v2_sparse_classes_10k_train_005779 | 3,242 | no_license | [
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "multiply",
"signature": "def multiply(self, num1, num2)"
},
{
"docstring": "digit: a single digit string num: a str of number of any length",
"name": "single_mul",
"signature": "def single_mul(self, digit, num)"
},
... | 3 | stack_v2_sparse_classes_30k_train_000810 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def multiply(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def single_mul(self, digit, num): digit: a single digit string num: a str of number of any length
... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def multiply(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def single_mul(self, digit, num): digit: a single digit string num: a str of number of any length
... | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | <|skeleton|>
class Solution1:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def single_mul(self, digit, num):
"""digit: a single digit string num: a str of number of any length"""
<|body_1|>
def add(self, num1, num2):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution1:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
if len(num1) == 0 or len(num2) == 0:
return ''
ans = ''
if len(num1) > len(num2):
num1, num2 = (num2, num1)
for digit in num1:
temp = self.si... | the_stack_v2_python_sparse | 0043. Multiply Strings.py | pwang867/LeetCode-Solutions-Python | train | 0 | |
b1dcd0b9dcf074b5fde24a6e436e1acef0235e98 | [
"trashs_json = []\nemail = request.user.username\ntrash_repos = syncwerk_api.get_trash_repos_by_owner(email)\nfor r in trash_repos:\n trash = {'repo_id': r.repo_id, 'owner_email': email, 'owner_name': email2nickname(email), 'owner_contact_email': email2contact_email(email), 'repo_name': r.repo_name, 'org_id': r.... | <|body_start_0|>
trashs_json = []
email = request.user.username
trash_repos = syncwerk_api.get_trash_repos_by_owner(email)
for r in trash_repos:
trash = {'repo_id': r.repo_id, 'owner_email': email, 'owner_name': email2nickname(email), 'owner_contact_email': email2contact_emai... | DeletedRepos | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeletedRepos:
def get(self, request):
"""get the deleted-repos of owner"""
<|body_0|>
def post(self, request):
"""restore deleted-repo return: return True if success, otherwise api_error"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
trashs_json = ... | stack_v2_sparse_classes_10k_train_005780 | 2,806 | permissive | [
{
"docstring": "get the deleted-repos of owner",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "restore deleted-repo return: return True if success, otherwise api_error",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `DeletedRepos` described below.
Class description:
Implement the DeletedRepos class.
Method signatures and docstrings:
- def get(self, request): get the deleted-repos of owner
- def post(self, request): restore deleted-repo return: return True if success, otherwise api_error | Implement the Python class `DeletedRepos` described below.
Class description:
Implement the DeletedRepos class.
Method signatures and docstrings:
- def get(self, request): get the deleted-repos of owner
- def post(self, request): restore deleted-repo return: return True if success, otherwise api_error
<|skeleton|>
c... | 13b3ed26a04248211ef91ca70dccc617be27a3c3 | <|skeleton|>
class DeletedRepos:
def get(self, request):
"""get the deleted-repos of owner"""
<|body_0|>
def post(self, request):
"""restore deleted-repo return: return True if success, otherwise api_error"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeletedRepos:
def get(self, request):
"""get the deleted-repos of owner"""
trashs_json = []
email = request.user.username
trash_repos = syncwerk_api.get_trash_repos_by_owner(email)
for r in trash_repos:
trash = {'repo_id': r.repo_id, 'owner_email': email, 'o... | the_stack_v2_python_sparse | fhs/usr/share/python/syncwerk/restapi/restapi/api2/endpoints/deleted_repos.py | syncwerk/syncwerk-server-restapi | train | 0 | |
abc720d6deb39ac814e2f75038e5c195352327f3 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_java_time.JavaTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = AndroidSMSEventData()\nevent_data.address = self._GetRowValue(query_hash, row, 'address')\nevent_data.body = self... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_java_time.JavaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = AndroidSMSEventData()
... | SQLite parser plugin for Android text messages (SMS) database files. The Android text messages (SMS) database file is typically stored in: mmssms.dbs | AndroidSMSPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidSMSPlugin:
"""SQLite parser plugin for Android text messages (SMS) database files. The Android text messages (SMS) database file is typically stored in: mmssms.dbs"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. ... | stack_v2_sparse_classes_10k_train_005781 | 7,153 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.JavaTime: date and time value or None if not available.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_000390 | Implement the Python class `AndroidSMSPlugin` described below.
Class description:
SQLite parser plugin for Android text messages (SMS) database files. The Android text messages (SMS) database file is typically stored in: mmssms.dbs
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, va... | Implement the Python class `AndroidSMSPlugin` described below.
Class description:
SQLite parser plugin for Android text messages (SMS) database files. The Android text messages (SMS) database file is typically stored in: mmssms.dbs
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, va... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class AndroidSMSPlugin:
"""SQLite parser plugin for Android text messages (SMS) database files. The Android text messages (SMS) database file is typically stored in: mmssms.dbs"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AndroidSMSPlugin:
"""SQLite parser plugin for Android text messages (SMS) database files. The Android text messages (SMS) database file is typically stored in: mmssms.dbs"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_h... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/android_sms.py | log2timeline/plaso | train | 1,506 |
193aa09793dbbf1e5df5737b0ebe5f0ee6a9e996 | [
"ct = ContentType.objects.get_for_model(type(content_object))\nif distinction:\n dist_q = Q(eventrelation__distinction=distinction)\n cal_dist_q = Q(calendar__calendarrelation__distinction=distinction)\nelse:\n dist_q = Q()\n cal_dist_q = Q()\nif inherit:\n inherit_q = Q(cal_dist_q, calendar__calenda... | <|body_start_0|>
ct = ContentType.objects.get_for_model(type(content_object))
if distinction:
dist_q = Q(eventrelation__distinction=distinction)
cal_dist_q = Q(calendar__calendarrelation__distinction=distinction)
else:
dist_q = Q()
cal_dist_q = Q()... | >>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all().delete() >>> event1 = Event(**data) >>> event1.save() >>> data['title'] = 'Test2' >>... | EventRelationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventRelationManager:
""">>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all().delete() >>> event1 = Event(**data) ... | stack_v2_sparse_classes_10k_train_005782 | 27,357 | no_license | [
{
"docstring": "returns a queryset full of events, that relate to the object through, the distinction If inherit is false it will not consider the calendars that the events belong to. If inherit is true it will inherit all of the relations and distinctions that any calendar that it belongs to has, as long as th... | 2 | stack_v2_sparse_classes_30k_train_004651 | Implement the Python class `EventRelationManager` described below.
Class description:
>>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all... | Implement the Python class `EventRelationManager` described below.
Class description:
>>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all... | e0f86087145bd7bb181197f4498dba8783cb4759 | <|skeleton|>
class EventRelationManager:
""">>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all().delete() >>> event1 = Event(**data) ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventRelationManager:
""">>> EventRelation.objects.all().delete() >>> CalendarRelation.objects.all().delete() >>> data = { ... 'title': 'Test1', ... 'start': datetime.datetime(2008, 1, 1), ... 'end': datetime.datetime(2008, 1, 11) ... } >>> Event.objects.all().delete() >>> event1 = Event(**data) >>> event1.sa... | the_stack_v2_python_sparse | schedule/models/events.py | ippc/ippcdj | train | 2 |
e57a6304bc327d42064483e9b6290eeccd1752ba | [
"if context is None:\n context = {}\nres = super(exchange_partial_picking, self).default_get(cr, uid, fields, context=context)\nexchange_ids = context.get('active_ids', [])\nif not exchange_ids or not context.get('active_model') == 'exchange.order' or len(exchange_ids) != 1:\n return res\nexchange_id, = excha... | <|body_start_0|>
if context is None:
context = {}
res = super(exchange_partial_picking, self).default_get(cr, uid, fields, context=context)
exchange_ids = context.get('active_ids', [])
if not exchange_ids or not context.get('active_model') == 'exchange.order' or len(exchange_... | exchange_partial_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class exchange_partial_picking:
def default_get(self, cr, uid, fields, context=None):
"""This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values."""
<|body_0|>
def _partial_m... | stack_v2_sparse_classes_10k_train_005783 | 6,351 | no_license | [
{
"docstring": "This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values.",
"name": "default_get",
"signature": "def default_get(self, cr, uid, fields, context=None)"
},
{
"docstring": "Used... | 3 | null | Implement the Python class `exchange_partial_picking` described below.
Class description:
Implement the exchange_partial_picking class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context=None): This function gets default values from the object @param fields: List of fields for which we... | Implement the Python class `exchange_partial_picking` described below.
Class description:
Implement the exchange_partial_picking class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context=None): This function gets default values from the object @param fields: List of fields for which we... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class exchange_partial_picking:
def default_get(self, cr, uid, fields, context=None):
"""This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values."""
<|body_0|>
def _partial_m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class exchange_partial_picking:
def default_get(self, cr, uid, fields, context=None):
"""This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values."""
if context is None:
context = {}... | the_stack_v2_python_sparse | v_7/Dongola/common/stock_exchange/wizard/exchange_partial_picking.py | musabahmed/baba | train | 0 | |
c1ceafabbcaff4ef3a603106b9fb1d47d4c2d58b | [
"self.rects = rects\nself.sums = []\nfor w in rects:\n weight = (w[2] - w[0] + 1) * (w[3] - w[1] + 1)\n if not self.sums:\n self.sums.append(weight)\n else:\n self.sums.append(weight + self.sums[-1])",
"import bisect\npick = random.uniform(0, self.sums[-1])\nb = bisect.bisect_left(self.sums... | <|body_start_0|>
self.rects = rects
self.sums = []
for w in rects:
weight = (w[2] - w[0] + 1) * (w[3] - w[1] + 1)
if not self.sums:
self.sums.append(weight)
else:
self.sums.append(weight + self.sums[-1])
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type w: List[int] 268 ms"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
self.sums = []
for w in rects:
weight = (w[... | stack_v2_sparse_classes_10k_train_005784 | 2,805 | no_license | [
{
"docstring": ":type w: List[int] 268 ms",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: int",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002055 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type w: List[int] 268 ms
- def pick(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type w: List[int] 268 ms
- def pick(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type w: List[int] 268... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type w: List[int] 268 ms"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type w: List[int] 268 ms"""
self.rects = rects
self.sums = []
for w in rects:
weight = (w[2] - w[0] + 1) * (w[3] - w[1] + 1)
if not self.sums:
self.sums.append(weight)
else:
... | the_stack_v2_python_sparse | RandomPointInNonoverlappingRectangles_MID_882.py | 953250587/leetcode-python | train | 2 | |
cd329413dd26b6a026c49aee3add7dc5659be70c | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('chamathd', 'chamathd')\nprint('Fetching five-foot sea level data from Boston ArcGIS Open Data')\ncolName = 'chamathd.sea_level_five'\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/4ebe... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('chamathd', 'chamathd')
print('Fetching five-foot sea level data from Boston ArcGIS Open Data')
colName = 'chamathd.sea_level_five'
url = '... | fetch_sea_level_data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fetch_sea_level_data:
def execute(trial=False):
"""Retrieve some data sets for the MongoDB collection."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this... | stack_v2_sparse_classes_10k_train_005785 | 5,714 | no_license | [
{
"docstring": "Retrieve some data sets for the MongoDB collection.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that i... | 2 | stack_v2_sparse_classes_30k_train_002457 | Implement the Python class `fetch_sea_level_data` described below.
Class description:
Implement the fetch_sea_level_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets for the MongoDB collection.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None... | Implement the Python class `fetch_sea_level_data` described below.
Class description:
Implement the fetch_sea_level_data class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets for the MongoDB collection.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class fetch_sea_level_data:
def execute(trial=False):
"""Retrieve some data sets for the MongoDB collection."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class fetch_sea_level_data:
def execute(trial=False):
"""Retrieve some data sets for the MongoDB collection."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('chamathd', 'chamathd')
print('Fetching five-foo... | the_stack_v2_python_sparse | chamathd/fetch_sea_level_data.py | lingyigu/course-2017-spr-proj | train | 0 | |
e70651ef79d9ddeb6338d8757744f83e07b1bdef | [
"self.df = data\nself.feats = feats\nself.df.drop(['addr_state', 'installment', 'purpose'], 1, inplace=True)\nself.df = pd.get_dummies(self.df)\ny = self.df.int_rate.values\nself.df.drop('int_rate', axis=1, inplace=True)\nX, y = shuffle(self.df.values, y, random_state=30)\nX = X.astype(np.float32)\noffset = int(X.s... | <|body_start_0|>
self.df = data
self.feats = feats
self.df.drop(['addr_state', 'installment', 'purpose'], 1, inplace=True)
self.df = pd.get_dummies(self.df)
y = self.df.int_rate.values
self.df.drop('int_rate', axis=1, inplace=True)
X, y = shuffle(self.df.values, y... | This is the class for visulization methods of GBT | GBT_model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GBT_model:
"""This is the class for visulization methods of GBT"""
def __init__(self, data, feats):
"""Constructor"""
<|body_0|>
def gbt_model(self):
"""get the dataframe, test and training data Return ====== return accuracy of GBT regression"""
<|body_1|... | stack_v2_sparse_classes_10k_train_005786 | 4,025 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data, feats)"
},
{
"docstring": "get the dataframe, test and training data Return ====== return accuracy of GBT regression",
"name": "gbt_model",
"signature": "def gbt_model(self)"
},
{
"docstring"... | 5 | null | Implement the Python class `GBT_model` described below.
Class description:
This is the class for visulization methods of GBT
Method signatures and docstrings:
- def __init__(self, data, feats): Constructor
- def gbt_model(self): get the dataframe, test and training data Return ====== return accuracy of GBT regression... | Implement the Python class `GBT_model` described below.
Class description:
This is the class for visulization methods of GBT
Method signatures and docstrings:
- def __init__(self, data, feats): Constructor
- def gbt_model(self): get the dataframe, test and training data Return ====== return accuracy of GBT regression... | dc9185cbc5e65650d985ebecf877a157c8c19a13 | <|skeleton|>
class GBT_model:
"""This is the class for visulization methods of GBT"""
def __init__(self, data, feats):
"""Constructor"""
<|body_0|>
def gbt_model(self):
"""get the dataframe, test and training data Return ====== return accuracy of GBT regression"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GBT_model:
"""This is the class for visulization methods of GBT"""
def __init__(self, data, feats):
"""Constructor"""
self.df = data
self.feats = feats
self.df.drop(['addr_state', 'installment', 'purpose'], 1, inplace=True)
self.df = pd.get_dummies(self.df)
... | the_stack_v2_python_sparse | sj2384/GBT_model.py | ds-ga-1007/final_project | train | 0 |
1780e975aa396f6117a64666ecbb7754d356d4b3 | [
"self.__userNamespace = namespace\nself.__namespace = None\nself.__instance = None\nself.__importt()",
"try:\n if self.__userNamespace:\n self.__namespace = __import__(self.__userNamespace, fromlist=True)\n else:\n return None\nexcept Exception as e:\n return None",
"try:\n if classnam... | <|body_start_0|>
self.__userNamespace = namespace
self.__namespace = None
self.__instance = None
self.__importt()
<|end_body_0|>
<|body_start_1|>
try:
if self.__userNamespace:
self.__namespace = __import__(self.__userNamespace, fromlist=True)
... | R | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class R:
def __init__(self, namespace, *args, **kwargs):
"""热加载一个类 参数 - namespace: string, 格式:generic.requier:R"""
<|body_0|>
def __importt(self):
"""Import package if import fail will return None"""
<|body_1|>
def Instance(self, classname, *args):
"""... | stack_v2_sparse_classes_10k_train_005787 | 2,494 | no_license | [
{
"docstring": "热加载一个类 参数 - namespace: string, 格式:generic.requier:R",
"name": "__init__",
"signature": "def __init__(self, namespace, *args, **kwargs)"
},
{
"docstring": "Import package if import fail will return None",
"name": "__importt",
"signature": "def __importt(self)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_005923 | Implement the Python class `R` described below.
Class description:
Implement the R class.
Method signatures and docstrings:
- def __init__(self, namespace, *args, **kwargs): 热加载一个类 参数 - namespace: string, 格式:generic.requier:R
- def __importt(self): Import package if import fail will return None
- def Instance(self, c... | Implement the Python class `R` described below.
Class description:
Implement the R class.
Method signatures and docstrings:
- def __init__(self, namespace, *args, **kwargs): 热加载一个类 参数 - namespace: string, 格式:generic.requier:R
- def __importt(self): Import package if import fail will return None
- def Instance(self, c... | 1678f8f3450dd194c50ffc89dcc771f14976ca20 | <|skeleton|>
class R:
def __init__(self, namespace, *args, **kwargs):
"""热加载一个类 参数 - namespace: string, 格式:generic.requier:R"""
<|body_0|>
def __importt(self):
"""Import package if import fail will return None"""
<|body_1|>
def Instance(self, classname, *args):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class R:
def __init__(self, namespace, *args, **kwargs):
"""热加载一个类 参数 - namespace: string, 格式:generic.requier:R"""
self.__userNamespace = namespace
self.__namespace = None
self.__instance = None
self.__importt()
def __importt(self):
"""Import package if import fa... | the_stack_v2_python_sparse | generic/requier.py | TangJing/TDlib | train | 0 | |
61a5dff3746d83b2e879a0da368addc3f813edad | [
"dic = {root: None}\n\ndef dfs(node):\n if node:\n if node.left:\n dic[node.left] = node\n if node.right:\n dic[node.right] = node\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nl1, l2 = (p, q)\nwhile l1 != l2:\n l1 = dic.get(l1, q)\n l2 = dic.get(l2, p)\nr... | <|body_start_0|>
dic = {root: None}
def dfs(node):
if node:
if node.left:
dic[node.left] = node
if node.right:
dic[node.right] = node
dfs(node.left)
dfs(node.right)
dfs(root)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:存储父节点"""
<|body_0|>
def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:递归"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k_train_005788 | 5,443 | no_license | [
{
"docstring": "思路:存储父节点",
"name": "lowestCommonAncestor1",
"signature": "def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "思路:递归",
"name": "lowestCommonAncestor2",
"signature": "def lowestCommonAncestor2(self, root: 'TreeNo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 思路:存储父节点
- def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'Tre... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 思路:存储父节点
- def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'Tre... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:存储父节点"""
<|body_0|>
def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:递归"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor1(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""思路:存储父节点"""
dic = {root: None}
def dfs(node):
if node:
if node.left:
dic[node.left] = node
if node.right:
... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/236. Lowest Common Ancestor of a Binary Tree.py | yiming1012/MyLeetCode | train | 2 | |
07ddf16af34a8c0cb4136f3385dd7ccdebfbde2b | [
"if not root:\n return False\nstack = deque()\nprev = None\nwhile root or stack:\n if root:\n stack.append(root)\n root = root.left\n else:\n node = stack.pop()\n if prev and prev.val > node.val:\n return False\n prev = node\n root = node.right\nreturn T... | <|body_start_0|>
if not root:
return False
stack = deque()
prev = None
while root or stack:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
if prev and prev.val > nod... | These are class or static variables. Use self.prev and self.firstnode to access them inside a function. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""These are class or static variables. Use self.prev and self.firstnode to access them inside a function."""
def isValidBST(self, root):
"""similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then c... | stack_v2_sparse_classes_10k_train_005789 | 1,610 | no_license | [
{
"docstring": "similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then compare with the current poped up node. :type root: TreeNode :rtype: bool",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_004235 | Implement the Python class `Solution` described below.
Class description:
These are class or static variables. Use self.prev and self.firstnode to access them inside a function.
Method signatures and docstrings:
- def isValidBST(self, root): similar to inorder traverse. If this is an valide BST, the inorder traverse ... | Implement the Python class `Solution` described below.
Class description:
These are class or static variables. Use self.prev and self.firstnode to access them inside a function.
Method signatures and docstrings:
- def isValidBST(self, root): similar to inorder traverse. If this is an valide BST, the inorder traverse ... | 49d0831387227e69ae4067c1f5b7e828976377b4 | <|skeleton|>
class Solution:
"""These are class or static variables. Use self.prev and self.firstnode to access them inside a function."""
def isValidBST(self, root):
"""similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""These are class or static variables. Use self.prev and self.firstnode to access them inside a function."""
def isValidBST(self, root):
"""similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then compare with t... | the_stack_v2_python_sparse | binary_tree_divide_conquer/98_Validate Binary Search Tree.py | libinjungle/LeetCode_Python | train | 0 |
ebe141539dd6d2314dc63c5d9450aed1333338c3 | [
"parser = super(GenericRequest, self).get_parser(prog_name)\nparser.add_argument('-m', '--method', choices=self.app.workspace.config.ALL_METHODS, help='override query method')\nparser.add_argument('-k', '--kwargs', type=lambda x: dict(yaml.safe_load(x)), help='payload/params to send. format is yaml')\nparser.add_ar... | <|body_start_0|>
parser = super(GenericRequest, self).get_parser(prog_name)
parser.add_argument('-m', '--method', choices=self.app.workspace.config.ALL_METHODS, help='override query method')
parser.add_argument('-k', '--kwargs', type=lambda x: dict(yaml.safe_load(x)), help='payload/params to sen... | The generic request class for all requests | GenericRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericRequest:
"""The generic request class for all requests"""
def get_parser(self, prog_name):
"""Overriding parent method"""
<|body_0|>
def get_request(self, method, site_id, endpoint_id, args):
"""Get the request object"""
<|body_1|>
def update_... | stack_v2_sparse_classes_10k_train_005790 | 3,998 | permissive | [
{
"docstring": "Overriding parent method",
"name": "get_parser",
"signature": "def get_parser(self, prog_name)"
},
{
"docstring": "Get the request object",
"name": "get_request",
"signature": "def get_request(self, method, site_id, endpoint_id, args)"
},
{
"docstring": "Update th... | 4 | stack_v2_sparse_classes_30k_train_005166 | Implement the Python class `GenericRequest` described below.
Class description:
The generic request class for all requests
Method signatures and docstrings:
- def get_parser(self, prog_name): Overriding parent method
- def get_request(self, method, site_id, endpoint_id, args): Get the request object
- def update_requ... | Implement the Python class `GenericRequest` described below.
Class description:
The generic request class for all requests
Method signatures and docstrings:
- def get_parser(self, prog_name): Overriding parent method
- def get_request(self, method, site_id, endpoint_id, args): Get the request object
- def update_requ... | f65fc86163c25f843a94341f09b20db28c1511d7 | <|skeleton|>
class GenericRequest:
"""The generic request class for all requests"""
def get_parser(self, prog_name):
"""Overriding parent method"""
<|body_0|>
def get_request(self, method, site_id, endpoint_id, args):
"""Get the request object"""
<|body_1|>
def update_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GenericRequest:
"""The generic request class for all requests"""
def get_parser(self, prog_name):
"""Overriding parent method"""
parser = super(GenericRequest, self).get_parser(prog_name)
parser.add_argument('-m', '--method', choices=self.app.workspace.config.ALL_METHODS, help='ov... | the_stack_v2_python_sparse | resteasycli/cmd/generic_request.py | sayanarijit/RESTEasyCLI | train | 1 |
68cc1f9b71262520f022be5f6590957fb196284f | [
"if default is None:\n default = DEFAULT.copy()\n default.update(SPECTRAL_DEFAULT)\n default.update(WAVECAL_DEFAULT)\nsuper().__init__(default=default, config=config, pipecal_config=pipecal_config)",
"config = super().to_config()\nconfig['wavecal'] = True\nconfig['spatcal'] = False\nconfig['slitcorr'] = ... | <|body_start_0|>
if default is None:
default = DEFAULT.copy()
default.update(SPECTRAL_DEFAULT)
default.update(WAVECAL_DEFAULT)
super().__init__(default=default, config=config, pipecal_config=pipecal_config)
<|end_body_0|>
<|body_start_1|>
config = super().to_... | Reduction parameters for the FLITECAM grism wavecal pipeline. | FLITECAMWavecalParameters | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLITECAMWavecalParameters:
"""Reduction parameters for the FLITECAM grism wavecal pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults fo... | stack_v2_sparse_classes_10k_train_005791 | 15,967 | permissive | [
{
"docstring": "Initialize parameters with default values. The various config files are used to override certain parameter defaults for particular observation modes, or dates, etc. Parameters ---------- config : dict-like, optional Reduction mode and auxiliary file configuration mapping, as returned from the so... | 5 | null | Implement the Python class `FLITECAMWavecalParameters` described below.
Class description:
Reduction parameters for the FLITECAM grism wavecal pipeline.
Method signatures and docstrings:
- def __init__(self, default=None, config=None, pipecal_config=None): Initialize parameters with default values. The various config... | Implement the Python class `FLITECAMWavecalParameters` described below.
Class description:
Reduction parameters for the FLITECAM grism wavecal pipeline.
Method signatures and docstrings:
- def __init__(self, default=None, config=None, pipecal_config=None): Initialize parameters with default values. The various config... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class FLITECAMWavecalParameters:
"""Reduction parameters for the FLITECAM grism wavecal pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FLITECAMWavecalParameters:
"""Reduction parameters for the FLITECAM grism wavecal pipeline."""
def __init__(self, default=None, config=None, pipecal_config=None):
"""Initialize parameters with default values. The various config files are used to override certain parameter defaults for particular ... | the_stack_v2_python_sparse | sofia_redux/pipeline/sofia/parameters/flitecam_wavecal_parameters.py | SOFIA-USRA/sofia_redux | train | 12 |
6f32b61133bca0cae2093845161675471fa5cb56 | [
"ans = []\n\ndef preorder(root):\n if not root:\n ans.append('#')\n while root:\n ans.append(str(root.val))\n preorder(root.left)\n preorder(root.right)\npreorder(root)\nreturn ' '.join(ans)",
"vals = collections.deque((val for val in data.split()))\n\ndef build():\n if vals:\... | <|body_start_0|>
ans = []
def preorder(root):
if not root:
ans.append('#')
while root:
ans.append(str(root.val))
preorder(root.left)
preorder(root.right)
preorder(root)
return ' '.join(ans)
<|end_bod... | 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_005792 | 1,873 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9fcd1ec0686db45d24e2c52a7987d58c6ef545a0 | <|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"""
ans = []
def preorder(root):
if not root:
ans.append('#')
while root:
ans.append(str(root.val))
preorder(... | the_stack_v2_python_sparse | Design/297-SerializeandDeserializeBinaryTree.py | szhmery/leetcode | train | 0 | |
1616e44c90fd3f1d113306e930b1e487630c1ebd | [
"yield from cls.decorations\nyield from super().variableDerivation(record)\nreturn",
"yield from cls.decorations\nyield from super().operatorDerivation(record)\nreturn"
] | <|body_start_0|>
yield from cls.decorations
yield from super().variableDerivation(record)
return
<|end_body_0|>
<|body_start_1|>
yield from cls.decorations
yield from super().operatorDerivation(record)
return
<|end_body_1|>
| Metaclass that decorates descriptors with a name and a type | Decorator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decorator:
"""Metaclass that decorates descriptors with a name and a type"""
def variableDerivation(cls, record):
"""Inject the local decorations to the variable inheritance hierarchy"""
<|body_0|>
def operatorDerivation(cls, record):
"""Inject the local decorati... | stack_v2_sparse_classes_10k_train_005793 | 1,161 | permissive | [
{
"docstring": "Inject the local decorations to the variable inheritance hierarchy",
"name": "variableDerivation",
"signature": "def variableDerivation(cls, record)"
},
{
"docstring": "Inject the local decorations to the operator inheritance hierarcrhy",
"name": "operatorDerivation",
"si... | 2 | null | Implement the Python class `Decorator` described below.
Class description:
Metaclass that decorates descriptors with a name and a type
Method signatures and docstrings:
- def variableDerivation(cls, record): Inject the local decorations to the variable inheritance hierarchy
- def operatorDerivation(cls, record): Inje... | Implement the Python class `Decorator` described below.
Class description:
Metaclass that decorates descriptors with a name and a type
Method signatures and docstrings:
- def variableDerivation(cls, record): Inject the local decorations to the variable inheritance hierarchy
- def operatorDerivation(cls, record): Inje... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Decorator:
"""Metaclass that decorates descriptors with a name and a type"""
def variableDerivation(cls, record):
"""Inject the local decorations to the variable inheritance hierarchy"""
<|body_0|>
def operatorDerivation(cls, record):
"""Inject the local decorati... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Decorator:
"""Metaclass that decorates descriptors with a name and a type"""
def variableDerivation(cls, record):
"""Inject the local decorations to the variable inheritance hierarchy"""
yield from cls.decorations
yield from super().variableDerivation(record)
return
d... | the_stack_v2_python_sparse | packages/pyre/descriptors/Decorator.py | pyre/pyre | train | 27 |
943be5fca1f4a25075e5ae8a05c425e6bab3a95a | [
"if not root:\n return 0\n\ndef dfs(node, dep, deps):\n if not node.left and (not node.right):\n deps.append(dep)\n return\n if node.left:\n dfs(node.left, dep + 1, deps)\n if node.right:\n dfs(node.right, dep + 1, deps)\ndeps = []\ndfs(node, 0, deps)\nreturn max(deps)",
"i... | <|body_start_0|>
if not root:
return 0
def dfs(node, dep, deps):
if not node.left and (not node.right):
deps.append(dep)
return
if node.left:
dfs(node.left, dep + 1, deps)
if node.right:
dfs(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
"""pretty fast, but need maintain a list."""
<|body_0|>
def maxDepth(self, root):
"""do not need to maintain a list but little slower because need to call max every recursion."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_005794 | 1,320 | no_license | [
{
"docstring": "pretty fast, but need maintain a list.",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": "do not need to maintain a list but little slower because need to call max every recursion.",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"... | 2 | stack_v2_sparse_classes_30k_train_001446 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): pretty fast, but need maintain a list.
- def maxDepth(self, root): do not need to maintain a list but little slower because need to call max every recur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): pretty fast, but need maintain a list.
- def maxDepth(self, root): do not need to maintain a list but little slower because need to call max every recur... | eafadd711f6ec1b60d78442280f1c44b6296209d | <|skeleton|>
class Solution:
def maxDepth(self, root):
"""pretty fast, but need maintain a list."""
<|body_0|>
def maxDepth(self, root):
"""do not need to maintain a list but little slower because need to call max every recursion."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
"""pretty fast, but need maintain a list."""
if not root:
return 0
def dfs(node, dep, deps):
if not node.left and (not node.right):
deps.append(dep)
return
if node.left:
... | the_stack_v2_python_sparse | cyc/tree/recursion/104.py | Veraph/LeetCode_Practice | train | 0 | |
010a5eda3d42169112042145140e28c0d5d19a12 | [
"try:\n userDetail = {'realname': request.user.detail.realname, 'idCard': request.user.detail.idCard, 'gender': request.user.detail.gender}\nexcept AttributeError as e:\n detailForm = DetailForm()\nelse:\n detailForm = DetailForm(userDetail)\nreturn render(request, 'usermgr/user/userdetail.html', locals())... | <|body_start_0|>
try:
userDetail = {'realname': request.user.detail.realname, 'idCard': request.user.detail.idCard, 'gender': request.user.detail.gender}
except AttributeError as e:
detailForm = DetailForm()
else:
detailForm = DetailForm(userDetail)
re... | 处理用户信息相关请求 | UserDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetail:
"""处理用户信息相关请求"""
def get(self, request):
"""处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面"""
<|body_0|>
def post(self, request):
"""处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_005795 | 12,349 | no_license | [
{
"docstring": "处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果",
"name": "post",
"signature": "def post(self, request)"... | 3 | stack_v2_sparse_classes_30k_train_005918 | Implement the Python class `UserDetail` described below.
Class description:
处理用户信息相关请求
Method signatures and docstrings:
- def get(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面
- def post(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果
- ... | Implement the Python class `UserDetail` described below.
Class description:
处理用户信息相关请求
Method signatures and docstrings:
- def get(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面
- def post(self, request): 处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果
- ... | 26c49e8f525ca57dca27f8de53d15bcab24d00e4 | <|skeleton|>
class UserDetail:
"""处理用户信息相关请求"""
def get(self, request):
"""处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面"""
<|body_0|>
def post(self, request):
"""处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理结果"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserDetail:
"""处理用户信息相关请求"""
def get(self, request):
"""处理用户信息相关请求 :param request: django路由响应默认携带request对象 :return: 返回用户信息处理页面"""
try:
userDetail = {'realname': request.user.detail.realname, 'idCard': request.user.detail.idCard, 'gender': request.user.detail.gender}
ex... | the_stack_v2_python_sparse | iframe_api/views.py | A35-Zhou/Rental-House-Manager | train | 0 |
0c9d3b202e065b18475a060706c950b1b397b5a1 | [
"destination = validate_branch_exists_in_city(data.get('destination'))\nbooking_station = validate_branch_exists_in_city(data.get('booking_station'))\nif not destination:\n raise serializers.ValidationError({'errors': {'destination': \"We don't have a branch in that city.\"}})\nelif not booking_station:\n rai... | <|body_start_0|>
destination = validate_branch_exists_in_city(data.get('destination'))
booking_station = validate_branch_exists_in_city(data.get('booking_station'))
if not destination:
raise serializers.ValidationError({'errors': {'destination': "We don't have a branch in that city."... | Serializer to handle the Cargo serialization. | CargoSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
<|body_0|>
def create(self, validated_data):
"""Ensure that we create the Cargo using the correct method."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_005796 | 2,171 | permissive | [
{
"docstring": "Ensure all passed data is valid.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Ensure that we create the Cargo using the correct method.",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003874 | Implement the Python class `CargoSerializer` described below.
Class description:
Serializer to handle the Cargo serialization.
Method signatures and docstrings:
- def validate(self, data): Ensure all passed data is valid.
- def create(self, validated_data): Ensure that we create the Cargo using the correct method. | Implement the Python class `CargoSerializer` described below.
Class description:
Serializer to handle the Cargo serialization.
Method signatures and docstrings:
- def validate(self, data): Ensure all passed data is valid.
- def create(self, validated_data): Ensure that we create the Cargo using the correct method.
<... | 60d034681da66771412fc73402d690a9fcaa5920 | <|skeleton|>
class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
<|body_0|>
def create(self, validated_data):
"""Ensure that we create the Cargo using the correct method."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CargoSerializer:
"""Serializer to handle the Cargo serialization."""
def validate(self, data):
"""Ensure all passed data is valid."""
destination = validate_branch_exists_in_city(data.get('destination'))
booking_station = validate_branch_exists_in_city(data.get('booking_station'))... | the_stack_v2_python_sparse | cargotracker/cargo/serializers.py | MandelaK/CargoTracker | train | 0 |
e4e887d2eb53be8eea6d859965d5ba2b03863b32 | [
"def action(event):\n print(event)\nreturn Reactor(action)",
"def action(event):\n getattr(obj, function_name)(*args, **kwargs)\nreturn Reactor(action)",
"def action(event):\n logger.log(loglevel, str(event))\nreturn Reactor(action)",
"import requests\n\ndef action(event):\n resp = requests.post(u... | <|body_start_0|>
def action(event):
print(event)
return Reactor(action)
<|end_body_0|>
<|body_start_1|>
def action(event):
getattr(obj, function_name)(*args, **kwargs)
return Reactor(action)
<|end_body_1|>
<|body_start_2|>
def action(event):
... | A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances | ReactorFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReactorFactory:
"""A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances"""
def stdout(cls):
"""Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`"""
<|bod... | stack_v2_sparse_classes_10k_train_005797 | 2,372 | permissive | [
{
"docstring": "Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`",
"name": "stdout",
"signature": "def stdout(cls)"
},
{
"docstring": "Factory method returning a reactor that calls a method on an object. Args: obj (object): the tar... | 4 | stack_v2_sparse_classes_30k_train_006157 | Implement the Python class `ReactorFactory` described below.
Class description:
A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances
Method signatures and docstrings:
- def stdout(cls): Factory method returning a reactor that prints events to stdout. Returns:... | Implement the Python class `ReactorFactory` described below.
Class description:
A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances
Method signatures and docstrings:
- def stdout(cls): Factory method returning a reactor that prints events to stdout. Returns:... | d90da85473208fa50484d1cd3b06ce70aeb03e06 | <|skeleton|>
class ReactorFactory:
"""A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances"""
def stdout(cls):
"""Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReactorFactory:
"""A factory class that exposes methods to quickly create useful :obj:`baroque.entities.reactor.Reactor` instances"""
def stdout(cls):
"""Factory method returning a reactor that prints events to stdout. Returns: :obj:`baroque.entities.reactor.Reactor`"""
def action(event):... | the_stack_v2_python_sparse | baroque/defaults/reactors.py | baroquehq/baroque | train | 5 |
ddee675240ce5bebe9cebf29a1384f12f0b802ec | [
"self = object.__new__(cls)\nself.url = url\nself.tags = tags\nself.provider = provider\nreturn self",
"repr_parts = [self.__class__.__name__, '(', repr(self.url), ', ', repr(self.tags)]\nprovider = self.provider\nif provider is not None:\n repr_parts.append(', ')\n repr_parts.append(repr(provider))\nrepr_p... | <|body_start_0|>
self = object.__new__(cls)
self.url = url
self.tags = tags
self.provider = provider
return self
<|end_body_0|>
<|body_start_1|>
repr_parts = [self.__class__.__name__, '(', repr(self.url), ', ', repr(self.tags)]
provider = self.provider
if... | Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image. | ImageDetail | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageDetail:
"""Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image."""
def __new__(cls, url, tags, provider=None):
"""Creates a new image detail. Parame... | stack_v2_sparse_classes_10k_train_005798 | 2,073 | no_license | [
{
"docstring": "Creates a new image detail. Parameters ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None, `str` = `None`, Optional Provider of the image.",
"name": "__new__",
"signature": "def __new__(cls, url, tags, provider=None)"
},... | 4 | stack_v2_sparse_classes_30k_train_001194 | Implement the Python class `ImageDetail` described below.
Class description:
Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image.
Method signatures and docstrings:
- def __new__(cls, url,... | Implement the Python class `ImageDetail` described below.
Class description:
Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image.
Method signatures and docstrings:
- def __new__(cls, url,... | 74f92b598e86606ea3a269311316cddd84a5215f | <|skeleton|>
class ImageDetail:
"""Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image."""
def __new__(cls, url, tags, provider=None):
"""Creates a new image detail. Parame... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageDetail:
"""Represents an image. Attributes ---------- url : `str` Url to the image. tags : `frozenset` of `str` Additional tags for the image. provider : `None`, `str` The provider of the image."""
def __new__(cls, url, tags, provider=None):
"""Creates a new image detail. Parameters --------... | the_stack_v2_python_sparse | koishi/plugins/image_handling_core/image_detail.py | HuyaneMatsu/Koishi | train | 17 |
929d3db7f6d44b5bb2c9ed216f0e9bece8f0bf6a | [
"if not root:\n return root\nwhile root:\n if root.val > p.val and root.val > q.val:\n root = root.left\n elif root.val < p.val and root.val < q.val:\n root = root.right\n else:\n return root",
"if not root:\n return root\nif p.val > q.val:\n return self.lowestCommonAncestor... | <|body_start_0|>
if not root:
return root
while root:
if root.val > p.val and root.val > q.val:
root = root.left
elif root.val < p.val and root.val < q.val:
root = root.right
else:
return root
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor_recursive(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: ... | stack_v2_sparse_classes_10k_train_005799 | 3,093 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowest... | 3 | stack_v2_sparse_classes_30k_train_001606 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def lowestCommonAncestor_recursive(self, root, p, q): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def lowestCommonAncestor_recursive(self, root, p, q): :typ... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor_recursive(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if not root:
return root
while root:
if root.val > p.val and root.val > q.val:
root = root.left
elif... | the_stack_v2_python_sparse | src/lt_235.py | oxhead/CodingYourWay | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.