blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0886b848387c9429222689b57906509c38b56c28 | [
"from readthedocs.projects.models import Project\nproject = Project.objects.get(slug=project_slug)\nbase_project = project.publisherproject_set.all().first()\nif not base_project or private:\n return super(ItaliaResolver, self).base_resolve_path(project_slug, filename, version_slug, language, private, single_ver... | <|body_start_0|>
from readthedocs.projects.models import Project
project = Project.objects.get(slug=project_slug)
base_project = project.publisherproject_set.all().first()
if not base_project or private:
return super(ItaliaResolver, self).base_resolve_path(project_slug, filen... | Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account | ItaliaResolver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItaliaResolver:
"""Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account"""
def base_resolve_path(self, project_slug, filename, version_slug=None, language=None, private=False, single_version=No... | stack_v2_sparse_classes_36k_train_031700 | 4,501 | permissive | [
{
"docstring": "Generates the URL for a document according to its project / publisher. :param project_slug: project (document) slug :param filename: filename :param version_slug: version slug :param language: language :param private: if document is private :param single_version: if document has single version :... | 4 | stack_v2_sparse_classes_30k_train_008051 | Implement the Python class `ItaliaResolver` described below.
Class description:
Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account
Method signatures and docstrings:
- def base_resolve_path(self, project_slug, filename... | Implement the Python class `ItaliaResolver` described below.
Class description:
Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account
Method signatures and docstrings:
- def base_resolve_path(self, project_slug, filename... | 649965d7589eb1d30efdc7906c3ee7dc5a9e3656 | <|skeleton|>
class ItaliaResolver:
"""Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account"""
def base_resolve_path(self, project_slug, filename, version_slug=None, language=None, private=False, single_version=No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItaliaResolver:
"""Custom path resolver for built documentation. Resolves to public domain without use of subdomains or /doc/* paths. It also takes publisher into account"""
def base_resolve_path(self, project_slug, filename, version_slug=None, language=None, private=False, single_version=None, subprojec... | the_stack_v2_python_sparse | readthedocs/docsitalia/resolver.py | italia/docs.italia.it | train | 19 |
3db510594192bfc6ded144f13b99bf3c13d1f565 | [
"tails = [0] * len(nums)\nsize = 0\nfor x in nums:\n i, j = (0, size)\n while i != j:\n m = (i + j) / 2\n if tails[m] < x:\n i = m + 1\n else:\n j = m\n tails[i] = x\n size = max(i + 1, size)\nreturn size",
"if not nums:\n return 0\ndp = [1] * len(nums)\nf... | <|body_start_0|>
tails = [0] * len(nums)
size = 0
for x in nums:
i, j = (0, size)
while i != j:
m = (i + j) / 2
if tails[m] < x:
i = m + 1
else:
j = m
tails[i] = x
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
"""https://discuss.leetcode.com/topic/28738/java-python-binary-search-o-nlogn-time-with-explanation/2 tails is an array storing the smallest tail of all increasing subsequences with length i+1 in tails[i]. For example, say we have nums = [4,5,6,3], ... | stack_v2_sparse_classes_36k_train_031701 | 2,311 | no_license | [
{
"docstring": "https://discuss.leetcode.com/topic/28738/java-python-binary-search-o-nlogn-time-with-explanation/2 tails is an array storing the smallest tail of all increasing subsequences with length i+1 in tails[i]. For example, say we have nums = [4,5,6,3], then all the available increasing subsequences are... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): https://discuss.leetcode.com/topic/28738/java-python-binary-search-o-nlogn-time-with-explanation/2 tails is an array storing the smallest tail of all... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): https://discuss.leetcode.com/topic/28738/java-python-binary-search-o-nlogn-time-with-explanation/2 tails is an array storing the smallest tail of all... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
"""https://discuss.leetcode.com/topic/28738/java-python-binary-search-o-nlogn-time-with-explanation/2 tails is an array storing the smallest tail of all increasing subsequences with length i+1 in tails[i]. For example, say we have nums = [4,5,6,3], ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
"""https://discuss.leetcode.com/topic/28738/java-python-binary-search-o-nlogn-time-with-explanation/2 tails is an array storing the smallest tail of all increasing subsequences with length i+1 in tails[i]. For example, say we have nums = [4,5,6,3], then all the a... | the_stack_v2_python_sparse | review/300. Longest Increasing Subsequence.py | zhangpengGenedock/leetcode_python | train | 1 | |
3a46a63d0e3797ac25869926bb92b6092e18df52 | [
"last_jump = True\ndist = nums[0]\nfor i in range(1, len(nums)):\n if last_jump and dist > 0:\n last_jump = True\n dist = max(dist - 1, nums[i])\n else:\n last_jump = False\nreturn last_jump",
"can_jump_at = {}\n\ndef can_jump_recursive_memoize(i):\n if i in can_jump_at:\n ret... | <|body_start_0|>
last_jump = True
dist = nums[0]
for i in range(1, len(nums)):
if last_jump and dist > 0:
last_jump = True
dist = max(dist - 1, nums[i])
else:
last_jump = False
return last_jump
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump_recursive(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
last_jump = True
dist = nums[0]
... | stack_v2_sparse_classes_36k_train_031702 | 1,277 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "can_jump_recursive",
"signature": "def can_jump_recursive(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001389 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump_recursive(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def can_jump_recursive(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def canJum... | 9d0ff0f8705451947a6605ab5ef92bb3e27a7147 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def can_jump_recursive(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
last_jump = True
dist = nums[0]
for i in range(1, len(nums)):
if last_jump and dist > 0:
last_jump = True
dist = max(dist - 1, nums[i])
else:
... | the_stack_v2_python_sparse | dynamic_programming/jump_game.py | rayt579/leetcode | train | 0 | |
8de2024a2a527db07a59f6ccc1efc09d9980ef70 | [
"seen = set()\n\ndef area(r, c):\n if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) and ((r, c) not in seen) and grid[r][c]):\n return 0\n seen.add((r, c))\n return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)\nreturn max((area(r, c) for r in range(len(grid)) for c in ra... | <|body_start_0|>
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) and ((r, c) not in seen) and grid[r][c]):
return 0
seen.add((r, c))
return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
"""offical solution: https://leetcode.com/problems/max-area-of-island/solution/ dfs 递归解法 :type grid: List[List[int]] :rtype: int"""
<|body_0|>
def maxAreaOfIsland2(self, grid):
"""offical solution: https://leetcode.com/probl... | stack_v2_sparse_classes_36k_train_031703 | 2,409 | no_license | [
{
"docstring": "offical solution: https://leetcode.com/problems/max-area-of-island/solution/ dfs 递归解法 :type grid: List[List[int]] :rtype: int",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(self, grid)"
},
{
"docstring": "offical solution: https://leetcode.com/problems/max-area-of... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): offical solution: https://leetcode.com/problems/max-area-of-island/solution/ dfs 递归解法 :type grid: List[List[int]] :rtype: int
- def maxAreaOfIsla... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): offical solution: https://leetcode.com/problems/max-area-of-island/solution/ dfs 递归解法 :type grid: List[List[int]] :rtype: int
- def maxAreaOfIsla... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
"""offical solution: https://leetcode.com/problems/max-area-of-island/solution/ dfs 递归解法 :type grid: List[List[int]] :rtype: int"""
<|body_0|>
def maxAreaOfIsland2(self, grid):
"""offical solution: https://leetcode.com/probl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAreaOfIsland(self, grid):
"""offical solution: https://leetcode.com/problems/max-area-of-island/solution/ dfs 递归解法 :type grid: List[List[int]] :rtype: int"""
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) and ((r, c) not ... | the_stack_v2_python_sparse | 695. Max Area of Island.py | zhangpengGenedock/leetcode_python | train | 1 | |
e8f37e648f2c2b29e8fb524f3ff503a802783aaf | [
"s_list = []\nfor i in range(0, len(s), 2 * k):\n cut = s[i:i + k]\n s_list.append(cut[::-1])\n s_list.append(s[i + k:i + 2 * k])\nreturn ''.join(s_list)",
"s = list(s)\nfor i in range(0, len(s), 2 * k):\n s[i:i + k] = reversed(s[i:i + k])\nreturn ''.join(s)"
] | <|body_start_0|>
s_list = []
for i in range(0, len(s), 2 * k):
cut = s[i:i + k]
s_list.append(cut[::-1])
s_list.append(s[i + k:i + 2 * k])
return ''.join(s_list)
<|end_body_0|>
<|body_start_1|>
s = list(s)
for i in range(0, len(s), 2 * k):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_0|>
def reverseStr_other_solution(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s_list = []
for ... | stack_v2_sparse_classes_36k_train_031704 | 731 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: str",
"name": "reverseStr",
"signature": "def reverseStr(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: str",
"name": "reverseStr_other_solution",
"signature": "def reverseStr_other_solution(self, s, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseStr(self, s, k): :type s: str :type k: int :rtype: str
- def reverseStr_other_solution(self, s, k): :type s: str :type k: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseStr(self, s, k): :type s: str :type k: int :rtype: str
- def reverseStr_other_solution(self, s, k): :type s: str :type k: int :rtype: str
<|skeleton|>
class Solution:... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_0|>
def reverseStr_other_solution(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
s_list = []
for i in range(0, len(s), 2 * k):
cut = s[i:i + k]
s_list.append(cut[::-1])
s_list.append(s[i + k:i + 2 * k])
return ''.join(s_list)
def revers... | the_stack_v2_python_sparse | LeetCode/String/541_reverse_string_II.py | XyK0907/for_work | train | 0 | |
fe9bc94758b8ba4ae12d0873b8435bd1637b6c44 | [
"self.rect = Rect((0, 0), size)\nself.image = pygame.display.set_mode(size, flags, depth)\nself._opengl = flags & OPENGL\nwidgets._locals.SCREEN = self\nwidgets._locals.Font.set_fonts()",
"if attr != 'image':\n return getattr(self.image, attr)\nraise AttributeError('image')"
] | <|body_start_0|>
self.rect = Rect((0, 0), size)
self.image = pygame.display.set_mode(size, flags, depth)
self._opengl = flags & OPENGL
widgets._locals.SCREEN = self
widgets._locals.Font.set_fonts()
<|end_body_0|>
<|body_start_1|>
if attr != 'image':
return ge... | Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size. | Screen | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Screen:
"""Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size."""
def __init__(self, size, flags=0, depth=0):
"""Args: size, flags, depth: Arguments for pygame.di... | stack_v2_sparse_classes_36k_train_031705 | 1,201 | permissive | [
{
"docstring": "Args: size, flags, depth: Arguments for pygame.display.set_mode()",
"name": "__init__",
"signature": "def __init__(self, size, flags=0, depth=0)"
},
{
"docstring": "Redirect attribute access to self.image",
"name": "__getattr__",
"signature": "def __getattr__(self, attr)"... | 2 | stack_v2_sparse_classes_30k_train_014971 | Implement the Python class `Screen` described below.
Class description:
Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size.
Method signatures and docstrings:
- def __init__(self, size, flags=0, de... | Implement the Python class `Screen` described below.
Class description:
Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size.
Method signatures and docstrings:
- def __init__(self, size, flags=0, de... | 95cb53b664f312e0830f010c0c96be94d4a4db90 | <|skeleton|>
class Screen:
"""Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size."""
def __init__(self, size, flags=0, depth=0):
"""Args: size, flags, depth: Arguments for pygame.di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Screen:
"""Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size."""
def __init__(self, size, flags=0, depth=0):
"""Args: size, flags, depth: Arguments for pygame.display.set_mod... | the_stack_v2_python_sparse | pygame/GUI- widgets-SGC/sgc/surface.py | furas/python-examples | train | 176 |
62da1c75cfc3b08a5c306e4bee070e1e3de30cf2 | [
"self.snake = [[0, 0]]\nself.food = food\nself.width = width\nself.height = height\nself.eat = 0",
"x, y = self.snake[0]\nif direction == 'U':\n x = x - 1\nelif direction == 'L':\n y = y - 1\nelif direction == 'R':\n y = y + 1\nelif direction == 'D':\n x = x + 1\nif 0 <= x < self.height and 0 <= y < s... | <|body_start_0|>
self.snake = [[0, 0]]
self.food = food
self.width = width
self.height = height
self.eat = 0
<|end_body_0|>
<|body_start_1|>
x, y = self.snake[0]
if direction == 'U':
x = x - 1
elif direction == 'L':
y = y - 1
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k_train_031706 | 15,245 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_014798 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | leetcode_python/Design/design-snake-game.py | yennanliu/CS_basics | train | 64 | |
1809ac811b3aa166def31e207ce6c8ab0fcc0046 | [
"if self.request.method in ('GET', 'PUT', 'PATCH'):\n return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsDeputyLeaderOfCommunity())\nelif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nelif self.request.method == 'DELETE':\n return (permissions.IsAuthenticated(), IsI... | <|body_start_0|>
if self.request.method in ('GET', 'PUT', 'PATCH'):
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsDeputyLeaderOfCommunity())
elif self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
elif self.request.method == 'DELETE':... | Generated Microsoft Word document view set | GeneratedDocxViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneratedDocxViewSet:
"""Generated Microsoft Word document view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_031707 | 7,281 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List generated Microsoft Word documents... | 3 | stack_v2_sparse_classes_30k_train_003582 | Implement the Python class `GeneratedDocxViewSet` described below.
Class description:
Generated Microsoft Word document view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List genera... | Implement the Python class `GeneratedDocxViewSet` described below.
Class description:
Generated Microsoft Word document view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List genera... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class GeneratedDocxViewSet:
"""Generated Microsoft Word document view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneratedDocxViewSet:
"""Generated Microsoft Word document view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method in ('GET', 'PUT', 'PATCH'):
return (permissions.IsAuthenticated(), IsInActiveCommunity(), IsDeputyLeaderOfCommunity())
elif se... | the_stack_v2_python_sparse | generator/views.py | 810Teams/clubs-and-events-backend | train | 3 |
cad06c4ca8dcdbd54feb59fa35504b141896b48d | [
"for k in range(len(s) - 1):\n if s[k:k + 2] == '++':\n if not self.canWin(s[:k] + '--' + s[k + 2:]):\n return True\nreturn False",
"def dp(i, j):\n for k in range(i, j):\n if s[k:k + 2] == '++':\n if not dp(i, k - 1) and (not dp(k + 2, j)):\n return True\n... | <|body_start_0|>
for k in range(len(s) - 1):
if s[k:k + 2] == '++':
if not self.canWin(s[:k] + '--' + s[k + 2:]):
return True
return False
<|end_body_0|>
<|body_start_1|>
def dp(i, j):
for k in range(i, j):
if s[k:k + 2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def canWin1(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for k in range(len(s) - 1):
if s[k:k + 2] == '++':
... | stack_v2_sparse_classes_36k_train_031708 | 1,684 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "canWin",
"signature": "def canWin(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "canWin1",
"signature": "def canWin1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017060 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canWin(self, s): :type s: str :rtype: bool
- def canWin1(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canWin(self, s): :type s: str :rtype: bool
- def canWin1(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :... | f3ec3e6a82ad092bc5d83732af582dc987da6aac | <|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def canWin1(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
for k in range(len(s) - 1):
if s[k:k + 2] == '++':
if not self.canWin(s[:k] + '--' + s[k + 2:]):
return True
return False
def canWin1(self, s):
""":type s: str :r... | the_stack_v2_python_sparse | dp_game_theory_293_FlipGame.py | lonelyarcher/leetcode.python3 | train | 0 | |
1d4f4e6f207fad81c4bca588960f3a2c7664535d | [
"if self.request.method in permissions.SAFE_METHODS:\n return (permissions.IsAuthenticated(),)\nif self.request.method == 'POST':\n return (permissions.IsAuthenticated(),)\nreturn (permissions.IsAuthenticated(), IsAdminOfTeam())",
"serializer = self.serializer_class(data=request.data)\nif serializer.is_vali... | <|body_start_0|>
if self.request.method in permissions.SAFE_METHODS:
return (permissions.IsAuthenticated(),)
if self.request.method == 'POST':
return (permissions.IsAuthenticated(),)
return (permissions.IsAuthenticated(), IsAdminOfTeam())
<|end_body_0|>
<|body_start_1|>
... | TeamViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamViewSet:
def get_permissions(self):
"""Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfT... | stack_v2_sparse_classes_36k_train_031709 | 14,739 | no_license | [
{
"docstring": "Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfTeam :return: :rtype:",
"name": "get_permissions... | 5 | stack_v2_sparse_classes_30k_train_001261 | Implement the Python class `TeamViewSet` described below.
Class description:
Implement the TeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The cre... | Implement the Python class `TeamViewSet` described below.
Class description:
Implement the TeamViewSet class.
Method signatures and docstrings:
- def get_permissions(self): Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The cre... | 8f296850eeab1df4c52bb7b9df0681884449e761 | <|skeleton|>
class TeamViewSet:
def get_permissions(self):
"""Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamViewSet:
def get_permissions(self):
"""Any operation is permitted only if the user is Authenticated. The create method is permitted only too if the user is Authenticated. Note: The create method isn't a SAFE_METHOD The others actions (Destroy) is only permitted if the user IsAdminOfTeam :return: :... | the_stack_v2_python_sparse | src/web/teams/views.py | CiberRato/pei2015-ciberrato | train | 0 | |
6983285d25db43cd9ac76c66c65844e4856c9588 | [
"if n <= 0:\n return False\nif n == 1:\n return True\nwhile n > 1:\n if n % 2 == 1:\n return False\n n = n / 2\nreturn True",
"if n <= 0:\n return False\nif n & n - 1 == 0:\n return True\nreturn False"
] | <|body_start_0|>
if n <= 0:
return False
if n == 1:
return True
while n > 1:
if n % 2 == 1:
return False
n = n / 2
return True
<|end_body_0|>
<|body_start_1|>
if n <= 0:
return False
if n & n - 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfTwo2(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n <= 0:
return False
if n == 1:
... | stack_v2_sparse_classes_36k_train_031710 | 1,237 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo",
"signature": "def isPowerOfTwo(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo2",
"signature": "def isPowerOfTwo2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOfTwo2(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOfTwo2(self, n): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfTwo2(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n <= 0:
return False
if n == 1:
return True
while n > 1:
if n % 2 == 1:
return False
n = n / 2
return True
def isPowerOfTwo2(self... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00231.Power of Two.py | roger6blog/LeetCode | train | 0 | |
e84502dbafcf5a9ed43bcbc93ffd75e7002d8905 | [
"super().__init__(friendly_name, friendly_name, device, None, None, retry_times)\nself._command_on = 1\nself._command_off = 0\nself._load_power = None",
"try:\n self._device.set_power(packet)\nexcept (socket.timeout, ValueError) as error:\n if retry < 1:\n _LOGGER.error('Error during sending a packet... | <|body_start_0|>
super().__init__(friendly_name, friendly_name, device, None, None, retry_times)
self._command_on = 1
self._command_off = 0
self._load_power = None
<|end_body_0|>
<|body_start_1|>
try:
self._device.set_power(packet)
except (socket.timeout, Val... | Representation of an Broadlink switch. | BroadlinkSP1Switch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadlinkSP1Switch:
"""Representation of an Broadlink switch."""
def __init__(self, friendly_name, device, retry_times):
"""Initialize the switch."""
<|body_0|>
def _sendpacket(self, packet, retry):
"""Send packet to device."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_031711 | 12,879 | permissive | [
{
"docstring": "Initialize the switch.",
"name": "__init__",
"signature": "def __init__(self, friendly_name, device, retry_times)"
},
{
"docstring": "Send packet to device.",
"name": "_sendpacket",
"signature": "def _sendpacket(self, packet, retry)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000178 | Implement the Python class `BroadlinkSP1Switch` described below.
Class description:
Representation of an Broadlink switch.
Method signatures and docstrings:
- def __init__(self, friendly_name, device, retry_times): Initialize the switch.
- def _sendpacket(self, packet, retry): Send packet to device. | Implement the Python class `BroadlinkSP1Switch` described below.
Class description:
Representation of an Broadlink switch.
Method signatures and docstrings:
- def __init__(self, friendly_name, device, retry_times): Initialize the switch.
- def _sendpacket(self, packet, retry): Send packet to device.
<|skeleton|>
cla... | ecdcfb835dc708aa8cd035adbe41dfb104203586 | <|skeleton|>
class BroadlinkSP1Switch:
"""Representation of an Broadlink switch."""
def __init__(self, friendly_name, device, retry_times):
"""Initialize the switch."""
<|body_0|>
def _sendpacket(self, packet, retry):
"""Send packet to device."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BroadlinkSP1Switch:
"""Representation of an Broadlink switch."""
def __init__(self, friendly_name, device, retry_times):
"""Initialize the switch."""
super().__init__(friendly_name, friendly_name, device, None, None, retry_times)
self._command_on = 1
self._command_off = 0
... | the_stack_v2_python_sparse | homeassistant/components/broadlink/switch.py | callsSolve/core | train | 1 |
b677fa3bf4be8b437b3d5a58b1359788747a0b0b | [
"from dials.util.options import ArgumentParser\nimport libtbx.load_env\nusage = 'usage: %s experiment1.json experiment2.json reflections1.pickle reflections2.pickle' % libtbx.env.dispatcher_name\nself.parser = ArgumentParser(usage=usage, sort_options=True, phil=phil_scope, read_experiments=True, read_datablocks=Tru... | <|body_start_0|>
from dials.util.options import ArgumentParser
import libtbx.load_env
usage = 'usage: %s experiment1.json experiment2.json reflections1.pickle reflections2.pickle' % libtbx.env.dispatcher_name
self.parser = ArgumentParser(usage=usage, sort_options=True, phil=phil_scope, r... | Class to parse the command line options. | Script | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Script:
"""Class to parse the command line options."""
def __init__(self):
"""Set the expected options."""
<|body_0|>
def run(self):
"""Parse the options."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from dials.util.options import ArgumentPar... | stack_v2_sparse_classes_36k_train_031712 | 1,742 | no_license | [
{
"docstring": "Set the expected options.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parse the options.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `Script` described below.
Class description:
Class to parse the command line options.
Method signatures and docstrings:
- def __init__(self): Set the expected options.
- def run(self): Parse the options. | Implement the Python class `Script` described below.
Class description:
Class to parse the command line options.
Method signatures and docstrings:
- def __init__(self): Set the expected options.
- def run(self): Parse the options.
<|skeleton|>
class Script:
"""Class to parse the command line options."""
def... | e660c7395e3e3349d43ccd6e59cc099042c5c512 | <|skeleton|>
class Script:
"""Class to parse the command line options."""
def __init__(self):
"""Set the expected options."""
<|body_0|>
def run(self):
"""Parse the options."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Script:
"""Class to parse the command line options."""
def __init__(self):
"""Set the expected options."""
from dials.util.options import ArgumentParser
import libtbx.load_env
usage = 'usage: %s experiment1.json experiment2.json reflections1.pickle reflections2.pickle' % l... | the_stack_v2_python_sparse | work_pre_experiment/test.py | nksauter/LS49 | train | 8 |
4d7eae44bb40ce78d61057806fd082b3ea5234d5 | [
"raw_mentors = [{'name': 'Анна-Мария Ангелова', 'teams': [{'id': 268, 'name': 'Линейно Сортиране', 'room': '321'}]}]\nloaded_mentors, loaded_team_mentors = load_mentors(raw_mentors)\nself.assertEqual(len(loaded_mentors), 1)\nself.assertEqual(len(loaded_team_mentors), 1)\nloaded_mentor = loaded_mentors[0]\nself.asse... | <|body_start_0|>
raw_mentors = [{'name': 'Анна-Мария Ангелова', 'teams': [{'id': 268, 'name': 'Линейно Сортиране', 'room': '321'}]}]
loaded_mentors, loaded_team_mentors = load_mentors(raw_mentors)
self.assertEqual(len(loaded_mentors), 1)
self.assertEqual(len(loaded_team_mentors), 1)
... | TestLoaders | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLoaders:
def test_load_mentors(self):
"""The method should load Mentor and TeamMentors objects"""
<|body_0|>
def test_load_technologies(self):
"""The function should return a list of Tech objects"""
<|body_1|>
def test_load_teams_and_team_tech(self):... | stack_v2_sparse_classes_36k_train_031713 | 3,721 | no_license | [
{
"docstring": "The method should load Mentor and TeamMentors objects",
"name": "test_load_mentors",
"signature": "def test_load_mentors(self)"
},
{
"docstring": "The function should return a list of Tech objects",
"name": "test_load_technologies",
"signature": "def test_load_technologie... | 3 | stack_v2_sparse_classes_30k_train_021017 | Implement the Python class `TestLoaders` described below.
Class description:
Implement the TestLoaders class.
Method signatures and docstrings:
- def test_load_mentors(self): The method should load Mentor and TeamMentors objects
- def test_load_technologies(self): The function should return a list of Tech objects
- d... | Implement the Python class `TestLoaders` described below.
Class description:
Implement the TestLoaders class.
Method signatures and docstrings:
- def test_load_mentors(self): The method should load Mentor and TeamMentors objects
- def test_load_technologies(self): The function should return a list of Tech objects
- d... | d7212f35cd448e55009141bd6e42b55f7f05779b | <|skeleton|>
class TestLoaders:
def test_load_mentors(self):
"""The method should load Mentor and TeamMentors objects"""
<|body_0|>
def test_load_technologies(self):
"""The function should return a list of Tech objects"""
<|body_1|>
def test_load_teams_and_team_tech(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLoaders:
def test_load_mentors(self):
"""The method should load Mentor and TeamMentors objects"""
raw_mentors = [{'name': 'Анна-Мария Ангелова', 'teams': [{'id': 268, 'name': 'Линейно Сортиране', 'room': '321'}]}]
loaded_mentors, loaded_team_mentors = load_mentors(raw_mentors)
... | the_stack_v2_python_sparse | week14/01/tests.py | PetosPy/hackbulgaria_python | train | 0 | |
62de178bbbe4f50fe1369ed7d499ccdbac9c32db | [
"parent = request.GET.get('id', '')\ncaseId = request.GET.get('caseId', '')\nfilterInputValue = request.GET.get('filterInputValue', '')\nif parent:\n obj = SceneInterface.objects.filter(parent=parent).order_by('sortNumber')\n if filterInputValue:\n obj = obj.filter(Q(url__contains=filterInputValue) | Q... | <|body_start_0|>
parent = request.GET.get('id', '')
caseId = request.GET.get('caseId', '')
filterInputValue = request.GET.get('filterInputValue', '')
if parent:
obj = SceneInterface.objects.filter(parent=parent).order_by('sortNumber')
if filterInputValue:
... | SceneInterfaceList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SceneInterfaceList:
def get(self, request, *args, **kwargs):
"""场景接口用例列表"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建场景接口"""
<|body_1|>
def put(self, request, *args, **kwargs):
"""编辑接口用例"""
<|body_2|>
def delete(self... | stack_v2_sparse_classes_36k_train_031714 | 23,358 | no_license | [
{
"docstring": "场景接口用例列表",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "创建场景接口",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "编辑接口用例",
"name": "put",
"signature": "def put(self, requ... | 4 | stack_v2_sparse_classes_30k_train_017210 | Implement the Python class `SceneInterfaceList` described below.
Class description:
Implement the SceneInterfaceList class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 场景接口用例列表
- def post(self, request, *args, **kwargs): 创建场景接口
- def put(self, request, *args, **kwargs): 编辑接口用例
- def d... | Implement the Python class `SceneInterfaceList` described below.
Class description:
Implement the SceneInterfaceList class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 场景接口用例列表
- def post(self, request, *args, **kwargs): 创建场景接口
- def put(self, request, *args, **kwargs): 编辑接口用例
- def d... | f2523d6e51cde1b53ac6f453f8066b4b90c523b9 | <|skeleton|>
class SceneInterfaceList:
def get(self, request, *args, **kwargs):
"""场景接口用例列表"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建场景接口"""
<|body_1|>
def put(self, request, *args, **kwargs):
"""编辑接口用例"""
<|body_2|>
def delete(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SceneInterfaceList:
def get(self, request, *args, **kwargs):
"""场景接口用例列表"""
parent = request.GET.get('id', '')
caseId = request.GET.get('caseId', '')
filterInputValue = request.GET.get('filterInputValue', '')
if parent:
obj = SceneInterface.objects.filter(pa... | the_stack_v2_python_sparse | api/interface/rest/sceneInterface.py | zhuzhanhao1/backend | train | 0 | |
9f2e53fc8680d56e85e2af4185ee2fd7756039e2 | [
"self.metric = Gauge('mssql_performance_counters', 'Several performance counters of SQL Server.', labelnames=['server', 'port', 'counter_name'], registry=registry)\nself.query = \"\\n SELECT\\n counter_name AS %s\\n , cntr_value AS %s\\n FROM sys.dm_os_performance_count... | <|body_start_0|>
self.metric = Gauge('mssql_performance_counters', 'Several performance counters of SQL Server.', labelnames=['server', 'port', 'counter_name'], registry=registry)
self.query = "\n SELECT\n counter_name AS %s\n , cntr_value AS %s\n FROM sys.d... | PerformanceCounters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerformanceCounters:
def __init__(self, registry):
"""Initialize query and metrics"""
<|body_0|>
def collect(self, app, rows):
"""Collect from the query result :param rows: query result :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.m... | stack_v2_sparse_classes_36k_train_031715 | 1,557 | permissive | [
{
"docstring": "Initialize query and metrics",
"name": "__init__",
"signature": "def __init__(self, registry)"
},
{
"docstring": "Collect from the query result :param rows: query result :return:",
"name": "collect",
"signature": "def collect(self, app, rows)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017568 | Implement the Python class `PerformanceCounters` described below.
Class description:
Implement the PerformanceCounters class.
Method signatures and docstrings:
- def __init__(self, registry): Initialize query and metrics
- def collect(self, app, rows): Collect from the query result :param rows: query result :return: | Implement the Python class `PerformanceCounters` described below.
Class description:
Implement the PerformanceCounters class.
Method signatures and docstrings:
- def __init__(self, registry): Initialize query and metrics
- def collect(self, app, rows): Collect from the query result :param rows: query result :return:
... | 18eec896827dddc631e5a936cf64bba9872e4d13 | <|skeleton|>
class PerformanceCounters:
def __init__(self, registry):
"""Initialize query and metrics"""
<|body_0|>
def collect(self, app, rows):
"""Collect from the query result :param rows: query result :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PerformanceCounters:
def __init__(self, registry):
"""Initialize query and metrics"""
self.metric = Gauge('mssql_performance_counters', 'Several performance counters of SQL Server.', labelnames=['server', 'port', 'counter_name'], registry=registry)
self.query = "\n SELECT\n ... | the_stack_v2_python_sparse | app/prom/metrics/general/app/prom/metrics/general/performance_counters.py | IntershopCommunicationsAG/ish-monitoring-mssqldb-exporter | train | 1 | |
9c0db0ab9ed3ff18e980aa7590bc3c4d5e187a27 | [
"self.method = ''\nself.to_ = ''\nself.from_ = ''\nself.via = ''\nself.cseq = '0'\nself.call_id = ''\nself.max_forwards = '0'\nself.content_type = ''\nself.body = {}\nif session:\n self.to_ = session.to_\n self.from_ = session.from_\n self.via = session.via\n self.call_id = session.call_id\nelif message... | <|body_start_0|>
self.method = ''
self.to_ = ''
self.from_ = ''
self.via = ''
self.cseq = '0'
self.call_id = ''
self.max_forwards = '0'
self.content_type = ''
self.body = {}
if session:
self.to_ = session.to_
self.fr... | Represents a MSNSLP/1.0 message No session initiation here, it's just a higher level interface to build/parse SLP messages | SLPMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SLPMessage:
"""Represents a MSNSLP/1.0 message No session initiation here, it's just a higher level interface to build/parse SLP messages"""
def __init__(self, message=None, session=None):
"""initializes most attributes to empty"""
<|body_0|>
def parse(self, message):
... | stack_v2_sparse_classes_36k_train_031716 | 6,865 | no_license | [
{
"docstring": "initializes most attributes to empty",
"name": "__init__",
"signature": "def __init__(self, message=None, session=None)"
},
{
"docstring": "parses a message and sets the attributes to rebuild it the param must be without binary headers SLPErrors should me handled replying 500 int... | 3 | stack_v2_sparse_classes_30k_train_019457 | Implement the Python class `SLPMessage` described below.
Class description:
Represents a MSNSLP/1.0 message No session initiation here, it's just a higher level interface to build/parse SLP messages
Method signatures and docstrings:
- def __init__(self, message=None, session=None): initializes most attributes to empt... | Implement the Python class `SLPMessage` described below.
Class description:
Represents a MSNSLP/1.0 message No session initiation here, it's just a higher level interface to build/parse SLP messages
Method signatures and docstrings:
- def __init__(self, message=None, session=None): initializes most attributes to empt... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class SLPMessage:
"""Represents a MSNSLP/1.0 message No session initiation here, it's just a higher level interface to build/parse SLP messages"""
def __init__(self, message=None, session=None):
"""initializes most attributes to empty"""
<|body_0|>
def parse(self, message):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SLPMessage:
"""Represents a MSNSLP/1.0 message No session initiation here, it's just a higher level interface to build/parse SLP messages"""
def __init__(self, message=None, session=None):
"""initializes most attributes to empty"""
self.method = ''
self.to_ = ''
self.from_... | the_stack_v2_python_sparse | emesene/rev1286-1505/left-trunk-1505/emesenelib/p2p/slp.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
bf52cdb366bf2827c2168f9a33a80c59443be497 | [
"super().__init__()\nself._mask = mask\nself._use_condition = use_condition\nself._log_scale = tf.keras.Sequential([tf.keras.layers.Dense(hidden_size, activation='relu'), tf.keras.layers.Dense(hidden_size, activation='relu'), tf.keras.layers.Dense(784, activation='tanh')])\nself._shift = tf.keras.Sequential([tf.ker... | <|body_start_0|>
super().__init__()
self._mask = mask
self._use_condition = use_condition
self._log_scale = tf.keras.Sequential([tf.keras.layers.Dense(hidden_size, activation='relu'), tf.keras.layers.Dense(hidden_size, activation='relu'), tf.keras.layers.Dense(784, activation='tanh')])
... | Class conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _log_scale: _shift: | ClassConditionedAffineCouplingLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassConditionedAffineCouplingLayer:
"""Class conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _log_scale: _shift:"""
def __init__(self, hidden_size, mask, use_condition):
"""Initializes the object. Args: hidden_size: mask: use_condition:"""
... | stack_v2_sparse_classes_36k_train_031717 | 12,897 | no_license | [
{
"docstring": "Initializes the object. Args: hidden_size: mask: use_condition:",
"name": "__init__",
"signature": "def __init__(self, hidden_size, mask, use_condition)"
},
{
"docstring": "Applies the layer to the inputs. Args: image: embedding: reverse: Returns:",
"name": "call",
"signa... | 2 | stack_v2_sparse_classes_30k_train_018741 | Implement the Python class `ClassConditionedAffineCouplingLayer` described below.
Class description:
Class conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _log_scale: _shift:
Method signatures and docstrings:
- def __init__(self, hidden_size, mask, use_condition): Initializes the ob... | Implement the Python class `ClassConditionedAffineCouplingLayer` described below.
Class description:
Class conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _log_scale: _shift:
Method signatures and docstrings:
- def __init__(self, hidden_size, mask, use_condition): Initializes the ob... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class ClassConditionedAffineCouplingLayer:
"""Class conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _log_scale: _shift:"""
def __init__(self, hidden_size, mask, use_condition):
"""Initializes the object. Args: hidden_size: mask: use_condition:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassConditionedAffineCouplingLayer:
"""Class conditioned convolutional affine coupling layer. Attributes: _mask _use_condition: _log_scale: _shift:"""
def __init__(self, hidden_size, mask, use_condition):
"""Initializes the object. Args: hidden_size: mask: use_condition:"""
super().__ini... | the_stack_v2_python_sparse | flow.py | gaotianxiang/text-to-image-synthesis | train | 0 |
df28d7e54b31d485826249bf2fefd291e4dc0db0 | [
"self.arr = A\nself.countIdx = 0\nself.numIdx = 1",
"val = -1\nfor _ in range(n):\n while self.countIdx < len(self.arr) and self.arr[self.countIdx] == 0:\n self.countIdx += 2\n self.numIdx += 2\n if self.countIdx >= len(self.arr):\n return -1\n val = self.arr[self.numIdx]\n self.a... | <|body_start_0|>
self.arr = A
self.countIdx = 0
self.numIdx = 1
<|end_body_0|>
<|body_start_1|>
val = -1
for _ in range(n):
while self.countIdx < len(self.arr) and self.arr[self.countIdx] == 0:
self.countIdx += 2
self.numIdx += 2
... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.arr = A
self.countIdx = 0
self.numIdx = 1
<|end_body_0|>
<|b... | stack_v2_sparse_classes_36k_train_031718 | 826 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | null | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.arr = A
self.countIdx = 0
self.numIdx = 1
def next(self, n):
""":type n: int :rtype: int"""
val = -1
for _ in range(n):
while self.countIdx < len(self.arr) and self.arr[se... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0851_0900/LeetCode0900_RLEIterator.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
6dbbb0165a3e7b4a8f5c1900e13b0dda93327c4f | [
"super(RDB_Conv, self).__init__()\nCin = inChannels\nG = growRate\nself.shgroup = sh_groups\nself.congroup = conv_groups\nself.conv = Sequential(ops.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1, groups=self.congroup), ops.Relu())",
"if self.data_format == 'channels_first':\n out = self.conv(channel... | <|body_start_0|>
super(RDB_Conv, self).__init__()
Cin = inChannels
G = growRate
self.shgroup = sh_groups
self.congroup = conv_groups
self.conv = Sequential(ops.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1, groups=self.congroup), ops.Relu())
<|end_body_0|>
<|b... | Convolution operation of efficient residual dense block with shuffle and group. | RDB_Conv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RDB_Conv:
"""Convolution operation of efficient residual dense block with shuffle and group."""
def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3):
"""Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rat... | stack_v2_sparse_classes_36k_train_031719 | 14,306 | permissive | [
{
"docstring": "Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rate of block :type growRate: int :param sh_groups: group number of shuffle operation :type sh_groups: int :param conv_groups: group number of convolution operation :type conv_groups: int :... | 2 | null | Implement the Python class `RDB_Conv` described below.
Class description:
Convolution operation of efficient residual dense block with shuffle and group.
Method signatures and docstrings:
- def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): Initialize Block. :param inChannels: channel number o... | Implement the Python class `RDB_Conv` described below.
Class description:
Convolution operation of efficient residual dense block with shuffle and group.
Method signatures and docstrings:
- def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): Initialize Block. :param inChannels: channel number o... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class RDB_Conv:
"""Convolution operation of efficient residual dense block with shuffle and group."""
def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3):
"""Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RDB_Conv:
"""Convolution operation of efficient residual dense block with shuffle and group."""
def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3):
"""Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rate of block :t... | the_stack_v2_python_sparse | zeus/networks/erdb_esr.py | huawei-noah/xingtian | train | 308 |
b08e9db1778462e00fc9d2ddf6754b22946829e5 | [
"threading.Thread.__init__(self)\nself.logger = logging.getLogger('raspberry.cameraThread')\nself.logger.info('initializing Camera thread')\nself.stoprequest = threading.Event()",
"while not self.stoprequest.isSet():\n timestamp = int(datetime.datetime.now().timestamp() * 1000)\n yield ('img/image%d.jpg' % ... | <|body_start_0|>
threading.Thread.__init__(self)
self.logger = logging.getLogger('raspberry.cameraThread')
self.logger.info('initializing Camera thread')
self.stoprequest = threading.Event()
<|end_body_0|>
<|body_start_1|>
while not self.stoprequest.isSet():
timestam... | Thread for handling RPi camera. | CameraThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraThread:
"""Thread for handling RPi camera."""
def __init__(self):
"""Init CameraHandler class."""
<|body_0|>
def filenames(self):
"""Generate filename."""
<|body_1|>
def run(self):
"""Start recording images."""
<|body_2|>
d... | stack_v2_sparse_classes_36k_train_031720 | 1,417 | no_license | [
{
"docstring": "Init CameraHandler class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generate filename.",
"name": "filenames",
"signature": "def filenames(self)"
},
{
"docstring": "Start recording images.",
"name": "run",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_train_020037 | Implement the Python class `CameraThread` described below.
Class description:
Thread for handling RPi camera.
Method signatures and docstrings:
- def __init__(self): Init CameraHandler class.
- def filenames(self): Generate filename.
- def run(self): Start recording images.
- def join(self, timeout=None): Stop record... | Implement the Python class `CameraThread` described below.
Class description:
Thread for handling RPi camera.
Method signatures and docstrings:
- def __init__(self): Init CameraHandler class.
- def filenames(self): Generate filename.
- def run(self): Start recording images.
- def join(self, timeout=None): Stop record... | a0c4604cdeb83ac22e46f4f8ac9a622816236e51 | <|skeleton|>
class CameraThread:
"""Thread for handling RPi camera."""
def __init__(self):
"""Init CameraHandler class."""
<|body_0|>
def filenames(self):
"""Generate filename."""
<|body_1|>
def run(self):
"""Start recording images."""
<|body_2|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CameraThread:
"""Thread for handling RPi camera."""
def __init__(self):
"""Init CameraHandler class."""
threading.Thread.__init__(self)
self.logger = logging.getLogger('raspberry.cameraThread')
self.logger.info('initializing Camera thread')
self.stoprequest = threa... | the_stack_v2_python_sparse | Project in Embedded Systems/self-driving-car-master-d842d43e64bd34805fc2207191fe49be3fa28046/raspberry/cameraThread.py | pty41/2017_2018_course_assignment | train | 0 |
e9d5f911db466574d83bbbdff41d017b178f8281 | [
"if not isinstance(zoom_range, (list, tuple)) or len(zoom_range) != 2:\n raise ValueError('zoom_range argument must be list/tuple with two values!')\nself.zoom_range = zoom_range\nself.reference = reference\nself.lazy = lazy",
"zoom_x = np.exp(random.gauss(np.log(self.zoom_range[0]), np.log(self.zoom_range[1])... | <|body_start_0|>
if not isinstance(zoom_range, (list, tuple)) or len(zoom_range) != 2:
raise ValueError('zoom_range argument must be list/tuple with two values!')
self.zoom_range = zoom_range
self.reference = reference
self.lazy = lazy
<|end_body_0|>
<|body_start_1|>
... | Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. | RandomZoom2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomZoom2D:
"""Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, zoom_range, refer... | stack_v2_sparse_classes_36k_train_031721 | 21,674 | permissive | [
{
"docstring": "Initialize a RandomZoom2D object Arguments --------- zoom_range : list or tuple Lower and Upper bounds on zoom parameter. e.g. zoom_range = (0.7,0.9) will result in a random draw of the zoom parameters between 0.7 and 0.9 reference : ANTsImage (optional but recommended) image providing the refer... | 2 | null | Implement the Python class `RandomZoom2D` described below.
Class description:
Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
Meth... | Implement the Python class `RandomZoom2D` described below.
Class description:
Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
Meth... | 41f2dd3fcf72654f284dac1a9448033e963f0afb | <|skeleton|>
class RandomZoom2D:
"""Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, zoom_range, refer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomZoom2D:
"""Apply a Zoom2D transform to an image, but with the zoom parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, zoom_range, reference=None, la... | the_stack_v2_python_sparse | ants/contrib/sampling/affine2d.py | ANTsX/ANTsPy | train | 483 |
6261a4ee54b79853f3df6615a20c309af7d6946c | [
"super(InputSmotionBase, self).store(sc)\nif type(sc) is Smotion:\n self.mode.store('dummy')\nelif type(sc) is ReplicaExchange:\n self.mode.store('remd')\n self.remd.store(sc)\nelif type(sc) is MetaDyn:\n self.mode.store('metad')\n self.metad.store(sc)\nelif type(sc) is DMD:\n self.mode.store('dmd... | <|body_start_0|>
super(InputSmotionBase, self).store(sc)
if type(sc) is Smotion:
self.mode.store('dummy')
elif type(sc) is ReplicaExchange:
self.mode.store('remd')
self.remd.store(sc)
elif type(sc) is MetaDyn:
self.mode.store('metad')
... | Smotion calculation input class. A class to encompass the different "smotion" calculations. Attributes: mode: An obligatory string giving the kind of smootion calculation to be performed. Fields: | InputSmotionBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputSmotionBase:
"""Smotion calculation input class. A class to encompass the different "smotion" calculations. Attributes: mode: An obligatory string giving the kind of smootion calculation to be performed. Fields:"""
def store(self, sc):
"""Takes a smootion calculation instance an... | stack_v2_sparse_classes_36k_train_031722 | 4,820 | no_license | [
{
"docstring": "Takes a smootion calculation instance and stores a minimal representation of it. Args: sc: A smootion calculation class.",
"name": "store",
"signature": "def store(self, sc)"
},
{
"docstring": "Creates a smootion calculator object. Returns: An ensemble object of the appropriate m... | 2 | stack_v2_sparse_classes_30k_train_010253 | Implement the Python class `InputSmotionBase` described below.
Class description:
Smotion calculation input class. A class to encompass the different "smotion" calculations. Attributes: mode: An obligatory string giving the kind of smootion calculation to be performed. Fields:
Method signatures and docstrings:
- def ... | Implement the Python class `InputSmotionBase` described below.
Class description:
Smotion calculation input class. A class to encompass the different "smotion" calculations. Attributes: mode: An obligatory string giving the kind of smootion calculation to be performed. Fields:
Method signatures and docstrings:
- def ... | 57f255266d4668bafef0881d1e7cbf8a27270ddd | <|skeleton|>
class InputSmotionBase:
"""Smotion calculation input class. A class to encompass the different "smotion" calculations. Attributes: mode: An obligatory string giving the kind of smootion calculation to be performed. Fields:"""
def store(self, sc):
"""Takes a smootion calculation instance an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputSmotionBase:
"""Smotion calculation input class. A class to encompass the different "smotion" calculations. Attributes: mode: An obligatory string giving the kind of smootion calculation to be performed. Fields:"""
def store(self, sc):
"""Takes a smootion calculation instance and stores a mi... | the_stack_v2_python_sparse | ipi/inputs/smotion/smotion.py | i-pi/i-pi | train | 170 |
790dbd28b7d09ada3db7eb5fed8c3e4e869ef927 | [
"if not head or not head.next or (not head.next.next):\n return\ncur = head\nlst = []\nwhile cur:\n lst.append(cur)\n cur = cur.next\ni = 0\nj = -i if i < 0 else -(i + 1)\nwhile lst[i] != lst[j]:\n lst[i].next = lst[j]\n i = j\n j = -i if i < 0 else -(i + 1)\nlst[i].next = None",
"if not head or... | <|body_start_0|>
if not head or not head.next or (not head.next.next):
return
cur = head
lst = []
while cur:
lst.append(cur)
cur = cur.next
i = 0
j = -i if i < 0 else -(i + 1)
while lst[i] != lst[j]:
lst[i].next = ls... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reorderList(self, head):
"""07/26/2018 05:12"""
<|body_0|>
def reorderList(self, head):
"""07/26/2018 05:45"""
<|body_1|>
def reorderList(self, head: Optional[ListNode]) -> None:
"""Do not return anything, modify head in-place inste... | stack_v2_sparse_classes_36k_train_031723 | 3,188 | no_license | [
{
"docstring": "07/26/2018 05:12",
"name": "reorderList",
"signature": "def reorderList(self, head)"
},
{
"docstring": "07/26/2018 05:45",
"name": "reorderList",
"signature": "def reorderList(self, head)"
},
{
"docstring": "Do not return anything, modify head in-place instead.",
... | 3 | stack_v2_sparse_classes_30k_test_000705 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): 07/26/2018 05:12
- def reorderList(self, head): 07/26/2018 05:45
- def reorderList(self, head: Optional[ListNode]) -> None: Do not return anything, m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reorderList(self, head): 07/26/2018 05:12
- def reorderList(self, head): 07/26/2018 05:45
- def reorderList(self, head: Optional[ListNode]) -> None: Do not return anything, m... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def reorderList(self, head):
"""07/26/2018 05:12"""
<|body_0|>
def reorderList(self, head):
"""07/26/2018 05:45"""
<|body_1|>
def reorderList(self, head: Optional[ListNode]) -> None:
"""Do not return anything, modify head in-place inste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reorderList(self, head):
"""07/26/2018 05:12"""
if not head or not head.next or (not head.next.next):
return
cur = head
lst = []
while cur:
lst.append(cur)
cur = cur.next
i = 0
j = -i if i < 0 else -(i + ... | the_stack_v2_python_sparse | leetcode/solved/143_Reorder_List/solution.py | sungminoh/algorithms | train | 0 | |
c6d230cdcfaef450de89da720c929356634afd61 | [
"if not nums:\n self.root = None\n return\n\ndef make_tree(start, end):\n root = Node()\n if start == end:\n root.val = nums[start]\n return root\n left = make_tree(start, (start + end) // 2)\n right = make_tree((start + end) // 2 + 1, end)\n root.val = left.val + right.val\n r... | <|body_start_0|>
if not nums:
self.root = None
return
def make_tree(start, end):
root = Node()
if start == end:
root.val = nums[start]
return root
left = make_tree(start, (start + end) // 2)
right = ... | 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: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_031724 | 2,123 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_012464 | 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: void
- 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: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 4416d0c711b8978f12de960c29d00a9d9792b9e0 | <|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: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if not nums:
self.root = None
return
def make_tree(start, end):
root = Node()
if start == end:
root.val = nums[start]
return root
... | the_stack_v2_python_sparse | 301-400/307. Range Sum Query - Mutable.py | Ys-Zhou/leetcode-medi-p3 | train | 0 | |
96179e5b9f1d36ec9f201ed907d704a504babe3e | [
"super().__init__()\nself.masking = masking\nself.mask_value = mask_value\nself.classifier = torch.nn.Linear(in_features, initial_out_features)\nau_init = torch.zeros(initial_out_features, dtype=torch.int8)\nself.register_buffer('active_units', au_init)",
"device = self._adaptation_device\nin_features = self.clas... | <|body_start_0|>
super().__init__()
self.masking = masking
self.mask_value = mask_value
self.classifier = torch.nn.Linear(in_features, initial_out_features)
au_init = torch.zeros(initial_out_features, dtype=torch.int8)
self.register_buffer('active_units', au_init)
<|end_b... | Output layer that incrementally adds units whenever new classes are encountered. Typically used in class-incremental benchmarks where the number of classes grows over time. | IncrementalClassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncrementalClassifier:
"""Output layer that incrementally adds units whenever new classes are encountered. Typically used in class-incremental benchmarks where the number of classes grows over time."""
def __init__(self, in_features, initial_out_features=2, masking=True, mask_value=-1000):
... | stack_v2_sparse_classes_36k_train_031725 | 18,161 | permissive | [
{
"docstring": ":param in_features: number of input features. :param initial_out_features: initial number of classes (can be dynamically expanded). :param masking: whether unused units should be masked (default=True). :param mask_value: the value used for masked units (default=-1000).",
"name": "__init__",
... | 3 | null | Implement the Python class `IncrementalClassifier` described below.
Class description:
Output layer that incrementally adds units whenever new classes are encountered. Typically used in class-incremental benchmarks where the number of classes grows over time.
Method signatures and docstrings:
- def __init__(self, in_... | Implement the Python class `IncrementalClassifier` described below.
Class description:
Output layer that incrementally adds units whenever new classes are encountered. Typically used in class-incremental benchmarks where the number of classes grows over time.
Method signatures and docstrings:
- def __init__(self, in_... | deb2b3e842046f48efc96e55a16d7a566e022c72 | <|skeleton|>
class IncrementalClassifier:
"""Output layer that incrementally adds units whenever new classes are encountered. Typically used in class-incremental benchmarks where the number of classes grows over time."""
def __init__(self, in_features, initial_out_features=2, masking=True, mask_value=-1000):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IncrementalClassifier:
"""Output layer that incrementally adds units whenever new classes are encountered. Typically used in class-incremental benchmarks where the number of classes grows over time."""
def __init__(self, in_features, initial_out_features=2, masking=True, mask_value=-1000):
""":pa... | the_stack_v2_python_sparse | avalanche/models/dynamic_modules.py | ContinualAI/avalanche | train | 1,424 |
225e71926ac565f2a715295a41f76838e85d7087 | [
"from apysc.expression import expression_file_util\nif self._condition is None:\n raise ValueError(\"If expression's condition argument can't be set None.\")\nexpression: str = f'if ({self._condition.variable_name}) {{'\nexpression_file_util.append_js_expression(expression=expression)",
"from apysc.expression ... | <|body_start_0|>
from apysc.expression import expression_file_util
if self._condition is None:
raise ValueError("If expression's condition argument can't be set None.")
expression: str = f'if ({self._condition.variable_name}) {{'
expression_file_util.append_js_expression(expr... | If | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class If:
def _append_enter_expression(self) -> None:
"""Append if branch instruction start expression to file."""
<|body_0|>
def _set_last_scope(self) -> None:
"""Set expression last scope value."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from apysc... | stack_v2_sparse_classes_36k_train_031726 | 901 | permissive | [
{
"docstring": "Append if branch instruction start expression to file.",
"name": "_append_enter_expression",
"signature": "def _append_enter_expression(self) -> None"
},
{
"docstring": "Set expression last scope value.",
"name": "_set_last_scope",
"signature": "def _set_last_scope(self) ... | 2 | null | Implement the Python class `If` described below.
Class description:
Implement the If class.
Method signatures and docstrings:
- def _append_enter_expression(self) -> None: Append if branch instruction start expression to file.
- def _set_last_scope(self) -> None: Set expression last scope value. | Implement the Python class `If` described below.
Class description:
Implement the If class.
Method signatures and docstrings:
- def _append_enter_expression(self) -> None: Append if branch instruction start expression to file.
- def _set_last_scope(self) -> None: Set expression last scope value.
<|skeleton|>
class I... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class If:
def _append_enter_expression(self) -> None:
"""Append if branch instruction start expression to file."""
<|body_0|>
def _set_last_scope(self) -> None:
"""Set expression last scope value."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class If:
def _append_enter_expression(self) -> None:
"""Append if branch instruction start expression to file."""
from apysc.expression import expression_file_util
if self._condition is None:
raise ValueError("If expression's condition argument can't be set None.")
expre... | the_stack_v2_python_sparse | apysc/branch/_if.py | TrendingTechnology/apysc | train | 0 | |
cc4bada5b88553ed0a9586fcbd3f2b6f4cdea9bf | [
"super(Encoder, self).__init__()\ninitialW = chainer.initializers.Uniform if initialW is None else initialW\ninitial_bias = chainer.initializers.Uniform if initial_bias is None else initial_bias\nself.do_history_mask = False\nwith self.init_scope():\n self.conv_subsampling_factor = 1\n channels = 64\n if i... | <|body_start_0|>
super(Encoder, self).__init__()
initialW = chainer.initializers.Uniform if initialW is None else initialW
initial_bias = chainer.initializers.Uniform if initial_bias is None else initial_bias
self.do_history_mask = False
with self.init_scope():
self.c... | Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h ... | Encoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidd... | stack_v2_sparse_classes_36k_train_031727 | 4,911 | permissive | [
{
"docstring": "Initialize Encoder. Args: idim (int): Input dimension. args (Namespace): Training config. initialW (int, optional): Initializer to initialize the weight. initial_bias (bool, optional): Initializer to initialize the bias.",
"name": "__init__",
"signature": "def __init__(self, idim, attent... | 2 | stack_v2_sparse_classes_30k_train_019920 | Implement the Python class `Encoder` described below.
Class description:
Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer.... | Implement the Python class `Encoder` described below.
Class description:
Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer.... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class Encoder:
"""Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder. Args: input_type(str): Sampling type. `input_type` must be `conv2d` or 'linear' currently. idim (int): Dimension of inputs. n_layers (int): Number of encoder layers. n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a... | the_stack_v2_python_sparse | espnet/nets/chainer_backend/transformer/encoder.py | espnet/espnet | train | 7,242 |
66d250f8940e46a44874308919a7ebdb031cae1e | [
"self.file = file\nif loadVelocities is not None or loadBoxVectors is not None:\n warnings.warn('loadVelocities and loadBoxVectors have been deprecated. velocities and box information is loaded automatically if the inpcrd file contains them.', DeprecationWarning)\nresults = amber_file_parser.readAmberCoordinates... | <|body_start_0|>
self.file = file
if loadVelocities is not None or loadBoxVectors is not None:
warnings.warn('loadVelocities and loadBoxVectors have been deprecated. velocities and box information is loaded automatically if the inpcrd file contains them.', DeprecationWarning)
results... | AmberInpcrdFile parses an AMBER inpcrd file and loads the data stored in it. | AmberInpcrdFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmberInpcrdFile:
"""AmberInpcrdFile parses an AMBER inpcrd file and loads the data stored in it."""
def __init__(self, file, loadVelocities=None, loadBoxVectors=None):
"""Load an inpcrd file. An inpcrd file contains atom positions and, optionally, velocities and periodic box dimensio... | stack_v2_sparse_classes_36k_train_031728 | 5,661 | no_license | [
{
"docstring": "Load an inpcrd file. An inpcrd file contains atom positions and, optionally, velocities and periodic box dimensions. Parameters ---------- file : str The name of the file to load loadVelocities : bool Deprecated. Velocities are loaded automatically if present loadBoxVectors : bool Deprecated. Bo... | 4 | stack_v2_sparse_classes_30k_train_001370 | Implement the Python class `AmberInpcrdFile` described below.
Class description:
AmberInpcrdFile parses an AMBER inpcrd file and loads the data stored in it.
Method signatures and docstrings:
- def __init__(self, file, loadVelocities=None, loadBoxVectors=None): Load an inpcrd file. An inpcrd file contains atom positi... | Implement the Python class `AmberInpcrdFile` described below.
Class description:
AmberInpcrdFile parses an AMBER inpcrd file and loads the data stored in it.
Method signatures and docstrings:
- def __init__(self, file, loadVelocities=None, loadBoxVectors=None): Load an inpcrd file. An inpcrd file contains atom positi... | d2593f386a627d069b5ec17a3a2f4ecd40d85dd1 | <|skeleton|>
class AmberInpcrdFile:
"""AmberInpcrdFile parses an AMBER inpcrd file and loads the data stored in it."""
def __init__(self, file, loadVelocities=None, loadBoxVectors=None):
"""Load an inpcrd file. An inpcrd file contains atom positions and, optionally, velocities and periodic box dimensio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmberInpcrdFile:
"""AmberInpcrdFile parses an AMBER inpcrd file and loads the data stored in it."""
def __init__(self, file, loadVelocities=None, loadBoxVectors=None):
"""Load an inpcrd file. An inpcrd file contains atom positions and, optionally, velocities and periodic box dimensions. Parameter... | the_stack_v2_python_sparse | wrappers/python/openmm/app/amberinpcrdfile.py | openmm/openmm | train | 875 |
362027481ab0c88f1cdaee5515780ced0dabd4b0 | [
"self.wordDict = {}\nfor i, w in enumerate(words):\n if w in self.wordDict:\n self.wordDict[w].append(i)\n else:\n self.wordDict[w] = [i]",
"index1 = self.wordDict[word1]\nindex2 = self.wordDict[word2]\ni = j = 0\nminDist = sys.maxsize\nwhile i < len(index1) and j < len(index2):\n idx1 = in... | <|body_start_0|>
self.wordDict = {}
for i, w in enumerate(words):
if w in self.wordDict:
self.wordDict[w].append(i)
else:
self.wordDict[w] = [i]
<|end_body_0|>
<|body_start_1|>
index1 = self.wordDict[word1]
index2 = self.wordDict[w... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wordDict = {}
for i, w i... | stack_v2_sparse_classes_36k_train_031729 | 2,135 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 7a459e9742958e63be8886874904e5ab2489411a | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.wordDict = {}
for i, w in enumerate(words):
if w in self.wordDict:
self.wordDict[w].append(i)
else:
self.wordDict[w] = [i]
def shortest(self, word1, w... | the_stack_v2_python_sparse | Medium/244.py | Hellofafar/Leetcode | train | 6 | |
b556daaa9806409b7f5fdf06b67a6aaa51fc9782 | [
"\"\"\"\n 1. consider using reduce, really necessary?\n 2. since it's prefix, that is to say, every char must exist in strings\n \"\"\"\nif not strs:\n return ''\nmax_index = 0\nfor i, clist in enumerate(zip(*strs)):\n result = set(clist)\n if len(result) > 1:\n return strs[0][:... | <|body_start_0|>
"""
1. consider using reduce, really necessary?
2. since it's prefix, that is to say, every char must exist in strings
"""
if not strs:
return ''
max_index = 0
for i, clist in enumerate(zip(*strs)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def rewrite(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
1. consider using red... | stack_v2_sparse_classes_36k_train_031730 | 2,085 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "rewrite",
"signature": "def rewrite(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013266 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def rewrite(self, strs): :type strs: List[str] :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def rewrite(self, strs): :type strs: List[str] :rtype: str
<|skeleton|>
class Solution:
def longest... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def rewrite(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
"""
1. consider using reduce, really necessary?
2. since it's prefix, that is to say, every char must exist in strings
"""
if not strs:
ret... | the_stack_v2_python_sparse | co_ms/14_Longest_Common_Prefix.py | vsdrun/lc_public | train | 6 | |
54cc8d6b276725df84e6580629170333ca8c9e3b | [
"asn_file = self.get_data(self.test_dir, 'jw93065-a3001_20170511t111213_tso3_001_asn.json')\nfor file in raw_from_asn(asn_file):\n self.get_data(self.test_dir, file)\nstep = Tso3Pipeline()\nstep.scale_detection = False\nstep.outlier_detection.weight_type = 'exptime'\nstep.outlier_detection.pixfrac = 1.0\nstep.ou... | <|body_start_0|>
asn_file = self.get_data(self.test_dir, 'jw93065-a3001_20170511t111213_tso3_001_asn.json')
for file in raw_from_asn(asn_file):
self.get_data(self.test_dir, file)
step = Tso3Pipeline()
step.scale_detection = False
step.outlier_detection.weight_type = '... | TestTso3Pipeline | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTso3Pipeline:
def test_tso3_pipeline_nrc1(self):
"""Regression test of calwebb_tso3 pipeline on NIRCam simulated data. Default imaging mode outlier_detection will be tested here."""
<|body_0|>
def test_tso3_pipeline_nrc2(self):
"""Regression test of calwebb_tso3 ... | stack_v2_sparse_classes_36k_train_031731 | 3,720 | permissive | [
{
"docstring": "Regression test of calwebb_tso3 pipeline on NIRCam simulated data. Default imaging mode outlier_detection will be tested here.",
"name": "test_tso3_pipeline_nrc1",
"signature": "def test_tso3_pipeline_nrc1(self)"
},
{
"docstring": "Regression test of calwebb_tso3 pipeline on NIRC... | 2 | stack_v2_sparse_classes_30k_train_014010 | Implement the Python class `TestTso3Pipeline` described below.
Class description:
Implement the TestTso3Pipeline class.
Method signatures and docstrings:
- def test_tso3_pipeline_nrc1(self): Regression test of calwebb_tso3 pipeline on NIRCam simulated data. Default imaging mode outlier_detection will be tested here.
... | Implement the Python class `TestTso3Pipeline` described below.
Class description:
Implement the TestTso3Pipeline class.
Method signatures and docstrings:
- def test_tso3_pipeline_nrc1(self): Regression test of calwebb_tso3 pipeline on NIRCam simulated data. Default imaging mode outlier_detection will be tested here.
... | e3a5b2d8bb50d92ccca46cd3bbd6585d5238000a | <|skeleton|>
class TestTso3Pipeline:
def test_tso3_pipeline_nrc1(self):
"""Regression test of calwebb_tso3 pipeline on NIRCam simulated data. Default imaging mode outlier_detection will be tested here."""
<|body_0|>
def test_tso3_pipeline_nrc2(self):
"""Regression test of calwebb_tso3 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTso3Pipeline:
def test_tso3_pipeline_nrc1(self):
"""Regression test of calwebb_tso3 pipeline on NIRCam simulated data. Default imaging mode outlier_detection will be tested here."""
asn_file = self.get_data(self.test_dir, 'jw93065-a3001_20170511t111213_tso3_001_asn.json')
for file ... | the_stack_v2_python_sparse | jwst/tests_nightly/general/nircam/test_tso3.py | mperrin/jwst | train | 0 | |
4b7dbc37ca1193edfd9c28576acc69bafc348d05 | [
"lead_ids = self.search([('demand', '=', True)])\nproperty_obj = self.env['account.asset.asset']\ntemplate_id = self.env['ir.model.data'].get_object_reference('realestate', 'email_template_demand_property')[1]\nif lead_ids and lead_ids.ids:\n for lead_rec in lead_ids:\n req_args = [('bedroom', '<=', lead_... | <|body_start_0|>
lead_ids = self.search([('demand', '=', True)])
property_obj = self.env['account.asset.asset']
template_id = self.env['ir.model.data'].get_object_reference('realestate', 'email_template_demand_property')[1]
if lead_ids and lead_ids.ids:
for lead_rec in lead_i... | crm_lead | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class crm_lead:
def cron_property_demand(self):
"""This is scheduler function which send mails to customers, who are demanded properties. @param self: The object pointer"""
<|body_0|>
def _lead_create_contact(self, lead, name, is_company, parent_id=False):
"""This method i... | stack_v2_sparse_classes_36k_train_031732 | 6,484 | no_license | [
{
"docstring": "This is scheduler function which send mails to customers, who are demanded properties. @param self: The object pointer",
"name": "cron_property_demand",
"signature": "def cron_property_demand(self)"
},
{
"docstring": "This method is used to create customer when lead convert to op... | 2 | stack_v2_sparse_classes_30k_train_008086 | Implement the Python class `crm_lead` described below.
Class description:
Implement the crm_lead class.
Method signatures and docstrings:
- def cron_property_demand(self): This is scheduler function which send mails to customers, who are demanded properties. @param self: The object pointer
- def _lead_create_contact(... | Implement the Python class `crm_lead` described below.
Class description:
Implement the crm_lead class.
Method signatures and docstrings:
- def cron_property_demand(self): This is scheduler function which send mails to customers, who are demanded properties. @param self: The object pointer
- def _lead_create_contact(... | faf6dfa178c869ba660b86bf0efb307985250c76 | <|skeleton|>
class crm_lead:
def cron_property_demand(self):
"""This is scheduler function which send mails to customers, who are demanded properties. @param self: The object pointer"""
<|body_0|>
def _lead_create_contact(self, lead, name, is_company, parent_id=False):
"""This method i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class crm_lead:
def cron_property_demand(self):
"""This is scheduler function which send mails to customers, who are demanded properties. @param self: The object pointer"""
lead_ids = self.search([('demand', '=', True)])
property_obj = self.env['account.asset.asset']
template_id = se... | the_stack_v2_python_sparse | realestate/models/crm_lead.py | eman000tahaz/arc-s | train | 0 | |
83db85fbccc750afc169950bda6a77a859a1c7f9 | [
"self.hass = hass\nsession = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)\nself.requester = AiohttpSessionRequester(session, with_sleep=True)\nself.upnp_factory = UpnpFactory(self.requester, non_strict=True)\nself.devices = {}\nself.sources = {}",
"assert config_entry.unique_id\ndevice = DmsDevi... | <|body_start_0|>
self.hass = hass
session = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)
self.requester = AiohttpSessionRequester(session, with_sleep=True)
self.upnp_factory = UpnpFactory(self.requester, non_strict=True)
self.devices = {}
self.sources = ... | Storage class for domain global data. | DlnaDmsData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DlnaDmsData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
<|body_0|>
async def async_setup_entry(self, config_entry: ConfigEntry) -> bool:
"""Create a DMS device connection from a confi... | stack_v2_sparse_classes_36k_train_031733 | 25,637 | permissive | [
{
"docstring": "Initialize global data.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Create a DMS device connection from a config entry.",
"name": "async_setup_entry",
"signature": "async def async_setup_entry(self, config_entry:... | 3 | null | Implement the Python class `DlnaDmsData` described below.
Class description:
Storage class for domain global data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize global data.
- async def async_setup_entry(self, config_entry: ConfigEntry) -> bool: Create a DMS device co... | Implement the Python class `DlnaDmsData` described below.
Class description:
Storage class for domain global data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize global data.
- async def async_setup_entry(self, config_entry: ConfigEntry) -> bool: Create a DMS device co... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DlnaDmsData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
<|body_0|>
async def async_setup_entry(self, config_entry: ConfigEntry) -> bool:
"""Create a DMS device connection from a confi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DlnaDmsData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
self.hass = hass
session = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)
self.requester = AiohttpSessionRequester(sessio... | the_stack_v2_python_sparse | homeassistant/components/dlna_dms/dms.py | home-assistant/core | train | 35,501 |
cef60fd4ba8cfacbde5250863002e2f5baea7091 | [
"def dist(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\nheap = []\ngraph = {}\nfor i in range(len(points)):\n for j in range(i + 1, len(points)):\n d = dist(points[i], points[j])\n graph.setdefault(i, {})[j] = graph.setdefault(j, {})[i] = d\n heappush(heap, (d, i, j))\n\nclas... | <|body_start_0|>
def dist(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
heap = []
graph = {}
for i in range(len(points)):
for j in range(i + 1, len(points)):
d = dist(points[i], points[j])
graph.setdefault(i, {})[j] = grap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
"""Time complexity: O(n^2*log(n^2)) Space complexity: O(n^2)"""
<|body_0|>
def minCostConnectPoints(self, points: List[List[int]]) -> int:
"""Time complexity: O(n^2) Space complexity: O(n^2)"""... | stack_v2_sparse_classes_36k_train_031734 | 6,484 | no_license | [
{
"docstring": "Time complexity: O(n^2*log(n^2)) Space complexity: O(n^2)",
"name": "minCostConnectPoints",
"signature": "def minCostConnectPoints(self, points: List[List[int]]) -> int"
},
{
"docstring": "Time complexity: O(n^2) Space complexity: O(n^2)",
"name": "minCostConnectPoints",
... | 3 | stack_v2_sparse_classes_30k_train_014992 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostConnectPoints(self, points: List[List[int]]) -> int: Time complexity: O(n^2*log(n^2)) Space complexity: O(n^2)
- def minCostConnectPoints(self, points: List[List[int]]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostConnectPoints(self, points: List[List[int]]) -> int: Time complexity: O(n^2*log(n^2)) Space complexity: O(n^2)
- def minCostConnectPoints(self, points: List[List[int]]... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
"""Time complexity: O(n^2*log(n^2)) Space complexity: O(n^2)"""
<|body_0|>
def minCostConnectPoints(self, points: List[List[int]]) -> int:
"""Time complexity: O(n^2) Space complexity: O(n^2)"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCostConnectPoints(self, points: List[List[int]]) -> int:
"""Time complexity: O(n^2*log(n^2)) Space complexity: O(n^2)"""
def dist(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
heap = []
graph = {}
for i in range(len(points)):
... | the_stack_v2_python_sparse | leetcode/solved/1706_Min_Cost_to_Connect_All_Points/solution.py | sungminoh/algorithms | train | 0 | |
323203ee605eae5e5619cf67fdbb1fc079274de3 | [
"VapiInterface.__init__(self, config, _ClientCertificateStub)\nself._VAPI_OPERATION_IDS = {}\nself._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})\nself._VAPI_OPERATION_IDS.update({'get_task': 'get$task'})\nself._VAPI_OPERATION_IDS.update({'update_task': 'update$task'})",
"task_id = self._invoke('creat... | <|body_start_0|>
VapiInterface.__init__(self, config, _ClientCertificateStub)
self._VAPI_OPERATION_IDS = {}
self._VAPI_OPERATION_IDS.update({'create_task': 'create$task'})
self._VAPI_OPERATION_IDS.update({'get_task': 'get$task'})
self._VAPI_OPERATION_IDS.update({'update_task': 'u... | The ``ClientCertificate`` interface provides methods to add and retrieve client certificate. This class was added in vSphere API 7.0.0. | ClientCertificate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientCertificate:
"""The ``ClientCertificate`` interface provides methods to add and retrieve client certificate. This class was added in vSphere API 7.0.0."""
def __init__(self, config):
""":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configurat... | stack_v2_sparse_classes_36k_train_031735 | 43,803 | permissive | [
{
"docstring": ":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be used for creating the stub.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Generate a new self signed client certificate. Existing client cert... | 4 | null | Implement the Python class `ClientCertificate` described below.
Class description:
The ``ClientCertificate`` interface provides methods to add and retrieve client certificate. This class was added in vSphere API 7.0.0.
Method signatures and docstrings:
- def __init__(self, config): :type config: :class:`vmware.vapi.b... | Implement the Python class `ClientCertificate` described below.
Class description:
The ``ClientCertificate`` interface provides methods to add and retrieve client certificate. This class was added in vSphere API 7.0.0.
Method signatures and docstrings:
- def __init__(self, config): :type config: :class:`vmware.vapi.b... | c07e1be98615201139b26c28db3aa584c4254b66 | <|skeleton|>
class ClientCertificate:
"""The ``ClientCertificate`` interface provides methods to add and retrieve client certificate. This class was added in vSphere API 7.0.0."""
def __init__(self, config):
""":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configurat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientCertificate:
"""The ``ClientCertificate`` interface provides methods to add and retrieve client certificate. This class was added in vSphere API 7.0.0."""
def __init__(self, config):
""":type config: :class:`vmware.vapi.bindings.stub.StubConfiguration` :param config: Configuration to be use... | the_stack_v2_python_sparse | com/vmware/vcenter/trusted_infrastructure/trust_authority_clusters/kms/providers_client.py | adammillerio/vsphere-automation-sdk-python | train | 0 |
99c8c384b081271c6a6599b17906b01e1fa62678 | [
"actor_ids = NominationEntry.objects.order_by().values_list('actor').distinct()\nactors = User.objects.filter(id__in=actor_ids)\nreturn ((a.id, a.username) for a in actors)",
"if not self.value():\n return None\nreturn queryset.filter(actor__id=self.value())"
] | <|body_start_0|>
actor_ids = NominationEntry.objects.order_by().values_list('actor').distinct()
actors = User.objects.filter(id__in=actor_ids)
return ((a.id, a.username) for a in actors)
<|end_body_0|>
<|body_start_1|>
if not self.value():
return None
return queryset... | Actor Filter for NominationEntry Admin list page. | NominationEntryActorFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NominationEntryActorFilter:
"""Actor Filter for NominationEntry Admin list page."""
def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]:
"""Selectable values for viewer to filter by."""
<|body_0|>
def queryset(self, request: HttpR... | stack_v2_sparse_classes_36k_train_031736 | 14,240 | permissive | [
{
"docstring": "Selectable values for viewer to filter by.",
"name": "lookups",
"signature": "def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]"
},
{
"docstring": "Query to filter the list of Users against.",
"name": "queryset",
"signature": "de... | 2 | null | Implement the Python class `NominationEntryActorFilter` described below.
Class description:
Actor Filter for NominationEntry Admin list page.
Method signatures and docstrings:
- def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: Selectable values for viewer to filter by.
- d... | Implement the Python class `NominationEntryActorFilter` described below.
Class description:
Actor Filter for NominationEntry Admin list page.
Method signatures and docstrings:
- def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]: Selectable values for viewer to filter by.
- d... | cb6326cabee6570a5725702cb2893ae39f752279 | <|skeleton|>
class NominationEntryActorFilter:
"""Actor Filter for NominationEntry Admin list page."""
def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]:
"""Selectable values for viewer to filter by."""
<|body_0|>
def queryset(self, request: HttpR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NominationEntryActorFilter:
"""Actor Filter for NominationEntry Admin list page."""
def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]:
"""Selectable values for viewer to filter by."""
actor_ids = NominationEntry.objects.order_by().values_list('ac... | the_stack_v2_python_sparse | pydis_site/apps/api/admin.py | python-discord/site | train | 746 |
7178540ea4ce038e1ecca25ea90e3846dc79ddd9 | [
"self.config = config\nself.regs = config['model']['regs']\nself.decay = self.regs[0]\nself.norm_adj = config['model']['norm_adj']\nself.model = LightGCN(config['model'], self.norm_adj)\nsuper(LightGCNEngine, self).__init__(config)\nself.model.to(self.device)",
"assert hasattr(self, 'model'), 'Please specify the ... | <|body_start_0|>
self.config = config
self.regs = config['model']['regs']
self.decay = self.regs[0]
self.norm_adj = config['model']['norm_adj']
self.model = LightGCN(config['model'], self.norm_adj)
super(LightGCNEngine, self).__init__(config)
self.model.to(self.de... | LightGCNEngine Class. | LightGCNEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightGCNEngine:
"""LightGCNEngine Class."""
def __init__(self, config):
"""Initialize LightGCNEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train the model in a single batch. Args: batch_data (list): batch users, positive items and nega... | stack_v2_sparse_classes_36k_train_031737 | 6,800 | permissive | [
{
"docstring": "Initialize LightGCNEngine Class.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Train the model in a single batch. Args: batch_data (list): batch users, positive items and negative items. Return: loss (float): batch loss.",
"name": "train_s... | 4 | stack_v2_sparse_classes_30k_val_000850 | Implement the Python class `LightGCNEngine` described below.
Class description:
LightGCNEngine Class.
Method signatures and docstrings:
- def __init__(self, config): Initialize LightGCNEngine Class.
- def train_single_batch(self, batch_data): Train the model in a single batch. Args: batch_data (list): batch users, po... | Implement the Python class `LightGCNEngine` described below.
Class description:
LightGCNEngine Class.
Method signatures and docstrings:
- def __init__(self, config): Initialize LightGCNEngine Class.
- def train_single_batch(self, batch_data): Train the model in a single batch. Args: batch_data (list): batch users, po... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class LightGCNEngine:
"""LightGCNEngine Class."""
def __init__(self, config):
"""Initialize LightGCNEngine Class."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train the model in a single batch. Args: batch_data (list): batch users, positive items and nega... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LightGCNEngine:
"""LightGCNEngine Class."""
def __init__(self, config):
"""Initialize LightGCNEngine Class."""
self.config = config
self.regs = config['model']['regs']
self.decay = self.regs[0]
self.norm_adj = config['model']['norm_adj']
self.model = LightG... | the_stack_v2_python_sparse | beta_rec/models/lightgcn.py | beta-team/beta-recsys | train | 156 |
b5bddce0d29beccca91238e0419841b737b54dd1 | [
"self.m = collections.defaultdict(int)\nself.totalWeight = 0\nfor k, v in enumerate(w):\n self.m[k] = v\n self.totalWeight += v",
"sum, target = (0, randint(0, self.totalWeight))\nfor k, v in self.m.iteritems():\n sum += v\n if sum >= target:\n return k\nreturn 0"
] | <|body_start_0|>
self.m = collections.defaultdict(int)
self.totalWeight = 0
for k, v in enumerate(w):
self.m[k] = v
self.totalWeight += v
<|end_body_0|>
<|body_start_1|>
sum, target = (0, randint(0, self.totalWeight))
for k, v in self.m.iteritems():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.m = collections.defaultdict(int)
self.totalWeight = 0
for k, v in enumerate... | stack_v2_sparse_classes_36k_train_031738 | 2,037 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 340ae58fb65b97aa6c6ab2daa8cbd82d1093deae | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.m = collections.defaultdict(int)
self.totalWeight = 0
for k, v in enumerate(w):
self.m[k] = v
self.totalWeight += v
def pickIndex(self):
""":rtype: int"""
sum, target = (... | the_stack_v2_python_sparse | learnpythonthehardway/random-pick-with-weight.py | dgpllc/leetcode-python | train | 0 | |
e414b9cfff9b2e02e1ad30f1b94d84923381efab | [
"user = form.user_cache\nlogin(self.request, user)\nreturn super(LoginView, self).form_valid(form)",
"url = self.request.GET.get('next', '')\nif not url:\n url = '/'\nreturn url"
] | <|body_start_0|>
user = form.user_cache
login(self.request, user)
return super(LoginView, self).form_valid(form)
<|end_body_0|>
<|body_start_1|>
url = self.request.GET.get('next', '')
if not url:
url = '/'
return url
<|end_body_1|>
| LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
def form_valid(self, form):
"""Logs user in if the form is valid. Inherits user_cache from django.contrib.auth.forms.AuthenticationForm."""
<|body_0|>
def get_success_url(self):
"""Looks up a next page in the url, and returns it as success_url. If there is... | stack_v2_sparse_classes_36k_train_031739 | 3,332 | no_license | [
{
"docstring": "Logs user in if the form is valid. Inherits user_cache from django.contrib.auth.forms.AuthenticationForm.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Looks up a next page in the url, and returns it as success_url. If there is none (is empt... | 2 | stack_v2_sparse_classes_30k_train_020219 | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def form_valid(self, form): Logs user in if the form is valid. Inherits user_cache from django.contrib.auth.forms.AuthenticationForm.
- def get_success_url(self): Looks up a ne... | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def form_valid(self, form): Logs user in if the form is valid. Inherits user_cache from django.contrib.auth.forms.AuthenticationForm.
- def get_success_url(self): Looks up a ne... | b42847ddb77698e3864ae8bb2686a869b5900d7b | <|skeleton|>
class LoginView:
def form_valid(self, form):
"""Logs user in if the form is valid. Inherits user_cache from django.contrib.auth.forms.AuthenticationForm."""
<|body_0|>
def get_success_url(self):
"""Looks up a next page in the url, and returns it as success_url. If there is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginView:
def form_valid(self, form):
"""Logs user in if the form is valid. Inherits user_cache from django.contrib.auth.forms.AuthenticationForm."""
user = form.user_cache
login(self.request, user)
return super(LoginView, self).form_valid(form)
def get_success_url(self):... | the_stack_v2_python_sparse | Expedientedental/accounts/views.py | jesselpineda/dental-record | train | 0 | |
02b5da61f9f19061525ed4459258e50e3bf0bd27 | [
"self._cap = capacity\nself._size = 0\nself._table = {}\nself._head = Node(0, -1)\nself._tail = Node(0, -1)\nself._head.next = self._tail\nself._tail.prev = self._head",
"if key not in self._table:\n return -1\nnode = self._table[key]\nnode.prev.next = node.next\nnode.next.prev = node.prev\nnode.next = self._t... | <|body_start_0|>
self._cap = capacity
self._size = 0
self._table = {}
self._head = Node(0, -1)
self._tail = Node(0, -1)
self._head.next = self._tail
self._tail.prev = self._head
<|end_body_0|>
<|body_start_1|>
if key not in self._table:
return... | LRUCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_031740 | 2,110 | permissive | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | e38774cab5cf757ed858547780a8582951f117b4 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self._cap = capacity
self._size = 0
self._table = {}
self._head = Node(0, -1)
self._tail = Node(0, -1)
self._head.next = self._tail
self._tail.prev = self._head
def get(self, ... | the_stack_v2_python_sparse | crack-data-structures-and-algorithms/leetcode/python-impl/lru_cache_q146.py | kingsamchen/Eureka | train | 28 | |
d0c44c99119ac2e02260ff2f0b0d23a3c6d45be4 | [
"super(AttentionPooling, self).__init__()\ntotal_features_channels = molecule_channels + hidden_channels\nself.lin = nn.Linear(total_features_channels, hidden_channels)\nself.last_rep = nn.Linear(hidden_channels, hidden_channels)",
"att = torch.sigmoid(self.lin(torch.cat((input_rep, final_rep), dim=1)))\ng = att.... | <|body_start_0|>
super(AttentionPooling, self).__init__()
total_features_channels = molecule_channels + hidden_channels
self.lin = nn.Linear(total_features_channels, hidden_channels)
self.last_rep = nn.Linear(hidden_channels, hidden_channels)
<|end_body_0|>
<|body_start_1|>
att ... | The attention pooling layer from [chen2020]_. | AttentionPooling | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionPooling:
"""The attention pooling layer from [chen2020]_."""
def __init__(self, molecule_channels: int, hidden_channels: int):
"""Instantiate the attention pooling layer. :param molecule_channels: Input node features. :param hidden_channels: Final node representation."""
... | stack_v2_sparse_classes_36k_train_031741 | 25,672 | no_license | [
{
"docstring": "Instantiate the attention pooling layer. :param molecule_channels: Input node features. :param hidden_channels: Final node representation.",
"name": "__init__",
"signature": "def __init__(self, molecule_channels: int, hidden_channels: int)"
},
{
"docstring": "Compute an attention... | 2 | stack_v2_sparse_classes_30k_train_014394 | Implement the Python class `AttentionPooling` described below.
Class description:
The attention pooling layer from [chen2020]_.
Method signatures and docstrings:
- def __init__(self, molecule_channels: int, hidden_channels: int): Instantiate the attention pooling layer. :param molecule_channels: Input node features. ... | Implement the Python class `AttentionPooling` described below.
Class description:
The attention pooling layer from [chen2020]_.
Method signatures and docstrings:
- def __init__(self, molecule_channels: int, hidden_channels: int): Instantiate the attention pooling layer. :param molecule_channels: Input node features. ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class AttentionPooling:
"""The attention pooling layer from [chen2020]_."""
def __init__(self, molecule_channels: int, hidden_channels: int):
"""Instantiate the attention pooling layer. :param molecule_channels: Input node features. :param hidden_channels: Final node representation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentionPooling:
"""The attention pooling layer from [chen2020]_."""
def __init__(self, molecule_channels: int, hidden_channels: int):
"""Instantiate the attention pooling layer. :param molecule_channels: Input node features. :param hidden_channels: Final node representation."""
super(At... | the_stack_v2_python_sparse | generated/test_AstraZeneca_chemicalx.py | jansel/pytorch-jit-paritybench | train | 35 |
f2eda4d92f282a8554973a8eb5aa1b48d52041f6 | [
"result = {}\npart_obj = self.pool.get('res.partner')\nfor company in self.browse(cr, uid, ids, context=context):\n result[company.id] = {}.fromkeys(field_names, False)\n if company.partner_id:\n data = part_obj.read(cr, SUPERUSER_ID, [company.partner_id.id], field_names, context=context)[0]\n f... | <|body_start_0|>
result = {}
part_obj = self.pool.get('res.partner')
for company in self.browse(cr, uid, ids, context=context):
result[company.id] = {}.fromkeys(field_names, False)
if company.partner_id:
data = part_obj.read(cr, SUPERUSER_ID, [company.part... | ResCompany | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResCompany:
def _get_baremo_data(self, cr, uid, ids, field_names, arg, context=None):
"""Read the 'baremo_id' functional field."""
<|body_0|>
def _set_baremo_data(self, cr, uid, company_id, name, value, arg, context=None):
"""Write the 'baremo_id' functional field.""... | stack_v2_sparse_classes_36k_train_031742 | 4,557 | no_license | [
{
"docstring": "Read the 'baremo_id' functional field.",
"name": "_get_baremo_data",
"signature": "def _get_baremo_data(self, cr, uid, ids, field_names, arg, context=None)"
},
{
"docstring": "Write the 'baremo_id' functional field.",
"name": "_set_baremo_data",
"signature": "def _set_bar... | 2 | null | Implement the Python class `ResCompany` described below.
Class description:
Implement the ResCompany class.
Method signatures and docstrings:
- def _get_baremo_data(self, cr, uid, ids, field_names, arg, context=None): Read the 'baremo_id' functional field.
- def _set_baremo_data(self, cr, uid, company_id, name, value... | Implement the Python class `ResCompany` described below.
Class description:
Implement the ResCompany class.
Method signatures and docstrings:
- def _get_baremo_data(self, cr, uid, ids, field_names, arg, context=None): Read the 'baremo_id' functional field.
- def _set_baremo_data(self, cr, uid, company_id, name, value... | 511dc410b4eba1f8ea939c6af02a5adea5122c92 | <|skeleton|>
class ResCompany:
def _get_baremo_data(self, cr, uid, ids, field_names, arg, context=None):
"""Read the 'baremo_id' functional field."""
<|body_0|>
def _set_baremo_data(self, cr, uid, company_id, name, value, arg, context=None):
"""Write the 'baremo_id' functional field.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResCompany:
def _get_baremo_data(self, cr, uid, ids, field_names, arg, context=None):
"""Read the 'baremo_id' functional field."""
result = {}
part_obj = self.pool.get('res.partner')
for company in self.browse(cr, uid, ids, context=context):
result[company.id] = {}.... | the_stack_v2_python_sparse | baremo/model/baremo.py | yelizariev/addons-vauxoo | train | 3 | |
4b94ca7e51bfd8e719af121db9e1b83f8003a6de | [
"def helper(root):\n res = []\n if root:\n res.append(str(root.val))\n left = helper(root.left)\n right = helper(root.right)\n res.extend(left)\n res.extend(right)\n else:\n res.append(self.NULL)\n return res\nres = helper(root)\nreturn self.SPLITER.join(res)",
... | <|body_start_0|>
def helper(root):
res = []
if root:
res.append(str(root.val))
left = helper(root.left)
right = helper(root.right)
res.extend(left)
res.extend(right)
else:
res.appe... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031743 | 1,518 | 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:... | 4d340a45fb2e9459d47cbe179ebfa7a82e5f1b8c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def helper(root):
res = []
if root:
res.append(str(root.val))
left = helper(root.left)
right = helper(root.right)
... | the_stack_v2_python_sparse | 291_SerializeAndDeserializeBinaryTree/solution.py | llgeek/leetcode | train | 1 | |
2fc4f77ca82809f3878cb8bd5e1bd270e86c1ee1 | [
"name = 'hg'\nif os.name == 'nt':\n name += '.exe'\nbinary = self.find_binary(name)\nif binary and os.path.isdir(binary):\n full_path = os.path.join(binary, name)\n if os.path.exists(full_path):\n binary = full_path\nif not binary:\n show_error((u'Unable to find %s. Please set the hg_binary setti... | <|body_start_0|>
name = 'hg'
if os.name == 'nt':
name += '.exe'
binary = self.find_binary(name)
if binary and os.path.isdir(binary):
full_path = os.path.join(binary, name)
if os.path.exists(full_path):
binary = full_path
if not ... | Allows upgrading a local mercurial-repository-based package | HgUpgrader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HgUpgrader:
"""Allows upgrading a local mercurial-repository-based package"""
def retrieve_binary(self):
"""Returns the path to the hg executable :return: The string path to the executable or False on error"""
<|body_0|>
def run(self):
"""Updates the repository w... | stack_v2_sparse_classes_36k_train_031744 | 2,166 | permissive | [
{
"docstring": "Returns the path to the hg executable :return: The string path to the executable or False on error",
"name": "retrieve_binary",
"signature": "def retrieve_binary(self)"
},
{
"docstring": "Updates the repository with remote changes :return: False or error, or True on success",
... | 3 | stack_v2_sparse_classes_30k_train_005802 | Implement the Python class `HgUpgrader` described below.
Class description:
Allows upgrading a local mercurial-repository-based package
Method signatures and docstrings:
- def retrieve_binary(self): Returns the path to the hg executable :return: The string path to the executable or False on error
- def run(self): Upd... | Implement the Python class `HgUpgrader` described below.
Class description:
Allows upgrading a local mercurial-repository-based package
Method signatures and docstrings:
- def retrieve_binary(self): Returns the path to the hg executable :return: The string path to the executable or False on error
- def run(self): Upd... | 8c9833710577de6db6e8b1db5d9196e19e19d117 | <|skeleton|>
class HgUpgrader:
"""Allows upgrading a local mercurial-repository-based package"""
def retrieve_binary(self):
"""Returns the path to the hg executable :return: The string path to the executable or False on error"""
<|body_0|>
def run(self):
"""Updates the repository w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HgUpgrader:
"""Allows upgrading a local mercurial-repository-based package"""
def retrieve_binary(self):
"""Returns the path to the hg executable :return: The string path to the executable or False on error"""
name = 'hg'
if os.name == 'nt':
name += '.exe'
bina... | the_stack_v2_python_sparse | EthanBrown.SublimeText2.UtilPackages/tools/PackageCache/Package Control/package_control/upgraders/hg_upgrader.py | Iristyle/ChocolateyPackages | train | 19 |
a62139b6ecff048c0b00e5e8c9072df92e7f71ed | [
"self.safe_update(**kwargs)\nif butler is not None:\n self.log.warn('Ignoring butler')\nrun_dict = dict(runs=[], rafts=[])\nfor key, val in sorted(data.items()):\n run_dict['runs'].append(key[4:])\n run_dict['rafts'].append(key[0:3])\n data[key] = val.replace(self.config.filekey, self.config.infilekey)\... | <|body_start_0|>
self.safe_update(**kwargs)
if butler is not None:
self.log.warn('Ignoring butler')
run_dict = dict(runs=[], rafts=[])
for key, val in sorted(data.items()):
run_dict['runs'].append(key[4:])
run_dict['rafts'].append(key[0:3])
... | Summarize the results for the analysis of variations of the bias frames | SuperbiasSummaryTask | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperbiasSummaryTask:
"""Summarize the results for the analysis of variations of the bias frames"""
def extract(self, butler, data, **kwargs):
"""Make a summary table of the superbias statistics Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or othe... | stack_v2_sparse_classes_36k_train_031745 | 8,427 | permissive | [
{
"docstring": "Make a summary table of the superbias statistics Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) contain the input data kwargs Used to override default configuration Returns ------- dtables : `TableDict` The resulting data",
"name": "extr... | 2 | null | Implement the Python class `SuperbiasSummaryTask` described below.
Class description:
Summarize the results for the analysis of variations of the bias frames
Method signatures and docstrings:
- def extract(self, butler, data, **kwargs): Make a summary table of the superbias statistics Parameters ---------- butler : `... | Implement the Python class `SuperbiasSummaryTask` described below.
Class description:
Summarize the results for the analysis of variations of the bias frames
Method signatures and docstrings:
- def extract(self, butler, data, **kwargs): Make a summary table of the superbias statistics Parameters ---------- butler : `... | 28418284fdaf2b2fb0afbeccd4324f7ad3e676c8 | <|skeleton|>
class SuperbiasSummaryTask:
"""Summarize the results for the analysis of variations of the bias frames"""
def extract(self, butler, data, **kwargs):
"""Make a summary table of the superbias statistics Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or othe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperbiasSummaryTask:
"""Summarize the results for the analysis of variations of the bias frames"""
def extract(self, butler, data, **kwargs):
"""Make a summary table of the superbias statistics Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) ... | the_stack_v2_python_sparse | python/lsst/eo_utils/bias/superbias_stats.py | lsst-camera-dh/EO-utilities | train | 2 |
ee7b959f12a81d2d981a9ebf5c2fdb4cef154f76 | [
"super(ImprovedGAN_Discriminator, self).__init__()\nself.use_gpu = use_gpu\nself.n_B = n_B\nself.n_C = n_C\nself.featmap_dim = featmap_dim\nself.conv1 = nn.Conv2d(n_channel, featmap_dim / 4, 5, stride=2, padding=2)\nself.conv2 = nn.Conv2d(featmap_dim / 4, featmap_dim / 2, 5, stride=2, padding=2)\nself.BN2 = nn.Batc... | <|body_start_0|>
super(ImprovedGAN_Discriminator, self).__init__()
self.use_gpu = use_gpu
self.n_B = n_B
self.n_C = n_C
self.featmap_dim = featmap_dim
self.conv1 = nn.Conv2d(n_channel, featmap_dim / 4, 5, stride=2, padding=2)
self.conv2 = nn.Conv2d(featmap_dim / 4... | ImprovedGAN_Discriminator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImprovedGAN_Discriminator:
def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16):
"""Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch."""
<|body_0|>
def forward(self, x):
"""Archi... | stack_v2_sparse_classes_36k_train_031746 | 19,546 | no_license | [
{
"docstring": "Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch.",
"name": "__init__",
"signature": "def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16)"
},
{
"docstring": "Architecture is similar to DCGAN... | 2 | stack_v2_sparse_classes_30k_train_006703 | Implement the Python class `ImprovedGAN_Discriminator` described below.
Class description:
Implement the ImprovedGAN_Discriminator class.
Method signatures and docstrings:
- def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): Minibatch discrimination: learn a tensor to encode side inform... | Implement the Python class `ImprovedGAN_Discriminator` described below.
Class description:
Implement the ImprovedGAN_Discriminator class.
Method signatures and docstrings:
- def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): Minibatch discrimination: learn a tensor to encode side inform... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ImprovedGAN_Discriminator:
def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16):
"""Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch."""
<|body_0|>
def forward(self, x):
"""Archi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImprovedGAN_Discriminator:
def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16):
"""Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch."""
super(ImprovedGAN_Discriminator, self).__init__()
self.use_g... | the_stack_v2_python_sparse | generated/test_AaronYALai_Generative_Adversarial_Networks_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 | |
38dda69bd47b357246faf9679e9f7737450a2562 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.androidManagedAppRegistration'.casefold():\... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | The ManagedAppEntity is the base entity type for all other entity types under app management workflow. | ManagedAppRegistration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedAppRegistration:
"""The ManagedAppEntity is the base entity type for all other entity types under app management workflow."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppRegistration:
"""Creates a new instance of the appropriate class... | stack_v2_sparse_classes_36k_train_031747 | 8,053 | 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: ManagedAppRegistration",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `ManagedAppRegistration` described below.
Class description:
The ManagedAppEntity is the base entity type for all other entity types under app management workflow.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppRegi... | Implement the Python class `ManagedAppRegistration` described below.
Class description:
The ManagedAppEntity is the base entity type for all other entity types under app management workflow.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppRegi... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ManagedAppRegistration:
"""The ManagedAppEntity is the base entity type for all other entity types under app management workflow."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppRegistration:
"""Creates a new instance of the appropriate class... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManagedAppRegistration:
"""The ManagedAppEntity is the base entity type for all other entity types under app management workflow."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppRegistration:
"""Creates a new instance of the appropriate class based on dis... | the_stack_v2_python_sparse | msgraph/generated/models/managed_app_registration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
f0fb1b4387b455604fa3d01f6c93bdedb8d29991 | [
"shape = np.array([2, 3, 4])\ndata = np.zeros(shape)\ngraph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[('data_node', {'shape': shape, 'value': data})])\ngraph_ref = build_graph_with_attrs(nodes_with_attrs=self.nodes + self.new_nodes, edges_with_attrs=... | <|body_start_0|>
shape = np.array([2, 3, 4])
data = np.zeros(shape)
graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[('data_node', {'shape': shape, 'value': data})])
graph_ref = build_graph_with_attrs(nodes_with_attrs=self.... | CreateConstNodesReplacementTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateConstNodesReplacementTest:
def test_one_node(self):
"""We should add Const node and data node."""
<|body_0|>
def test_one_bin_node(self):
"""Nothing should happen."""
<|body_1|>
def test_two_nodes_with_bin(self):
"""Test case for data node ... | stack_v2_sparse_classes_36k_train_031748 | 4,410 | permissive | [
{
"docstring": "We should add Const node and data node.",
"name": "test_one_node",
"signature": "def test_one_node(self)"
},
{
"docstring": "Nothing should happen.",
"name": "test_one_bin_node",
"signature": "def test_one_bin_node(self)"
},
{
"docstring": "Test case for data node... | 4 | stack_v2_sparse_classes_30k_train_006646 | Implement the Python class `CreateConstNodesReplacementTest` described below.
Class description:
Implement the CreateConstNodesReplacementTest class.
Method signatures and docstrings:
- def test_one_node(self): We should add Const node and data node.
- def test_one_bin_node(self): Nothing should happen.
- def test_tw... | Implement the Python class `CreateConstNodesReplacementTest` described below.
Class description:
Implement the CreateConstNodesReplacementTest class.
Method signatures and docstrings:
- def test_one_node(self): We should add Const node and data node.
- def test_one_bin_node(self): Nothing should happen.
- def test_tw... | e4bed7a31c9f00d8afbfcabee3f64f55496ae56a | <|skeleton|>
class CreateConstNodesReplacementTest:
def test_one_node(self):
"""We should add Const node and data node."""
<|body_0|>
def test_one_bin_node(self):
"""Nothing should happen."""
<|body_1|>
def test_two_nodes_with_bin(self):
"""Test case for data node ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateConstNodesReplacementTest:
def test_one_node(self):
"""We should add Const node and data node."""
shape = np.array([2, 3, 4])
data = np.zeros(shape)
graph = build_graph_with_attrs(nodes_with_attrs=self.nodes, edges_with_attrs=self.edges, update_nodes_attributes=[('data_no... | the_stack_v2_python_sparse | tools/mo/unit_tests/mo/back/SpecialNodesFinalization_test.py | openvinotoolkit/openvino | train | 3,953 | |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"self.prob = prob\nself.flip_axis = flip_axis\nsuper().__init__()",
"if isinstance(self.flip_axis, (tuple, list)):\n flip_axis = self.flip_axis[random.randint(0, len(self.flip_axis) - 1)]\nelse:\n flip_axis = self.flip_axis\nif random.random() < self.prob:\n img = F.flip_3d(img, axis=flip_axis)\n if l... | <|body_start_0|>
self.prob = prob
self.flip_axis = flip_axis
super().__init__()
<|end_body_0|>
<|body_start_1|>
if isinstance(self.flip_axis, (tuple, list)):
flip_axis = self.flip_axis[random.randint(0, len(self.flip_axis) - 1)]
else:
flip_axis = self.fli... | Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1. | RandomFlip3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomFlip3D:
"""Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
<|body_0|>
def __call__(self, img, label=None):
"""Args:... | stack_v2_sparse_classes_36k_train_031749 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, prob=0.5, flip_axis=[0, 1, 2])"
},
{
"docstring": "Args: img (numpy ndarray): 3D Image to be flipped. label (numpy ndarray): 3D Label to be flipped. Returns: (np.array). Image after transformation.",
"name": "__call_... | 2 | stack_v2_sparse_classes_30k_val_000309 | Implement the Python class `RandomFlip3D` described below.
Class description:
Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1.
Method signatures and docstrings:
- def __init__(self, prob=0.5, flip_axis=[0, 1, 2]): init
- def __call__(self, im... | Implement the Python class `RandomFlip3D` described below.
Class description:
Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1.
Method signatures and docstrings:
- def __init__(self, prob=0.5, flip_axis=[0, 1, 2]): init
- def __call__(self, im... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomFlip3D:
"""Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
<|body_0|>
def __call__(self, img, label=None):
"""Args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomFlip3D:
"""Flip an 3D image with a certain probability. Args: prob (float, optional): A probability of vertical flipping. Default: 0.1."""
def __init__(self, prob=0.5, flip_axis=[0, 1, 2]):
"""init"""
self.prob = prob
self.flip_axis = flip_axis
super().__init__()
... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
f47aaca0be484a0e53045f98283a76623d99fe06 | [
"cur = 1\nprev = 0\nret = 0\nfor i in range(1, len(s)):\n if s[i] == s[i - 1]:\n cur += 1\n else:\n prev = cur\n cur = 1\n if prev >= cur:\n ret += 1\nreturn ret",
"counter = {'0': 0, '1': 0}\nret = 0\nif not s:\n return ret\ncounter[s[0]] += 1\nfor i in range(1, len(s)):\n... | <|body_start_0|>
cur = 1
prev = 0
ret = 0
for i in range(1, len(s)):
if s[i] == s[i - 1]:
cur += 1
else:
prev = cur
cur = 1
if prev >= cur:
ret += 1
return ret
<|end_body_0|>
<|bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countBinarySubstrings(self, s: str) -> int:
"""two-pointers + math"""
<|body_0|>
def countBinarySubstrings_error(self, s: str) -> int:
"""two-pointers + math"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = 1
prev = 0
... | stack_v2_sparse_classes_36k_train_031750 | 1,917 | no_license | [
{
"docstring": "two-pointers + math",
"name": "countBinarySubstrings",
"signature": "def countBinarySubstrings(self, s: str) -> int"
},
{
"docstring": "two-pointers + math",
"name": "countBinarySubstrings_error",
"signature": "def countBinarySubstrings_error(self, s: str) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBinarySubstrings(self, s: str) -> int: two-pointers + math
- def countBinarySubstrings_error(self, s: str) -> int: two-pointers + math | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBinarySubstrings(self, s: str) -> int: two-pointers + math
- def countBinarySubstrings_error(self, s: str) -> int: two-pointers + math
<|skeleton|>
class Solution:
... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def countBinarySubstrings(self, s: str) -> int:
"""two-pointers + math"""
<|body_0|>
def countBinarySubstrings_error(self, s: str) -> int:
"""two-pointers + math"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countBinarySubstrings(self, s: str) -> int:
"""two-pointers + math"""
cur = 1
prev = 0
ret = 0
for i in range(1, len(s)):
if s[i] == s[i - 1]:
cur += 1
else:
prev = cur
cur = 1
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/696 Count Binary Substrings.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
d12f18fac3189a2336398c1f6e851f4c17bca63a | [
"Talker.__init__(self)\nself.visualize = visualize\nself.obs = obs\nself.obs.reducer = self\nself.speak('the reducing mosasaurus is grabbing a fly spanker to analyze\\n {0}'.format(self.obs))\nself.setup()\nself.speak('mosasaurus is ready to reduce')\nself.label = label\nself.extractionDirectory = os.path.join(self... | <|body_start_0|>
Talker.__init__(self)
self.visualize = visualize
self.obs = obs
self.obs.reducer = self
self.speak('the reducing mosasaurus is grabbing a fly spanker to analyze\n {0}'.format(self.obs))
self.setup()
self.speak('mosasaurus is ready to reduce')
... | Reducers are objects for reducing data, either interactively or not. This could be pictured as a mosasaurus, wearing a loupe and carrying lots of data structures around in its knapsack. | Reducer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reducer:
"""Reducers are objects for reducing data, either interactively or not. This could be pictured as a mosasaurus, wearing a loupe and carrying lots of data structures around in its knapsack."""
def __init__(self, obs, label='default', visualize=True):
"""initialize from an obs... | stack_v2_sparse_classes_36k_train_031751 | 3,100 | permissive | [
{
"docstring": "initialize from an observation",
"name": "__init__",
"signature": "def __init__(self, obs, label='default', visualize=True)"
},
{
"docstring": "Setup all the basic components, or give them easier shortcuts.",
"name": "setup",
"signature": "def setup(self)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_007292 | Implement the Python class `Reducer` described below.
Class description:
Reducers are objects for reducing data, either interactively or not. This could be pictured as a mosasaurus, wearing a loupe and carrying lots of data structures around in its knapsack.
Method signatures and docstrings:
- def __init__(self, obs,... | Implement the Python class `Reducer` described below.
Class description:
Reducers are objects for reducing data, either interactively or not. This could be pictured as a mosasaurus, wearing a loupe and carrying lots of data structures around in its knapsack.
Method signatures and docstrings:
- def __init__(self, obs,... | 09f24956d080044b996ca1e646525acd8b0ccbe0 | <|skeleton|>
class Reducer:
"""Reducers are objects for reducing data, either interactively or not. This could be pictured as a mosasaurus, wearing a loupe and carrying lots of data structures around in its knapsack."""
def __init__(self, obs, label='default', visualize=True):
"""initialize from an obs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reducer:
"""Reducers are objects for reducing data, either interactively or not. This could be pictured as a mosasaurus, wearing a loupe and carrying lots of data structures around in its knapsack."""
def __init__(self, obs, label='default', visualize=True):
"""initialize from an observation"""
... | the_stack_v2_python_sparse | mosasaurus/Reducer.py | zkbt/mosasaurus | train | 3 |
fa83e0fddf69bd0119cf9f296cd1f4783cbea9b4 | [
"self.backup_type = backup_type\nself.copy_partially_successful_run = copy_partially_successful_run\nself.granularity_bucket = granularity_bucket\nself.id = id\nself.retention_policy = retention_policy",
"if dictionary is None:\n return None\nbackup_type = dictionary.get('backupType')\ncopy_partially_successfu... | <|body_start_0|>
self.backup_type = backup_type
self.copy_partially_successful_run = copy_partially_successful_run
self.granularity_bucket = granularity_bucket
self.id = id
self.retention_policy = retention_policy
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'ExtendedRetentionPolicyProto' model. Message that specifies additional retention policies to apply to backup snapshots. Attributes: backup_type (int): The backup type to which this extended retention applies to. If this is not set, the extended retention will be applicable to all non-log backup t... | ExtendedRetentionPolicyProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtendedRetentionPolicyProto:
"""Implementation of the 'ExtendedRetentionPolicyProto' model. Message that specifies additional retention policies to apply to backup snapshots. Attributes: backup_type (int): The backup type to which this extended retention applies to. If this is not set, the exten... | stack_v2_sparse_classes_36k_train_031752 | 4,004 | permissive | [
{
"docstring": "Constructor for the ExtendedRetentionPolicyProto class",
"name": "__init__",
"signature": "def __init__(self, backup_type=None, copy_partially_successful_run=None, granularity_bucket=None, id=None, retention_policy=None)"
},
{
"docstring": "Creates an instance of this model from ... | 2 | stack_v2_sparse_classes_30k_train_013534 | Implement the Python class `ExtendedRetentionPolicyProto` described below.
Class description:
Implementation of the 'ExtendedRetentionPolicyProto' model. Message that specifies additional retention policies to apply to backup snapshots. Attributes: backup_type (int): The backup type to which this extended retention ap... | Implement the Python class `ExtendedRetentionPolicyProto` described below.
Class description:
Implementation of the 'ExtendedRetentionPolicyProto' model. Message that specifies additional retention policies to apply to backup snapshots. Attributes: backup_type (int): The backup type to which this extended retention ap... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ExtendedRetentionPolicyProto:
"""Implementation of the 'ExtendedRetentionPolicyProto' model. Message that specifies additional retention policies to apply to backup snapshots. Attributes: backup_type (int): The backup type to which this extended retention applies to. If this is not set, the exten... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtendedRetentionPolicyProto:
"""Implementation of the 'ExtendedRetentionPolicyProto' model. Message that specifies additional retention policies to apply to backup snapshots. Attributes: backup_type (int): The backup type to which this extended retention applies to. If this is not set, the extended retention... | the_stack_v2_python_sparse | cohesity_management_sdk/models/extended_retention_policy_proto.py | cohesity/management-sdk-python | train | 24 |
4e45b30da29f47329ff8bfa430e4473f001bd760 | [
"li = []\nfor i in range(n):\n li.append(nums[i])\n for j in range(i + 1, n):\n li.append(li[-1] + nums[j])\nli.sort()\nres = sum(li[left - 1:right])\nreturn res % (10 ** 9 + 7)",
"prefix_and = [0]\npre_and = 0\nfor num in nums:\n pre_and += num\n prefix_and.append(pre_and)\nlength = len(prefix... | <|body_start_0|>
li = []
for i in range(n):
li.append(nums[i])
for j in range(i + 1, n):
li.append(li[-1] + nums[j])
li.sort()
res = sum(li[left - 1:right])
return res % (10 ** 9 + 7)
<|end_body_0|>
<|body_start_1|>
prefix_and = [0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rangeSum(self, nums, n, left, right):
""":type nums: List[int] :type n: int :type left: int :type right: int :rtype: int"""
<|body_0|>
def rangeSum(self, nums, n, left, right):
""":type nums: List[int] :type n: int :type left: int :type right: int :rtyp... | stack_v2_sparse_classes_36k_train_031753 | 1,118 | no_license | [
{
"docstring": ":type nums: List[int] :type n: int :type left: int :type right: int :rtype: int",
"name": "rangeSum",
"signature": "def rangeSum(self, nums, n, left, right)"
},
{
"docstring": ":type nums: List[int] :type n: int :type left: int :type right: int :rtype: int",
"name": "rangeSum... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeSum(self, nums, n, left, right): :type nums: List[int] :type n: int :type left: int :type right: int :rtype: int
- def rangeSum(self, nums, n, left, right): :type nums: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeSum(self, nums, n, left, right): :type nums: List[int] :type n: int :type left: int :type right: int :rtype: int
- def rangeSum(self, nums, n, left, right): :type nums: ... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def rangeSum(self, nums, n, left, right):
""":type nums: List[int] :type n: int :type left: int :type right: int :rtype: int"""
<|body_0|>
def rangeSum(self, nums, n, left, right):
""":type nums: List[int] :type n: int :type left: int :type right: int :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rangeSum(self, nums, n, left, right):
""":type nums: List[int] :type n: int :type left: int :type right: int :rtype: int"""
li = []
for i in range(n):
li.append(nums[i])
for j in range(i + 1, n):
li.append(li[-1] + nums[j])
... | the_stack_v2_python_sparse | 1508_Range_Sum_of_Sorted_Subarray_Sums.py | bingli8802/leetcode | train | 0 | |
fdce529a626ebb5590dc5bff1c80a121fafc7020 | [
"max_nums = set()\nfor k in range(3):\n curr_max = float('-inf')\n for n in nums:\n if n not in max_nums and n > curr_max:\n curr_max = n\n if curr_max != float('-inf'):\n max_nums.add(curr_max)\nreturn min(max_nums) if len(max_nums) == 3 else max(max_nums)",
"first = second = th... | <|body_start_0|>
max_nums = set()
for k in range(3):
curr_max = float('-inf')
for n in nums:
if n not in max_nums and n > curr_max:
curr_max = n
if curr_max != float('-inf'):
max_nums.add(curr_max)
return min... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def thirdMax_1(self, nums):
"""Returns 3rd maximum unique number in array nums. If there's no such, returns 1st / 2nd max unique number. Simple algorithm. Algorithm description: 1) Create a set of max numbers. 2) Loop over array 3 times. 3) Choose next max number that doesn't e... | stack_v2_sparse_classes_36k_train_031754 | 2,200 | no_license | [
{
"docstring": "Returns 3rd maximum unique number in array nums. If there's no such, returns 1st / 2nd max unique number. Simple algorithm. Algorithm description: 1) Create a set of max numbers. 2) Loop over array 3 times. 3) Choose next max number that doesn't equal numbers in the set. 4) If we found 3 max num... | 2 | stack_v2_sparse_classes_30k_train_008842 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax_1(self, nums): Returns 3rd maximum unique number in array nums. If there's no such, returns 1st / 2nd max unique number. Simple algorithm. Algorithm description: 1) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax_1(self, nums): Returns 3rd maximum unique number in array nums. If there's no such, returns 1st / 2nd max unique number. Simple algorithm. Algorithm description: 1) ... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def thirdMax_1(self, nums):
"""Returns 3rd maximum unique number in array nums. If there's no such, returns 1st / 2nd max unique number. Simple algorithm. Algorithm description: 1) Create a set of max numbers. 2) Loop over array 3 times. 3) Choose next max number that doesn't e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def thirdMax_1(self, nums):
"""Returns 3rd maximum unique number in array nums. If there's no such, returns 1st / 2nd max unique number. Simple algorithm. Algorithm description: 1) Create a set of max numbers. 2) Loop over array 3 times. 3) Choose next max number that doesn't equal numbers i... | the_stack_v2_python_sparse | Arrays/third_max_number.py | vladn90/Algorithms | train | 0 | |
fba224569305d34df69d5eb19a139218b5736b18 | [
"Frame.__init__(self, master)\nself.pack()\nself.updateArtistWidgets()",
"tag_name = Frame(self)\nartist_name = Frame(self)\nnewGenre_name = Frame(self)\nself.labeltag = Label(tag_name, text='Update Artist Genre')\nself.labelArtist = Label(artist_name, text='Artist Name')\nself.labelNewGenre = Label(newGenre_name... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.updateArtistWidgets()
<|end_body_0|>
<|body_start_1|>
tag_name = Frame(self)
artist_name = Frame(self)
newGenre_name = Frame(self)
self.labeltag = Label(tag_name, text='Update Artist Genre')
s... | Application main window class. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def updateArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k_train_031755 | 2,288 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "updateArtistWidgets",
"signature": "def updateArtistWidgets(self)"
},
{
"docstrin... | 3 | null | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def updateArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Hand... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def updateArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Hand... | 2dba11861f91e4bdc1ef28279132a6d8dd4ccf54 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def updateArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.updateArtistWidgets()
def updateArtistWidgets(self):
"""Add all the widgets to t... | the_stack_v2_python_sparse | Mux_Gui/Update_Artist_Gui.py | rduvalwa5/Mux | train | 0 |
ff046abe78ec256785e4479dcf80a8f70495548a | [
"self.auto_mileage = 0.0\nself.manual_mileage = 0.0\nself.disengagements = 0",
"last_pos = None\nlast_mode = 'Unknown'\nmileage = collections.defaultdict(lambda: 0.0)\nchassis = chassis_pb2.Chassis()\nlocalization = localization_pb2.LocalizationEstimate()\nreader = RecordReader(bag_file)\nfor msg in reader.read_m... | <|body_start_0|>
self.auto_mileage = 0.0
self.manual_mileage = 0.0
self.disengagements = 0
<|end_body_0|>
<|body_start_1|>
last_pos = None
last_mode = 'Unknown'
mileage = collections.defaultdict(lambda: 0.0)
chassis = chassis_pb2.Chassis()
localization = ... | Calculate mileage | MileageCalculator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MileageCalculator:
"""Calculate mileage"""
def __init__(self):
"""Init."""
<|body_0|>
def calculate(self, bag_file):
"""Calculate mileage"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.auto_mileage = 0.0
self.manual_mileage = 0.0
... | stack_v2_sparse_classes_36k_train_031756 | 3,604 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calculate mileage",
"name": "calculate",
"signature": "def calculate(self, bag_file)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000491 | Implement the Python class `MileageCalculator` described below.
Class description:
Calculate mileage
Method signatures and docstrings:
- def __init__(self): Init.
- def calculate(self, bag_file): Calculate mileage | Implement the Python class `MileageCalculator` described below.
Class description:
Calculate mileage
Method signatures and docstrings:
- def __init__(self): Init.
- def calculate(self, bag_file): Calculate mileage
<|skeleton|>
class MileageCalculator:
"""Calculate mileage"""
def __init__(self):
"""I... | 105f7fd19220dc4c04be1e075b1a5d932eaa2f3f | <|skeleton|>
class MileageCalculator:
"""Calculate mileage"""
def __init__(self):
"""Init."""
<|body_0|>
def calculate(self, bag_file):
"""Calculate mileage"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MileageCalculator:
"""Calculate mileage"""
def __init__(self):
"""Init."""
self.auto_mileage = 0.0
self.manual_mileage = 0.0
self.disengagements = 0
def calculate(self, bag_file):
"""Calculate mileage"""
last_pos = None
last_mode = 'Unknown'
... | the_stack_v2_python_sparse | modules/tools/rosbag/stat_mileage.py | lgsvl/apollo-5.0 | train | 86 |
dec0762029a5c3440d78cddf4fa7db34e0e94e19 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)",
"sqr_sumx1 = np.sum(X1 ** 2, 1).reshape(-1, 1)\nsqr_sumx2 = np.sum(X2 ** 2, 1)\nsqr_dist = sqr_sumx1 + sqr_sumx2 - 2 * np.dot(X1, X2.T)\nkernel = self.sigma_f ** 2 * np.exp(-0.5 / self.l ** 2 * sqr_dist)\... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(X_init, X_init)
<|end_body_0|>
<|body_start_1|>
sqr_sumx1 = np.sum(X1 ** 2, 1).reshape(-1, 1)
sqr_sumx2 = np.sum(X2 ** 2, 1)
sqr_dist = sqr_sumx1 + sqr... | Represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor. Sets the public instance attributes X, Y, l, and sigma_f corresponding to the respective constructor inputs Sets the public instance attribute K... | stack_v2_sparse_classes_36k_train_031757 | 4,488 | no_license | [
{
"docstring": "Class constructor. Sets the public instance attributes X, Y, l, and sigma_f corresponding to the respective constructor inputs Sets the public instance attribute K, representing the current covariance kernel matrix for the Gaussian process Arguments --------- - X_init : numpy.ndarray Array of sh... | 4 | null | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor. Sets the public instance attributes X, Y, l, and sigma_f corresponding to the respectiv... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor. Sets the public instance attributes X, Y, l, and sigma_f corresponding to the respectiv... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor. Sets the public instance attributes X, Y, l, and sigma_f corresponding to the respective constructor inputs Sets the public instance attribute K... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor. Sets the public instance attributes X, Y, l, and sigma_f corresponding to the respective constructor inputs Sets the public instance attribute K, representin... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/2-gp.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
12a0fdae3314c0cf443252f3556a8781433a6af4 | [
"super().__init__()\nself.interval: float = interval\nself.func: Callable[..., None] = func\nself.finished: threading.Event = threading.Event()\nself._running: threading.Lock = threading.Lock()\nif args is None:\n args = ()\nself.args: tuple[Any] = args\nif kwargs is None:\n kwargs = {}\nself.kwargs: dict[Any... | <|body_start_0|>
super().__init__()
self.interval: float = interval
self.func: Callable[..., None] = func
self.finished: threading.Event = threading.Event()
self._running: threading.Lock = threading.Lock()
if args is None:
args = ()
self.args: tuple[An... | Based on threading.Timer but cancel() returns if the timer was already running. | Timer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timer:
"""Based on threading.Timer but cancel() returns if the timer was already running."""
def __init__(self, interval: float, func: Callable[..., None], args: tuple[Any]=None, kwargs: dict[Any, Any]=None) -> None:
"""Create a Timer instance. :param interval: time interval :param f... | stack_v2_sparse_classes_36k_train_031758 | 6,786 | permissive | [
{
"docstring": "Create a Timer instance. :param interval: time interval :param func: function to call when timer finishes :param args: function arguments :param kwargs: function keyword arguments",
"name": "__init__",
"signature": "def __init__(self, interval: float, func: Callable[..., None], args: tup... | 3 | null | Implement the Python class `Timer` described below.
Class description:
Based on threading.Timer but cancel() returns if the timer was already running.
Method signatures and docstrings:
- def __init__(self, interval: float, func: Callable[..., None], args: tuple[Any]=None, kwargs: dict[Any, Any]=None) -> None: Create ... | Implement the Python class `Timer` described below.
Class description:
Based on threading.Timer but cancel() returns if the timer was already running.
Method signatures and docstrings:
- def __init__(self, interval: float, func: Callable[..., None], args: tuple[Any]=None, kwargs: dict[Any, Any]=None) -> None: Create ... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class Timer:
"""Based on threading.Timer but cancel() returns if the timer was already running."""
def __init__(self, interval: float, func: Callable[..., None], args: tuple[Any]=None, kwargs: dict[Any, Any]=None) -> None:
"""Create a Timer instance. :param interval: time interval :param f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Timer:
"""Based on threading.Timer but cancel() returns if the timer was already running."""
def __init__(self, interval: float, func: Callable[..., None], args: tuple[Any]=None, kwargs: dict[Any, Any]=None) -> None:
"""Create a Timer instance. :param interval: time interval :param func: function... | the_stack_v2_python_sparse | daemon/core/location/event.py | coreemu/core | train | 606 |
93b897b9cc2c6728e0447f2b7a13af7b00b44e4c | [
"if self.IDEAL_CUTS or self.INTER_DEP_CUTS or self.INTRA_DEP_CUTS or self.MONITOR_SPLIT:\n return True\nelse:\n return False",
"if self.INTER_DEP_CUTS or self.INTRA_DEP_CUTS:\n return True\nelse:\n return False"
] | <|body_start_0|>
if self.IDEAL_CUTS or self.INTER_DEP_CUTS or self.INTRA_DEP_CUTS or self.MONITOR_SPLIT:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if self.INTER_DEP_CUTS or self.INTRA_DEP_CUTS:
return True
else:
return... | Solver | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solver:
def callback_enabled(self):
"""Returns True iff the MILP solver is using a callback function."""
<|body_0|>
def dep_cuts_enabled(self):
"""Returns True iff the MILP solver is using dependency cuts."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031759 | 5,536 | permissive | [
{
"docstring": "Returns True iff the MILP solver is using a callback function.",
"name": "callback_enabled",
"signature": "def callback_enabled(self)"
},
{
"docstring": "Returns True iff the MILP solver is using dependency cuts.",
"name": "dep_cuts_enabled",
"signature": "def dep_cuts_en... | 2 | stack_v2_sparse_classes_30k_train_013388 | Implement the Python class `Solver` described below.
Class description:
Implement the Solver class.
Method signatures and docstrings:
- def callback_enabled(self): Returns True iff the MILP solver is using a callback function.
- def dep_cuts_enabled(self): Returns True iff the MILP solver is using dependency cuts. | Implement the Python class `Solver` described below.
Class description:
Implement the Solver class.
Method signatures and docstrings:
- def callback_enabled(self): Returns True iff the MILP solver is using a callback function.
- def dep_cuts_enabled(self): Returns True iff the MILP solver is using dependency cuts.
<... | 57e9608041d230b5d78c4f2afb890b81035436a1 | <|skeleton|>
class Solver:
def callback_enabled(self):
"""Returns True iff the MILP solver is using a callback function."""
<|body_0|>
def dep_cuts_enabled(self):
"""Returns True iff the MILP solver is using dependency cuts."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solver:
def callback_enabled(self):
"""Returns True iff the MILP solver is using a callback function."""
if self.IDEAL_CUTS or self.INTER_DEP_CUTS or self.INTRA_DEP_CUTS or self.MONITOR_SPLIT:
return True
else:
return False
def dep_cuts_enabled(self):
... | the_stack_v2_python_sparse | src/Parameters.py | pkouvaros/venus2_vnncomp21 | train | 0 | |
cf7f8e5f4b2ab085e09fc485224662d5c0119e6d | [
"super(AdamLossScalingOptimizer, self).__init__(False, name)\nself.learning_rate = tf.cast(learning_rate, dtype=weights_dtype)\nself.loss_scaling = loss_scaling\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon",
"assignments = []\nfor grad, param in grads_and_vars:\n if grad is None or param... | <|body_start_0|>
super(AdamLossScalingOptimizer, self).__init__(False, name)
self.learning_rate = tf.cast(learning_rate, dtype=weights_dtype)
self.loss_scaling = loss_scaling
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
<|end_body_0|>
<|body_start_1|>... | A basic Adam optimizer that includes loss scaling. | AdamLossScalingOptimizer | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamLossScalingOptimizer:
"""A basic Adam optimizer that includes loss scaling."""
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16):
"""Constructs a AdamLossScalingOptimizer."""
... | stack_v2_sparse_classes_36k_train_031760 | 3,902 | permissive | [
{
"docstring": "Constructs a AdamLossScalingOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16)"
},
{
"docstring": "See base class.",
"name": "apply_... | 3 | stack_v2_sparse_classes_30k_train_001056 | Implement the Python class `AdamLossScalingOptimizer` described below.
Class description:
A basic Adam optimizer that includes loss scaling.
Method signatures and docstrings:
- def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.fl... | Implement the Python class `AdamLossScalingOptimizer` described below.
Class description:
A basic Adam optimizer that includes loss scaling.
Method signatures and docstrings:
- def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.fl... | 46d2b7687b829778369fc6328170a7b14761e5c6 | <|skeleton|>
class AdamLossScalingOptimizer:
"""A basic Adam optimizer that includes loss scaling."""
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16):
"""Constructs a AdamLossScalingOptimizer."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdamLossScalingOptimizer:
"""A basic Adam optimizer that includes loss scaling."""
def __init__(self, learning_rate, loss_scaling, beta_1=0.9, beta_2=0.999, epsilon=1e-06, name='AdamLossScalingOptimizer', weights_dtype=tf.float16):
"""Constructs a AdamLossScalingOptimizer."""
super(AdamLo... | the_stack_v2_python_sparse | applications/tensorflow/conformer/ipu_optimizer.py | payoto/graphcore_examples | train | 0 |
3381a9138c5525d1bf3a77d35b79f4586eafc6b8 | [
"startTime = datetime.datetime.now()\nif trial:\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\ndocument = repo[DEMOGRAPHIC_DATA_COUNTY_NAME].find_one()\nkeys = []\nfor key in do... | <|body_start_0|>
startTime = datetime.datetime.now()
if trial:
endTime = datetime.datetime.now()
return {'start': startTime, 'end': endTime}
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate(TEAM_NAME, TEAM_NAME)
document = re... | transformationSummaryMetrics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transformationSummaryMetrics:
def execute(trial=False):
"""Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': ... | stack_v2_sparse_classes_36k_train_031761 | 7,267 | no_license | [
{
"docstring": "Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': '9,861', 'Town_Max': 'Littleton town, Middlesex County, Massachuset... | 2 | stack_v2_sparse_classes_30k_train_007414 | Implement the Python class `transformationSummaryMetrics` described below.
Class description:
Implement the transformationSummaryMetrics class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Popu... | Implement the Python class `transformationSummaryMetrics` described below.
Class description:
Implement the transformationSummaryMetrics class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Popu... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class transformationSummaryMetrics:
def execute(trial=False):
"""Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class transformationSummaryMetrics:
def execute(trial=False):
"""Retrieve summary demographic data for all facts by county and town and insert into collection ex) {'Fact': 'Population estimates, July 1, 2017, (V2017)', 'Town_Min': 'Middleton town, Essex County, Massachusetts', 'Town_Min_Val': '9,861', 'Town... | the_stack_v2_python_sparse | ldisalvo_skeesara_vidyaap/transformationSummaryMetrics.py | maximega/course-2019-spr-proj | train | 2 | |
46692a96e0f31433821ea622d366179306bb7cbc | [
"torch.nn.Module.__init__(self)\nif hidden_size % num_heads:\n raise ValueError('hidden size must be a multiple of the number of attention heads')\nself.attention = Attention(hidden_size, hidden_size, num_heads, hidden_size // num_heads, dropout=dropout, initializer_range=initializer_range)\nself.dense = torch.n... | <|body_start_0|>
torch.nn.Module.__init__(self)
if hidden_size % num_heads:
raise ValueError('hidden size must be a multiple of the number of attention heads')
self.attention = Attention(hidden_size, hidden_size, num_heads, hidden_size // num_heads, dropout=dropout, initializer_range... | TransformerEncoder | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02):
"""hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer ... | stack_v2_sparse_classes_36k_train_031762 | 6,126 | permissive | [
{
"docstring": "hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer dropout - dropout probability (0. means \"no dropout\") initializer_range - stddev for random weight matrix initialization",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_006332 | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): hidden_size - hidden size, must be multiple of... | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02): hidden_size - hidden size, must be multiple of... | 84c1c9507b3b1bffd2a08a86efaf9bc9955271e0 | <|skeleton|>
class TransformerEncoder:
def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02):
"""hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoder:
def __init__(self, hidden_size=768, num_heads=12, intermediate_size=3072, dropout=0.1, initializer_range=0.02):
"""hidden_size - hidden size, must be multiple of num_heads num_heads - number of attention heads. intermediate_size - size of the intermediate dense layer dropout - drop... | the_stack_v2_python_sparse | tbert/transformer.py | qianrenjian/tbert | train | 0 | |
76a2e77854bc0a8058da6f26826daab8771820ae | [
"trie = Trie()\nfor word, freq in zip(sentences, times):\n trie.insert(word, freq)\nself.trie = trie\nself.currSearch = ''\nself.node = trie.root",
"if c == '#':\n self.trie.insert(self.currSearch, 1)\n self.currSearch = ''\n self.node = self.trie.root\n return []\nelse:\n self.currSearch += c\n... | <|body_start_0|>
trie = Trie()
for word, freq in zip(sentences, times):
trie.insert(word, freq)
self.trie = trie
self.currSearch = ''
self.node = trie.root
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.trie.insert(self.currSearch, 1)
... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
trie = Trie()
... | stack_v2_sparse_classes_36k_train_031763 | 1,657 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005366 | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | 2d5c09b63438aee7925252d5c6c4ede872bf52f1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
trie = Trie()
for word, freq in zip(sentences, times):
trie.insert(word, freq)
self.trie = trie
self.currSearch = ''
self.node = trie.ro... | the_stack_v2_python_sparse | algorithms/google/AutoComplete.py | james4388/algorithm-1 | train | 1 | |
e2c1552cb5ed88acd0b5612787f4a03adb3afe90 | [
"houses.sort()\nheaters.sort()\nradius = 0\ni = 0\nfor house in houses:\n while i < len(heaters) and heaters[i] < house:\n i += 1\n if i == 0:\n radius = max(radius, heaters[i] - house)\n elif i == len(heaters):\n return max(radius, houses[-1] - heaters[-1])\n else:\n radius ... | <|body_start_0|>
houses.sort()
heaters.sort()
radius = 0
i = 0
for house in houses:
while i < len(heaters) and heaters[i] < house:
i += 1
if i == 0:
radius = max(radius, heaters[i] - house)
elif i == len(heaters)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRadius(self, houses, heaters):
""":type houses: List[int] :type heaters: List[int] :rtype: int"""
<|body_0|>
def findRadius_work(self, houses, heaters):
""":type houses: List[int] :type heaters: List[int] :rtype: int"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_031764 | 2,366 | no_license | [
{
"docstring": ":type houses: List[int] :type heaters: List[int] :rtype: int",
"name": "findRadius",
"signature": "def findRadius(self, houses, heaters)"
},
{
"docstring": ":type houses: List[int] :type heaters: List[int] :rtype: int",
"name": "findRadius_work",
"signature": "def findRad... | 2 | stack_v2_sparse_classes_30k_train_004506 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRadius(self, houses, heaters): :type houses: List[int] :type heaters: List[int] :rtype: int
- def findRadius_work(self, houses, heaters): :type houses: List[int] :type he... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRadius(self, houses, heaters): :type houses: List[int] :type heaters: List[int] :rtype: int
- def findRadius_work(self, houses, heaters): :type houses: List[int] :type he... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def findRadius(self, houses, heaters):
""":type houses: List[int] :type heaters: List[int] :rtype: int"""
<|body_0|>
def findRadius_work(self, houses, heaters):
""":type houses: List[int] :type heaters: List[int] :rtype: int"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRadius(self, houses, heaters):
""":type houses: List[int] :type heaters: List[int] :rtype: int"""
houses.sort()
heaters.sort()
radius = 0
i = 0
for house in houses:
while i < len(heaters) and heaters[i] < house:
i +=... | the_stack_v2_python_sparse | Problems/0400_0499/0475_Heaters/Project_Python3/Heaters.py | NobuyukiInoue/LeetCode | train | 0 | |
220298629e35dbd4b040b1169f4a3a081120642d | [
"time = timezone.now() + datetime.timedelta(days=30)\nfuture_question = Question(pub_date=time)\nself.assertIs(future_question.was_published_recently(), False)",
"time = timezone.now() - datetime.timedelta(days=1)\nold_question = Question(pub_date=time)\nself.assertIs(old_question.was_published_recently(), False)... | <|body_start_0|>
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
<|end_body_0|>
<|body_start_1|>
time = timezone.now() - datetime.timedelta(days=1)
old_question = Questio... | QuestionMethonTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionMethonTests:
def test_was_published_recently_with_future_question(self):
"""在将来发布的问卷应该返回False :return:"""
<|body_0|>
def test_was_published_recently_with_old_question(self):
"""只要超过一天就返回false :return:"""
<|body_1|>
def test_was_published_recently... | stack_v2_sparse_classes_36k_train_031765 | 1,907 | permissive | [
{
"docstring": "在将来发布的问卷应该返回False :return:",
"name": "test_was_published_recently_with_future_question",
"signature": "def test_was_published_recently_with_future_question(self)"
},
{
"docstring": "只要超过一天就返回false :return:",
"name": "test_was_published_recently_with_old_question",
"signat... | 3 | stack_v2_sparse_classes_30k_train_015527 | Implement the Python class `QuestionMethonTests` described below.
Class description:
Implement the QuestionMethonTests class.
Method signatures and docstrings:
- def test_was_published_recently_with_future_question(self): 在将来发布的问卷应该返回False :return:
- def test_was_published_recently_with_old_question(self): 只要超过一天就返回f... | Implement the Python class `QuestionMethonTests` described below.
Class description:
Implement the QuestionMethonTests class.
Method signatures and docstrings:
- def test_was_published_recently_with_future_question(self): 在将来发布的问卷应该返回False :return:
- def test_was_published_recently_with_old_question(self): 只要超过一天就返回f... | 5e1df18be3d70bbe5403860e2f4775737b71ca81 | <|skeleton|>
class QuestionMethonTests:
def test_was_published_recently_with_future_question(self):
"""在将来发布的问卷应该返回False :return:"""
<|body_0|>
def test_was_published_recently_with_old_question(self):
"""只要超过一天就返回false :return:"""
<|body_1|>
def test_was_published_recently... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionMethonTests:
def test_was_published_recently_with_future_question(self):
"""在将来发布的问卷应该返回False :return:"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
de... | the_stack_v2_python_sparse | DjangoStudy/polls/tests.py | zhangjiang1203/Python- | train | 0 | |
0d4f7d61f4a35c62f973ef175267e9b3999931d0 | [
"self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.bakery = Company.objects.create(name='bakery', caffe=self.ca... | <|body_start_0|>
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')
self.bakery = Company.objects.c... | Expense model tests. | ExpenseModelTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpenseModelTest:
"""Expense model tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_name(self):
"""Check if name is unique across one caffe."""
<|body_1|>
def test_expense_validation(self):
"""Check expense validation."""... | stack_v2_sparse_classes_36k_train_031766 | 8,665 | permissive | [
{
"docstring": "Test data setup.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check if name is unique across one caffe.",
"name": "test_name",
"signature": "def test_name(self)"
},
{
"docstring": "Check expense validation.",
"name": "test_expense_valid... | 3 | stack_v2_sparse_classes_30k_train_016103 | Implement the Python class `ExpenseModelTest` described below.
Class description:
Expense model tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_name(self): Check if name is unique across one caffe.
- def test_expense_validation(self): Check expense validation. | Implement the Python class `ExpenseModelTest` described below.
Class description:
Expense model tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_name(self): Check if name is unique across one caffe.
- def test_expense_validation(self): Check expense validation.
<|skeleton|>
cla... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class ExpenseModelTest:
"""Expense model tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_name(self):
"""Check if name is unique across one caffe."""
<|body_1|>
def test_expense_validation(self):
"""Check expense validation."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpenseModelTest:
"""Expense model tests."""
def setUp(self):
"""Test data setup."""
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', stree... | the_stack_v2_python_sparse | caffe/cash/test_models.py | VirrageS/io-kawiarnie | train | 3 |
2955a24ef7d61ddce4e07a01bdd518262cab889f | [
"differentiator.refresh()\nop = differentiator.generate_differentiable_op(analytic_op=op)\n\ndef exact_grad(theta):\n new_theta = 2 * np.pi * theta\n return -2 * np.pi * np.sin(new_theta) * np.exp(np.cos(new_theta))\nbit = cirq.GridQubit(0, 0)\ncircuits = util.convert_to_tensor([cirq.Circuit(cirq.X(bit) ** sy... | <|body_start_0|>
differentiator.refresh()
op = differentiator.generate_differentiable_op(analytic_op=op)
def exact_grad(theta):
new_theta = 2 * np.pi * theta
return -2 * np.pi * np.sin(new_theta) * np.exp(np.cos(new_theta))
bit = cirq.GridQubit(0, 0)
circ... | Test correctness of the differentiators to reference cirq algorithm. | AnalyticGradientCorrectnessTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyticGradientCorrectnessTest:
"""Test correctness of the differentiators to reference cirq algorithm."""
def test_backprop(self, differentiator, op):
"""Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results."""
<|bo... | stack_v2_sparse_classes_36k_train_031767 | 22,303 | permissive | [
{
"docstring": "Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results.",
"name": "test_backprop",
"signature": "def test_backprop(self, differentiator, op)"
},
{
"docstring": "Compare TFQ differentiators to fine-grained noiseless cirq fin... | 4 | stack_v2_sparse_classes_30k_train_012696 | Implement the Python class `AnalyticGradientCorrectnessTest` described below.
Class description:
Test correctness of the differentiators to reference cirq algorithm.
Method signatures and docstrings:
- def test_backprop(self, differentiator, op): Test that gradients are correctly backpropagated through a quantum circ... | Implement the Python class `AnalyticGradientCorrectnessTest` described below.
Class description:
Test correctness of the differentiators to reference cirq algorithm.
Method signatures and docstrings:
- def test_backprop(self, differentiator, op): Test that gradients are correctly backpropagated through a quantum circ... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class AnalyticGradientCorrectnessTest:
"""Test correctness of the differentiators to reference cirq algorithm."""
def test_backprop(self, differentiator, op):
"""Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalyticGradientCorrectnessTest:
"""Test correctness of the differentiators to reference cirq algorithm."""
def test_backprop(self, differentiator, op):
"""Test that gradients are correctly backpropagated through a quantum circuit via comparison to analytical results."""
differentiator.re... | the_stack_v2_python_sparse | tensorflow_quantum/python/differentiators/gradient_test.py | tensorflow/quantum | train | 1,799 |
7d699325ade4a2586207ee9b172537847435d24f | [
"self.enable_capture = enable_capture\nself.sampling_percentage = sampling_percentage\nself.destination_s3_uri = destination_s3_uri\nsagemaker_session = sagemaker_session or Session()\nif self.destination_s3_uri is None:\n self.destination_s3_uri = s3.s3_path_join('s3://', sagemaker_session.default_bucket(), sag... | <|body_start_0|>
self.enable_capture = enable_capture
self.sampling_percentage = sampling_percentage
self.destination_s3_uri = destination_s3_uri
sagemaker_session = sagemaker_session or Session()
if self.destination_s3_uri is None:
self.destination_s3_uri = s3.s3_pat... | Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring. | DataCaptureConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCaptureConfig:
"""Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring."""
def __init__(self, enable_capture, sampling_percentage=20, destina... | stack_v2_sparse_classes_36k_train_031768 | 5,109 | permissive | [
{
"docstring": "Initialize a DataCaptureConfig object for capturing data from Amazon SageMaker Endpoints. Args: enable_capture (bool): Required. Whether data capture should be enabled or not. sampling_percentage (int): Optional. Default=20. The percentage of data to sample. Must be between 0 and 100. destinatio... | 2 | null | Implement the Python class `DataCaptureConfig` described below.
Class description:
Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring.
Method signatures and docstrings:
... | Implement the Python class `DataCaptureConfig` described below.
Class description:
Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring.
Method signatures and docstrings:
... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class DataCaptureConfig:
"""Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring."""
def __init__(self, enable_capture, sampling_percentage=20, destina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataCaptureConfig:
"""Configuration object passed in when deploying models to Amazon SageMaker Endpoints. This object specifies configuration related to endpoint data capture for use with Amazon SageMaker Model Monitoring."""
def __init__(self, enable_capture, sampling_percentage=20, destination_s3_uri=N... | the_stack_v2_python_sparse | src/sagemaker/model_monitor/data_capture_config.py | aws/sagemaker-python-sdk | train | 2,050 |
2f8b3c285eb27e30cdbaf9f62d22c873af84a012 | [
"if hyperparameter_config is None:\n hyperparameter_config = configs.encoder_decoder()\nsuper().__init__(name, parent=None, hyperparameter_config=hyperparameter_config, spatial_scale=spatial_scale)\nself.setup_children()\npass",
"with tf.variable_scope(self.name.replace(' ', '_')):\n for blockset in self.ch... | <|body_start_0|>
if hyperparameter_config is None:
hyperparameter_config = configs.encoder_decoder()
super().__init__(name, parent=None, hyperparameter_config=hyperparameter_config, spatial_scale=spatial_scale)
self.setup_children()
pass
<|end_body_0|>
<|body_start_1|>
... | Controls the creation of an encoder-decoder network (u-net). TODO Attributes: | EncoderDecoderGene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderDecoderGene:
"""Controls the creation of an encoder-decoder network (u-net). TODO Attributes:"""
def __init__(self, name: str, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0):
"""Constructor. Args: name (str): This gene's name. hyperparamet... | stack_v2_sparse_classes_36k_train_031769 | 3,787 | no_license | [
{
"docstring": "Constructor. Args: name (str): This gene's name. hyperparameter_config (Optional[mt.HyperparameterConfig]): The HyperparameterConfig governing this Gene's hyperparameters. If none is supplied, use genenet.hyperparameter_config.encoder_decoder(). spatial_scale (int): The spatial scale of the data... | 4 | stack_v2_sparse_classes_30k_train_006028 | Implement the Python class `EncoderDecoderGene` described below.
Class description:
Controls the creation of an encoder-decoder network (u-net). TODO Attributes:
Method signatures and docstrings:
- def __init__(self, name: str, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0): Cons... | Implement the Python class `EncoderDecoderGene` described below.
Class description:
Controls the creation of an encoder-decoder network (u-net). TODO Attributes:
Method signatures and docstrings:
- def __init__(self, name: str, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0): Cons... | 6b78dc5e1e793a206ae3f4860d3a9ac887e663e5 | <|skeleton|>
class EncoderDecoderGene:
"""Controls the creation of an encoder-decoder network (u-net). TODO Attributes:"""
def __init__(self, name: str, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0):
"""Constructor. Args: name (str): This gene's name. hyperparamet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderDecoderGene:
"""Controls the creation of an encoder-decoder network (u-net). TODO Attributes:"""
def __init__(self, name: str, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0):
"""Constructor. Args: name (str): This gene's name. hyperparameter_config (Op... | the_stack_v2_python_sparse | example3/src/_private/genenet/genes/EncoderDecoderGene.py | leapmanlab/examples | train | 1 |
d6991f0c2e7e8beedf0459088feac249c8f1967e | [
"if not isinstance(nums, list) or len(nums) == 0 or k > len(nums) or (k <= 0):\n return\nstart = 0\nend = len(nums) - 1\nindex = self.partition(nums, start, end)\nwhile index != k - 1:\n if index > k - 1:\n end = index - 1\n index = self.partition(nums, start, end)\n elif index < k - 1:\n ... | <|body_start_0|>
if not isinstance(nums, list) or len(nums) == 0 or k > len(nums) or (k <= 0):
return
start = 0
end = len(nums) - 1
index = self.partition(nums, start, end)
while index != k - 1:
if index > k - 1:
end = index - 1
... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def get_least_k(self, nums, k):
"""快排的思想解决取最大/最小k个数的问题: 时间复杂度:n + n/2 + n/4 + n/8 + ... = n + (n - n/2) + (n/2 - n/4) + ... = 2n = O(n) :param nums: 数组 :param k: 最小数字个数 :return: 最小k个数字"""
<|body_0|>
def partition(self, data, start, end):
"""快排:partition :p... | stack_v2_sparse_classes_36k_train_031770 | 4,146 | no_license | [
{
"docstring": "快排的思想解决取最大/最小k个数的问题: 时间复杂度:n + n/2 + n/4 + n/8 + ... = n + (n - n/2) + (n/2 - n/4) + ... = 2n = O(n) :param nums: 数组 :param k: 最小数字个数 :return: 最小k个数字",
"name": "get_least_k",
"signature": "def get_least_k(self, nums, k)"
},
{
"docstring": "快排:partition :param data: 数组 :param star... | 2 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def get_least_k(self, nums, k): 快排的思想解决取最大/最小k个数的问题: 时间复杂度:n + n/2 + n/4 + n/8 + ... = n + (n - n/2) + (n/2 - n/4) + ... = 2n = O(n) :param nums: 数组 :param k: 最小数字个数 :return: 最... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def get_least_k(self, nums, k): 快排的思想解决取最大/最小k个数的问题: 时间复杂度:n + n/2 + n/4 + n/8 + ... = n + (n - n/2) + (n/2 - n/4) + ... = 2n = O(n) :param nums: 数组 :param k: 最小数字个数 :return: 最... | 9fdc4b1a2b59b7aed22ddfe92aade487b4c19b71 | <|skeleton|>
class Solution1:
def get_least_k(self, nums, k):
"""快排的思想解决取最大/最小k个数的问题: 时间复杂度:n + n/2 + n/4 + n/8 + ... = n + (n - n/2) + (n/2 - n/4) + ... = 2n = O(n) :param nums: 数组 :param k: 最小数字个数 :return: 最小k个数字"""
<|body_0|>
def partition(self, data, start, end):
"""快排:partition :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def get_least_k(self, nums, k):
"""快排的思想解决取最大/最小k个数的问题: 时间复杂度:n + n/2 + n/4 + n/8 + ... = n + (n - n/2) + (n/2 - n/4) + ... = 2n = O(n) :param nums: 数组 :param k: 最小数字个数 :return: 最小k个数字"""
if not isinstance(nums, list) or len(nums) == 0 or k > len(nums) or (k <= 0):
retur... | the_stack_v2_python_sparse | my_target_offer/40_k_least_numbers.py | MemoryForSky/Data-Structures-and-Algorithms | train | 0 | |
e6b6cf397c89651c9eac2b5850a9530a654fddd3 | [
"self.links = links\nself.joint_constraints = joint_constraints\nself.effector_dims = effector_dims\nself.distance_from_page = distance_from_page\nself.min_phi = math.radians(min_phi)\nself.max_phi = math.radians(max_phi)\nself.ee_angle = math.atan(effector_dims[1] / effector_dims[0])\nself.base = np.array([1, 0])\... | <|body_start_0|>
self.links = links
self.joint_constraints = joint_constraints
self.effector_dims = effector_dims
self.distance_from_page = distance_from_page
self.min_phi = math.radians(min_phi)
self.max_phi = math.radians(max_phi)
self.ee_angle = math.atan(effec... | IKSolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IKSolver:
def __init__(self, links, joint_constraints, effector_dims, distance_from_page, min_phi, max_phi, phi_steps):
"""Keyword arguments: links = The lengths of the robot links (1x3 vector) joint_constraints = The minimal and maximal angle each joint can have (3x2 vector) effector_di... | stack_v2_sparse_classes_36k_train_031771 | 5,986 | no_license | [
{
"docstring": "Keyword arguments: links = The lengths of the robot links (1x3 vector) joint_constraints = The minimal and maximal angle each joint can have (3x2 vector) effector_dims = The size of the end effector ([x, y] vector) distance_from_page = distance between the center of the page and the position of ... | 3 | stack_v2_sparse_classes_30k_train_021285 | Implement the Python class `IKSolver` described below.
Class description:
Implement the IKSolver class.
Method signatures and docstrings:
- def __init__(self, links, joint_constraints, effector_dims, distance_from_page, min_phi, max_phi, phi_steps): Keyword arguments: links = The lengths of the robot links (1x3 vecto... | Implement the Python class `IKSolver` described below.
Class description:
Implement the IKSolver class.
Method signatures and docstrings:
- def __init__(self, links, joint_constraints, effector_dims, distance_from_page, min_phi, max_phi, phi_steps): Keyword arguments: links = The lengths of the robot links (1x3 vecto... | 501f85d25924a1625ce116231d37ecc2baa699ba | <|skeleton|>
class IKSolver:
def __init__(self, links, joint_constraints, effector_dims, distance_from_page, min_phi, max_phi, phi_steps):
"""Keyword arguments: links = The lengths of the robot links (1x3 vector) joint_constraints = The minimal and maximal angle each joint can have (3x2 vector) effector_di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IKSolver:
def __init__(self, links, joint_constraints, effector_dims, distance_from_page, min_phi, max_phi, phi_steps):
"""Keyword arguments: links = The lengths of the robot links (1x3 vector) joint_constraints = The minimal and maximal angle each joint can have (3x2 vector) effector_dims = The size ... | the_stack_v2_python_sparse | simulation/InverseKinematics.py | Evelyn-H/robotic-arm | train | 0 | |
c59bb2ad83060b6d79fef3591faee09a3d8eda91 | [
"super().__init__(cutoff, n_jobs)\nself.subst_mat = subst_mat\nself.gap_open = gap_open\nself.gap_extend = gap_extend",
"subst_mat = parasail.Matrix(self.subst_mat)\ntarget = seqs[i_row]\nprofile = parasail.profile_create_16(target, subst_mat)\n\ndef coord_generator():\n for j, s2 in enumerate(seqs[i_row:], st... | <|body_start_0|>
super().__init__(cutoff, n_jobs)
self.subst_mat = subst_mat
self.gap_open = gap_open
self.gap_extend = gap_extend
<|end_body_0|>
<|body_start_1|>
subst_mat = parasail.Matrix(self.subst_mat)
target = seqs[i_row]
profile = parasail.profile_create_1... | Calculates distance between sequences based on pairwise sequence alignment. The distance between two sequences is defined as $S_{1,2}^{max} - S_{1,2}$ where $S_{1,2} $ is the alignment score of sequences 1 and 2 and $S_{1,2}^{max}$ is the max. achievable alignment score of sequences 1 and 2 defined as $\\min(S_{1,1}, S... | _AlignmentDistanceCalculator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _AlignmentDistanceCalculator:
"""Calculates distance between sequences based on pairwise sequence alignment. The distance between two sequences is defined as $S_{1,2}^{max} - S_{1,2}$ where $S_{1,2} $ is the alignment score of sequences 1 and 2 and $S_{1,2}^{max}$ is the max. achievable alignment... | stack_v2_sparse_classes_36k_train_031772 | 24,618 | permissive | [
{
"docstring": "Class to generate pairwise alignment distances High-performance sequence alignment through parasail library [Daily2016]_ Parameters ---------- cutoff see `_DistanceCalculator` n_jobs see `_DistanceCalculator` subst_mat Name of parasail substitution matrix gap_open Gap open penalty gap_extend Gap... | 3 | stack_v2_sparse_classes_30k_test_000437 | Implement the Python class `_AlignmentDistanceCalculator` described below.
Class description:
Calculates distance between sequences based on pairwise sequence alignment. The distance between two sequences is defined as $S_{1,2}^{max} - S_{1,2}$ where $S_{1,2} $ is the alignment score of sequences 1 and 2 and $S_{1,2}^... | Implement the Python class `_AlignmentDistanceCalculator` described below.
Class description:
Calculates distance between sequences based on pairwise sequence alignment. The distance between two sequences is defined as $S_{1,2}^{max} - S_{1,2}$ where $S_{1,2} $ is the alignment score of sequences 1 and 2 and $S_{1,2}^... | afb105e5abda13e51d6075b70dd9b92a1e60b29e | <|skeleton|>
class _AlignmentDistanceCalculator:
"""Calculates distance between sequences based on pairwise sequence alignment. The distance between two sequences is defined as $S_{1,2}^{max} - S_{1,2}$ where $S_{1,2} $ is the alignment score of sequences 1 and 2 and $S_{1,2}^{max}$ is the max. achievable alignment... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _AlignmentDistanceCalculator:
"""Calculates distance between sequences based on pairwise sequence alignment. The distance between two sequences is defined as $S_{1,2}^{max} - S_{1,2}$ where $S_{1,2} $ is the alignment score of sequences 1 and 2 and $S_{1,2}^{max}$ is the max. achievable alignment score of seq... | the_stack_v2_python_sparse | scirpy/_preprocessing/_tcr_dist.py | grst-anaconda/scirpy | train | 0 |
8830d03f7afc24bf42f2bbd190460924c67e853d | [
"self.nlabel = nlabel\nself.lamb = lamb\nself.value1 = value1\nself.value2 = value2\nself.niter = niter\nself.pairwise_cost = -self.value1 * self.lamb * np.eye(self.nlabel)\nself.pairwise_cost = self.pairwise_cost.astype(np.int32)",
"assert unary_term.shape[1] == self.nlabel, 'Unary term have wrong labels'\nnvert... | <|body_start_0|>
self.nlabel = nlabel
self.lamb = lamb
self.value1 = value1
self.value2 = value2
self.niter = niter
self.pairwise_cost = -self.value1 * self.lamb * np.eye(self.nlabel)
self.pairwise_cost = self.pairwise_cost.astype(np.int32)
<|end_body_0|>
<|body_... | DiscreteEnergyMinimize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteEnergyMinimize:
def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10):
"""Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000"""
<|body_0|>
def solve(self, unary_term, pairwise_term, k):
... | stack_v2_sparse_classes_36k_train_031773 | 2,206 | permissive | [
{
"docstring": "Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000",
"name": "__init__",
"signature": "def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10)"
},
{
"docstring": "Args : unary_term - Numpy 2d array [nv... | 2 | stack_v2_sparse_classes_30k_train_015360 | Implement the Python class `DiscreteEnergyMinimize` described below.
Class description:
Implement the DiscreteEnergyMinimize class.
Method signatures and docstrings:
- def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10): Args: nlabel - int lamb - float should be positive value1 - int defaults to be 1... | Implement the Python class `DiscreteEnergyMinimize` described below.
Class description:
Implement the DiscreteEnergyMinimize class.
Method signatures and docstrings:
- def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10): Args: nlabel - int lamb - float should be positive value1 - int defaults to be 1... | 62c811c37001302e6759a18d6143b8ad657e4910 | <|skeleton|>
class DiscreteEnergyMinimize:
def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10):
"""Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000"""
<|body_0|>
def solve(self, unary_term, pairwise_term, k):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteEnergyMinimize:
def __init__(self, nlabel, lamb, value1=100, value2=10000, niter=10):
"""Args: nlabel - int lamb - float should be positive value1 - int defaults to be 100 value2 - int defaults to be 10000"""
self.nlabel = nlabel
self.lamb = lamb
self.value1 = value1
... | the_stack_v2_python_sparse | utils/pygco_op.py | snu-mllab/Deep-Hash-Table-CVPR19 | train | 12 | |
785a0d8ace5814fc0b171658892c5f18bd0fd885 | [
"super().__init__()\nself._use_condition = use_condition\nself._model = tf.keras.Sequential([tf.keras.layers.Conv2D(64, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormalization(), tf.keras.layers.LeakyReLU(), tf.keras.layers.Conv2D(128, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormaliz... | <|body_start_0|>
super().__init__()
self._use_condition = use_condition
self._model = tf.keras.Sequential([tf.keras.layers.Conv2D(64, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormalization(), tf.keras.layers.LeakyReLU(), tf.keras.layers.Conv2D(128, [5, 5], strides=2, padding='sam... | Class conditioned discriminator. This discriminator is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: _intermediate_layer: _final_layer | ClassConditionedDiscriminator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassConditionedDiscriminator:
"""Class conditioned discriminator. This discriminator is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: _intermediate_layer: _final_layer"""
def __init__(self, use_condition):
"""Initializes the object. Args: use_condition:"""
... | stack_v2_sparse_classes_36k_train_031774 | 12,085 | no_license | [
{
"docstring": "Initializes the object. Args: use_condition:",
"name": "__init__",
"signature": "def __init__(self, use_condition)"
},
{
"docstring": "Applies the model to the inputs. Args: image: embedding: Returns:",
"name": "call",
"signature": "def call(self, image, embedding)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019815 | Implement the Python class `ClassConditionedDiscriminator` described below.
Class description:
Class conditioned discriminator. This discriminator is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: _intermediate_layer: _final_layer
Method signatures and docstrings:
- def __init__(self, use_cond... | Implement the Python class `ClassConditionedDiscriminator` described below.
Class description:
Class conditioned discriminator. This discriminator is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: _intermediate_layer: _final_layer
Method signatures and docstrings:
- def __init__(self, use_cond... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class ClassConditionedDiscriminator:
"""Class conditioned discriminator. This discriminator is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: _intermediate_layer: _final_layer"""
def __init__(self, use_condition):
"""Initializes the object. Args: use_condition:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassConditionedDiscriminator:
"""Class conditioned discriminator. This discriminator is used by MNIST and FMNIST datasets. Attributes: _use_condition: _model: _intermediate_layer: _final_layer"""
def __init__(self, use_condition):
"""Initializes the object. Args: use_condition:"""
super(... | the_stack_v2_python_sparse | gan.py | gaotianxiang/text-to-image-synthesis | train | 0 |
0192f5c1becc8097e579a4a02b2821f032af2c7f | [
"ctype, object_pk = self.get_target_ctype_pk(context)\nif not object_pk:\n return self.comment_model.objects.none()\nqs = self.comment_model.objects.filter(content_type=ctype, object_pk=smart_unicode(object_pk))\nqs = qs.filter(is_public=True)\nif getattr(settings, 'COMMENTS_HIDE_REMOVED', False):\n qs = qs.f... | <|body_start_0|>
ctype, object_pk = self.get_target_ctype_pk(context)
if not object_pk:
return self.comment_model.objects.none()
qs = self.comment_model.objects.filter(content_type=ctype, object_pk=smart_unicode(object_pk))
qs = qs.filter(is_public=True)
if getattr(se... | EllaMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EllaMixin:
def get_query_set(self, context):
"""Override for the django..comments..BaseCommentNode.get_query_set that ignores the site FK"""
<|body_0|>
def get_target_ctype_pk(self, context):
"""override of the default behavior that handles Publishables specifically ... | stack_v2_sparse_classes_36k_train_031775 | 5,481 | no_license | [
{
"docstring": "Override for the django..comments..BaseCommentNode.get_query_set that ignores the site FK",
"name": "get_query_set",
"signature": "def get_query_set(self, context)"
},
{
"docstring": "override of the default behavior that handles Publishables specifically - it returns their speci... | 2 | null | Implement the Python class `EllaMixin` described below.
Class description:
Implement the EllaMixin class.
Method signatures and docstrings:
- def get_query_set(self, context): Override for the django..comments..BaseCommentNode.get_query_set that ignores the site FK
- def get_target_ctype_pk(self, context): override o... | Implement the Python class `EllaMixin` described below.
Class description:
Implement the EllaMixin class.
Method signatures and docstrings:
- def get_query_set(self, context): Override for the django..comments..BaseCommentNode.get_query_set that ignores the site FK
- def get_target_ctype_pk(self, context): override o... | edcae8ac03816631cf8fbae98b7730479f4c41b6 | <|skeleton|>
class EllaMixin:
def get_query_set(self, context):
"""Override for the django..comments..BaseCommentNode.get_query_set that ignores the site FK"""
<|body_0|>
def get_target_ctype_pk(self, context):
"""override of the default behavior that handles Publishables specifically ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EllaMixin:
def get_query_set(self, context):
"""Override for the django..comments..BaseCommentNode.get_query_set that ignores the site FK"""
ctype, object_pk = self.get_target_ctype_pk(context)
if not object_pk:
return self.comment_model.objects.none()
qs = self.com... | the_stack_v2_python_sparse | ella/ellacomments/templatetags/ellacomments_tags.py | majerm/ella | train | 1 | |
c4c67e00a2b651a1c24bfbabe921cd297fa26048 | [
"self._app = app\nself._title = title\nself._version = version\nself._url_logo = url_logo\nself._description = description",
"if self._app.openapi_schema:\n return self._app.openapi_schema\nopenapi_schema = get_openapi(title=self._title, version=self._version, routes=self._app.routes, description=self._descrip... | <|body_start_0|>
self._app = app
self._title = title
self._version = version
self._url_logo = url_logo
self._description = description
<|end_body_0|>
<|body_start_1|>
if self._app.openapi_schema:
return self._app.openapi_schema
openapi_schema = get_op... | Schema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Schema:
def __init__(self, app: FastAPI, title: str, version: str, url_logo: str, description: str) -> None:
"""[summary] Args: app (FastAPI): app instance title (str): titulo da documentação version (str): versão da aplicação url_logo (str): url da logo description (str): descrição"""
... | stack_v2_sparse_classes_36k_train_031776 | 1,233 | permissive | [
{
"docstring": "[summary] Args: app (FastAPI): app instance title (str): titulo da documentação version (str): versão da aplicação url_logo (str): url da logo description (str): descrição",
"name": "__init__",
"signature": "def __init__(self, app: FastAPI, title: str, version: str, url_logo: str, descri... | 2 | stack_v2_sparse_classes_30k_train_016460 | Implement the Python class `Schema` described below.
Class description:
Implement the Schema class.
Method signatures and docstrings:
- def __init__(self, app: FastAPI, title: str, version: str, url_logo: str, description: str) -> None: [summary] Args: app (FastAPI): app instance title (str): titulo da documentação v... | Implement the Python class `Schema` described below.
Class description:
Implement the Schema class.
Method signatures and docstrings:
- def __init__(self, app: FastAPI, title: str, version: str, url_logo: str, description: str) -> None: [summary] Args: app (FastAPI): app instance title (str): titulo da documentação v... | 5bbd6903305db07cc18330ec86fb04ca518e9dab | <|skeleton|>
class Schema:
def __init__(self, app: FastAPI, title: str, version: str, url_logo: str, description: str) -> None:
"""[summary] Args: app (FastAPI): app instance title (str): titulo da documentação version (str): versão da aplicação url_logo (str): url da logo description (str): descrição"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Schema:
def __init__(self, app: FastAPI, title: str, version: str, url_logo: str, description: str) -> None:
"""[summary] Args: app (FastAPI): app instance title (str): titulo da documentação version (str): versão da aplicação url_logo (str): url da logo description (str): descrição"""
self._a... | the_stack_v2_python_sparse | api/project/infrastructure/open_api/open_api_schema.py | sharof2000/ms-fastapi-template | train | 0 | |
e5d62b559d6e309344d0247a1420de4adffcd386 | [
"super(FramePredNet, self).__init__()\ndim = len(vol_size)\nself.unet_model = Unet(vol_size, [enc_nf, dec_nf])\nconv_fn = getattr(nn, 'Conv%dd' % dim)\nself.flow = conv_fn(dec_nf[-1], dim, kernel_size=3, padding=1)\nnd = Normal(0, 1e-05)\nself.flow.weight = nn.Parameter(nd.sample(self.flow.weight.shape))\nself.flow... | <|body_start_0|>
super(FramePredNet, self).__init__()
dim = len(vol_size)
self.unet_model = Unet(vol_size, [enc_nf, dec_nf])
conv_fn = getattr(nn, 'Conv%dd' % dim)
self.flow = conv_fn(dec_nf[-1], dim, kernel_size=3, padding=1)
nd = Normal(0, 1e-05)
self.flow.weigh... | "" implementation of voxelmorph. | FramePredNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FramePredNet:
""""" implementation of voxelmorph."""
def __init__(self, vol_size, enc_nf, dec_nf, full_size=True):
""":param vol_size: volume size of the atlas :param enc_nf: the number of features maps for encoding stages :param dec_nf: the number of features maps for decoding stage... | stack_v2_sparse_classes_36k_train_031777 | 8,888 | permissive | [
{
"docstring": ":param vol_size: volume size of the atlas :param enc_nf: the number of features maps for encoding stages :param dec_nf: the number of features maps for decoding stages :param full_size: boolean value full amount of decoding layers",
"name": "__init__",
"signature": "def __init__(self, vo... | 2 | stack_v2_sparse_classes_30k_train_004393 | Implement the Python class `FramePredNet` described below.
Class description:
"" implementation of voxelmorph.
Method signatures and docstrings:
- def __init__(self, vol_size, enc_nf, dec_nf, full_size=True): :param vol_size: volume size of the atlas :param enc_nf: the number of features maps for encoding stages :par... | Implement the Python class `FramePredNet` described below.
Class description:
"" implementation of voxelmorph.
Method signatures and docstrings:
- def __init__(self, vol_size, enc_nf, dec_nf, full_size=True): :param vol_size: volume size of the atlas :param enc_nf: the number of features maps for encoding stages :par... | 730f7dff2239ef716841390311b5b9250149acaf | <|skeleton|>
class FramePredNet:
""""" implementation of voxelmorph."""
def __init__(self, vol_size, enc_nf, dec_nf, full_size=True):
""":param vol_size: volume size of the atlas :param enc_nf: the number of features maps for encoding stages :param dec_nf: the number of features maps for decoding stage... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FramePredNet:
""""" implementation of voxelmorph."""
def __init__(self, vol_size, enc_nf, dec_nf, full_size=True):
""":param vol_size: volume size of the atlas :param enc_nf: the number of features maps for encoding stages :param dec_nf: the number of features maps for decoding stages :param full... | the_stack_v2_python_sparse | annolid/motion/deformation.py | healthonrails/annolid | train | 25 |
94db1cc20cd2c9607dae078b5e593bc13a0e5ae8 | [
"self.average = average\nif average not in [None, 'micro', 'macro', 'weighted']:\n raise ValueError('Wrong value of average parameter')",
"true_positive = torch.eq(labels, predictions).sum().float()\nf1_score = torch.div(true_positive, len(labels))\nreturn f1_score",
"true_count = torch.eq(labels, label_id).... | <|body_start_0|>
self.average = average
if average not in [None, 'micro', 'macro', 'weighted']:
raise ValueError('Wrong value of average parameter')
<|end_body_0|>
<|body_start_1|>
true_positive = torch.eq(labels, predictions).sum().float()
f1_score = torch.div(true_positive... | Class for f1 calculation in Pytorch. | F1Score | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class F1Score:
"""Class for f1 calculation in Pytorch."""
def __init__(self, average: str='weighted'):
"""Init. Args: average: averaging method"""
<|body_0|>
def calc_f1_micro(predictions: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
"""Calculate f1 micro. Args... | stack_v2_sparse_classes_36k_train_031778 | 3,207 | permissive | [
{
"docstring": "Init. Args: average: averaging method",
"name": "__init__",
"signature": "def __init__(self, average: str='weighted')"
},
{
"docstring": "Calculate f1 micro. Args: predictions: tensor with predictions labels: tensor with original labels Returns: f1 score",
"name": "calc_f1_mi... | 4 | stack_v2_sparse_classes_30k_train_015617 | Implement the Python class `F1Score` described below.
Class description:
Class for f1 calculation in Pytorch.
Method signatures and docstrings:
- def __init__(self, average: str='weighted'): Init. Args: average: averaging method
- def calc_f1_micro(predictions: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: Cal... | Implement the Python class `F1Score` described below.
Class description:
Class for f1 calculation in Pytorch.
Method signatures and docstrings:
- def __init__(self, average: str='weighted'): Init. Args: average: averaging method
- def calc_f1_micro(predictions: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: Cal... | 9ca46a9540ec93a7e0a0b13f7a4972630976f472 | <|skeleton|>
class F1Score:
"""Class for f1 calculation in Pytorch."""
def __init__(self, average: str='weighted'):
"""Init. Args: average: averaging method"""
<|body_0|>
def calc_f1_micro(predictions: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
"""Calculate f1 micro. Args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class F1Score:
"""Class for f1 calculation in Pytorch."""
def __init__(self, average: str='weighted'):
"""Init. Args: average: averaging method"""
self.average = average
if average not in [None, 'micro', 'macro', 'weighted']:
raise ValueError('Wrong value of average paramete... | the_stack_v2_python_sparse | src/metrics/f1_score.py | Bencpr/lightning_hydra_template | train | 0 |
aeb3ab99d75b26bd66743ad4a6bee3666807a4ab | [
"bc = helpers.MakeBarcode('part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False)\nself.assertIn('part', bc)\nself.assertIn('tool', bc)\nself.assertIn('\"tool\": \"InvenTree\"', bc)\ndata = json.loads(bc)\nself.assertEqual(data['part']['id'], 3)\nself.assertEqual(data['part']['url'], 'www.google.com')",
"bc =... | <|body_start_0|>
bc = helpers.MakeBarcode('part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False)
self.assertIn('part', bc)
self.assertIn('tool', bc)
self.assertIn('"tool": "InvenTree"', bc)
data = json.loads(bc)
self.assertEqual(data['part']['id'], 3)
self.as... | Tests for barcode string creation. | TestMakeBarcode | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMakeBarcode:
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
<|body_0|>
def test_barcode_brief(self):
"""Test creation of simple barcode."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_031779 | 41,191 | permissive | [
{
"docstring": "Test creation of barcode with extended data.",
"name": "test_barcode_extended",
"signature": "def test_barcode_extended(self)"
},
{
"docstring": "Test creation of simple barcode.",
"name": "test_barcode_brief",
"signature": "def test_barcode_brief(self)"
}
] | 2 | null | Implement the Python class `TestMakeBarcode` described below.
Class description:
Tests for barcode string creation.
Method signatures and docstrings:
- def test_barcode_extended(self): Test creation of barcode with extended data.
- def test_barcode_brief(self): Test creation of simple barcode. | Implement the Python class `TestMakeBarcode` described below.
Class description:
Tests for barcode string creation.
Method signatures and docstrings:
- def test_barcode_extended(self): Test creation of barcode with extended data.
- def test_barcode_brief(self): Test creation of simple barcode.
<|skeleton|>
class Tes... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestMakeBarcode:
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
<|body_0|>
def test_barcode_brief(self):
"""Test creation of simple barcode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMakeBarcode:
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
bc = helpers.MakeBarcode('part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False)
self.assertIn('part', bc)
self.assertIn('tool'... | the_stack_v2_python_sparse | InvenTree/InvenTree/tests.py | inventree/InvenTree | train | 3,077 |
ac1c3aa9e64d4773e93327f3808d8d8b03cb45b5 | [
"self.pi_means = means\nself.pi_variances = variances\nself.weight = weight",
"C1_coef = 0.5 * (np.log(pi_variances / q_variances) + pi_means ** 2 / pi_variances - q_means ** 2 / q_variances)\nC2_coef = q_means / q_variances - pi_means / pi_variances\nC3_coef = 1.0 / 2.0 * pi_variances - 1.0 / 2.0 * q_variances\n... | <|body_start_0|>
self.pi_means = means
self.pi_variances = variances
self.weight = weight
<|end_body_0|>
<|body_start_1|>
C1_coef = 0.5 * (np.log(pi_variances / q_variances) + pi_means ** 2 / pi_variances - q_means ** 2 / q_variances)
C2_coef = q_means / q_variances - pi_means /... | Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) | MFN_MFN_ED | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFN_MFN_ED:
"""Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)"""
def __init__(self, means, variances, weight=1.0):
"""MFN ... | stack_v2_sparse_classes_36k_train_031780 | 14,750 | no_license | [
{
"docstring": "MFN for prior specified by vector of means & variances",
"name": "__init__",
"signature": "def __init__(self, means, variances, weight=1.0)"
},
{
"docstring": "Compute the inner coefficients before taking the squares",
"name": "ED_term",
"signature": "def ED_term(self, q_... | 3 | stack_v2_sparse_classes_30k_val_000860 | Implement the Python class `MFN_MFN_ED` described below.
Class description:
Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)
Method signatures and docstrings:... | Implement the Python class `MFN_MFN_ED` described below.
Class description:
Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)
Method signatures and docstrings:... | 6e51c10227ca8300853f2341906503d072cc0685 | <|skeleton|>
class MFN_MFN_ED:
"""Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)"""
def __init__(self, means, variances, weight=1.0):
"""MFN ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MFN_MFN_ED:
"""Exponential Divergence where q and pi are both mean field normals. Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable)"""
def __init__(self, means, variances, weight=1.0):
"""MFN for prior spe... | the_stack_v2_python_sparse | Divergence.py | JeremiasKnoblauch/GVI_consistency | train | 0 |
b34e89e290add15839718564e8e9873770e94768 | [
"if isinstance(ksize, int):\n self.ksize = (ksize,) * 2\nelse:\n self.ksize = ksize\nif isinstance(stride, int):\n self.stride = (stride,) * 2\nelse:\n self.stride = stride\nif isinstance(pad, int):\n self.pad = (0,) + (pad,) * 2 + (0,)\nelse:\n self.pad = (0,) + tuple(pad) + (0,)\nself.param = np... | <|body_start_0|>
if isinstance(ksize, int):
self.ksize = (ksize,) * 2
else:
self.ksize = ksize
if isinstance(stride, int):
self.stride = (stride,) * 2
else:
self.stride = stride
if isinstance(pad, int):
self.pad = (0,) +... | Convolution | Convolution2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Convolution2d:
"""Convolution"""
def __init__(self, in_channels, out_channels, ksize, stride=1, pad=0, std=1.0, istrainable=True):
"""construct convolution layer Parameters ---------- in_channels : int number of channels of input out_channels : int number of channels of output ksize ... | stack_v2_sparse_classes_36k_train_031781 | 3,343 | no_license | [
{
"docstring": "construct convolution layer Parameters ---------- in_channels : int number of channels of input out_channels : int number of channels of output ksize : int or tuple size of kernels stride : int or tuple stride of kernel applications pad : int or tuple padding image std : float standard deviation... | 3 | null | Implement the Python class `Convolution2d` described below.
Class description:
Convolution
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, ksize, stride=1, pad=0, std=1.0, istrainable=True): construct convolution layer Parameters ---------- in_channels : int number of channels of inp... | Implement the Python class `Convolution2d` described below.
Class description:
Convolution
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, ksize, stride=1, pad=0, std=1.0, istrainable=True): construct convolution layer Parameters ---------- in_channels : int number of channels of inp... | 77056922f23176065b056d5ca136a43971831969 | <|skeleton|>
class Convolution2d:
"""Convolution"""
def __init__(self, in_channels, out_channels, ksize, stride=1, pad=0, std=1.0, istrainable=True):
"""construct convolution layer Parameters ---------- in_channels : int number of channels of input out_channels : int number of channels of output ksize ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Convolution2d:
"""Convolution"""
def __init__(self, in_channels, out_channels, ksize, stride=1, pad=0, std=1.0, istrainable=True):
"""construct convolution layer Parameters ---------- in_channels : int number of channels of input out_channels : int number of channels of output ksize : int or tupl... | the_stack_v2_python_sparse | prml/neural_networks/layers/convolution.py | zgcgreat/PRML-1 | train | 0 |
e778ecf5e261d1613886e2203374cef870b1e693 | [
"self.id = id\nself.street = street\nself.number = number\nself.complement = complement\nself.zip_code = zip_code\nself.neighborhood = neighborhood\nself.city = city\nself.state = state\nself.country = country\nself.status = status\nself.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None\nse... | <|body_start_0|>
self.id = id
self.street = street
self.number = number
self.complement = complement
self.zip_code = zip_code
self.neighborhood = neighborhood
self.city = city
self.state = state
self.country = country
self.status = status
... | Implementation of the 'GetAddressResponse' model. Response object for getting an Address Attributes: id (string): TODO: type description here. street (string): TODO: type description here. number (string): TODO: type description here. complement (string): TODO: type description here. zip_code (string): TODO: type descr... | GetAddressResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAddressResponse:
"""Implementation of the 'GetAddressResponse' model. Response object for getting an Address Attributes: id (string): TODO: type description here. street (string): TODO: type description here. number (string): TODO: type description here. complement (string): TODO: type descrip... | stack_v2_sparse_classes_36k_train_031782 | 5,631 | permissive | [
{
"docstring": "Constructor for the GetAddressResponse class",
"name": "__init__",
"signature": "def __init__(self, id=None, street=None, number=None, complement=None, zip_code=None, neighborhood=None, city=None, state=None, country=None, status=None, created_at=None, updated_at=None, metadata=None, lin... | 2 | stack_v2_sparse_classes_30k_train_011772 | Implement the Python class `GetAddressResponse` described below.
Class description:
Implementation of the 'GetAddressResponse' model. Response object for getting an Address Attributes: id (string): TODO: type description here. street (string): TODO: type description here. number (string): TODO: type description here. ... | Implement the Python class `GetAddressResponse` described below.
Class description:
Implementation of the 'GetAddressResponse' model. Response object for getting an Address Attributes: id (string): TODO: type description here. street (string): TODO: type description here. number (string): TODO: type description here. ... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class GetAddressResponse:
"""Implementation of the 'GetAddressResponse' model. Response object for getting an Address Attributes: id (string): TODO: type description here. street (string): TODO: type description here. number (string): TODO: type description here. complement (string): TODO: type descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetAddressResponse:
"""Implementation of the 'GetAddressResponse' model. Response object for getting an Address Attributes: id (string): TODO: type description here. street (string): TODO: type description here. number (string): TODO: type description here. complement (string): TODO: type description here. zi... | the_stack_v2_python_sparse | mundiapi/models/get_address_response.py | mundipagg/MundiAPI-PYTHON | train | 10 |
dec55fa9365df11da8c439ac816cd2b0f1f4ce10 | [
"robot = self.get_object()\nparts = robot.robot_parts.all().order_by('product__item__name')\nserializer = RobotPartSerializer(parts, many=True, context={'request': request})\nreturn Response(serializer.data)",
"robot = self.get_object()\nrobot_parts = robot.robot_parts.all()\npart_ids = robot_parts.values_list('p... | <|body_start_0|>
robot = self.get_object()
parts = robot.robot_parts.all().order_by('product__item__name')
serializer = RobotPartSerializer(parts, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
robot = self.get_object()
... | API endpoint that allows robots to be viewed or edited. | RobotViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RobotViewSet:
"""API endpoint that allows robots to be viewed or edited."""
def parts_manifest_current(self, request, pk=None):
"""Return a list of all parts currently used by this robot."""
<|body_0|>
def parts_manifest_optimal(self, request, pk=None):
"""Return... | stack_v2_sparse_classes_36k_train_031783 | 2,239 | permissive | [
{
"docstring": "Return a list of all parts currently used by this robot.",
"name": "parts_manifest_current",
"signature": "def parts_manifest_current(self, request, pk=None)"
},
{
"docstring": "Return a list of all products used by this robot, optimized such that each product shown is the lowest... | 2 | stack_v2_sparse_classes_30k_train_000854 | Implement the Python class `RobotViewSet` described below.
Class description:
API endpoint that allows robots to be viewed or edited.
Method signatures and docstrings:
- def parts_manifest_current(self, request, pk=None): Return a list of all parts currently used by this robot.
- def parts_manifest_optimal(self, requ... | Implement the Python class `RobotViewSet` described below.
Class description:
API endpoint that allows robots to be viewed or edited.
Method signatures and docstrings:
- def parts_manifest_current(self, request, pk=None): Return a list of all parts currently used by this robot.
- def parts_manifest_optimal(self, requ... | e121100ad5217042397c01e81c6ef9888f3569d6 | <|skeleton|>
class RobotViewSet:
"""API endpoint that allows robots to be viewed or edited."""
def parts_manifest_current(self, request, pk=None):
"""Return a list of all parts currently used by this robot."""
<|body_0|>
def parts_manifest_optimal(self, request, pk=None):
"""Return... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RobotViewSet:
"""API endpoint that allows robots to be viewed or edited."""
def parts_manifest_current(self, request, pk=None):
"""Return a list of all parts currently used by this robot."""
robot = self.get_object()
parts = robot.robot_parts.all().order_by('product__item__name')
... | the_stack_v2_python_sparse | parts_manager/robots/viewsets.py | gunthercox/RobotPartsManager | train | 4 |
e7c06cc84f7c385ed0ad2e842cb762455e0c8214 | [
"res = ''\nfor i in range(len(strs)):\n new_str = ','.join([str(ord(c)) for c in strs[i]])\n res = res + ':' + new_str\nreturn res",
"if len(s) == 0:\n return []\nif s == ':':\n return ['']\nenc_strs = s.split(':')\nres = []\nfor i in range(1, len(enc_strs)):\n if len(enc_strs[i]) == 0:\n re... | <|body_start_0|>
res = ''
for i in range(len(strs)):
new_str = ','.join([str(ord(c)) for c in strs[i]])
res = res + ':' + new_str
return res
<|end_body_0|>
<|body_start_1|>
if len(s) == 0:
return []
if s == ':':
return ['']
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = ''
... | stack_v2_sparse_classes_36k_train_031784 | 1,491 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_val_000834 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | 9cef9b11e16412449a46312d766f7eafcf162724 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
res = ''
for i in range(len(strs)):
new_str = ','.join([str(ord(c)) for c in strs[i]])
res = res + ':' + new_str
return res
def decode(self, s: str) -> ... | the_stack_v2_python_sparse | 271-Encode-and-Decode-Strings.py | zuqqhi2/my-leetcode-answers | train | 0 | |
b004f15e2c5bd73cb4cef13ac97c223b6e2ea704 | [
"for directory, _, _ in os.walk(path):\n if directory.endswith('.kext'):\n return directory\nraise RuntimeError('No .kext directory under %s' % path)",
"self.SyncTransactionLog()\nif not args.driver:\n raise IOError('No driver supplied.')\npub_key = config_lib.CONFIG.Get('Client.driver_signing_public... | <|body_start_0|>
for directory, _, _ in os.walk(path):
if directory.endswith('.kext'):
return directory
raise RuntimeError('No .kext directory under %s' % path)
<|end_body_0|>
<|body_start_1|>
self.SyncTransactionLog()
if not args.driver:
raise IO... | Installs a driver. Note that only drivers with a signature that validates with client_config.DRIVER_SIGNING_CERT can be loaded. | InstallDriver | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstallDriver:
"""Installs a driver. Note that only drivers with a signature that validates with client_config.DRIVER_SIGNING_CERT can be loaded."""
def _FindKext(self, path):
"""Find the .kext directory under path. Args: path: path string to search Returns: kext directory path strin... | stack_v2_sparse_classes_36k_train_031785 | 15,219 | permissive | [
{
"docstring": "Find the .kext directory under path. Args: path: path string to search Returns: kext directory path string or raises if not found. Raises: RuntimeError: if there is no kext under the path.",
"name": "_FindKext",
"signature": "def _FindKext(self, path)"
},
{
"docstring": "Initiali... | 2 | null | Implement the Python class `InstallDriver` described below.
Class description:
Installs a driver. Note that only drivers with a signature that validates with client_config.DRIVER_SIGNING_CERT can be loaded.
Method signatures and docstrings:
- def _FindKext(self, path): Find the .kext directory under path. Args: path:... | Implement the Python class `InstallDriver` described below.
Class description:
Installs a driver. Note that only drivers with a signature that validates with client_config.DRIVER_SIGNING_CERT can be loaded.
Method signatures and docstrings:
- def _FindKext(self, path): Find the .kext directory under path. Args: path:... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class InstallDriver:
"""Installs a driver. Note that only drivers with a signature that validates with client_config.DRIVER_SIGNING_CERT can be loaded."""
def _FindKext(self, path):
"""Find the .kext directory under path. Args: path: path string to search Returns: kext directory path strin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstallDriver:
"""Installs a driver. Note that only drivers with a signature that validates with client_config.DRIVER_SIGNING_CERT can be loaded."""
def _FindKext(self, path):
"""Find the .kext directory under path. Args: path: path string to search Returns: kext directory path string or raises i... | the_stack_v2_python_sparse | client/client_actions/osx/osx.py | defaultnamehere/grr | train | 3 |
a3eefcf273e6104796d1aa19884b2e4fdac78faa | [
"if user_id is None:\n request_dict = RequestDict()\n user_query = User.query\n sort = request_dict.get('sort', default='id')\n order = request_dict.get('order', default='asc')\n if sort == 'id':\n sort = 'user_id'\n user_query = sort_list(User, user_query, sort, order)\n page = request_... | <|body_start_0|>
if user_id is None:
request_dict = RequestDict()
user_query = User.query
sort = request_dict.get('sort', default='id')
order = request_dict.get('order', default='asc')
if sort == 'id':
sort = 'user_id'
user_... | UsersAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersAPI:
def get(self, user_id=None):
"""GET /api/v1/users GET /api/v1/users/<user_id>"""
<|body_0|>
def post(self):
"""POST /api/v1/users"""
<|body_1|>
def put(self, user_id):
"""PUT /api/v1/users/<user_id>"""
<|body_2|>
def delete... | stack_v2_sparse_classes_36k_train_031786 | 4,576 | no_license | [
{
"docstring": "GET /api/v1/users GET /api/v1/users/<user_id>",
"name": "get",
"signature": "def get(self, user_id=None)"
},
{
"docstring": "POST /api/v1/users",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "PUT /api/v1/users/<user_id>",
"name": "put",
... | 4 | stack_v2_sparse_classes_30k_train_007608 | Implement the Python class `UsersAPI` described below.
Class description:
Implement the UsersAPI class.
Method signatures and docstrings:
- def get(self, user_id=None): GET /api/v1/users GET /api/v1/users/<user_id>
- def post(self): POST /api/v1/users
- def put(self, user_id): PUT /api/v1/users/<user_id>
- def delete... | Implement the Python class `UsersAPI` described below.
Class description:
Implement the UsersAPI class.
Method signatures and docstrings:
- def get(self, user_id=None): GET /api/v1/users GET /api/v1/users/<user_id>
- def post(self): POST /api/v1/users
- def put(self, user_id): PUT /api/v1/users/<user_id>
- def delete... | d66ad8df15369920010de8664b8ca14adab35e3a | <|skeleton|>
class UsersAPI:
def get(self, user_id=None):
"""GET /api/v1/users GET /api/v1/users/<user_id>"""
<|body_0|>
def post(self):
"""POST /api/v1/users"""
<|body_1|>
def put(self, user_id):
"""PUT /api/v1/users/<user_id>"""
<|body_2|>
def delete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersAPI:
def get(self, user_id=None):
"""GET /api/v1/users GET /api/v1/users/<user_id>"""
if user_id is None:
request_dict = RequestDict()
user_query = User.query
sort = request_dict.get('sort', default='id')
order = request_dict.get('order', de... | the_stack_v2_python_sparse | apps/web/user/apis/rest_api.py | AngelLiang/flask-api-app-template | train | 1 | |
d99756690e1ff4f14ad46e571810fd77d57261ee | [
"sol = []\nif not s:\n return ''\ninterval = max(numRows + numRows - 2, 1)\nfor i in range(0, len(s), interval):\n sol.append(self.createsegment(s[i:i + interval], numRows))\npresol = ''.join(list(map(''.join, zip(*sol)))).replace(' ', '')\nreturn presol",
"if len(substring) < n + n - 2:\n substring = su... | <|body_start_0|>
sol = []
if not s:
return ''
interval = max(numRows + numRows - 2, 1)
for i in range(0, len(s), interval):
sol.append(self.createsegment(s[i:i + interval], numRows))
presol = ''.join(list(map(''.join, zip(*sol)))).replace(' ', '')
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str >>> Solution.createsegment('PAYPALISHIRING', 3)"""
<|body_0|>
def createsegment(self, substring, n):
"""Creates segment from substring. Len of substr is guaranteed to be N + (N-2)... | stack_v2_sparse_classes_36k_train_031787 | 1,825 | no_license | [
{
"docstring": ":type s: str :type numRows: int :rtype: str >>> Solution.createsegment('PAYPALISHIRING', 3)",
"name": "convert",
"signature": "def convert(self, s, numRows)"
},
{
"docstring": "Creates segment from substring. Len of substr is guaranteed to be N + (N-2) >>> Solution.createsegment(... | 2 | stack_v2_sparse_classes_30k_train_019541 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str >>> Solution.createsegment('PAYPALISHIRING', 3)
- def createsegment(self, substring, n): Creates segmen... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str >>> Solution.createsegment('PAYPALISHIRING', 3)
- def createsegment(self, substring, n): Creates segmen... | 2cc179bdb33a97294a2bf99dbda278e935165943 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str >>> Solution.createsegment('PAYPALISHIRING', 3)"""
<|body_0|>
def createsegment(self, substring, n):
"""Creates segment from substring. Len of substr is guaranteed to be N + (N-2)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str >>> Solution.createsegment('PAYPALISHIRING', 3)"""
sol = []
if not s:
return ''
interval = max(numRows + numRows - 2, 1)
for i in range(0, len(s), interval):
... | the_stack_v2_python_sparse | leetcode/6zigzag.py | Zedmor/hackerrank-puzzles | train | 0 | |
f1bf01b6020d5b709afa9c0b75477723dd82072d | [
"if request.current_user_id != user_id:\n abort(403)\n return\nreturn user_api.user_get_preferences(user_id)",
"if request.current_user_id != user_id:\n abort(403)\nreturn user_api.user_update_preferences(user_id, body)"
] | <|body_start_0|>
if request.current_user_id != user_id:
abort(403)
return
return user_api.user_get_preferences(user_id)
<|end_body_0|>
<|body_start_1|>
if request.current_user_id != user_id:
abort(403)
return user_api.user_update_preferences(user_id, ... | UserPreferencesController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPreferencesController:
def get_all(self, user_id):
"""Return all preferences for the current user."""
<|body_0|>
def post(self, user_id, body):
"""Allow a user to update their preferences. Note that a user must explicitly set a preference value to Null/None to ha... | stack_v2_sparse_classes_36k_train_031788 | 2,010 | no_license | [
{
"docstring": "Return all preferences for the current user.",
"name": "get_all",
"signature": "def get_all(self, user_id)"
},
{
"docstring": "Allow a user to update their preferences. Note that a user must explicitly set a preference value to Null/None to have it deleted. :param user_id The ID ... | 2 | stack_v2_sparse_classes_30k_train_007566 | Implement the Python class `UserPreferencesController` described below.
Class description:
Implement the UserPreferencesController class.
Method signatures and docstrings:
- def get_all(self, user_id): Return all preferences for the current user.
- def post(self, user_id, body): Allow a user to update their preferenc... | Implement the Python class `UserPreferencesController` described below.
Class description:
Implement the UserPreferencesController class.
Method signatures and docstrings:
- def get_all(self, user_id): Return all preferences for the current user.
- def post(self, user_id, body): Allow a user to update their preferenc... | ee2c628cd798f08615cc3135653286c51149bc91 | <|skeleton|>
class UserPreferencesController:
def get_all(self, user_id):
"""Return all preferences for the current user."""
<|body_0|>
def post(self, user_id, body):
"""Allow a user to update their preferences. Note that a user must explicitly set a preference value to Null/None to ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPreferencesController:
def get_all(self, user_id):
"""Return all preferences for the current user."""
if request.current_user_id != user_id:
abort(403)
return
return user_api.user_get_preferences(user_id)
def post(self, user_id, body):
"""Allow ... | the_stack_v2_python_sparse | radar/api/v1/user_preference.py | j-griffith/radar | train | 0 | |
ffc3fb6a2c2c88ad2ec192e4725e6ab1ccd3460f | [
"super(DenseSynthesizer, self).__init__()\nself.factorized = factorized\nif self.factorized:\n assert len_a == max_sent_len // len_b\n self.linear_2_a = nn.Linear(feature_size, len_a * head_num)\n self.linear_2_b = nn.Linear(feature_size, len_b * head_num)\n self.head_num = head_num\n self.len_a = le... | <|body_start_0|>
super(DenseSynthesizer, self).__init__()
self.factorized = factorized
if self.factorized:
assert len_a == max_sent_len // len_b
self.linear_2_a = nn.Linear(feature_size, len_a * head_num)
self.linear_2_b = nn.Linear(feature_size, len_b * head_... | The implementation of Dense Synthesizer in "SYNTHESIZER: Rethinking Self-Attention in Transformer Models" (https://arxiv.org/abs/2005.00743) This module generate a fix (H x L x L) attention weight for a sentence x The attention weight is only depend on each x_i. formulation: x shape is [Batch size, seq len, hid dim], F... | DenseSynthesizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseSynthesizer:
"""The implementation of Dense Synthesizer in "SYNTHESIZER: Rethinking Self-Attention in Transformer Models" (https://arxiv.org/abs/2005.00743) This module generate a fix (H x L x L) attention weight for a sentence x The attention weight is only depend on each x_i. formulation: ... | stack_v2_sparse_classes_36k_train_031789 | 5,337 | no_license | [
{
"docstring": "if factorized is True, the trainable model parameter is: Linear1 (hid dim -> hid dim) Linear2 (hid dim -> max sent len) else the trainable parameter is: Linear_1 (hid dim -> hid dim) Linear_2_a (hid dim -> len_a) Linear_2_b (hid dim -> len_b) to reduce the parameter count, remove the linear_1 ="... | 2 | stack_v2_sparse_classes_30k_train_020065 | Implement the Python class `DenseSynthesizer` described below.
Class description:
The implementation of Dense Synthesizer in "SYNTHESIZER: Rethinking Self-Attention in Transformer Models" (https://arxiv.org/abs/2005.00743) This module generate a fix (H x L x L) attention weight for a sentence x The attention weight is... | Implement the Python class `DenseSynthesizer` described below.
Class description:
The implementation of Dense Synthesizer in "SYNTHESIZER: Rethinking Self-Attention in Transformer Models" (https://arxiv.org/abs/2005.00743) This module generate a fix (H x L x L) attention weight for a sentence x The attention weight is... | 9206e5aa6535ef53460be7c25eeade60dbaed3d1 | <|skeleton|>
class DenseSynthesizer:
"""The implementation of Dense Synthesizer in "SYNTHESIZER: Rethinking Self-Attention in Transformer Models" (https://arxiv.org/abs/2005.00743) This module generate a fix (H x L x L) attention weight for a sentence x The attention weight is only depend on each x_i. formulation: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DenseSynthesizer:
"""The implementation of Dense Synthesizer in "SYNTHESIZER: Rethinking Self-Attention in Transformer Models" (https://arxiv.org/abs/2005.00743) This module generate a fix (H x L x L) attention weight for a sentence x The attention weight is only depend on each x_i. formulation: x shape is [B... | the_stack_v2_python_sparse | src/module/synthesizer/dense_synthesizer.py | zhengxxn/NMT | train | 0 |
650d67064f6e81d41be941cd2bba21bdb7820344 | [
"self.v0 = des_v\nself.T = hdwy_t\nself.s0 = min_gap\nself.a = accel\nself.b = deccel\nself.delta = 4",
"for key in means.keys():\n if key not in variances:\n if debug:\n print('Key {} appears in means for IDM, but not variances.'.format(key))\n continue\n elif key is 'des_v':\n ... | <|body_start_0|>
self.v0 = des_v
self.T = hdwy_t
self.s0 = min_gap
self.a = accel
self.b = deccel
self.delta = 4
<|end_body_0|>
<|body_start_1|>
for key in means.keys():
if key not in variances:
if debug:
print('Key... | The intelligent driver model (IDM) is used to model the longitudinal acceleration for human drivers. | IDM_Model | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IDM_Model:
"""The intelligent driver model (IDM) is used to model the longitudinal acceleration for human drivers."""
def __init__(self, des_v=30, hdwy_t=1.5, min_gap=2.0, accel=0.3, deccel=3.0):
"""Arguments des_v: Float, the desired velocity of this driver, if there was an open roa... | stack_v2_sparse_classes_36k_train_031790 | 14,116 | permissive | [
{
"docstring": "Arguments des_v: Float, the desired velocity of this driver, if there was an open road (m/s). hdwy_t: The desired time-headway of this driver (seconds). This means the driver would like be able to cover the distance to the leading vehicle in at least this amount of time, at constant velocity. mi... | 3 | stack_v2_sparse_classes_30k_train_018580 | Implement the Python class `IDM_Model` described below.
Class description:
The intelligent driver model (IDM) is used to model the longitudinal acceleration for human drivers.
Method signatures and docstrings:
- def __init__(self, des_v=30, hdwy_t=1.5, min_gap=2.0, accel=0.3, deccel=3.0): Arguments des_v: Float, the ... | Implement the Python class `IDM_Model` described below.
Class description:
The intelligent driver model (IDM) is used to model the longitudinal acceleration for human drivers.
Method signatures and docstrings:
- def __init__(self, des_v=30, hdwy_t=1.5, min_gap=2.0, accel=0.3, deccel=3.0): Arguments des_v: Float, the ... | 71415d9fc71bc636ac1f5de1a90f033b4e519538 | <|skeleton|>
class IDM_Model:
"""The intelligent driver model (IDM) is used to model the longitudinal acceleration for human drivers."""
def __init__(self, des_v=30, hdwy_t=1.5, min_gap=2.0, accel=0.3, deccel=3.0):
"""Arguments des_v: Float, the desired velocity of this driver, if there was an open roa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IDM_Model:
"""The intelligent driver model (IDM) is used to model the longitudinal acceleration for human drivers."""
def __init__(self, des_v=30, hdwy_t=1.5, min_gap=2.0, accel=0.3, deccel=3.0):
"""Arguments des_v: Float, the desired velocity of this driver, if there was an open road (m/s). hdwy... | the_stack_v2_python_sparse | driver_models.py | syeda27/MonoRARP | train | 2 |
f0f24b75e753ba1a7c545f926ca085fd5158b3c6 | [
"if self.website_published:\n self.write({'website_published': False})\nelse:\n self.write({'website_published': True})",
"if self.filter_id:\n domain = safe_eval(self.filter_id.domain)\n domain += ['|', ('website_id', '=', None), ('website_id', '=', self.slider_id.website_id.id), ('website_published'... | <|body_start_0|>
if self.website_published:
self.write({'website_published': False})
else:
self.write({'website_published': True})
<|end_body_0|>
<|body_start_1|>
if self.filter_id:
domain = safe_eval(self.filter_id.domain)
domain += ['|', ('websi... | SliderFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SliderFilter:
def website_publish_button(self):
"""Set slider filter published and unpublished on website :return:"""
<|body_0|>
def _onchange_filter_id(self):
"""If selected Filter has no any product the raise the warning and remove that filter :return:"""
<... | stack_v2_sparse_classes_36k_train_031791 | 1,733 | no_license | [
{
"docstring": "Set slider filter published and unpublished on website :return:",
"name": "website_publish_button",
"signature": "def website_publish_button(self)"
},
{
"docstring": "If selected Filter has no any product the raise the warning and remove that filter :return:",
"name": "_oncha... | 2 | stack_v2_sparse_classes_30k_train_019844 | Implement the Python class `SliderFilter` described below.
Class description:
Implement the SliderFilter class.
Method signatures and docstrings:
- def website_publish_button(self): Set slider filter published and unpublished on website :return:
- def _onchange_filter_id(self): If selected Filter has no any product t... | Implement the Python class `SliderFilter` described below.
Class description:
Implement the SliderFilter class.
Method signatures and docstrings:
- def website_publish_button(self): Set slider filter published and unpublished on website :return:
- def _onchange_filter_id(self): If selected Filter has no any product t... | 148dd95d991a348ebbaff9396759a7dd1fe6e101 | <|skeleton|>
class SliderFilter:
def website_publish_button(self):
"""Set slider filter published and unpublished on website :return:"""
<|body_0|>
def _onchange_filter_id(self):
"""If selected Filter has no any product the raise the warning and remove that filter :return:"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SliderFilter:
def website_publish_button(self):
"""Set slider filter published and unpublished on website :return:"""
if self.website_published:
self.write({'website_published': False})
else:
self.write({'website_published': True})
def _onchange_filter_id(s... | the_stack_v2_python_sparse | custom/addons/emipro_theme_base/model/slider_filter.py | marionumza/saas | train | 0 | |
f04e4966acd9085b3a334aa40a4e031c10e82e54 | [
"self.__args__ = args\nself.__kargs__ = kargs\nself.__topic__ = topic\nself.__conn__ = connection\nself.__balanced__ = balanced",
"cons = None\ntopic = self.__conn__.create_topic(self.__topic__)\nif self.__balanced__ is True:\n cons = topic.get_balanced_consumer(*self.__args__, **self.__kargs__)\nelse:\n co... | <|body_start_0|>
self.__args__ = args
self.__kargs__ = kargs
self.__topic__ = topic
self.__conn__ = connection
self.__balanced__ = balanced
<|end_body_0|>
<|body_start_1|>
cons = None
topic = self.__conn__.create_topic(self.__topic__)
if self.__balanced__... | A class capable of create a consumer connection. | ConsumerFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerFactory:
"""A class capable of create a consumer connection."""
def __init__(self, connection, topic, balanced, args, kargs):
"""Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds ... | stack_v2_sparse_classes_36k_train_031792 | 2,257 | permissive | [
{
"docstring": "Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds the connection information topic: str Name of topic that messages will be read from balanced: bool True for a balanced consumer False for a simple co... | 3 | stack_v2_sparse_classes_30k_train_008744 | Implement the Python class `ConsumerFactory` described below.
Class description:
A class capable of create a consumer connection.
Method signatures and docstrings:
- def __init__(self, connection, topic, balanced, args, kargs): Create a ConsumerFactory. A object capable of create a consumer connection Parameters ----... | Implement the Python class `ConsumerFactory` described below.
Class description:
A class capable of create a consumer connection.
Method signatures and docstrings:
- def __init__(self, connection, topic, balanced, args, kargs): Create a ConsumerFactory. A object capable of create a consumer connection Parameters ----... | f2c958df88c5698148aae4c5314dd39e31e995c3 | <|skeleton|>
class ConsumerFactory:
"""A class capable of create a consumer connection."""
def __init__(self, connection, topic, balanced, args, kargs):
"""Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsumerFactory:
"""A class capable of create a consumer connection."""
def __init__(self, connection, topic, balanced, args, kargs):
"""Create a ConsumerFactory. A object capable of create a consumer connection Parameters ---------- connection: ConnectionBuilder A object that holds the connectio... | the_stack_v2_python_sparse | kafka_client_decorators/kafka/consumer_factory.py | cdsedson/kafka-decorator | train | 1 |
b269c5963df6e2986513560b1c158dc5e1ec4958 | [
"super(Text_Encoder, self).__init__()\nself.fc1_text_dim = model_parameters.FC1_TEXT_DIM\nself.fc2_text_dim = model_parameters.FC2_TEXT_DIM\nself.fine_tune_text = model_parameters.FINE_TUNE_TEXT\nself.fine_tune_text_layers = model_parameters.FINE_TUNE_TEXT_LAYERS\nself.dropout_p = model_parameters.DROPOUT_P\nself.c... | <|body_start_0|>
super(Text_Encoder, self).__init__()
self.fc1_text_dim = model_parameters.FC1_TEXT_DIM
self.fc2_text_dim = model_parameters.FC2_TEXT_DIM
self.fine_tune_text = model_parameters.FINE_TUNE_TEXT
self.fine_tune_text_layers = model_parameters.FINE_TUNE_TEXT_LAYERS
... | Text Encoder MOdel | Text_Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Text_Encoder:
"""Text Encoder MOdel"""
def __init__(self):
"""@param fine_tune_text (bool): Set `False` to fine-tune the BERT model"""
<|body_0|>
def forward(self, input_ids, attention_mask):
"""Feed input to BERT and the classifier to compute logits. @param inpu... | stack_v2_sparse_classes_36k_train_031793 | 9,539 | no_license | [
{
"docstring": "@param fine_tune_text (bool): Set `False` to fine-tune the BERT model",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Feed input to BERT and the classifier to compute logits. @param input_ids (torch.Tensor): an input tensor with shape (batch_size, max_l... | 3 | stack_v2_sparse_classes_30k_train_020216 | Implement the Python class `Text_Encoder` described below.
Class description:
Text Encoder MOdel
Method signatures and docstrings:
- def __init__(self): @param fine_tune_text (bool): Set `False` to fine-tune the BERT model
- def forward(self, input_ids, attention_mask): Feed input to BERT and the classifier to comput... | Implement the Python class `Text_Encoder` described below.
Class description:
Text Encoder MOdel
Method signatures and docstrings:
- def __init__(self): @param fine_tune_text (bool): Set `False` to fine-tune the BERT model
- def forward(self, input_ids, attention_mask): Feed input to BERT and the classifier to comput... | cf4d2a603ec0cbfaab0ce550f19110742970bcba | <|skeleton|>
class Text_Encoder:
"""Text Encoder MOdel"""
def __init__(self):
"""@param fine_tune_text (bool): Set `False` to fine-tune the BERT model"""
<|body_0|>
def forward(self, input_ids, attention_mask):
"""Feed input to BERT and the classifier to compute logits. @param inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Text_Encoder:
"""Text Encoder MOdel"""
def __init__(self):
"""@param fine_tune_text (bool): Set `False` to fine-tune the BERT model"""
super(Text_Encoder, self).__init__()
self.fc1_text_dim = model_parameters.FC1_TEXT_DIM
self.fc2_text_dim = model_parameters.FC2_TEXT_DIM
... | the_stack_v2_python_sparse | code/src/sub_modules.py | mudit-dhawan/FND | train | 2 |
0dede8582813858998aafa1921f7aa86ed0d54e4 | [
"invalid = u'! # $ % ^ & * ( ) = + , : ; \" | ~ / \\\\ \\x00 \\u202a'.split()\nbase = u'User%sName'\nfor c in invalid:\n name = base % c\n assert not user.isValidName(self.request, name)",
"cases = (u' User Name', u'User Name ', u'User Name')\nfor test in cases:\n assert not user.isValidName(self.reque... | <|body_start_0|>
invalid = u'! # $ % ^ & * ( ) = + , : ; " | ~ / \\ \x00 \u202a'.split()
base = u'User%sName'
for c in invalid:
name = base % c
assert not user.isValidName(self.request, name)
<|end_body_0|>
<|body_start_1|>
cases = (u' User Name', u'User Name ', ... | TestIsValidName | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIsValidName:
def testNonAlnumCharacters(self):
"""user: isValidName: reject unicode non alpha numeric characters : and , used in acl rules, we might add more characters to the syntax."""
<|body_0|>
def testWhitespace(self):
"""user: isValidName: reject leading, t... | stack_v2_sparse_classes_36k_train_031794 | 11,347 | no_license | [
{
"docstring": "user: isValidName: reject unicode non alpha numeric characters : and , used in acl rules, we might add more characters to the syntax.",
"name": "testNonAlnumCharacters",
"signature": "def testNonAlnumCharacters(self)"
},
{
"docstring": "user: isValidName: reject leading, trailing... | 3 | stack_v2_sparse_classes_30k_train_020053 | Implement the Python class `TestIsValidName` described below.
Class description:
Implement the TestIsValidName class.
Method signatures and docstrings:
- def testNonAlnumCharacters(self): user: isValidName: reject unicode non alpha numeric characters : and , used in acl rules, we might add more characters to the synt... | Implement the Python class `TestIsValidName` described below.
Class description:
Implement the TestIsValidName class.
Method signatures and docstrings:
- def testNonAlnumCharacters(self): user: isValidName: reject unicode non alpha numeric characters : and , used in acl rules, we might add more characters to the synt... | d6e801402c4538bdfb34a97cf07153101167c1ec | <|skeleton|>
class TestIsValidName:
def testNonAlnumCharacters(self):
"""user: isValidName: reject unicode non alpha numeric characters : and , used in acl rules, we might add more characters to the syntax."""
<|body_0|>
def testWhitespace(self):
"""user: isValidName: reject leading, t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestIsValidName:
def testNonAlnumCharacters(self):
"""user: isValidName: reject unicode non alpha numeric characters : and , used in acl rules, we might add more characters to the syntax."""
invalid = u'! # $ % ^ & * ( ) = + , : ; " | ~ / \\ \x00 \u202a'.split()
base = u'User%sName'
... | the_stack_v2_python_sparse | MoinMoin/_tests/test_user.py | happytk/jardin | train | 0 | |
f8f00c84b39fbfc47da8edb6cc68243aa298f503 | [
"self.num = num\nself.queue = queue\nself.interval = interval\nthread = threading.Thread(target=self.run, args=())\nthread.daemon = True\nthread.start()",
"while True:\n if self.queue.empty():\n print('[{}] Doing something imporant in the background'.format(self.num))\n else:\n val = self.queu... | <|body_start_0|>
self.num = num
self.queue = queue
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
<|end_body_0|>
<|body_start_1|>
while True:
if self.queue.empty():
prin... | Threading example class The run() method will be started and it will run in the background until the application exits. | ThreadingExample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, num, queue, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body... | stack_v2_sparse_classes_36k_train_031795 | 1,475 | no_license | [
{
"docstring": "Constructor :type interval: int :param interval: Check interval, in seconds",
"name": "__init__",
"signature": "def __init__(self, num, queue, interval=1)"
},
{
"docstring": "Method that runs forever",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `ThreadingExample` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, num, queue, interval=1): Constructor :type interval: int :par... | Implement the Python class `ThreadingExample` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, num, queue, interval=1): Constructor :type interval: int :par... | 5376dd48b1cefb4faba9d2ef6a8a497b6b1d6c67 | <|skeleton|>
class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, num, queue, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadingExample:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, num, queue, interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
self.num = num
... | the_stack_v2_python_sparse | python/test-multiprocessing/threading_example.py | hyunjun/practice | train | 3 |
6e89f90a25df44a9580d8a73c8b9d2592759872d | [
"data = request.get_json()\nif not department_check(data, department_keys):\n return ('Bad Request', 400)\ntitle = data.get('title')\nitem_id = add_department(title)\ndepartment = {'title': title, 'id': item_id}\nresp = jsonify(department)\nresp.status_code = 201\nlog_msg = f'dep {item_id}, {title}, created : {d... | <|body_start_0|>
data = request.get_json()
if not department_check(data, department_keys):
return ('Bad Request', 400)
title = data.get('title')
item_id = add_department(title)
department = {'title': title, 'id': item_id}
resp = jsonify(department)
res... | Departments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Departments:
def post(self):
"""Create department with data from POST reuest body.json :return: departmen id, title"""
<|body_0|>
def get(self):
"""Returns list of departments :return: list of departments"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031796 | 3,115 | no_license | [
{
"docstring": "Create department with data from POST reuest body.json :return: departmen id, title",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Returns list of departments :return: list of departments",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000858 | Implement the Python class `Departments` described below.
Class description:
Implement the Departments class.
Method signatures and docstrings:
- def post(self): Create department with data from POST reuest body.json :return: departmen id, title
- def get(self): Returns list of departments :return: list of department... | Implement the Python class `Departments` described below.
Class description:
Implement the Departments class.
Method signatures and docstrings:
- def post(self): Create department with data from POST reuest body.json :return: departmen id, title
- def get(self): Returns list of departments :return: list of department... | 8452b3671afce50b733379f278d1adf89e6e2ec9 | <|skeleton|>
class Departments:
def post(self):
"""Create department with data from POST reuest body.json :return: departmen id, title"""
<|body_0|>
def get(self):
"""Returns list of departments :return: list of departments"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Departments:
def post(self):
"""Create department with data from POST reuest body.json :return: departmen id, title"""
data = request.get_json()
if not department_check(data, department_keys):
return ('Bad Request', 400)
title = data.get('title')
item_id = a... | the_stack_v2_python_sparse | department-app/rest/rest_departments.py | dgiart/final05_python_2021 | train | 0 | |
cdc35512ca3fca83e9d59f6ee5dd53612279d744 | [
"self.unchecked_text = kwargs.get('text')\nself.unchecked_image = kwargs.get('image')\nself.checked_text = kwargs.pop('checked_text', None)\nself.checked_image = kwargs.pop('checked_image', None)\nself.on_toggle = kwargs.pop('on_toggle', None)\nself.is_checked = False\nkwargs['command'] = self.toggle\nkwargs['compo... | <|body_start_0|>
self.unchecked_text = kwargs.get('text')
self.unchecked_image = kwargs.get('image')
self.checked_text = kwargs.pop('checked_text', None)
self.checked_image = kwargs.pop('checked_image', None)
self.on_toggle = kwargs.pop('on_toggle', None)
self.is_checked ... | A toggle button which works like a checkbox, and can be checked and unchecked with different text and images | ToggleButton | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToggleButton:
"""A toggle button which works like a checkbox, and can be checked and unchecked with different text and images"""
def __init__(self, master=None, **kwargs):
"""Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and im... | stack_v2_sparse_classes_36k_train_031797 | 1,465 | permissive | [
{
"docstring": "Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and image both default to the unchecked state)",
"name": "__init__",
"signature": "def __init__(self, master=None, **kwargs)"
},
{
"docstring": "Toggles the button state",
"... | 2 | stack_v2_sparse_classes_30k_train_006053 | Implement the Python class `ToggleButton` described below.
Class description:
A toggle button which works like a checkbox, and can be checked and unchecked with different text and images
Method signatures and docstrings:
- def __init__(self, master=None, **kwargs): Extra parameters: checked_text (str) checked_image (... | Implement the Python class `ToggleButton` described below.
Class description:
A toggle button which works like a checkbox, and can be checked and unchecked with different text and images
Method signatures and docstrings:
- def __init__(self, master=None, **kwargs): Extra parameters: checked_text (str) checked_image (... | a98ed281386c0e5c6e439c4a43b20f813d012bd7 | <|skeleton|>
class ToggleButton:
"""A toggle button which works like a checkbox, and can be checked and unchecked with different text and images"""
def __init__(self, master=None, **kwargs):
"""Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToggleButton:
"""A toggle button which works like a checkbox, and can be checked and unchecked with different text and images"""
def __init__(self, master=None, **kwargs):
"""Extra parameters: checked_text (str) checked_image (PhotoImage) on_toggle(is_checked) (function) (text and image both defa... | the_stack_v2_python_sparse | gui/widgets/toggle_button.py | StetHD/Telebackup | train | 0 |
13b33546f69ac59eafa92fe6f60d2eb9622f4b94 | [
"self.population = []\nfor i in range(simulation.grid_size):\n row = []\n for j in range(simulation.grid_size):\n person = Person()\n row.append(person)\n self.population.append(row)",
"infected_count = int(round(simulation.infection_percent * simulation.population_size, 0))\ninfections = 0... | <|body_start_0|>
self.population = []
for i in range(simulation.grid_size):
row = []
for j in range(simulation.grid_size):
person = Person()
row.append(person)
self.population.append(row)
<|end_body_0|>
<|body_start_1|>
infecte... | A class to model a whole population of Person objects | Population | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Population:
"""A class to model a whole population of Person objects"""
def __init__(self, simulation):
"""Initialize attributes"""
<|body_0|>
def initial_infection(self, simulation):
"""Infect an initial portion of the population based on initial conditions of t... | stack_v2_sparse_classes_36k_train_031798 | 14,904 | permissive | [
{
"docstring": "Initialize attributes",
"name": "__init__",
"signature": "def __init__(self, simulation)"
},
{
"docstring": "Infect an initial portion of the population based on initial conditions of the sim",
"name": "initial_infection",
"signature": "def initial_infection(self, simulat... | 5 | stack_v2_sparse_classes_30k_train_004310 | Implement the Python class `Population` described below.
Class description:
A class to model a whole population of Person objects
Method signatures and docstrings:
- def __init__(self, simulation): Initialize attributes
- def initial_infection(self, simulation): Infect an initial portion of the population based on in... | Implement the Python class `Population` described below.
Class description:
A class to model a whole population of Person objects
Method signatures and docstrings:
- def __init__(self, simulation): Initialize attributes
- def initial_infection(self, simulation): Infect an initial portion of the population based on in... | a9f44d20ae212b5cbc190ac49ca7acc638ff4228 | <|skeleton|>
class Population:
"""A class to model a whole population of Person objects"""
def __init__(self, simulation):
"""Initialize attributes"""
<|body_0|>
def initial_infection(self, simulation):
"""Infect an initial portion of the population based on initial conditions of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Population:
"""A class to model a whole population of Person objects"""
def __init__(self, simulation):
"""Initialize attributes"""
self.population = []
for i in range(simulation.grid_size):
row = []
for j in range(simulation.grid_size):
per... | the_stack_v2_python_sparse | 9_Classes/challenge_40_code.py | demoanddemo/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | train | 0 |
49d00060bdcf1b332810888e9588173a20dc97f2 | [
"with mute_signals(post_save):\n profile = self.create_and_login_user()\n self.client.force_login(profile.user)\nresponse = self.client.get('/404/')\nassert response.status_code == status.HTTP_404_NOT_FOUND\nassert response.context['authenticated'] is True\nassert response.context['name'] == profile.preferred... | <|body_start_0|>
with mute_signals(post_save):
profile = self.create_and_login_user()
self.client.force_login(profile.user)
response = self.client.get('/404/')
assert response.status_code == status.HTTP_404_NOT_FOUND
assert response.context['authenticated'] is Tru... | Tests for 404 and 500 handlers | HandlerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandlerTests:
"""Tests for 404 and 500 handlers"""
def test_404_error_context_logged_in(self):
"""Assert context values for 404 error page when logged in"""
<|body_0|>
def test_404_error_context_logged_out(self):
"""Assert context values for 404 error page when l... | stack_v2_sparse_classes_36k_train_031799 | 17,507 | no_license | [
{
"docstring": "Assert context values for 404 error page when logged in",
"name": "test_404_error_context_logged_in",
"signature": "def test_404_error_context_logged_in(self)"
},
{
"docstring": "Assert context values for 404 error page when logged out",
"name": "test_404_error_context_logged... | 4 | stack_v2_sparse_classes_30k_train_003498 | Implement the Python class `HandlerTests` described below.
Class description:
Tests for 404 and 500 handlers
Method signatures and docstrings:
- def test_404_error_context_logged_in(self): Assert context values for 404 error page when logged in
- def test_404_error_context_logged_out(self): Assert context values for ... | Implement the Python class `HandlerTests` described below.
Class description:
Tests for 404 and 500 handlers
Method signatures and docstrings:
- def test_404_error_context_logged_in(self): Assert context values for 404 error page when logged in
- def test_404_error_context_logged_out(self): Assert context values for ... | 8eb49dfa808f144693735d95fa7305c480485852 | <|skeleton|>
class HandlerTests:
"""Tests for 404 and 500 handlers"""
def test_404_error_context_logged_in(self):
"""Assert context values for 404 error page when logged in"""
<|body_0|>
def test_404_error_context_logged_out(self):
"""Assert context values for 404 error page when l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HandlerTests:
"""Tests for 404 and 500 handlers"""
def test_404_error_context_logged_in(self):
"""Assert context values for 404 error page when logged in"""
with mute_signals(post_save):
profile = self.create_and_login_user()
self.client.force_login(profile.user)
... | the_stack_v2_python_sparse | ui/views_test.py | singingwolfboy/micromasters | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.