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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de83447ea09faceb22852cf86615187b2f79bf05 | [
"del name\nif value:\n queryset = queryset.filter(company_id=value).order_by('-is_top', '-pk')\nreturn queryset",
"del name\nif value:\n return queryset.filter(owner_id=self.request.user.pk)\nreturn queryset.exclude(owner_id=self.request.user.pk)"
] | <|body_start_0|>
del name
if value:
queryset = queryset.filter(company_id=value).order_by('-is_top', '-pk')
return queryset
<|end_body_0|>
<|body_start_1|>
del name
if value:
return queryset.filter(owner_id=self.request.user.pk)
return queryset.ex... | Review filterset. | ReviewFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewFilter:
"""Review filterset."""
def _company(queryset, name, value):
"""Filter by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset"""
<|body_0|>
def _is_mine(self, queryset, name, value):
"""Fi... | stack_v2_sparse_classes_36k_train_002300 | 2,436 | no_license | [
{
"docstring": "Filter by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset",
"name": "_company",
"signature": "def _company(queryset, name, value)"
},
{
"docstring": "Filter by owner. :param queryset: Reviews queryset :param name: f... | 2 | null | Implement the Python class `ReviewFilter` described below.
Class description:
Review filterset.
Method signatures and docstrings:
- def _company(queryset, name, value): Filter by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset
- def _is_mine(self, query... | Implement the Python class `ReviewFilter` described below.
Class description:
Review filterset.
Method signatures and docstrings:
- def _company(queryset, name, value): Filter by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset
- def _is_mine(self, query... | 713b9d84ac70d964d46f189ab1f9c7b944b9684b | <|skeleton|>
class ReviewFilter:
"""Review filterset."""
def _company(queryset, name, value):
"""Filter by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset"""
<|body_0|>
def _is_mine(self, queryset, name, value):
"""Fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewFilter:
"""Review filterset."""
def _company(queryset, name, value):
"""Filter by company. :param queryset: Reviews queryset :param name: filter name :param value: filter value :return: queryset"""
del name
if value:
queryset = queryset.filter(company_id=value).o... | the_stack_v2_python_sparse | jobadvisor/reviews/filters.py | ewgen19892/jobadvisor | train | 0 |
307ae4f7792a56ffad33caf97f2ca3012d825a60 | [
"def transform(node):\n if node:\n vals.append(str(node.val))\n transform(node.left)\n transform(node.right)\n else:\n vals.append('#')\nvals = []\ntransform(root)\nreturn ' '.join(vals)",
"def helper(queue):\n if not queue:\n return None\n val = queue.popleft()\n ... | <|body_start_0|>
def transform(node):
if node:
vals.append(str(node.val))
transform(node.left)
transform(node.right)
else:
vals.append('#')
vals = []
transform(root)
return ' '.join(vals)
<|end_body_0... | 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|>
def deserialize1(self... | stack_v2_sparse_classes_36k_train_002301 | 2,059 | 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... | 3 | 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:... | 502e121cc25fcd81afe3d029145aeee56db794f0 | <|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|>
def deserialize1(self... | 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 transform(node):
if node:
vals.append(str(node.val))
transform(node.left)
transform(node.right)
else:
... | the_stack_v2_python_sparse | tree_graph/297serialize.py | qinzhouhit/leetcode | train | 0 | |
c90ca684564322672d6257ce8e4667b17759bda9 | [
"max_count = -float('inf')\ndp = [[0] * len(arr) for _ in range(len(arr))]\nfor i in range(len(arr)):\n dp[i][i] = (arr[i], arr[i])\n max_count = max(max_count, dp[i][i][0])\n for j in range(i):\n min_index = dp[i - 1][j][1]\n count = dp[i - 1][j][0]\n if i - 1 != j:\n count... | <|body_start_0|>
max_count = -float('inf')
dp = [[0] * len(arr) for _ in range(len(arr))]
for i in range(len(arr)):
dp[i][i] = (arr[i], arr[i])
max_count = max(max_count, dp[i][i][0])
for j in range(i):
min_index = dp[i - 1][j][1]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def __maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def ___maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
<|... | stack_v2_sparse_classes_36k_train_002302 | 3,423 | permissive | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "_maximumSum",
"signature": "def _maximumSum(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "__maximumSum",
"signature": "def __maximumSum(self, arr)"
},
{
"docstring": ":type arr: List[int] :rt... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maximumSum(self, arr): :type arr: List[int] :rtype: int
- def __maximumSum(self, arr): :type arr: List[int] :rtype: int
- def ___maximumSum(self, arr): :type arr: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _maximumSum(self, arr): :type arr: List[int] :rtype: int
- def __maximumSum(self, arr): :type arr: List[int] :rtype: int
- def ___maximumSum(self, arr): :type arr: List[int] ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def __maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
def ___maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _maximumSum(self, arr):
""":type arr: List[int] :rtype: int"""
max_count = -float('inf')
dp = [[0] * len(arr) for _ in range(len(arr))]
for i in range(len(arr)):
dp[i][i] = (arr[i], arr[i])
max_count = max(max_count, dp[i][i][0])
... | the_stack_v2_python_sparse | 1186.maximum-subarray-sum-with-one-deletion.py | windard/leeeeee | train | 0 | |
cc4c8af2b84a314da4ea31f7105882aa9138cc0b | [
"b_ret, d_edge = get_edge_info(name)\nif not b_ret:\n d_msg = {'error': '{}'.format(d_edge)}\n return (d_msg, 404)\nreturn d_edge",
"b_ret, s_msg = delete_edge(name)\nif not b_ret:\n d_msg = {'error': s_msg}\n return (d_msg, 404)\nreturn (None, 204)",
"data = request.json\nb_ret, s_msg = update_edge... | <|body_start_0|>
b_ret, d_edge = get_edge_info(name)
if not b_ret:
d_msg = {'error': '{}'.format(d_edge)}
return (d_msg, 404)
return d_edge
<|end_body_0|>
<|body_start_1|>
b_ret, s_msg = delete_edge(name)
if not b_ret:
d_msg = {'error': s_msg}... | EdgeItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeItem:
def get(self, name):
"""Returns the edge information."""
<|body_0|>
def delete(self, name):
"""Deletes the edge."""
<|body_1|>
def patch(self, name):
"""Update the edge information."""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_002303 | 2,559 | permissive | [
{
"docstring": "Returns the edge information.",
"name": "get",
"signature": "def get(self, name)"
},
{
"docstring": "Deletes the edge.",
"name": "delete",
"signature": "def delete(self, name)"
},
{
"docstring": "Update the edge information.",
"name": "patch",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_020272 | Implement the Python class `EdgeItem` described below.
Class description:
Implement the EdgeItem class.
Method signatures and docstrings:
- def get(self, name): Returns the edge information.
- def delete(self, name): Deletes the edge.
- def patch(self, name): Update the edge information. | Implement the Python class `EdgeItem` described below.
Class description:
Implement the EdgeItem class.
Method signatures and docstrings:
- def get(self, name): Returns the edge information.
- def delete(self, name): Deletes the edge.
- def patch(self, name): Update the edge information.
<|skeleton|>
class EdgeItem:... | 65d01799296fce043e87ba58106f8fa8c1d8aa98 | <|skeleton|>
class EdgeItem:
def get(self, name):
"""Returns the edge information."""
<|body_0|>
def delete(self, name):
"""Deletes the edge."""
<|body_1|>
def patch(self, name):
"""Update the edge information."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeItem:
def get(self, name):
"""Returns the edge information."""
b_ret, d_edge = get_edge_info(name)
if not b_ret:
d_msg = {'error': '{}'.format(d_edge)}
return (d_msg, 404)
return d_edge
def delete(self, name):
"""Deletes the edge."""
... | the_stack_v2_python_sparse | pengrixio/api/edge/endpoints/route.py | iorchard/pengrixio | train | 0 | |
09a1d9ce4b8b9c63666f9c5a1cc054d94e08d07c | [
"super().__init__(transparent=True)\nself._on_ok = on_ok\nself._on_cancel = on_cancel\nself._panel = Compound()\nself._panel.add_widget(panel_widget)\n_panel_size = panel_widget.get_size(engine)\nwindow_size = engine.get_window_size()\n_panel_topleft = Point((window_size.width - _panel_size.width) // 2, (window_siz... | <|body_start_0|>
super().__init__(transparent=True)
self._on_ok = on_ok
self._on_cancel = on_cancel
self._panel = Compound()
self._panel.add_widget(panel_widget)
_panel_size = panel_widget.get_size(engine)
window_size = engine.get_window_size()
_panel_topl... | Displays message and requires answer or confirmation. | MessageBox | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageBox:
"""Displays message and requires answer or confirmation."""
def __init__(self, text, font, panel_widget, engine, text_shift=None, on_ok=None, on_cancel=None):
"""Creates message box with given text and font (required). Panel widget will be draw under the text and will be ... | stack_v2_sparse_classes_36k_train_002304 | 16,213 | permissive | [
{
"docstring": "Creates message box with given text and font (required). Panel widget will be draw under the text and will be aligned to the center of the screen. Text will start from the topleft corner of the panel plus optional text_shift. Optional on_ok and on_cancel events can be passed. Both should be call... | 2 | stack_v2_sparse_classes_30k_train_010941 | Implement the Python class `MessageBox` described below.
Class description:
Displays message and requires answer or confirmation.
Method signatures and docstrings:
- def __init__(self, text, font, panel_widget, engine, text_shift=None, on_ok=None, on_cancel=None): Creates message box with given text and font (require... | Implement the Python class `MessageBox` described below.
Class description:
Displays message and requires answer or confirmation.
Method signatures and docstrings:
- def __init__(self, text, font, panel_widget, engine, text_shift=None, on_ok=None, on_cancel=None): Creates message box with given text and font (require... | 584de7ad3e0817e28ee8e14e0298a06cae8e672e | <|skeleton|>
class MessageBox:
"""Displays message and requires answer or confirmation."""
def __init__(self, text, font, panel_widget, engine, text_shift=None, on_ok=None, on_cancel=None):
"""Creates message box with given text and font (required). Panel widget will be draw under the text and will be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageBox:
"""Displays message and requires answer or confirmation."""
def __init__(self, text, font, panel_widget, engine, text_shift=None, on_ok=None, on_cancel=None):
"""Creates message box with given text and font (required). Panel widget will be draw under the text and will be aligned to th... | the_stack_v2_python_sparse | nanomyth/view/sdl/context.py | clckwrkbdgr/nanomyth | train | 0 |
99645b6c12aeaeb6296bd3205e29ee3a65a8920e | [
"if n == 1:\n return 1\nif n == 2:\n return 2\nreturn self.climb_stairs(n - 1) + self.climb_stairs(n - 2)",
"dp = {1: 1, 2: 2}\nfor i in range(3, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nreturn dp[n]",
"if n == 1 or n == 2:\n return n\na, b, tmp = (1, 2, 0)\nfor i in range(3, n + 1):\n tmp = a + ... | <|body_start_0|>
if n == 1:
return 1
if n == 2:
return 2
return self.climb_stairs(n - 1) + self.climb_stairs(n - 2)
<|end_body_0|>
<|body_start_1|>
dp = {1: 1, 2: 2}
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def climb_stairs(self, n: int) -> int:
"""递归。"""
<|body_0|>
def climb_stairs_2(self, n: int) -> int:
"""动态规划。"""
<|body_1|>
def climb_stairs_3(self, n: int) -> int:
"""动态规划(优化空间)。"""
<|body_2|>
def climb_stairs_4(se... | stack_v2_sparse_classes_36k_train_002305 | 2,158 | no_license | [
{
"docstring": "递归。",
"name": "climb_stairs",
"signature": "def climb_stairs(self, n: int) -> int"
},
{
"docstring": "动态规划。",
"name": "climb_stairs_2",
"signature": "def climb_stairs_2(self, n: int) -> int"
},
{
"docstring": "动态规划(优化空间)。",
"name": "climb_stairs_3",
"signa... | 4 | null | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def climb_stairs(self, n: int) -> int: 递归。
- def climb_stairs_2(self, n: int) -> int: 动态规划。
- def climb_stairs_3(self, n: int) -> int: 动态规划(优化空间)。
- def climb_sta... | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def climb_stairs(self, n: int) -> int: 递归。
- def climb_stairs_2(self, n: int) -> int: 动态规划。
- def climb_stairs_3(self, n: int) -> int: 动态规划(优化空间)。
- def climb_sta... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def climb_stairs(self, n: int) -> int:
"""递归。"""
<|body_0|>
def climb_stairs_2(self, n: int) -> int:
"""动态规划。"""
<|body_1|>
def climb_stairs_3(self, n: int) -> int:
"""动态规划(优化空间)。"""
<|body_2|>
def climb_stairs_4(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def climb_stairs(self, n: int) -> int:
"""递归。"""
if n == 1:
return 1
if n == 2:
return 2
return self.climb_stairs(n - 1) + self.climb_stairs(n - 2)
def climb_stairs_2(self, n: int) -> int:
"""动态规划。"""
dp = {1: 1, 2:... | the_stack_v2_python_sparse | 0070_climbing-stairs.py | Nigirimeshi/leetcode | train | 0 | |
a69c132bd1b1fa468a8abb189844ac73080c36be | [
"if len(nums) <= 1:\n return False\nfor i in range(len(nums)):\n for j in range(len(nums)):\n if i is not j and nums[i] + nums[j] == target:\n return [i, j]",
"if len(nums) <= 1:\n return False\nbuf_dict = {}\nfor i in range(len(nums)):\n if nums[i] in buf_dict:\n return [buf_... | <|body_start_0|>
if len(nums) <= 1:
return False
for i in range(len(nums)):
for j in range(len(nums)):
if i is not j and nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
if len(nums) <= 1:
return F... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twosum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twosum_hash(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twosum_enumerate(self... | stack_v2_sparse_classes_36k_train_002306 | 1,310 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twosum",
"signature": "def twosum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twosum_hash",
"signature": "def twosum_hash(self, nums, targ... | 3 | stack_v2_sparse_classes_30k_val_000471 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twosum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twosum_hash(self, nums, target): :type nums: List[int] :type target: int :rtype: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twosum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twosum_hash(self, nums, target): :type nums: List[int] :type target: int :rtype: L... | 326d2656b2f852f64c43ab4932ebd0819ae6d5b9 | <|skeleton|>
class Solution:
def twosum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twosum_hash(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twosum_enumerate(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twosum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
if len(nums) <= 1:
return False
for i in range(len(nums)):
for j in range(len(nums)):
if i is not j and nums[i] + nums[j] == target:
... | the_stack_v2_python_sparse | LeetCode/LeetCode_1.py | No1CharlesWu/Python | train | 0 | |
8b58ce2f1b5a01d3200561af10721fad1b1b04cc | [
"super().__init__()\nself._pokemon = pokemon\nself._name = Text(pokemon.nickname)\nself._name.position = (-self._name.width, 0)\nself.add(self._name, z=1)\nself._level_txt = cocos.sprite.Sprite(pyglet.image.load(PATH + '/assets/img/battle/hud/level.png'))\nself._level_txt.position = (5, -2)\nself.add(self._level_tx... | <|body_start_0|>
super().__init__()
self._pokemon = pokemon
self._name = Text(pokemon.nickname)
self._name.position = (-self._name.width, 0)
self.add(self._name, z=1)
self._level_txt = cocos.sprite.Sprite(pyglet.image.load(PATH + '/assets/img/battle/hud/level.png'))
... | The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update. | OpponentHUDLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpponentHUDLayer:
"""The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update."""
def __init__(self, pokemon: PokemonModel) -> None:
"""Create a new HUD sh... | stack_v2_sparse_classes_36k_train_002307 | 4,187 | no_license | [
{
"docstring": "Create a new HUD showing the opponent pokemon's information. :param pokemon: The opponent pokemon.",
"name": "__init__",
"signature": "def __init__(self, pokemon: PokemonModel) -> None"
},
{
"docstring": "Update the size and the color of the HP bar.",
"name": "update_hp",
... | 3 | stack_v2_sparse_classes_30k_val_001050 | Implement the Python class `OpponentHUDLayer` described below.
Class description:
The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `OpponentHUDLayer` described below.
Class description:
The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update.
Method signatures and docstrings:
- def __init__(... | dfff995e3e50a8cfa56af73d93de82c427bfa2f5 | <|skeleton|>
class OpponentHUDLayer:
"""The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update."""
def __init__(self, pokemon: PokemonModel) -> None:
"""Create a new HUD sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpponentHUDLayer:
"""The information about the opponent pokemon: name, level, HP Attributes: - HP_BAR_SIZE: The size in pixels of the HP bar. - HP_UPDATE_DURATION: The time it takes for the HP bar to update."""
def __init__(self, pokemon: PokemonModel) -> None:
"""Create a new HUD showing the opp... | the_stack_v2_python_sparse | src/views/battle/opponent_hud_layer.py | J-GG/Pymon | train | 0 |
261b2d0c5526a08309c3912f76f49198d7d2d49a | [
"super(sppasPhoneSet, self).__init__(filename, nodump=True, case_sensitive=True)\nfor key in symbols.phone:\n if symbols.phone[key] != 'pause':\n self.add(key)",
"d = sppasDictPron(dict_filename)\nfor key in d:\n value = d.get_pron(key)\n variants = value.split(separators.variants)\n for varian... | <|body_start_0|>
super(sppasPhoneSet, self).__init__(filename, nodump=True, case_sensitive=True)
for key in symbols.phone:
if symbols.phone[key] != 'pause':
self.add(key)
<|end_body_0|>
<|body_start_1|>
d = sppasDictPron(dict_filename)
for key in d:
... | Manager of the list of phonemes. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This class allows to manage the list of phonemes: - get it from a pronunciation dictionary, - read... | sppasPhoneSet | [
"GFDL-1.1-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasPhoneSet:
"""Manager of the list of phonemes. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This class allows to manage the list of phonemes: - get i... | stack_v2_sparse_classes_36k_train_002308 | 4,263 | permissive | [
{
"docstring": "Create a sppasPhoneSet instance. Add events to the list: laugh, dummy, noise, silence. :param filename (str) A file with 1 column containing the list of phonemes.",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Add the list of phones from... | 3 | stack_v2_sparse_classes_30k_train_019537 | Implement the Python class `sppasPhoneSet` described below.
Class description:
Manager of the list of phonemes. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This class allows ... | Implement the Python class `sppasPhoneSet` described below.
Class description:
Manager of the list of phonemes. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This class allows ... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasPhoneSet:
"""Manager of the list of phonemes. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This class allows to manage the list of phonemes: - get i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sppasPhoneSet:
"""Manager of the list of phonemes. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This class allows to manage the list of phonemes: - get it from a pron... | the_stack_v2_python_sparse | sppas/sppas/src/models/acm/phoneset.py | mirfan899/MTTS | train | 0 |
358813d77d8554d81c78611dbf6f1ed3ff92e515 | [
"super(HStoreField, self).__init__(*args, **kwargs)\nself.uniqueness = uniqueness\nself.required = required",
"value = Field.get_prep_value(self, value)\nif isinstance(value, dict):\n prep_value = {}\n for key, val in value.items():\n if isinstance(val, Expression):\n prep_value[key] = val... | <|body_start_0|>
super(HStoreField, self).__init__(*args, **kwargs)
self.uniqueness = uniqueness
self.required = required
<|end_body_0|>
<|body_start_1|>
value = Field.get_prep_value(self, value)
if isinstance(value, dict):
prep_value = {}
for key, val in... | Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end. | HStoreField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HStoreField:
"""Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end."""
def __init__(self, *args, uniqueness: Optional[List[Union[str, Tuple[str, ...]]]]=None, required... | stack_v2_sparse_classes_36k_train_002309 | 2,324 | permissive | [
{
"docstring": "Initializes a new instance of :see:HStoreField. Arguments: uniqueness: List of keys to enforce as unique. Use tuples to enforce multiple keys together to be unique. required: List of keys that should be enforced as required.",
"name": "__init__",
"signature": "def __init__(self, *args, u... | 3 | stack_v2_sparse_classes_30k_train_010391 | Implement the Python class `HStoreField` described below.
Class description:
Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end.
Method signatures and docstrings:
- def __init__(self, *args, un... | Implement the Python class `HStoreField` described below.
Class description:
Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end.
Method signatures and docstrings:
- def __init__(self, *args, un... | e5503cb3f3c1b7959bd55253d3a79296f4c8f0ef | <|skeleton|>
class HStoreField:
"""Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end."""
def __init__(self, *args, uniqueness: Optional[List[Union[str, Tuple[str, ...]]]]=None, required... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HStoreField:
"""Improved version of Django's :see:HStoreField that adds support for database-level constraints. Notes: - For the implementation of uniqueness, see the custom database back-end."""
def __init__(self, *args, uniqueness: Optional[List[Union[str, Tuple[str, ...]]]]=None, required: Optional[Li... | the_stack_v2_python_sparse | psqlextra/fields/hstore_field.py | SectorLabs/django-postgres-extra | train | 645 |
0a763de92b0b0258170c07b8b039d823b632ce69 | [
"self.logger.debug('Start unzipping the file: %s.' % zip_file)\ndir_name = os.path.basename(zip_file).rsplit('.', 1)[0]\nif not unzip_path:\n if add_dir:\n unzip_path = zip_file.rsplit('.', 1)[0]\n else:\n unzip_path = os.path.dirname(zip_file)\nwith zipfile.ZipFile(zip_file, 'r') as f:\n for... | <|body_start_0|>
self.logger.debug('Start unzipping the file: %s.' % zip_file)
dir_name = os.path.basename(zip_file).rsplit('.', 1)[0]
if not unzip_path:
if add_dir:
unzip_path = zip_file.rsplit('.', 1)[0]
else:
unzip_path = os.path.dirname... | cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17 | MyZip | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyZip:
"""cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17"""
def unzip_file(self, zip_file, unzip_path='', add_dir=False):
"""unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(s... | stack_v2_sparse_classes_36k_train_002310 | 2,756 | no_license | [
{
"docstring": "unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(str) unzipped path add_dir type(bool) whether to add a layer of directory when unzip the file Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-23",
"name": "unz... | 2 | stack_v2_sparse_classes_30k_train_020138 | Implement the Python class `MyZip` described below.
Class description:
cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17
Method signatures and docstrings:
- def unzip_file(self, zip_file, unzip_path='', add_dir=False): unzip the file. Args: zip_file type(str) ... | Implement the Python class `MyZip` described below.
Class description:
cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17
Method signatures and docstrings:
- def unzip_file(self, zip_file, unzip_path='', add_dir=False): unzip the file. Args: zip_file type(str) ... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class MyZip:
"""cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17"""
def unzip_file(self, zip_file, unzip_path='', add_dir=False):
"""unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyZip:
"""cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17"""
def unzip_file(self, zip_file, unzip_path='', add_dir=False):
"""unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(str) unzipped ... | the_stack_v2_python_sparse | lib/tools/public/my_zip.py | Lewescaiyong/auto_test_framework | train | 1 |
1bb7f8fe4e6e5f4d43b5a94162e7bbeae0cd7442 | [
"detector_dict1 = dict(binning='1,1', det=1, dataext=0, specaxis=1, specflip=False, spatflip=False, xgap=0.0, ygap=0.0, ysize=1.0, platescale=0.063, darkcurr=0.0335, saturation=59200.0, nonlinear=0.95, mincounts=-10000000000.0, numamplifiers=1, gain=np.atleast_1d(1.84), ronoise=np.atleast_1d(8.55), datasec=None, os... | <|body_start_0|>
detector_dict1 = dict(binning='1,1', det=1, dataext=0, specaxis=1, specflip=False, spatflip=False, xgap=0.0, ygap=0.0, ysize=1.0, platescale=0.063, darkcurr=0.0335, saturation=59200.0, nonlinear=0.95, mincounts=-10000000000.0, numamplifiers=1, gain=np.atleast_1d(1.84), ronoise=np.atleast_1d(8.5... | Child to handle JWST/NIRCAM WFSS specific code | JWSTNIRCamSpectrograph | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWSTNIRCamSpectrograph:
"""Child to handle JWST/NIRCAM WFSS specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is ... | stack_v2_sparse_classes_36k_train_002311 | 5,954 | permissive | [
{
"docstring": "Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is effectively **required** for NIRCAM. The optional use of ``hdu`` is only viable for automatically generated documentation. Args: det (:... | 3 | null | Implement the Python class `JWSTNIRCamSpectrograph` described below.
Class description:
Child to handle JWST/NIRCAM WFSS specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are re... | Implement the Python class `JWSTNIRCamSpectrograph` described below.
Class description:
Child to handle JWST/NIRCAM WFSS specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are re... | 0d2e2196afc6904050b1af4d572f5c643bb07e38 | <|skeleton|>
class JWSTNIRCamSpectrograph:
"""Child to handle JWST/NIRCAM WFSS specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JWSTNIRCamSpectrograph:
"""Child to handle JWST/NIRCAM WFSS specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. .. warning:: Many of the necessary detector parameters are read from the file header, meaning the ``hdu`` argument is effectively *... | the_stack_v2_python_sparse | pypeit/spectrographs/jwst_nircam.py | pypeit/PypeIt | train | 136 |
5e8b9932734bec2eac26839189e7c997956ec95b | [
"if request.version == 'v6':\n return self._post_v6(request)\nelif request.version == 'v7':\n return self._post_v6(request)\nraise Http404()",
"configuration = rest_util.parse_dict(request, 'configuration')\nname = rest_util.parse_string(request, 'name', required=False)\ntitle = rest_util.parse_string(reque... | <|body_start_0|>
if request.version == 'v6':
return self._post_v6(request)
elif request.version == 'v7':
return self._post_v6(request)
raise Http404()
<|end_body_0|>
<|body_start_1|>
configuration = rest_util.parse_dict(request, 'configuration')
name = re... | This view is the endpoint for validating a new workspace before attempting to actually create it | WorkspacesValidationView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspacesValidationView:
"""This view is the endpoint for validating a new workspace before attempting to actually create it"""
def post(self, request):
"""Validates a new workspace and returns any warnings discovered :param request: the HTTP POST request :type request: :class:`rest... | stack_v2_sparse_classes_36k_train_002312 | 19,677 | permissive | [
{
"docstring": "Validates a new workspace and returns any warnings discovered :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user",
"name": "post",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_011674 | Implement the Python class `WorkspacesValidationView` described below.
Class description:
This view is the endpoint for validating a new workspace before attempting to actually create it
Method signatures and docstrings:
- def post(self, request): Validates a new workspace and returns any warnings discovered :param r... | Implement the Python class `WorkspacesValidationView` described below.
Class description:
This view is the endpoint for validating a new workspace before attempting to actually create it
Method signatures and docstrings:
- def post(self, request): Validates a new workspace and returns any warnings discovered :param r... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class WorkspacesValidationView:
"""This view is the endpoint for validating a new workspace before attempting to actually create it"""
def post(self, request):
"""Validates a new workspace and returns any warnings discovered :param request: the HTTP POST request :type request: :class:`rest... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkspacesValidationView:
"""This view is the endpoint for validating a new workspace before attempting to actually create it"""
def post(self, request):
"""Validates a new workspace and returns any warnings discovered :param request: the HTTP POST request :type request: :class:`rest_framework.re... | the_stack_v2_python_sparse | scale/storage/views.py | kfconsultant/scale | train | 0 |
033e2d54d4ed512d9a229a39f02206314dc5ee0c | [
"if len(args) == 0 or isinstance(args[0], str):\n pi = None\nelif isinstance(args[0], pg.PlotItem):\n pi = args[0]\n args = list(args)\n args = tuple(args[1:])\nelse:\n try:\n pi = args[0].plotItem\n args = list(args)\n args = tuple(args[1:])\n except:\n raise RuntimeEr... | <|body_start_0|>
if len(args) == 0 or isinstance(args[0], str):
pi = None
elif isinstance(args[0], pg.PlotItem):
pi = args[0]
args = list(args)
args = tuple(args[1:])
else:
try:
pi = args[0].plotItem
args... | DateAxis | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateAxis:
def __init__(self, *args, **kwargs):
"""Override the init so that, if you pass a plotWidget, or some larger plot container (plotWidget, plotItem, plotWindow, etc) it will put itself in the proper place. There's some hackey-ness to make this work, and you should _probably_ make ... | stack_v2_sparse_classes_36k_train_002313 | 5,715 | permissive | [
{
"docstring": "Override the init so that, if you pass a plotWidget, or some larger plot container (plotWidget, plotItem, plotWindow, etc) it will put itself in the proper place. There's some hackey-ness to make this work, and you should _probably_ make the DateAxis and pass it as an argument to the plotItem co... | 4 | stack_v2_sparse_classes_30k_train_019411 | Implement the Python class `DateAxis` described below.
Class description:
Implement the DateAxis class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override the init so that, if you pass a plotWidget, or some larger plot container (plotWidget, plotItem, plotWindow, etc) it will put itself... | Implement the Python class `DateAxis` described below.
Class description:
Implement the DateAxis class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override the init so that, if you pass a plotWidget, or some larger plot container (plotWidget, plotItem, plotWindow, etc) it will put itself... | 16efc3e9148542d814a4210c0d88c838ef5a9293 | <|skeleton|>
class DateAxis:
def __init__(self, *args, **kwargs):
"""Override the init so that, if you pass a plotWidget, or some larger plot container (plotWidget, plotItem, plotWindow, etc) it will put itself in the proper place. There's some hackey-ness to make this work, and you should _probably_ make ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateAxis:
def __init__(self, *args, **kwargs):
"""Override the init so that, if you pass a plotWidget, or some larger plot container (plotWidget, plotItem, plotWindow, etc) it will put itself in the proper place. There's some hackey-ness to make this work, and you should _probably_ make the DateAxis a... | the_stack_v2_python_sparse | hsganalysis/ipg/items/DateAxis.py | SherwinGroup/HSG-turbo | train | 1 | |
85f30c89e58ba7e8b1be0a5d5b405614dd7e6806 | [
"self.nb_sub_images = nb_sub_images\nself.window_size = window_size\nself.recovery = recovery\nself.image_horiz_size = image_horiz_size",
"if idx < self.nb_sub_images - 1:\n pixel_step = self.window_size - self.recovery\n return (idx * pixel_step, idx * pixel_step + self.window_size)\nelif idx == self.nb_su... | <|body_start_0|>
self.nb_sub_images = nb_sub_images
self.window_size = window_size
self.recovery = recovery
self.image_horiz_size = image_horiz_size
<|end_body_0|>
<|body_start_1|>
if idx < self.nb_sub_images - 1:
pixel_step = self.window_size - self.recovery
... | Class that returns the limits of the slice of a lane. | LaneIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaneIterator:
"""Class that returns the limits of the slice of a lane."""
def __init__(self, nb_sub_images, window_size, recovery, image_horiz_size):
"""Construct the lane iterator. Args: nb_sub_images (integer): the number of sub-images that has been sliced. window_size (integer): t... | stack_v2_sparse_classes_36k_train_002314 | 2,071 | no_license | [
{
"docstring": "Construct the lane iterator. Args: nb_sub_images (integer): the number of sub-images that has been sliced. window_size (integer): the width of the sub-image. recovery (integer): the number of pixels to be taken twice per sub-image. image_horiz_size (integer): the horizontal size of the original ... | 2 | stack_v2_sparse_classes_30k_train_015499 | Implement the Python class `LaneIterator` described below.
Class description:
Class that returns the limits of the slice of a lane.
Method signatures and docstrings:
- def __init__(self, nb_sub_images, window_size, recovery, image_horiz_size): Construct the lane iterator. Args: nb_sub_images (integer): the number of ... | Implement the Python class `LaneIterator` described below.
Class description:
Class that returns the limits of the slice of a lane.
Method signatures and docstrings:
- def __init__(self, nb_sub_images, window_size, recovery, image_horiz_size): Construct the lane iterator. Args: nb_sub_images (integer): the number of ... | 237ca81580db43525d8945017c0565b9722046ad | <|skeleton|>
class LaneIterator:
"""Class that returns the limits of the slice of a lane."""
def __init__(self, nb_sub_images, window_size, recovery, image_horiz_size):
"""Construct the lane iterator. Args: nb_sub_images (integer): the number of sub-images that has been sliced. window_size (integer): t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaneIterator:
"""Class that returns the limits of the slice of a lane."""
def __init__(self, nb_sub_images, window_size, recovery, image_horiz_size):
"""Construct the lane iterator. Args: nb_sub_images (integer): the number of sub-images that has been sliced. window_size (integer): the width of t... | the_stack_v2_python_sparse | src/d5_model_evaluation/slice_lane/image_magnifier/lane_iterator.py | remingtonCarmi/TrackingSwimmingENPC | train | 0 |
d8601038faf68afadaf5ebd0b8f5011a05697369 | [
"if not item:\n item = self.GetRootItem()\n if not item:\n return []\nchildren = []\nchild, cookie = self.GetFirstChild(item)\nwhile child:\n children.append(child)\n if recursively:\n children.extend(self.GetItemChildren(child, True))\n child, cookie = self.GetNextChild(item, cookie)\n... | <|body_start_0|>
if not item:
item = self.GetRootItem()
if not item:
return []
children = []
child, cookie = self.GetFirstChild(item)
while child:
children.append(child)
if recursively:
children.extend(self.G... | This class provides methods that are not part of the API of any tree control, but are convenient to have available. | TreeHelper | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeHelper:
"""This class provides methods that are not part of the API of any tree control, but are convenient to have available."""
def GetItemChildren(self, item=None, recursively=False):
"""Return the children of item as a list."""
<|body_0|>
def GetIndexOfItem(self,... | stack_v2_sparse_classes_36k_train_002315 | 28,710 | permissive | [
{
"docstring": "Return the children of item as a list.",
"name": "GetItemChildren",
"signature": "def GetItemChildren(self, item=None, recursively=False)"
},
{
"docstring": "Return the index of item.",
"name": "GetIndexOfItem",
"signature": "def GetIndexOfItem(self, item)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_007159 | Implement the Python class `TreeHelper` described below.
Class description:
This class provides methods that are not part of the API of any tree control, but are convenient to have available.
Method signatures and docstrings:
- def GetItemChildren(self, item=None, recursively=False): Return the children of item as a ... | Implement the Python class `TreeHelper` described below.
Class description:
This class provides methods that are not part of the API of any tree control, but are convenient to have available.
Method signatures and docstrings:
- def GetItemChildren(self, item=None, recursively=False): Return the children of item as a ... | c21d9abf56e1756fa8073ccc3547ec9a85d83e2a | <|skeleton|>
class TreeHelper:
"""This class provides methods that are not part of the API of any tree control, but are convenient to have available."""
def GetItemChildren(self, item=None, recursively=False):
"""Return the children of item as a list."""
<|body_0|>
def GetIndexOfItem(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeHelper:
"""This class provides methods that are not part of the API of any tree control, but are convenient to have available."""
def GetItemChildren(self, item=None, recursively=False):
"""Return the children of item as a list."""
if not item:
item = self.GetRootItem()
... | the_stack_v2_python_sparse | venv/Lib/site-packages/wx/lib/mixins/treemixin.py | saleguas/deskOrg | train | 3 |
dd732261fa0c9448c704da188bc432f758871c20 | [
"super(KalmanFilter, self).__init__()\nself.stateVariance = sv\nself.measurementVariance = mv\nself.dt = dt\nself.b = np.array([[0], [255]])\nself.A = np.matrix([[1, self.dt, 0, 0], [0, 1, 0, 0], [0, 0, 1, self.dt], [0, 0, 0, 1]])\nself.H = np.matrix([[1, 0, 0, 0], [0, 0, 1, 0]])\nself.errorCov = np.matrix(self.sta... | <|body_start_0|>
super(KalmanFilter, self).__init__()
self.stateVariance = sv
self.measurementVariance = mv
self.dt = dt
self.b = np.array([[0], [255]])
self.A = np.matrix([[1, self.dt, 0, 0], [0, 1, 0, 0], [0, 0, 1, self.dt], [0, 0, 0, 1]])
self.H = np.matrix([[1... | KalmanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilter:
def __init__(self, center, dt=8, sv=6, mv=1):
"""Initialise Kalman filer"""
<|body_0|>
def predict(self):
"""Predicts the next state of the cell using the previous state information"""
<|body_1|>
def correct(self, center, flag):
"""... | stack_v2_sparse_classes_36k_train_002316 | 30,438 | no_license | [
{
"docstring": "Initialise Kalman filer",
"name": "__init__",
"signature": "def __init__(self, center, dt=8, sv=6, mv=1)"
},
{
"docstring": "Predicts the next state of the cell using the previous state information",
"name": "predict",
"signature": "def predict(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_test_000644 | Implement the Python class `KalmanFilter` described below.
Class description:
Implement the KalmanFilter class.
Method signatures and docstrings:
- def __init__(self, center, dt=8, sv=6, mv=1): Initialise Kalman filer
- def predict(self): Predicts the next state of the cell using the previous state information
- def ... | Implement the Python class `KalmanFilter` described below.
Class description:
Implement the KalmanFilter class.
Method signatures and docstrings:
- def __init__(self, center, dt=8, sv=6, mv=1): Initialise Kalman filer
- def predict(self): Predicts the next state of the cell using the previous state information
- def ... | 29f28ae4a284879fbca4d5e179db8aa6850525e0 | <|skeleton|>
class KalmanFilter:
def __init__(self, center, dt=8, sv=6, mv=1):
"""Initialise Kalman filer"""
<|body_0|>
def predict(self):
"""Predicts the next state of the cell using the previous state information"""
<|body_1|>
def correct(self, center, flag):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KalmanFilter:
def __init__(self, center, dt=8, sv=6, mv=1):
"""Initialise Kalman filer"""
super(KalmanFilter, self).__init__()
self.stateVariance = sv
self.measurementVariance = mv
self.dt = dt
self.b = np.array([[0], [255]])
self.A = np.matrix([[1, self... | the_stack_v2_python_sparse | GroupFCellTracker.py | ElakkiyaRaj/COMP9517ComputerVision | train | 0 | |
377810d07b9d61c9129779459ac6f0ecbb23a903 | [
"file = open(postgap.Globals.DATABASES_DIR + '/Phewas_Catalog.txt')\nres = [self.get_association(line, diseases, iris) for line in file]\nres = filter(lambda X: X is not None, res)\nlogging.info('\\tFound %i GWAS SNPs associated to diseases (%s) or EFO IDs (%s) in Phewas Catalog' % (len(res), ', '.join(diseases), '... | <|body_start_0|>
file = open(postgap.Globals.DATABASES_DIR + '/Phewas_Catalog.txt')
res = [self.get_association(line, diseases, iris) for line in file]
res = filter(lambda X: X is not None, res)
logging.info('\tFound %i GWAS SNPs associated to diseases (%s) or EFO IDs (%s) in Phewas Cata... | Phewas_Catalog | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Phewas_Catalog:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in PhewasCatalog Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
<|body_0|>
def get_association(self, line, diseases... | stack_v2_sparse_classes_36k_train_002317 | 27,853 | permissive | [
{
"docstring": "Returns all GWAS SNPs associated to a disease in PhewasCatalog Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]",
"name": "run",
"signature": "def run(self, diseases, iris)"
},
{
"docstring": "Phewas Catalog format: 1. ch... | 2 | stack_v2_sparse_classes_30k_train_019020 | Implement the Python class `Phewas_Catalog` described below.
Class description:
Implement the Phewas_Catalog class.
Method signatures and docstrings:
- def run(self, diseases, iris): Returns all GWAS SNPs associated to a disease in PhewasCatalog Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRI... | Implement the Python class `Phewas_Catalog` described below.
Class description:
Implement the Phewas_Catalog class.
Method signatures and docstrings:
- def run(self, diseases, iris): Returns all GWAS SNPs associated to a disease in PhewasCatalog Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRI... | d5a2d7b9238347c9a598fa8ac0da8cb737c6b6a6 | <|skeleton|>
class Phewas_Catalog:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in PhewasCatalog Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
<|body_0|>
def get_association(self, line, diseases... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Phewas_Catalog:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in PhewasCatalog Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
file = open(postgap.Globals.DATABASES_DIR + '/Phewas_Catalog.txt')
... | the_stack_v2_python_sparse | lib/postgap/GWAS.py | Ensembl/postgap | train | 41 | |
01282dc2416eeb07f85cd44b71f723324635ca0e | [
"if not compatibility.is_string(exchange):\n raise AMQPInvalidArgument('exchange should be a string')\nelif not compatibility.is_string(exchange_type):\n raise AMQPInvalidArgument('exchange_type should be a string')\nelif not isinstance(passive, bool):\n raise AMQPInvalidArgument('passive should be a boole... | <|body_start_0|>
if not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif not compatibility.is_string(exchange_type):
raise AMQPInvalidArgument('exchange_type should be a string')
elif not isinstance(passive, bool):
... | RabbitMQ Exchange Operations. | Exchange | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exchange:
"""RabbitMQ Exchange Operations."""
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None):
"""Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passiv... | stack_v2_sparse_classes_36k_train_002318 | 6,025 | permissive | [
{
"docstring": "Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param dict arguments: Exchange key/value arguments :raises AMQPI... | 4 | null | Implement the Python class `Exchange` described below.
Class description:
RabbitMQ Exchange Operations.
Method signatures and docstrings:
- def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None): Declare an Exchange. :param str exchange: Exchange name :... | Implement the Python class `Exchange` described below.
Class description:
RabbitMQ Exchange Operations.
Method signatures and docstrings:
- def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None): Declare an Exchange. :param str exchange: Exchange name :... | ca2e086818433abc08c014dd06bfd22d4985ea2a | <|skeleton|>
class Exchange:
"""RabbitMQ Exchange Operations."""
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None):
"""Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passiv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exchange:
"""RabbitMQ Exchange Operations."""
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None):
"""Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not cre... | the_stack_v2_python_sparse | amqpstorm/exchange.py | fake-name/ReadableWebProxy | train | 207 |
484529e80d14f07b46f1ba18d0a8e7c713274d59 | [
"self.pump = Pump('127.0.0.1', 1000)\nself.sensor = Sensor('127.0.0.2', 2000)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=75)\nself.pump.get_state = MagicMock(return_value='PUMP_OFF')\nself.controller.tick =... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 1000)
self.sensor = Sensor('127.0.0.2', 2000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=75)
... | This class performs an integration test on waterregulation | ModuleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTests:
"""This class performs an integration test on waterregulation"""
def setUp(self):
"""This method does a setup for integration testing raterregulation"""
<|body_0|>
def test_tick(self):
"""This method performs an integration test for tick"""
<... | stack_v2_sparse_classes_36k_train_002319 | 1,066 | no_license | [
{
"docstring": "This method does a setup for integration testing raterregulation",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "This method performs an integration test for tick",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | null | Implement the Python class `ModuleTests` described below.
Class description:
This class performs an integration test on waterregulation
Method signatures and docstrings:
- def setUp(self): This method does a setup for integration testing raterregulation
- def test_tick(self): This method performs an integration test ... | Implement the Python class `ModuleTests` described below.
Class description:
This class performs an integration test on waterregulation
Method signatures and docstrings:
- def setUp(self): This method does a setup for integration testing raterregulation
- def test_tick(self): This method performs an integration test ... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ModuleTests:
"""This class performs an integration test on waterregulation"""
def setUp(self):
"""This method does a setup for integration testing raterregulation"""
<|body_0|>
def test_tick(self):
"""This method performs an integration test for tick"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleTests:
"""This class performs an integration test on waterregulation"""
def setUp(self):
"""This method does a setup for integration testing raterregulation"""
self.pump = Pump('127.0.0.1', 1000)
self.sensor = Sensor('127.0.0.2', 2000)
self.decider = Decider(100, 0.0... | the_stack_v2_python_sparse | students/John_Sekora/lesson06/water_reg/waterregulation/integrationtest.py | aurel1212/Sp2018-Online | train | 0 |
6a98d4f9931c2e55ff004ef94ba33a50033ad1bd | [
"token_id = context.get('token_id')\ntoken_ref = self.token_api.get_token(token_id)\nuser_id_from_token = token_ref['user']['id']\nif not self._is_admin(context):\n if user_id_from_token != user_id:\n raise exception.Forbidden('Token belongs to another user')\nself.user_profile_api.delete_last_user_profil... | <|body_start_0|>
token_id = context.get('token_id')
token_ref = self.token_api.get_token(token_id)
user_id_from_token = token_ref['user']['id']
if not self._is_admin(context):
if user_id_from_token != user_id:
raise exception.Forbidden('Token belongs to anothe... | UserProfileController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileController:
def delete_user_profile(self, context, user_id):
"""user-token pair control"""
<|body_0|>
def get_user_profile(self, context, user_id):
"""user-token pair control"""
<|body_1|>
def create_user_profile(self, context, user_id, profil... | stack_v2_sparse_classes_36k_train_002320 | 3,348 | no_license | [
{
"docstring": "user-token pair control",
"name": "delete_user_profile",
"signature": "def delete_user_profile(self, context, user_id)"
},
{
"docstring": "user-token pair control",
"name": "get_user_profile",
"signature": "def get_user_profile(self, context, user_id)"
},
{
"docst... | 4 | null | Implement the Python class `UserProfileController` described below.
Class description:
Implement the UserProfileController class.
Method signatures and docstrings:
- def delete_user_profile(self, context, user_id): user-token pair control
- def get_user_profile(self, context, user_id): user-token pair control
- def c... | Implement the Python class `UserProfileController` described below.
Class description:
Implement the UserProfileController class.
Method signatures and docstrings:
- def delete_user_profile(self, context, user_id): user-token pair control
- def get_user_profile(self, context, user_id): user-token pair control
- def c... | 3ad63ac25dddd8ba4bd9ab958f3c418e513b4ac9 | <|skeleton|>
class UserProfileController:
def delete_user_profile(self, context, user_id):
"""user-token pair control"""
<|body_0|>
def get_user_profile(self, context, user_id):
"""user-token pair control"""
<|body_1|>
def create_user_profile(self, context, user_id, profil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileController:
def delete_user_profile(self, context, user_id):
"""user-token pair control"""
token_id = context.get('token_id')
token_ref = self.token_api.get_token(token_id)
user_id_from_token = token_ref['user']['id']
if not self._is_admin(context):
... | the_stack_v2_python_sparse | openstack-plus/no-longer-used/Keystone-extension/user_profile/controllers.py | netgroup-polito/frog3 | train | 9 | |
b2c8849b114ffbfe4722b43a1884203fb935c767 | [
"self._mask_num_classes = num_classes if use_category_for_mask else 1\nself._num_downsample_channels = num_downsample_channels\nself._mask_crop_size = mask_crop_size\nself._shape_prior_path = shape_prior_path\nself._batch_norm_activation = batch_norm_activation\nself._use_category_for_mask = use_category_for_mask",... | <|body_start_0|>
self._mask_num_classes = num_classes if use_category_for_mask else 1
self._num_downsample_channels = num_downsample_channels
self._mask_crop_size = mask_crop_size
self._shape_prior_path = shape_prior_path
self._batch_norm_activation = batch_norm_activation
... | ShapeMask Prior head. | ShapemaskPriorHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapemaskPriorHead:
"""ShapeMask Prior head."""
def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, shape_prior_path, batch_norm_activation):
"""Initialize params to build RetinaNet head. Args: num_classes: Number of output classes. num_dow... | stack_v2_sparse_classes_36k_train_002321 | 46,218 | permissive | [
{
"docstring": "Initialize params to build RetinaNet head. Args: num_classes: Number of output classes. num_downsample_channels: number of channels in mask branch. mask_crop_size: feature crop size. use_category_for_mask: use class information in mask branch. shape_prior_path: the path to load shape priors. bat... | 4 | null | Implement the Python class `ShapemaskPriorHead` described below.
Class description:
ShapeMask Prior head.
Method signatures and docstrings:
- def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, shape_prior_path, batch_norm_activation): Initialize params to build RetinaNet h... | Implement the Python class `ShapemaskPriorHead` described below.
Class description:
ShapeMask Prior head.
Method signatures and docstrings:
- def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, shape_prior_path, batch_norm_activation): Initialize params to build RetinaNet h... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class ShapemaskPriorHead:
"""ShapeMask Prior head."""
def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, shape_prior_path, batch_norm_activation):
"""Initialize params to build RetinaNet head. Args: num_classes: Number of output classes. num_dow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShapemaskPriorHead:
"""ShapeMask Prior head."""
def __init__(self, num_classes, num_downsample_channels, mask_crop_size, use_category_for_mask, shape_prior_path, batch_norm_activation):
"""Initialize params to build RetinaNet head. Args: num_classes: Number of output classes. num_downsample_chann... | the_stack_v2_python_sparse | models/official/detection/modeling/architecture/heads.py | tensorflow/tpu | train | 5,627 |
ac7ebee788c57e6edcc597f528c4c3bfb97bc370 | [
"string = ''\nfor s in strs:\n for char in s:\n if char == ':':\n string += '::'\n elif char == ';':\n string += ';;'\n else:\n string += char\n string += ':;'\nreturn string",
"strings = []\ni, curString = (0, '')\nwhile i < len(s) - 1:\n if s[i:i + ... | <|body_start_0|>
string = ''
for s in strs:
for char in s:
if char == ':':
string += '::'
elif char == ';':
string += ';;'
else:
string += char
string += ':;'
retur... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_002322 | 1,151 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 0e10a40921d9fa5ca8c53859e4b17bcb62ee899a | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
string = ''
for s in strs:
for char in s:
if char == ':':
string += '::'
elif char == ';':
... | the_stack_v2_python_sparse | encodeAndDecodeStrings.py | peinanteng/leetcode | train | 0 | |
6dbda99f4d3ff13cdd81df908ed2f84ff5c35818 | [
"if not isinstance(grid_points, np.ndarray):\n raise TypeError('Input grid_points is not a numpy array.')\nif grid_points.dtype == 'O':\n raise TypeError('Input grid_points array cannot be of dtype object.')\nif not np.can_cast(grid_points.dtype, np.float128):\n raise TypeError('Input grid_points dtype inc... | <|body_start_0|>
if not isinstance(grid_points, np.ndarray):
raise TypeError('Input grid_points is not a numpy array.')
if grid_points.dtype == 'O':
raise TypeError('Input grid_points array cannot be of dtype object.')
if not np.can_cast(grid_points.dtype, np.float128):
... | Base class for all Estimators working on specific IRF components. While usable, it is encuraged to use the actual class for the respective IRF component as it ensures further checks and if nessecarry e.g. unit handling. | BaseComponentEstimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseComponentEstimator:
"""Base class for all Estimators working on specific IRF components. While usable, it is encuraged to use the actual class for the respective IRF component as it ensures further checks and if nessecarry e.g. unit handling."""
def __init__(self, grid_points):
"... | stack_v2_sparse_classes_36k_train_002323 | 27,909 | permissive | [
{
"docstring": "Base __init__, doing sanity checks on the grid, building a triangulated version of the grid and intantiating inter- and extrapolator. Parameters ---------- grid_points: np.ndarray, shape=(n_points, n_dims): Raises ------ TypeError: When grid_points is not a np.ndarray TypeError: When grid_point ... | 3 | stack_v2_sparse_classes_30k_train_014731 | Implement the Python class `BaseComponentEstimator` described below.
Class description:
Base class for all Estimators working on specific IRF components. While usable, it is encuraged to use the actual class for the respective IRF component as it ensures further checks and if nessecarry e.g. unit handling.
Method sig... | Implement the Python class `BaseComponentEstimator` described below.
Class description:
Base class for all Estimators working on specific IRF components. While usable, it is encuraged to use the actual class for the respective IRF component as it ensures further checks and if nessecarry e.g. unit handling.
Method sig... | 12a609566230d01a68a822aad38f080b60c473ce | <|skeleton|>
class BaseComponentEstimator:
"""Base class for all Estimators working on specific IRF components. While usable, it is encuraged to use the actual class for the respective IRF component as it ensures further checks and if nessecarry e.g. unit handling."""
def __init__(self, grid_points):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseComponentEstimator:
"""Base class for all Estimators working on specific IRF components. While usable, it is encuraged to use the actual class for the respective IRF component as it ensures further checks and if nessecarry e.g. unit handling."""
def __init__(self, grid_points):
"""Base __init... | the_stack_v2_python_sparse | pyirf/interpolation/component_estimators.py | cta-observatory/pyirf | train | 13 |
d13d6302921ddf5f70a5a5f6562f5bbd6456bde6 | [
"self.name = 'facial_description'\nself.dimensions = (128, 0)\nself.model = cv2.dnn.readNetFromTorch(embedding_model_filename)\nself.align = align",
"npLandmarks = landmarks.data\nnpLandmarkIndices = [39, 42, 57]\nH = cv2.getAffineTransform(npLandmarks[npLandmarkIndices], 96 * MINMAX_TEMPLATE[npLandmarkIndices])\... | <|body_start_0|>
self.name = 'facial_description'
self.dimensions = (128, 0)
self.model = cv2.dnn.readNetFromTorch(embedding_model_filename)
self.align = align
<|end_body_0|>
<|body_start_1|>
npLandmarks = landmarks.data
npLandmarkIndices = [39, 42, 57]
H = cv2.g... | Represents the facial description estimator based on openface embeddings | FacialFeaturesEstimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacialFeaturesEstimator:
"""Represents the facial description estimator based on openface embeddings"""
def __init__(self, shape_predictor_config_filename, embedding_model_filename, align=True):
"""FacialFeaturesEstimator constructor"""
<|body_0|>
def align_face(self, rg... | stack_v2_sparse_classes_36k_train_002324 | 5,055 | permissive | [
{
"docstring": "FacialFeaturesEstimator constructor",
"name": "__init__",
"signature": "def __init__(self, shape_predictor_config_filename, embedding_model_filename, align=True)"
},
{
"docstring": "Align a face given a 2d template original code from openface (to be sure to extract correctly)",
... | 3 | stack_v2_sparse_classes_30k_train_011903 | Implement the Python class `FacialFeaturesEstimator` described below.
Class description:
Represents the facial description estimator based on openface embeddings
Method signatures and docstrings:
- def __init__(self, shape_predictor_config_filename, embedding_model_filename, align=True): FacialFeaturesEstimator const... | Implement the Python class `FacialFeaturesEstimator` described below.
Class description:
Represents the facial description estimator based on openface embeddings
Method signatures and docstrings:
- def __init__(self, shape_predictor_config_filename, embedding_model_filename, align=True): FacialFeaturesEstimator const... | 42390f62ed5701a32710341b01faa10efc448078 | <|skeleton|>
class FacialFeaturesEstimator:
"""Represents the facial description estimator based on openface embeddings"""
def __init__(self, shape_predictor_config_filename, embedding_model_filename, align=True):
"""FacialFeaturesEstimator constructor"""
<|body_0|>
def align_face(self, rg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FacialFeaturesEstimator:
"""Represents the facial description estimator based on openface embeddings"""
def __init__(self, shape_predictor_config_filename, embedding_model_filename, align=True):
"""FacialFeaturesEstimator constructor"""
self.name = 'facial_description'
self.dimens... | the_stack_v2_python_sparse | src/pyuwds3/reasoning/estimation/facial_features_estimator.py | AndrewJSchoen/uwds3 | train | 0 |
9a94603d6777366e8788a215acf4fe12cf941310 | [
"adm = LerngruppenAdministration()\nn = Nachricht.from_dict(api.payload)\nif n is not None:\n n.set_id(id)\n adm.save_nachricht(n)\n return ('', 200)\nelse:\n return ('', 500)",
"adm = LerngruppenAdministration()\nnach = adm.get_nachricht_by_id(id)\nif nach is not None:\n return nach\nelse:\n re... | <|body_start_0|>
adm = LerngruppenAdministration()
n = Nachricht.from_dict(api.payload)
if n is not None:
n.set_id(id)
adm.save_nachricht(n)
return ('', 200)
else:
return ('', 500)
<|end_body_0|>
<|body_start_1|>
adm = LerngruppenA... | NachrichtOperation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NachrichtOperation:
def put(self, id):
"""Update der Nachricht"""
<|body_0|>
def get(self, id):
"""Auslesen eines bestimmten Nachricht Objekts. Das auszulesene Objekt wird über die Id bestimmt"""
<|body_1|>
def post(self):
"""Anlegen einer neuen ... | stack_v2_sparse_classes_36k_train_002325 | 17,448 | no_license | [
{
"docstring": "Update der Nachricht",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Auslesen eines bestimmten Nachricht Objekts. Das auszulesene Objekt wird über die Id bestimmt",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Anlegen ein... | 4 | stack_v2_sparse_classes_30k_train_017304 | Implement the Python class `NachrichtOperation` described below.
Class description:
Implement the NachrichtOperation class.
Method signatures and docstrings:
- def put(self, id): Update der Nachricht
- def get(self, id): Auslesen eines bestimmten Nachricht Objekts. Das auszulesene Objekt wird über die Id bestimmt
- d... | Implement the Python class `NachrichtOperation` described below.
Class description:
Implement the NachrichtOperation class.
Method signatures and docstrings:
- def put(self, id): Update der Nachricht
- def get(self, id): Auslesen eines bestimmten Nachricht Objekts. Das auszulesene Objekt wird über die Id bestimmt
- d... | bffd4117874f1e3f9150c6f60f6dd7dd715b9c9e | <|skeleton|>
class NachrichtOperation:
def put(self, id):
"""Update der Nachricht"""
<|body_0|>
def get(self, id):
"""Auslesen eines bestimmten Nachricht Objekts. Das auszulesene Objekt wird über die Id bestimmt"""
<|body_1|>
def post(self):
"""Anlegen einer neuen ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NachrichtOperation:
def put(self, id):
"""Update der Nachricht"""
adm = LerngruppenAdministration()
n = Nachricht.from_dict(api.payload)
if n is not None:
n.set_id(id)
adm.save_nachricht(n)
return ('', 200)
else:
return ('... | the_stack_v2_python_sparse | src/main.py | DanielWeinert-dw073/T | train | 0 | |
a4ebc6de369f5d84d680afb4003e0ae70d97b2ae | [
"nx.Graph.__init__(self)\nself._TG = TG\nself._left = list()\nself._right = list()\nself._add_nodes()\nself._add_edges()",
"matching = nx.max_weight_matching(self, maxcardinality=True)\nelist = []\nfor key in matching:\n if key.count('left') > 0:\n l = int(key.replace('left_', ''))\n r = int(matc... | <|body_start_0|>
nx.Graph.__init__(self)
self._TG = TG
self._left = list()
self._right = list()
self._add_nodes()
self._add_edges()
<|end_body_0|>
<|body_start_1|>
matching = nx.max_weight_matching(self, maxcardinality=True)
elist = []
for key in ... | Flow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flow:
def __init__(self, TG):
"""creates bi-partite graph from directed one"""
<|body_0|>
def pathify(self):
"""compute maximum weight matching"""
<|body_1|>
def _add_edges(self):
"""adds edges between nodes"""
<|body_2|>
def _add_no... | stack_v2_sparse_classes_36k_train_002326 | 1,982 | no_license | [
{
"docstring": "creates bi-partite graph from directed one",
"name": "__init__",
"signature": "def __init__(self, TG)"
},
{
"docstring": "compute maximum weight matching",
"name": "pathify",
"signature": "def pathify(self)"
},
{
"docstring": "adds edges between nodes",
"name"... | 4 | stack_v2_sparse_classes_30k_train_003304 | Implement the Python class `Flow` described below.
Class description:
Implement the Flow class.
Method signatures and docstrings:
- def __init__(self, TG): creates bi-partite graph from directed one
- def pathify(self): compute maximum weight matching
- def _add_edges(self): adds edges between nodes
- def _add_nodes(... | Implement the Python class `Flow` described below.
Class description:
Implement the Flow class.
Method signatures and docstrings:
- def __init__(self, TG): creates bi-partite graph from directed one
- def pathify(self): compute maximum weight matching
- def _add_edges(self): adds edges between nodes
- def _add_nodes(... | 5a1e07abb07ed0fb99241b21af5b0ba045299d22 | <|skeleton|>
class Flow:
def __init__(self, TG):
"""creates bi-partite graph from directed one"""
<|body_0|>
def pathify(self):
"""compute maximum weight matching"""
<|body_1|>
def _add_edges(self):
"""adds edges between nodes"""
<|body_2|>
def _add_no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Flow:
def __init__(self, TG):
"""creates bi-partite graph from directed one"""
nx.Graph.__init__(self)
self._TG = TG
self._left = list()
self._right = list()
self._add_nodes()
self._add_edges()
def pathify(self):
"""compute maximum weight ma... | the_stack_v2_python_sparse | SINAH/scripts/graphs/Flow.py | jim-bo/SINAH | train | 0 | |
71b63bbc40baf93c1a91c1afb6e3bb6d704da2ef | [
"log_level = Default.get(name=LogUtil.LOG_LEVEL_KEY, category=LogUtil.category) or LogUtil.DEFAULT_LOG_LEVEL\nconfig = ConfigDict('cloudmesh.yaml')\nconfig['cloudmesh']['logging']['level'] = log_level\nconfig.save()",
"level = log_level.upper()\nDefault.set(key=LogUtil.LOG_LEVEL_KEY, value=log_level, category=Log... | <|body_start_0|>
log_level = Default.get(name=LogUtil.LOG_LEVEL_KEY, category=LogUtil.category) or LogUtil.DEFAULT_LOG_LEVEL
config = ConfigDict('cloudmesh.yaml')
config['cloudmesh']['logging']['level'] = log_level
config.save()
<|end_body_0|>
<|body_start_1|>
level = log_level.... | LogUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogUtil:
def save():
"""save the loglevel for a cloud to the cloudmesh.yaml file"""
<|body_0|>
def set_level(log_level):
"""sets th eloglevel in the database and the loglevel file from cloudmesh.yaml :param log_level: the loglevel :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_002327 | 4,305 | permissive | [
{
"docstring": "save the loglevel for a cloud to the cloudmesh.yaml file",
"name": "save",
"signature": "def save()"
},
{
"docstring": "sets th eloglevel in the database and the loglevel file from cloudmesh.yaml :param log_level: the loglevel :return:",
"name": "set_level",
"signature": ... | 6 | null | Implement the Python class `LogUtil` described below.
Class description:
Implement the LogUtil class.
Method signatures and docstrings:
- def save(): save the loglevel for a cloud to the cloudmesh.yaml file
- def set_level(log_level): sets th eloglevel in the database and the loglevel file from cloudmesh.yaml :param ... | Implement the Python class `LogUtil` described below.
Class description:
Implement the LogUtil class.
Method signatures and docstrings:
- def save(): save the loglevel for a cloud to the cloudmesh.yaml file
- def set_level(log_level): sets th eloglevel in the database and the loglevel file from cloudmesh.yaml :param ... | a5fc7dbaf2c51f1227cff346aedea4bf7f563fa9 | <|skeleton|>
class LogUtil:
def save():
"""save the loglevel for a cloud to the cloudmesh.yaml file"""
<|body_0|>
def set_level(log_level):
"""sets th eloglevel in the database and the loglevel file from cloudmesh.yaml :param log_level: the loglevel :return:"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogUtil:
def save():
"""save the loglevel for a cloud to the cloudmesh.yaml file"""
log_level = Default.get(name=LogUtil.LOG_LEVEL_KEY, category=LogUtil.category) or LogUtil.DEFAULT_LOG_LEVEL
config = ConfigDict('cloudmesh.yaml')
config['cloudmesh']['logging']['level'] = log_le... | the_stack_v2_python_sparse | cloudmesh_client/common/LogUtil.py | cloudmesh/client | train | 3 | |
7d0d2f98b410c5cb773c6eef2dbe50c5e6c78faa | [
"self.provider = DataProvider(**kwargs)\nself.provider.do()\nif is_averaged:\n self.df_X = self.provider.df_normalized.T\nelse:\n dfs = [df.copy() for df in self.provider.dfs_adjusted_read_count_wrtT0_log2]\n self.df_X = pd.concat([df.T for df in dfs])\ndrop_indices = self._getDropIndices(self.df_X.index)\... | <|body_start_0|>
self.provider = DataProvider(**kwargs)
self.provider.do()
if is_averaged:
self.df_X = self.provider.df_normalized.T
else:
dfs = [df.copy() for df in self.provider.dfs_adjusted_read_count_wrtT0_log2]
self.df_X = pd.concat([df.T for df i... | Exposes values described above. | NormalizedData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizedData:
"""Exposes values described above."""
def __init__(self, is_averaged=True, is_regulator=False, **kwargs):
""":param bool is_averaged: Use averaged read counts :param bool is_regulator: use regulators for TRN :param dict kwargs: options passed to DataProvider Public in... | stack_v2_sparse_classes_36k_train_002328 | 10,146 | permissive | [
{
"docstring": ":param bool is_averaged: Use averaged read counts :param bool is_regulator: use regulators for TRN :param dict kwargs: options passed to DataProvider Public instance variables: df_X are normalized read counts instances are either times (begin with T) for stage (S) ser_y - numeric value of state ... | 2 | stack_v2_sparse_classes_30k_train_015450 | Implement the Python class `NormalizedData` described below.
Class description:
Exposes values described above.
Method signatures and docstrings:
- def __init__(self, is_averaged=True, is_regulator=False, **kwargs): :param bool is_averaged: Use averaged read counts :param bool is_regulator: use regulators for TRN :pa... | Implement the Python class `NormalizedData` described below.
Class description:
Exposes values described above.
Method signatures and docstrings:
- def __init__(self, is_averaged=True, is_regulator=False, **kwargs): :param bool is_averaged: Use averaged read counts :param bool is_regulator: use regulators for TRN :pa... | 882136c033e80ea27d04332a9e184a779a6b641f | <|skeleton|>
class NormalizedData:
"""Exposes values described above."""
def __init__(self, is_averaged=True, is_regulator=False, **kwargs):
""":param bool is_averaged: Use averaged read counts :param bool is_regulator: use regulators for TRN :param dict kwargs: options passed to DataProvider Public in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizedData:
"""Exposes values described above."""
def __init__(self, is_averaged=True, is_regulator=False, **kwargs):
""":param bool is_averaged: Use averaged read counts :param bool is_regulator: use regulators for TRN :param dict kwargs: options passed to DataProvider Public instance variab... | the_stack_v2_python_sparse | xstate/python/common/trinary_data.py | uwescience/xstate | train | 2 |
8aeb3e04e6adda4f3bba79ed50a83b3718ead9f6 | [
"self.threshold = threshold\nself.controller = controller\nself._previous_input = None\nself.previous_input = None\nself.input_valid = True",
"self.previous_input = self._previous_input\njoycon_input = self.normalize_joystick(controller)\nparsed_input = []\nif 0 not in joycon_input:\n if self._previous_input i... | <|body_start_0|>
self.threshold = threshold
self.controller = controller
self._previous_input = None
self.previous_input = None
self.input_valid = True
<|end_body_0|>
<|body_start_1|>
self.previous_input = self._previous_input
joycon_input = self.normalize_joysti... | ControllerManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerManager:
def __init__(self, controller, threshold):
"""Creates a controller manager which can map controller inputs to keyboard inputs."""
<|body_0|>
def parse_input(self, controller):
"""Takes a given input from a contoller, normalizes, and returns the par... | stack_v2_sparse_classes_36k_train_002329 | 5,048 | no_license | [
{
"docstring": "Creates a controller manager which can map controller inputs to keyboard inputs.",
"name": "__init__",
"signature": "def __init__(self, controller, threshold)"
},
{
"docstring": "Takes a given input from a contoller, normalizes, and returns the parsed data",
"name": "parse_in... | 6 | stack_v2_sparse_classes_30k_train_011896 | Implement the Python class `ControllerManager` described below.
Class description:
Implement the ControllerManager class.
Method signatures and docstrings:
- def __init__(self, controller, threshold): Creates a controller manager which can map controller inputs to keyboard inputs.
- def parse_input(self, controller):... | Implement the Python class `ControllerManager` described below.
Class description:
Implement the ControllerManager class.
Method signatures and docstrings:
- def __init__(self, controller, threshold): Creates a controller manager which can map controller inputs to keyboard inputs.
- def parse_input(self, controller):... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class ControllerManager:
def __init__(self, controller, threshold):
"""Creates a controller manager which can map controller inputs to keyboard inputs."""
<|body_0|>
def parse_input(self, controller):
"""Takes a given input from a contoller, normalizes, and returns the par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerManager:
def __init__(self, controller, threshold):
"""Creates a controller manager which can map controller inputs to keyboard inputs."""
self.threshold = threshold
self.controller = controller
self._previous_input = None
self.previous_input = None
se... | the_stack_v2_python_sparse | pokered/modules/utils/managers/controller_manager.py | surranc20/pokered | train | 44 | |
b131735057de5e145c12e48404eae38f0efaf173 | [
"if not root:\n return []\nstack = []\nres = []\nstack.append([root, ''])\nwhile stack:\n node, ls = stack.pop()\n if not node.left and (not node.right):\n res.append(ls + str(node.val))\n if node.left:\n stack.append([node.left, ls + str(node.val) + '->'])\n if node.right:\n sta... | <|body_start_0|>
if not root:
return []
stack = []
res = []
stack.append([root, ''])
while stack:
node, ls = stack.pop()
if not node.left and (not node.right):
res.append(ls + str(node.val))
if node.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binaryTreePaths1(self, root):
""":type root: TreeNode :rtype: List[str] DFS+stack"""
<|body_0|>
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str] 回溯法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:... | stack_v2_sparse_classes_36k_train_002330 | 1,944 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[str] DFS+stack",
"name": "binaryTreePaths1",
"signature": "def binaryTreePaths1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[str] 回溯法",
"name": "binaryTreePaths",
"signature": "def binaryTreePaths(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths1(self, root): :type root: TreeNode :rtype: List[str] DFS+stack
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str] 回溯法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryTreePaths1(self, root): :type root: TreeNode :rtype: List[str] DFS+stack
- def binaryTreePaths(self, root): :type root: TreeNode :rtype: List[str] 回溯法
<|skeleton|>
cla... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def binaryTreePaths1(self, root):
""":type root: TreeNode :rtype: List[str] DFS+stack"""
<|body_0|>
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str] 回溯法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def binaryTreePaths1(self, root):
""":type root: TreeNode :rtype: List[str] DFS+stack"""
if not root:
return []
stack = []
res = []
stack.append([root, ''])
while stack:
node, ls = stack.pop()
if not node.left and (n... | the_stack_v2_python_sparse | out/production/leetcode/257.二叉树的所有路径.py | yangyuxiang1996/leetcode | train | 0 | |
1c262611e9bd9378a0a9f2f823bcd460a18d348f | [
"super(Actor, self).__init__()\nself.linear1 = nn.Linear(state_dim, 256)\nself.linear2 = nn.Linear(256, 256)\nself.linear3 = nn.Linear(256, action_dim)",
"x = F.relu(self.linear1(state))\nx = F.relu(self.linear2(x))\nx = torch.tanh(self.linear3(x))\nreturn x"
] | <|body_start_0|>
super(Actor, self).__init__()
self.linear1 = nn.Linear(state_dim, 256)
self.linear2 = nn.Linear(256, 256)
self.linear3 = nn.Linear(256, action_dim)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.linear1(state))
x = F.relu(self.linear2(x))
x = to... | Actor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
def __init__(self, state_dim, action_dim):
"""Initialize the network param: state_dim : Size of the state space param: action_dim: Size of the action space"""
<|body_0|>
def forward(self, state):
"""Define the forward pass param: state: The state of the enviro... | stack_v2_sparse_classes_36k_train_002331 | 11,016 | no_license | [
{
"docstring": "Initialize the network param: state_dim : Size of the state space param: action_dim: Size of the action space",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim)"
},
{
"docstring": "Define the forward pass param: state: The state of the environment",
... | 2 | stack_v2_sparse_classes_30k_train_007190 | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): Initialize the network param: state_dim : Size of the state space param: action_dim: Size of the action space
- def forward(self, state): Def... | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): Initialize the network param: state_dim : Size of the state space param: action_dim: Size of the action space
- def forward(self, state): Def... | 59dfeff2b84a9f018239fa0eddbf72cdb5056632 | <|skeleton|>
class Actor:
def __init__(self, state_dim, action_dim):
"""Initialize the network param: state_dim : Size of the state space param: action_dim: Size of the action space"""
<|body_0|>
def forward(self, state):
"""Define the forward pass param: state: The state of the enviro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actor:
def __init__(self, state_dim, action_dim):
"""Initialize the network param: state_dim : Size of the state space param: action_dim: Size of the action space"""
super(Actor, self).__init__()
self.linear1 = nn.Linear(state_dim, 256)
self.linear2 = nn.Linear(256, 256)
... | the_stack_v2_python_sparse | nn/ddpg/td3_controller.py | ShaneTsui/RacingCar | train | 1 | |
b43cb61973a4e9d90321c6d69200533dabaacdcb | [
"if not root:\n return ''\npreOrderList = []\n\ndef preOrder(node):\n if not node:\n preOrderList.append('#')\n return\n preOrderList.append(node.val)\n preOrder(node.left)\n preOrder(node.right)\npreOrder(root)\nreturn ' '.join(map(str, preOrderList))",
"if not data:\n return None... | <|body_start_0|>
if not root:
return ''
preOrderList = []
def preOrder(node):
if not node:
preOrderList.append('#')
return
preOrderList.append(node.val)
preOrder(node.left)
preOrder(node.right)
p... | 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_002332 | 2,238 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_013631 | 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:... | 63ac5a0921835b1e9d65f71e1346bbb7d66dad9b | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
preOrderList = []
def preOrder(node):
if not node:
preOrderList.append('#')
return
... | the_stack_v2_python_sparse | LeetCode/困难/树/297. 二叉树的序列化与反序列化.py | homezzm/leetcode | train | 1 | |
e7f2400e7d765a9b168719127be8f4659eba42ff | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Provides text analysis operations such as sentiment analysis and entity recognition. | LanguageServiceServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageServiceServicer:
"""Provides text analysis operations such as sentiment analysis and entity recognition."""
def AnalyzeSentiment(self, request, context):
"""Analyzes the sentiment of the provided text."""
<|body_0|>
def AnalyzeEntities(self, request, context):
... | stack_v2_sparse_classes_36k_train_002333 | 6,518 | no_license | [
{
"docstring": "Analyzes the sentiment of the provided text.",
"name": "AnalyzeSentiment",
"signature": "def AnalyzeSentiment(self, request, context)"
},
{
"docstring": "Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for eac... | 5 | stack_v2_sparse_classes_30k_train_005331 | Implement the Python class `LanguageServiceServicer` described below.
Class description:
Provides text analysis operations such as sentiment analysis and entity recognition.
Method signatures and docstrings:
- def AnalyzeSentiment(self, request, context): Analyzes the sentiment of the provided text.
- def AnalyzeEnti... | Implement the Python class `LanguageServiceServicer` described below.
Class description:
Provides text analysis operations such as sentiment analysis and entity recognition.
Method signatures and docstrings:
- def AnalyzeSentiment(self, request, context): Analyzes the sentiment of the provided text.
- def AnalyzeEnti... | d7424d21aa0dc121acc4d64b427ba365a3581a20 | <|skeleton|>
class LanguageServiceServicer:
"""Provides text analysis operations such as sentiment analysis and entity recognition."""
def AnalyzeSentiment(self, request, context):
"""Analyzes the sentiment of the provided text."""
<|body_0|>
def AnalyzeEntities(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageServiceServicer:
"""Provides text analysis operations such as sentiment analysis and entity recognition."""
def AnalyzeSentiment(self, request, context):
"""Analyzes the sentiment of the provided text."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details(... | the_stack_v2_python_sparse | google/cloud/language/v1/language_service_pb2_grpc.py | msachtler/bazel-event-protocol-parser | train | 1 |
422c720339597975b2e5f3877e749c5d60811a5a | [
"if self._context is None:\n context = {}\nif self._context.get('period_id', False):\n return self._context.get('period_id')\nperiods = self.env['account.period'].search([])\nreturn periods and periods[0] or False",
"account_invoice = self.env['account.invoice']\naccount_invoice_line = self.env['account.inv... | <|body_start_0|>
if self._context is None:
context = {}
if self._context.get('period_id', False):
return self._context.get('period_id')
periods = self.env['account.period'].search([])
return periods and periods[0] or False
<|end_body_0|>
<|body_start_1|>
... | ReconcileInvoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReconcileInvoice:
def _get_period(self):
"""this method use for get account period. --------------------------------------- :return: record set of period"""
<|body_0|>
def reconcile_invoice_with_advance_payment(self):
"""first month invoice reconcile with advance pay... | stack_v2_sparse_classes_36k_train_002334 | 1,631 | no_license | [
{
"docstring": "this method use for get account period. --------------------------------------- :return: record set of period",
"name": "_get_period",
"signature": "def _get_period(self)"
},
{
"docstring": "first month invoice reconcile with advance payment, :return:",
"name": "reconcile_inv... | 2 | stack_v2_sparse_classes_30k_train_008387 | Implement the Python class `ReconcileInvoice` described below.
Class description:
Implement the ReconcileInvoice class.
Method signatures and docstrings:
- def _get_period(self): this method use for get account period. --------------------------------------- :return: record set of period
- def reconcile_invoice_with_... | Implement the Python class `ReconcileInvoice` described below.
Class description:
Implement the ReconcileInvoice class.
Method signatures and docstrings:
- def _get_period(self): this method use for get account period. --------------------------------------- :return: record set of period
- def reconcile_invoice_with_... | 0e65e5d937b029beb69563772197b9b050748407 | <|skeleton|>
class ReconcileInvoice:
def _get_period(self):
"""this method use for get account period. --------------------------------------- :return: record set of period"""
<|body_0|>
def reconcile_invoice_with_advance_payment(self):
"""first month invoice reconcile with advance pay... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReconcileInvoice:
def _get_period(self):
"""this method use for get account period. --------------------------------------- :return: record set of period"""
if self._context is None:
context = {}
if self._context.get('period_id', False):
return self._context.get... | the_stack_v2_python_sparse | edsys_edu_fee/wizard/reconcile_invoice_with_advance_payment.py | probytesodoo/edsys_school_erp | train | 1 | |
7845a3d22d173f515479e3b4513b816c29be1400 | [
"if not arr:\n return True\nif arr.count(0) > 1:\n return True\nfor item in arr:\n if item == 0:\n continue\n if 2 * item in arr:\n return True\nreturn False",
"for i, a in enumerate(arr):\n for j, b in enumerate(arr):\n if i != j and a == b:\n return True\nreturn Fa... | <|body_start_0|>
if not arr:
return True
if arr.count(0) > 1:
return True
for item in arr:
if item == 0:
continue
if 2 * item in arr:
return True
return False
<|end_body_0|>
<|body_start_1|>
for i, a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkIfExist(self, arr):
""":type arr: List[int] :rtype: bool"""
<|body_0|>
def checkIfExist2(self, arr):
""":type arr: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not arr:
return True
... | stack_v2_sparse_classes_36k_train_002335 | 1,116 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: bool",
"name": "checkIfExist",
"signature": "def checkIfExist(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: bool",
"name": "checkIfExist2",
"signature": "def checkIfExist2(self, arr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020399 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkIfExist(self, arr): :type arr: List[int] :rtype: bool
- def checkIfExist2(self, arr): :type arr: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkIfExist(self, arr): :type arr: List[int] :rtype: bool
- def checkIfExist2(self, arr): :type arr: List[int] :rtype: bool
<|skeleton|>
class Solution:
def checkIfExi... | 690b685048c8e89d26047b6bc48b5f9af7d59cbb | <|skeleton|>
class Solution:
def checkIfExist(self, arr):
""":type arr: List[int] :rtype: bool"""
<|body_0|>
def checkIfExist2(self, arr):
""":type arr: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkIfExist(self, arr):
""":type arr: List[int] :rtype: bool"""
if not arr:
return True
if arr.count(0) > 1:
return True
for item in arr:
if item == 0:
continue
if 2 * item in arr:
re... | the_stack_v2_python_sparse | 数组/1346. 检查整数及其两倍数是否存在.py | SimmonsChen/LeetCode | train | 0 | |
2ae0e3ed21a64fbd0800600ab74e85a7735b2cbb | [
"self.cassandra_additional_params = cassandra_additional_params\nself.cassandra_connect_params = cassandra_connect_params\nself.couchbase_connect_params = couchbase_connect_params\nself.hbase_connect_params = hbase_connect_params\nself.hdfs_connect_params = hdfs_connect_params\nself.hive_connect_params = hive_conne... | <|body_start_0|>
self.cassandra_additional_params = cassandra_additional_params
self.cassandra_connect_params = cassandra_connect_params
self.couchbase_connect_params = couchbase_connect_params
self.hbase_connect_params = hbase_connect_params
self.hdfs_connect_params = hdfs_conne... | Implementation of the 'NoSqlConnectParams' model. TODO: type description here. Attributes: cassandra_additional_params (CassandraAdditionalParams): Additional params required for cassandra backup. cassandra_connect_params (CassandraConnectParams): Connect params for connecting to cassandra cluster. Set only if env_type... | NoSqlConnectParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoSqlConnectParams:
"""Implementation of the 'NoSqlConnectParams' model. TODO: type description here. Attributes: cassandra_additional_params (CassandraAdditionalParams): Additional params required for cassandra backup. cassandra_connect_params (CassandraConnectParams): Connect params for connect... | stack_v2_sparse_classes_36k_train_002336 | 6,130 | permissive | [
{
"docstring": "Constructor for the NoSqlConnectParams class",
"name": "__init__",
"signature": "def __init__(self, cassandra_additional_params=None, cassandra_connect_params=None, couchbase_connect_params=None, hbase_connect_params=None, hdfs_connect_params=None, hive_connect_params=None, mongodb_addit... | 2 | stack_v2_sparse_classes_30k_train_008502 | Implement the Python class `NoSqlConnectParams` described below.
Class description:
Implementation of the 'NoSqlConnectParams' model. TODO: type description here. Attributes: cassandra_additional_params (CassandraAdditionalParams): Additional params required for cassandra backup. cassandra_connect_params (CassandraCon... | Implement the Python class `NoSqlConnectParams` described below.
Class description:
Implementation of the 'NoSqlConnectParams' model. TODO: type description here. Attributes: cassandra_additional_params (CassandraAdditionalParams): Additional params required for cassandra backup. cassandra_connect_params (CassandraCon... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NoSqlConnectParams:
"""Implementation of the 'NoSqlConnectParams' model. TODO: type description here. Attributes: cassandra_additional_params (CassandraAdditionalParams): Additional params required for cassandra backup. cassandra_connect_params (CassandraConnectParams): Connect params for connect... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoSqlConnectParams:
"""Implementation of the 'NoSqlConnectParams' model. TODO: type description here. Attributes: cassandra_additional_params (CassandraAdditionalParams): Additional params required for cassandra backup. cassandra_connect_params (CassandraConnectParams): Connect params for connecting to cassan... | the_stack_v2_python_sparse | cohesity_management_sdk/models/no_sql_connect_params.py | cohesity/management-sdk-python | train | 24 |
3943cec6dd1d66b6a7543aa721fafe0fa03006b2 | [
"super().__init__(order=CallbackOrder.Optimizer + 1, node=CallbackNode.All)\nself.grad_norm_prefix = '_grad_norm'\nself.norm_type = norm_type\nself.accumulation_steps: int = accumulation_steps\nself._accumulation_counter: int = 0",
"if isinstance(model, (DataParallel, DistributedDataParallel)):\n model = model... | <|body_start_0|>
super().__init__(order=CallbackOrder.Optimizer + 1, node=CallbackNode.All)
self.grad_norm_prefix = '_grad_norm'
self.norm_type = norm_type
self.accumulation_steps: int = accumulation_steps
self._accumulation_counter: int = 0
<|end_body_0|>
<|body_start_1|>
... | Callback for logging model gradients. | GradNormLogger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradNormLogger:
"""Callback for logging model gradients."""
def __init__(self, norm_type: int=2, accumulation_steps: int=1):
"""Args: norm_type (int): norm type used to calculate norm of gradients. If `OptimizerCallback` provides non-default argument `grad_clip_params` with custom no... | stack_v2_sparse_classes_36k_train_002337 | 2,990 | permissive | [
{
"docstring": "Args: norm_type (int): norm type used to calculate norm of gradients. If `OptimizerCallback` provides non-default argument `grad_clip_params` with custom norm type, then corresponding norm type should be used in this class. accumulation_steps (int): number of steps before ``model.zero_grad()``. ... | 3 | null | Implement the Python class `GradNormLogger` described below.
Class description:
Callback for logging model gradients.
Method signatures and docstrings:
- def __init__(self, norm_type: int=2, accumulation_steps: int=1): Args: norm_type (int): norm type used to calculate norm of gradients. If `OptimizerCallback` provid... | Implement the Python class `GradNormLogger` described below.
Class description:
Callback for logging model gradients.
Method signatures and docstrings:
- def __init__(self, norm_type: int=2, accumulation_steps: int=1): Args: norm_type (int): norm type used to calculate norm of gradients. If `OptimizerCallback` provid... | a35297ecab8d1a6c2f00b6435ea1d6d37ec9f441 | <|skeleton|>
class GradNormLogger:
"""Callback for logging model gradients."""
def __init__(self, norm_type: int=2, accumulation_steps: int=1):
"""Args: norm_type (int): norm type used to calculate norm of gradients. If `OptimizerCallback` provides non-default argument `grad_clip_params` with custom no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradNormLogger:
"""Callback for logging model gradients."""
def __init__(self, norm_type: int=2, accumulation_steps: int=1):
"""Args: norm_type (int): norm type used to calculate norm of gradients. If `OptimizerCallback` provides non-default argument `grad_clip_params` with custom norm type, then... | the_stack_v2_python_sparse | catalyst/contrib/dl/callbacks/gradnorm_logger.py | saswat0/catalyst | train | 2 |
0517be427266528525028c8f4150b3867fc8de25 | [
"n = len(s)\nmax_ = 0\nret = ''\ndp = [[0] * n for _ in range(n + 1)]\nfor l in range(1, n + 1):\n for i in range(n - l + 1):\n if l == 1:\n dp[l][i] = 1\n elif l == 2 and s[i] == s[i + 1]:\n dp[l][i] = 2\n elif s[i] == s[i + l - 1] and dp[l - 2][i + 1]:\n dp... | <|body_start_0|>
n = len(s)
max_ = 0
ret = ''
dp = [[0] * n for _ in range(n + 1)]
for l in range(1, n + 1):
for i in range(n - l + 1):
if l == 1:
dp[l][i] = 1
elif l == 2 and s[i] == s[i + 1]:
dp... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(s)
max_ = 0
ret = ''
dp =... | stack_v2_sparse_classes_36k_train_002338 | 2,065 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome(self,... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
n = len(s)
max_ = 0
ret = ''
dp = [[0] * n for _ in range(n + 1)]
for l in range(1, n + 1):
for i in range(n - l + 1):
if l == 1:
dp[l][i] = ... | the_stack_v2_python_sparse | problems/longestPalindrome.py | joddiy/leetcode | train | 1 | |
4c9ee25f0b8d73001f622259d06d2f8bb7ad3f00 | [
"super().__init__(columns=columns)\nself.rescaling_columns = rescaling_columns\nself.keep_rescaling_col = keep_rescaling_col\nassert len(columns) == len(rescaling_columns)",
"df_res = df.drop(list(self.columns), axis='columns', errors='ignore').copy()\nif not self.keep_rescaling_col:\n df_res = df_res.drop(lis... | <|body_start_0|>
super().__init__(columns=columns)
self.rescaling_columns = rescaling_columns
self.keep_rescaling_col = keep_rescaling_col
assert len(columns) == len(rescaling_columns)
<|end_body_0|>
<|body_start_1|>
df_res = df.drop(list(self.columns), axis='columns', errors='i... | Rescales a column by another specified column. | RescaleTransform | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RescaleTransform:
"""Rescales a column by another specified column."""
def __init__(self, columns: Sequence[str], rescaling_columns: Sequence[str], keep_rescaling_col: bool=False) -> None:
"""Args: columns, a sequence of columns to rescale (numerators) rescaling_columns, a sequence o... | stack_v2_sparse_classes_36k_train_002339 | 31,072 | permissive | [
{
"docstring": "Args: columns, a sequence of columns to rescale (numerators) rescaling_columns, a sequence of columns to rescale by (denominators) keep_rescaling_column (bool), whether or not to retain the rescaling column in the dataframe",
"name": "__init__",
"signature": "def __init__(self, columns: ... | 3 | null | Implement the Python class `RescaleTransform` described below.
Class description:
Rescales a column by another specified column.
Method signatures and docstrings:
- def __init__(self, columns: Sequence[str], rescaling_columns: Sequence[str], keep_rescaling_col: bool=False) -> None: Args: columns, a sequence of column... | Implement the Python class `RescaleTransform` described below.
Class description:
Rescales a column by another specified column.
Method signatures and docstrings:
- def __init__(self, columns: Sequence[str], rescaling_columns: Sequence[str], keep_rescaling_col: bool=False) -> None: Args: columns, a sequence of column... | 40bab526af6562653c42dbb32b174524c44ce2ba | <|skeleton|>
class RescaleTransform:
"""Rescales a column by another specified column."""
def __init__(self, columns: Sequence[str], rescaling_columns: Sequence[str], keep_rescaling_col: bool=False) -> None:
"""Args: columns, a sequence of columns to rescale (numerators) rescaling_columns, a sequence o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RescaleTransform:
"""Rescales a column by another specified column."""
def __init__(self, columns: Sequence[str], rescaling_columns: Sequence[str], keep_rescaling_col: bool=False) -> None:
"""Args: columns, a sequence of columns to rescale (numerators) rescaling_columns, a sequence of columns to ... | the_stack_v2_python_sparse | PyStationB/libraries/ABEX/abex/transforms.py | mebristo/station-b-libraries | train | 0 |
76d2c3f74e8fae160396b4015ccec478dba97b87 | [
"self.id_ds_conf_ds = id_ds_conf_ds\nself.value_configuration = value_configuration\nself.FK_id_configuration_DCT_DCD = FK_id_configuration_DCT_DCD\nself.FK_id_dataset_DS_DCD = FK_id_dataset_DS_DCD",
"listOfDatasetDSConfig = []\nsqlObj = _DS_config_DS_SQL()\nresults = sqlObj.select_all_DDI_DB()\nfor element in re... | <|body_start_0|>
self.id_ds_conf_ds = id_ds_conf_ds
self.value_configuration = value_configuration
self.FK_id_configuration_DCT_DCD = FK_id_configuration_DCT_DCD
self.FK_id_dataset_DS_DCD = FK_id_dataset_DS_DCD
<|end_body_0|>
<|body_start_1|>
listOfDatasetDSConfig = []
s... | This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parameters declaration | Dataset_conf_ds | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset_conf_ds:
"""This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parame... | stack_v2_sparse_classes_36k_train_002340 | 2,721 | permissive | [
{
"docstring": "Constructor of the DDI_interactionDB object. All the parameters have a default value :param id_ds_conf_ds: id of the configurations dataset - -1 if unknown :param value_configuration: value of the bins - -1 if unknown :param FK_id_configuration_DCT_DCD: FK of the configurations (see table DATASE... | 3 | stack_v2_sparse_classes_30k_train_014621 | Implement the Python class `Dataset_conf_ds` described below.
Class description:
This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK a... | Implement the Python class `Dataset_conf_ds` described below.
Class description:
This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK a... | 862eb85746e8a3a9bbc0d6aef9abbd5eebe9765f | <|skeleton|>
class Dataset_conf_ds:
"""This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parame... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset_conf_ds:
"""This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parameters declarat... | the_stack_v2_python_sparse | objects_new/Dataset_config_dataset_new.py | diogo1790/inphinity | train | 1 |
ef729e1aa0d5800eb6f969c7e09b7d362efc38b1 | [
"if not len(height):\n return 0\ntotal_volume = last_volume = 0\nstack = []\ni = 0\nwhile i < len(height):\n if not len(stack) or height[i] <= height[stack[-1]]:\n stack.append(i)\n i += 1\n else:\n last_ind = stack.pop()\n last_volume = 0 if not len(stack) else (min(height[stac... | <|body_start_0|>
if not len(height):
return 0
total_volume = last_volume = 0
stack = []
i = 0
while i < len(height):
if not len(stack) or height[i] <= height[stack[-1]]:
stack.append(i)
i += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap2(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not len(height):
return 0
t... | stack_v2_sparse_classes_36k_train_002341 | 1,842 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap2",
"signature": "def trap2(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trap2(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trap2(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def trap(self, heigh... | 18ed31a3edf20a3e5a0b7a0b56acca5b98939693 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap2(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
if not len(height):
return 0
total_volume = last_volume = 0
stack = []
i = 0
while i < len(height):
if not len(stack) or height[i] <= height[stack[-1]]:
... | the_stack_v2_python_sparse | exercises/array/water_volume.py | nahgnaw/data-structure | train | 0 | |
eab8d70075f45def13faec0ba3fbb2c7ebb199dd | [
"mod_obj = self.pool.get('ir.model.data')\npicking_type = context.get('picking_type')\nlocation_id = False\nif context is None:\n context = {}\nif 'default_maintenance' in context and context['default_maintenance'] == True:\n return False\nelse:\n return super(stock_move, self)._default_location_destinatio... | <|body_start_0|>
mod_obj = self.pool.get('ir.model.data')
picking_type = context.get('picking_type')
location_id = False
if context is None:
context = {}
if 'default_maintenance' in context and context['default_maintenance'] == True:
return False
e... | stock_move | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_move:
def _default_location_destination(self, cr, uid, context=None):
"""Gets default address of partner for destination location @return: Address id or False"""
<|body_0|>
def _default_location_source(self, cr, uid, context=None):
"""Gets default address of pa... | stack_v2_sparse_classes_36k_train_002342 | 36,987 | no_license | [
{
"docstring": "Gets default address of partner for destination location @return: Address id or False",
"name": "_default_location_destination",
"signature": "def _default_location_destination(self, cr, uid, context=None)"
},
{
"docstring": "Gets default address of partner for source location @r... | 2 | stack_v2_sparse_classes_30k_train_019494 | Implement the Python class `stock_move` described below.
Class description:
Implement the stock_move class.
Method signatures and docstrings:
- def _default_location_destination(self, cr, uid, context=None): Gets default address of partner for destination location @return: Address id or False
- def _default_location_... | Implement the Python class `stock_move` described below.
Class description:
Implement the stock_move class.
Method signatures and docstrings:
- def _default_location_destination(self, cr, uid, context=None): Gets default address of partner for destination location @return: Address id or False
- def _default_location_... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_move:
def _default_location_destination(self, cr, uid, context=None):
"""Gets default address of partner for destination location @return: Address id or False"""
<|body_0|>
def _default_location_source(self, cr, uid, context=None):
"""Gets default address of pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_move:
def _default_location_destination(self, cr, uid, context=None):
"""Gets default address of partner for destination location @return: Address id or False"""
mod_obj = self.pool.get('ir.model.data')
picking_type = context.get('picking_type')
location_id = False
... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/vehicles_maintenance/models/stock_exchange.py | musabahmed/baba | train | 0 | |
9947882ffaf7e3326fcf4ac594c54183b42b1dc3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsInformationProtectionDesktopApp()",
"from .windows_information_protection_app import WindowsInformationProtectionApp\nfrom .windows_information_protection_app import WindowsInformationProtectionApp\nfields: Dict[str, Callable[[A... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WindowsInformationProtectionDesktopApp()
<|end_body_0|>
<|body_start_1|>
from .windows_information_protection_app import WindowsInformationProtectionApp
from .windows_information_protect... | Desktop App for Windows information protection | WindowsInformationProtectionDesktopApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsInformationProtectionDesktopApp:
"""Desktop App for Windows information protection"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionDesktopApp:
"""Creates a new instance of the appropriate class based on discriminator ... | stack_v2_sparse_classes_36k_train_002343 | 2,912 | 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: WindowsInformationProtectionDesktopApp",
"name": "create_from_discriminator_value",
"signature": "def create... | 3 | null | Implement the Python class `WindowsInformationProtectionDesktopApp` described below.
Class description:
Desktop App for Windows information protection
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionDesktopApp: Creates a new ... | Implement the Python class `WindowsInformationProtectionDesktopApp` described below.
Class description:
Desktop App for Windows information protection
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionDesktopApp: Creates a new ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WindowsInformationProtectionDesktopApp:
"""Desktop App for Windows information protection"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionDesktopApp:
"""Creates a new instance of the appropriate class based on discriminator ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsInformationProtectionDesktopApp:
"""Desktop App for Windows information protection"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsInformationProtectionDesktopApp:
"""Creates a new instance of the appropriate class based on discriminator value Args: p... | the_stack_v2_python_sparse | msgraph/generated/models/windows_information_protection_desktop_app.py | microsoftgraph/msgraph-sdk-python | train | 135 |
3dc843b971753512f7424aa8b0566d780b8decc1 | [
"self.server = None\nself.config = CORTXS3Config(base_cfg_path=base_config_path, cfg_type=config_type, log_init=False)\nself.create_logger_directory()\nLog.init(self.config.get_processor_logger_name(), self.config.get_processor_logger_directory(), level=self.config.get_file_log_level(), backup_count=self.config.get... | <|body_start_0|>
self.server = None
self.config = CORTXS3Config(base_cfg_path=base_config_path, cfg_type=config_type, log_init=False)
self.create_logger_directory()
Log.init(self.config.get_processor_logger_name(), self.config.get_processor_logger_directory(), level=self.config.get_file_... | Provides consumer for object recovery | ObjectRecoveryProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectRecoveryProcessor:
"""Provides consumer for object recovery"""
def __init__(self, base_config_path: str='/etc/cortx', config_type: str='yaml://'):
"""Initialise Server, config and create logger."""
<|body_0|>
def consume(self):
"""Consume the objects from o... | stack_v2_sparse_classes_36k_train_002344 | 4,267 | permissive | [
{
"docstring": "Initialise Server, config and create logger.",
"name": "__init__",
"signature": "def __init__(self, base_config_path: str='/etc/cortx', config_type: str='yaml://')"
},
{
"docstring": "Consume the objects from object recovery queue.",
"name": "consume",
"signature": "def c... | 4 | stack_v2_sparse_classes_30k_train_018041 | Implement the Python class `ObjectRecoveryProcessor` described below.
Class description:
Provides consumer for object recovery
Method signatures and docstrings:
- def __init__(self, base_config_path: str='/etc/cortx', config_type: str='yaml://'): Initialise Server, config and create logger.
- def consume(self): Consu... | Implement the Python class `ObjectRecoveryProcessor` described below.
Class description:
Provides consumer for object recovery
Method signatures and docstrings:
- def __init__(self, base_config_path: str='/etc/cortx', config_type: str='yaml://'): Initialise Server, config and create logger.
- def consume(self): Consu... | b1987967aec7e24530c9703db6f100d2c8289624 | <|skeleton|>
class ObjectRecoveryProcessor:
"""Provides consumer for object recovery"""
def __init__(self, base_config_path: str='/etc/cortx', config_type: str='yaml://'):
"""Initialise Server, config and create logger."""
<|body_0|>
def consume(self):
"""Consume the objects from o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectRecoveryProcessor:
"""Provides consumer for object recovery"""
def __init__(self, base_config_path: str='/etc/cortx', config_type: str='yaml://'):
"""Initialise Server, config and create logger."""
self.server = None
self.config = CORTXS3Config(base_cfg_path=base_config_path... | the_stack_v2_python_sparse | s3backgrounddelete/s3backgrounddelete/object_recovery_processor.py | Seagate/cortx-s3server | train | 38 |
dcfe8eb55b881fc6820f8767fd78f4f76e9804ca | [
"BaseMeta.__init__(cls, name, bases, attrs)\nfor t in cls._control_types:\n UiaMeta.control_type_to_cls[t] = cls",
"try:\n wrapper_match = UiaMeta.control_type_to_cls[element.control_type]\nexcept KeyError:\n wrapper_match = UIAWrapper\nreturn wrapper_match"
] | <|body_start_0|>
BaseMeta.__init__(cls, name, bases, attrs)
for t in cls._control_types:
UiaMeta.control_type_to_cls[t] = cls
<|end_body_0|>
<|body_start_1|>
try:
wrapper_match = UiaMeta.control_type_to_cls[element.control_type]
except KeyError:
wrapp... | Metaclass for UiaWrapper objects | UiaMeta | [
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LGPL-2.1-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UiaMeta:
"""Metaclass for UiaWrapper objects"""
def __init__(cls, name, bases, attrs):
"""Register the control types"""
<|body_0|>
def find_wrapper(element):
"""Find the correct wrapper for this UIA element"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_002345 | 35,850 | permissive | [
{
"docstring": "Register the control types",
"name": "__init__",
"signature": "def __init__(cls, name, bases, attrs)"
},
{
"docstring": "Find the correct wrapper for this UIA element",
"name": "find_wrapper",
"signature": "def find_wrapper(element)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000009 | Implement the Python class `UiaMeta` described below.
Class description:
Metaclass for UiaWrapper objects
Method signatures and docstrings:
- def __init__(cls, name, bases, attrs): Register the control types
- def find_wrapper(element): Find the correct wrapper for this UIA element | Implement the Python class `UiaMeta` described below.
Class description:
Metaclass for UiaWrapper objects
Method signatures and docstrings:
- def __init__(cls, name, bases, attrs): Register the control types
- def find_wrapper(element): Find the correct wrapper for this UIA element
<|skeleton|>
class UiaMeta:
""... | bf7f789d01b7c66ccd0c213db0a029da7e588c9e | <|skeleton|>
class UiaMeta:
"""Metaclass for UiaWrapper objects"""
def __init__(cls, name, bases, attrs):
"""Register the control types"""
<|body_0|>
def find_wrapper(element):
"""Find the correct wrapper for this UIA element"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UiaMeta:
"""Metaclass for UiaWrapper objects"""
def __init__(cls, name, bases, attrs):
"""Register the control types"""
BaseMeta.__init__(cls, name, bases, attrs)
for t in cls._control_types:
UiaMeta.control_type_to_cls[t] = cls
def find_wrapper(element):
... | the_stack_v2_python_sparse | pywinauto/controls/uiawrapper.py | pywinauto/pywinauto | train | 4,466 |
f578d1c2c1c30c31737ea5c5c8014b163bef5739 | [
"self.datatype = datatype\nself.datarange = datarange\nself.num = num\nself.strlen = strlen",
"@wraps(func)\ndef wrapper(*args, **kwargs):\n dataset = self.gener(self.datatype, self.datarange, self.num, self.strlen)\n return func(dataset, *args, **kwargs)\nreturn wrapper",
"if num <= 0:\n raise Excepti... | <|body_start_0|>
self.datatype = datatype
self.datarange = datarange
self.num = num
self.strlen = strlen
<|end_body_0|>
<|body_start_1|>
@wraps(func)
def wrapper(*args, **kwargs):
dataset = self.gener(self.datatype, self.datarange, self.num, self.strlen)
... | Attentions: This is a decorated class, you may use it by '@' | Random_gener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Random_gener:
"""Attentions: This is a decorated class, you may use it by '@'"""
def __init__(self, datatype, datarange, num, strlen):
"""Introduction ------------ constructor Parameters ---------- datatype: the type of the random data you need, it now only supports int,float or str ... | stack_v2_sparse_classes_36k_train_002346 | 5,425 | no_license | [
{
"docstring": "Introduction ------------ constructor Parameters ---------- datatype: the type of the random data you need, it now only supports int,float or str datarange: if your datatype is int or float, this will be a list of two elements, like[a,b] which means the random numbers generate are bigger than a,... | 4 | null | Implement the Python class `Random_gener` described below.
Class description:
Attentions: This is a decorated class, you may use it by '@'
Method signatures and docstrings:
- def __init__(self, datatype, datarange, num, strlen): Introduction ------------ constructor Parameters ---------- datatype: the type of the ran... | Implement the Python class `Random_gener` described below.
Class description:
Attentions: This is a decorated class, you may use it by '@'
Method signatures and docstrings:
- def __init__(self, datatype, datarange, num, strlen): Introduction ------------ constructor Parameters ---------- datatype: the type of the ran... | 661dba7ea846859056fd6ee7a310d352ca178e98 | <|skeleton|>
class Random_gener:
"""Attentions: This is a decorated class, you may use it by '@'"""
def __init__(self, datatype, datarange, num, strlen):
"""Introduction ------------ constructor Parameters ---------- datatype: the type of the random data you need, it now only supports int,float or str ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Random_gener:
"""Attentions: This is a decorated class, you may use it by '@'"""
def __init__(self, datatype, datarange, num, strlen):
"""Introduction ------------ constructor Parameters ---------- datatype: the type of the random data you need, it now only supports int,float or str datarange: if... | the_stack_v2_python_sparse | 包亦航2018011890/The_final_edition_of_all_the_homework/Random_filter_dec(second_homework)/Random_gener_dec.py | wanghan79/2020_Python | train | 4 |
d69703e5b7abe34a2b22a9aea0ce0f4dc67a46fa | [
"formatter = NumPySupportedFormat.get_format_handler(fmt=file_format)\ntemp_directory = pathlib.Path(tempfile.mkdtemp())\ncls.add_future_clearing_path(path=temp_directory)\nfile_path = temp_directory / f'{key}.{file_format}'\nformatter.save(obj=obj, file_path=str(file_path), **save_kwargs)\nartifact = Artifact(key=... | <|body_start_0|>
formatter = NumPySupportedFormat.get_format_handler(fmt=file_format)
temp_directory = pathlib.Path(tempfile.mkdtemp())
cls.add_future_clearing_path(path=temp_directory)
file_path = temp_directory / f'{key}.{file_format}'
formatter.save(obj=obj, file_path=str(file... | A base packager for builtin python dictionaries and lists of numpy arrays as they share common artifact and file types. | _NumPyNDArrayCollectionPackager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _NumPyNDArrayCollectionPackager:
"""A base packager for builtin python dictionaries and lists of numpy arrays as they share common artifact and file types."""
def pack_file(cls, obj: NumPyArrayCollectionType, key: str, file_format: str=DEFAULT_NUMPPY_ARRAY_COLLECTION_FORMAT, **save_kwargs) -... | stack_v2_sparse_classes_36k_train_002347 | 22,927 | permissive | [
{
"docstring": "Pack an array collection as a file by the given format. :param obj: The aray collection to pack. :param key: The key to use for the artifact. :param file_format: The file format to save as. Default is npy. :param save_kwargs: Additional keyword arguments to pass to the numpy save functions. :ret... | 2 | stack_v2_sparse_classes_30k_train_006442 | Implement the Python class `_NumPyNDArrayCollectionPackager` described below.
Class description:
A base packager for builtin python dictionaries and lists of numpy arrays as they share common artifact and file types.
Method signatures and docstrings:
- def pack_file(cls, obj: NumPyArrayCollectionType, key: str, file_... | Implement the Python class `_NumPyNDArrayCollectionPackager` described below.
Class description:
A base packager for builtin python dictionaries and lists of numpy arrays as they share common artifact and file types.
Method signatures and docstrings:
- def pack_file(cls, obj: NumPyArrayCollectionType, key: str, file_... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class _NumPyNDArrayCollectionPackager:
"""A base packager for builtin python dictionaries and lists of numpy arrays as they share common artifact and file types."""
def pack_file(cls, obj: NumPyArrayCollectionType, key: str, file_format: str=DEFAULT_NUMPPY_ARRAY_COLLECTION_FORMAT, **save_kwargs) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _NumPyNDArrayCollectionPackager:
"""A base packager for builtin python dictionaries and lists of numpy arrays as they share common artifact and file types."""
def pack_file(cls, obj: NumPyArrayCollectionType, key: str, file_format: str=DEFAULT_NUMPPY_ARRAY_COLLECTION_FORMAT, **save_kwargs) -> Tuple[Artif... | the_stack_v2_python_sparse | mlrun/package/packagers/numpy_packagers.py | mlrun/mlrun | train | 1,093 |
a6a96c26543381193d49fdb75a28b734882dbd29 | [
"def reverse(s, start, end):\n l = [c for i, c in enumerate(s) if start <= i < end]\n mid = (end - start) // 2\n length = end - start - 1\n i = 0\n while i < mid:\n t = l[i]\n l[i] = l[length - i]\n l[length - i] = t\n i += 1\n r = ''\n for c in l:\n r += c\n ... | <|body_start_0|>
def reverse(s, start, end):
l = [c for i, c in enumerate(s) if start <= i < end]
mid = (end - start) // 2
length = end - start - 1
i = 0
while i < mid:
t = l[i]
l[i] = l[length - i]
l[len... | 错误答案 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""错误答案"""
def reverseStr1(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_0|>
def reverseStr(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def reverse(s, start, e... | stack_v2_sparse_classes_36k_train_002348 | 1,429 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: str",
"name": "reverseStr1",
"signature": "def reverseStr1(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: str",
"name": "reverseStr",
"signature": "def reverseStr(self, s, k)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001008 | Implement the Python class `Solution` described below.
Class description:
错误答案
Method signatures and docstrings:
- def reverseStr1(self, s, k): :type s: str :type k: int :rtype: str
- def reverseStr(self, s, k): :type s: str :type k: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
错误答案
Method signatures and docstrings:
- def reverseStr1(self, s, k): :type s: str :type k: int :rtype: str
- def reverseStr(self, s, k): :type s: str :type k: int :rtype: str
<|skeleton|>
class Solution:
"""错误答案"""
def reverseStr1(se... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
"""错误答案"""
def reverseStr1(self, s, k):
""":type s: str :type k: int :rtype: str"""
<|body_0|>
def reverseStr(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 reverseStr1(self, s, k):
""":type s: str :type k: int :rtype: str"""
def reverse(s, start, end):
l = [c for i, c in enumerate(s) if start <= i < end]
mid = (end - start) // 2
length = end - start - 1
i = 0
... | the_stack_v2_python_sparse | py/leetcode/541.py | wfeng1991/learnpy | train | 0 |
b6c3293e779cdd2ccf14dd12ccecc9dc8d9704c9 | [
"super(MTQSOSLoss, self).__init__()\nself.lam = lam\nself.reconstruction_loss_fn = ReconstructionLoss()\nself.autoregression_loss_fn = FlowLoss()\nself.reconstruction_loss = None\nself.autoregression_loss = None\nself.total_loss = None",
"rec_loss = self.reconstruction_loss_fn(x, x_r, average)\narg_loss, nlog_pro... | <|body_start_0|>
super(MTQSOSLoss, self).__init__()
self.lam = lam
self.reconstruction_loss_fn = ReconstructionLoss()
self.autoregression_loss_fn = FlowLoss()
self.reconstruction_loss = None
self.autoregression_loss = None
self.total_loss = None
<|end_body_0|>
<|... | Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss. | MTQSOSLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTQSOSLoss:
"""Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss."""
def __init__(self, lam=1):
"""Class constructor. :param cpd_channels: number of bins in which the multinomial works. :param lam: weight of the autoregression loss... | stack_v2_sparse_classes_36k_train_002349 | 3,227 | permissive | [
{
"docstring": "Class constructor. :param cpd_channels: number of bins in which the multinomial works. :param lam: weight of the autoregression loss.",
"name": "__init__",
"signature": "def __init__(self, lam=1)"
},
{
"docstring": "Forward propagation. :param x: the batch of input samples. :para... | 2 | null | Implement the Python class `MTQSOSLoss` described below.
Class description:
Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss.
Method signatures and docstrings:
- def __init__(self, lam=1): Class constructor. :param cpd_channels: number of bins in which the multino... | Implement the Python class `MTQSOSLoss` described below.
Class description:
Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss.
Method signatures and docstrings:
- def __init__(self, lam=1): Class constructor. :param cpd_channels: number of bins in which the multino... | c996435a0578ea4160f934bc01041c2ef23468f3 | <|skeleton|>
class MTQSOSLoss:
"""Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss."""
def __init__(self, lam=1):
"""Class constructor. :param cpd_channels: number of bins in which the multinomial works. :param lam: weight of the autoregression loss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MTQSOSLoss:
"""Implements the loss of a LSA model. It is a sum of the reconstruction loss and the autoregression loss."""
def __init__(self, lam=1):
"""Class constructor. :param cpd_channels: number of bins in which the multinomial works. :param lam: weight of the autoregression loss."""
... | the_stack_v2_python_sparse | loss_functions/flow_loss.py | MPCAICDM/MPCA | train | 0 |
53cedcd0347ebfbdb87b8b533dc26168ce2ecf39 | [
"clone = self.filter(*args, **kwargs)\nclone = clone.order_by()\nif len(clone) >= 1:\n return clone._result_cache[0]\nreturn None",
"if model.id and model.id > 0:\n origin = self.first(id=model.id)\n if origin:\n model.create_user = origin.create_user\n model.create_time = origin.create_tim... | <|body_start_0|>
clone = self.filter(*args, **kwargs)
clone = clone.order_by()
if len(clone) >= 1:
return clone._result_cache[0]
return None
<|end_body_0|>
<|body_start_1|>
if model.id and model.id > 0:
origin = self.first(id=model.id)
if orig... | 自定义模型管理器 | BaseManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseManager:
"""自定义模型管理器"""
def first(self, *args, **kwargs):
"""获取一条数据"""
<|body_0|>
def save_new(self, model, user):
"""保存或更新数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
clone = self.filter(*args, **kwargs)
clone = clone.order_by... | stack_v2_sparse_classes_36k_train_002350 | 5,734 | no_license | [
{
"docstring": "获取一条数据",
"name": "first",
"signature": "def first(self, *args, **kwargs)"
},
{
"docstring": "保存或更新数据",
"name": "save_new",
"signature": "def save_new(self, model, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015619 | Implement the Python class `BaseManager` described below.
Class description:
自定义模型管理器
Method signatures and docstrings:
- def first(self, *args, **kwargs): 获取一条数据
- def save_new(self, model, user): 保存或更新数据 | Implement the Python class `BaseManager` described below.
Class description:
自定义模型管理器
Method signatures and docstrings:
- def first(self, *args, **kwargs): 获取一条数据
- def save_new(self, model, user): 保存或更新数据
<|skeleton|>
class BaseManager:
"""自定义模型管理器"""
def first(self, *args, **kwargs):
"""获取一条数据"""
... | 473e00e6d28baaf6b7b36de62583cf3f749816a2 | <|skeleton|>
class BaseManager:
"""自定义模型管理器"""
def first(self, *args, **kwargs):
"""获取一条数据"""
<|body_0|>
def save_new(self, model, user):
"""保存或更新数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseManager:
"""自定义模型管理器"""
def first(self, *args, **kwargs):
"""获取一条数据"""
clone = self.filter(*args, **kwargs)
clone = clone.order_by()
if len(clone) >= 1:
return clone._result_cache[0]
return None
def save_new(self, model, user):
"""保存或更新... | the_stack_v2_python_sparse | web/models.py | WsWHL/blog | train | 2 |
a83b47eb072515f5d2e4e08c2fb2a9897a271960 | [
"if not cleanup:\n cleanup = self.reference_cleanup\nHTMLtoREFs.__init__(self, filename, buffer, parsername=parsername, tag=tag, file_type=file_type, cleanup=cleanup, encoding=encoding)",
"references = []\nfor raw_block_references in self.raw_references:\n bibcode = raw_block_references['bibcode']\n bloc... | <|body_start_0|>
if not cleanup:
cleanup = self.reference_cleanup
HTMLtoREFs.__init__(self, filename, buffer, parsername=parsername, tag=tag, file_type=file_type, cleanup=cleanup, encoding=encoding)
<|end_body_0|>
<|body_start_1|>
references = []
for raw_block_references in ... | ADSHTMLtoREFs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADSHTMLtoREFs:
def __init__(self, filename, buffer, parsername, tag, file_type, cleanup=None, encoding='UTF-8'):
""":param filename: :param buffer: :param parsername: :param tag:"""
<|body_0|>
def process_and_dispatch(self):
"""this function does reference cleaning a... | stack_v2_sparse_classes_36k_train_002351 | 19,905 | permissive | [
{
"docstring": ":param filename: :param buffer: :param parsername: :param tag:",
"name": "__init__",
"signature": "def __init__(self, filename, buffer, parsername, tag, file_type, cleanup=None, encoding='UTF-8')"
},
{
"docstring": "this function does reference cleaning and then calls the parser ... | 2 | stack_v2_sparse_classes_30k_train_001896 | Implement the Python class `ADSHTMLtoREFs` described below.
Class description:
Implement the ADSHTMLtoREFs class.
Method signatures and docstrings:
- def __init__(self, filename, buffer, parsername, tag, file_type, cleanup=None, encoding='UTF-8'): :param filename: :param buffer: :param parsername: :param tag:
- def p... | Implement the Python class `ADSHTMLtoREFs` described below.
Class description:
Implement the ADSHTMLtoREFs class.
Method signatures and docstrings:
- def __init__(self, filename, buffer, parsername, tag, file_type, cleanup=None, encoding='UTF-8'): :param filename: :param buffer: :param parsername: :param tag:
- def p... | d41ed17b3b2fd7f5ae2deb48243f530cf7f494ee | <|skeleton|>
class ADSHTMLtoREFs:
def __init__(self, filename, buffer, parsername, tag, file_type, cleanup=None, encoding='UTF-8'):
""":param filename: :param buffer: :param parsername: :param tag:"""
<|body_0|>
def process_and_dispatch(self):
"""this function does reference cleaning a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ADSHTMLtoREFs:
def __init__(self, filename, buffer, parsername, tag, file_type, cleanup=None, encoding='UTF-8'):
""":param filename: :param buffer: :param parsername: :param tag:"""
if not cleanup:
cleanup = self.reference_cleanup
HTMLtoREFs.__init__(self, filename, buffer,... | the_stack_v2_python_sparse | adsrefpipe/refparsers/ADShtml.py | golnazads/ADSReferencePipeline | train | 1 | |
7329cbc75d49e312ae2aee2459f7932de250be7d | [
"self.algorithms = algorithms\nself.callbacks = callbacks\nself.queue = queue\nself.fast = fast",
"with open(evidence, 'rb') as file:\n cipher = getattr(hashlib, algorithm)()\n while True:\n data = file.read(buffer_size)\n if not data:\n break\n cipher.update(data)\nreturn ci... | <|body_start_0|>
self.algorithms = algorithms
self.callbacks = callbacks
self.queue = queue
self.fast = fast
<|end_body_0|>
<|body_start_1|>
with open(evidence, 'rb') as file:
cipher = getattr(hashlib, algorithm)()
while True:
data = file.... | Core multiprocessed class that processes the file-based evidence(s) asynchronously. | File | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class File:
"""Core multiprocessed class that processes the file-based evidence(s) asynchronously."""
def __init__(self, algorithms, callbacks, queue, fast=False):
""".. py:function:: __init__(self, algorithms, callbacks, queue) Initialization method for the class. :param self: current cla... | stack_v2_sparse_classes_36k_train_002352 | 10,116 | permissive | [
{
"docstring": ".. py:function:: __init__(self, algorithms, callbacks, queue) Initialization method for the class. :param self: current class instance :type self: class :param algorithms: list containing the name of the hash algorithm(s) to use :type algorithms: list :param callbacks: list containing the name o... | 5 | stack_v2_sparse_classes_30k_train_019556 | Implement the Python class `File` described below.
Class description:
Core multiprocessed class that processes the file-based evidence(s) asynchronously.
Method signatures and docstrings:
- def __init__(self, algorithms, callbacks, queue, fast=False): .. py:function:: __init__(self, algorithms, callbacks, queue) Init... | Implement the Python class `File` described below.
Class description:
Core multiprocessed class that processes the file-based evidence(s) asynchronously.
Method signatures and docstrings:
- def __init__(self, algorithms, callbacks, queue, fast=False): .. py:function:: __init__(self, algorithms, callbacks, queue) Init... | d485071065174b2fb4ed0c33d31e45243ff2ce20 | <|skeleton|>
class File:
"""Core multiprocessed class that processes the file-based evidence(s) asynchronously."""
def __init__(self, algorithms, callbacks, queue, fast=False):
""".. py:function:: __init__(self, algorithms, callbacks, queue) Initialization method for the class. :param self: current cla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class File:
"""Core multiprocessed class that processes the file-based evidence(s) asynchronously."""
def __init__(self, algorithms, callbacks, queue, fast=False):
""".. py:function:: __init__(self, algorithms, callbacks, queue) Initialization method for the class. :param self: current class instance :... | the_stack_v2_python_sparse | plast/framework/core/processors.py | Grukz/plast | train | 0 |
eec432be5e8567773e717138fb0c003a09d3e8da | [
"urls = []\nsoup = BeautifulSoup(html, 'html.parser')\njokes_as = soup.find_all('a', class_='contentHerf')\nfor a in jokes_as:\n urls.append(server_url + a.get('href'))\nreturn urls",
"soup = BeautifulSoup(html, 'html.parser')\njoke_content = soup.find('div', class_='content') if soup.find('div', class_='conte... | <|body_start_0|>
urls = []
soup = BeautifulSoup(html, 'html.parser')
jokes_as = soup.find_all('a', class_='contentHerf')
for a in jokes_as:
urls.append(server_url + a.get('href'))
return urls
<|end_body_0|>
<|body_start_1|>
soup = BeautifulSoup(html, 'html.pa... | 解析器 | HtmlParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParser:
"""解析器"""
def get_content_urls(self, server_url, html):
"""根据页面解析出每个joke的url :param server_url: server_url :param html: HTML string :return: list"""
<|body_0|>
def get_data_content(self, html):
"""根据页面解析出joke的内容 :param html: HTML string :return: conte... | stack_v2_sparse_classes_36k_train_002353 | 3,253 | no_license | [
{
"docstring": "根据页面解析出每个joke的url :param server_url: server_url :param html: HTML string :return: list",
"name": "get_content_urls",
"signature": "def get_content_urls(self, server_url, html)"
},
{
"docstring": "根据页面解析出joke的内容 :param html: HTML string :return: content string",
"name": "get_d... | 2 | stack_v2_sparse_classes_30k_train_005222 | Implement the Python class `HtmlParser` described below.
Class description:
解析器
Method signatures and docstrings:
- def get_content_urls(self, server_url, html): 根据页面解析出每个joke的url :param server_url: server_url :param html: HTML string :return: list
- def get_data_content(self, html): 根据页面解析出joke的内容 :param html: HTML ... | Implement the Python class `HtmlParser` described below.
Class description:
解析器
Method signatures and docstrings:
- def get_content_urls(self, server_url, html): 根据页面解析出每个joke的url :param server_url: server_url :param html: HTML string :return: list
- def get_data_content(self, html): 根据页面解析出joke的内容 :param html: HTML ... | 8593eec1834b5e945ee147b328570aba04743a92 | <|skeleton|>
class HtmlParser:
"""解析器"""
def get_content_urls(self, server_url, html):
"""根据页面解析出每个joke的url :param server_url: server_url :param html: HTML string :return: list"""
<|body_0|>
def get_data_content(self, html):
"""根据页面解析出joke的内容 :param html: HTML string :return: conte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParser:
"""解析器"""
def get_content_urls(self, server_url, html):
"""根据页面解析出每个joke的url :param server_url: server_url :param html: HTML string :return: list"""
urls = []
soup = BeautifulSoup(html, 'html.parser')
jokes_as = soup.find_all('a', class_='contentHerf')
... | the_stack_v2_python_sparse | QSBK-spider/qsbk-spider.py | AlexYangLong/SimpleSpiders | train | 1 |
a0f8d57168180fcb15fbdc91e57dbe859e9ace2a | [
"self.cdf = [0]\nself.data = rects\nfor rect in self.data:\n x1, y1, x2, y2 = rect\n self.cdf.append(self.cdf[-1] + (x2 - x1 + 1) * (y2 - y1 + 1))\nself.cdf = self.cdf[1:]\nself.cdf = [item - 1 for item in self.cdf]",
"rand = random.randint(0, self.cdf[-1])\nidx = bisect.bisect_left(self.cdf, rand)\nif idx ... | <|body_start_0|>
self.cdf = [0]
self.data = rects
for rect in self.data:
x1, y1, x2, y2 = rect
self.cdf.append(self.cdf[-1] + (x2 - x1 + 1) * (y2 - y1 + 1))
self.cdf = self.cdf[1:]
self.cdf = [item - 1 for item in self.cdf]
<|end_body_0|>
<|body_start_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.cdf = [0]
self.data = rects
for rect in self.data:
... | stack_v2_sparse_classes_36k_train_002354 | 2,408 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.cdf = [0]
self.data = rects
for rect in self.data:
x1, y1, x2, y2 = rect
self.cdf.append(self.cdf[-1] + (x2 - x1 + 1) * (y2 - y1 + 1))
self.cdf = self.cdf[1:]
se... | the_stack_v2_python_sparse | python/leetcode/sampling/497_random_point_rectangles.py | Levintsky/topcoder | train | 0 | |
d01fbc2b6e2c5336e854f94fc2dfd829c8688137 | [
"Extractor.__init__(self, 'Flickr')\nself.__apikey__ = apikey\nself.__secret__ = secret\nself.__flickr__ = flickrapi.FlickrAPI(apikey, secret)",
"rsp = self.__flickr__.photos.search(lat=lat, lon=lon, radius=radius, radius_units='km', per_page=100)\nif rsp.get('stat') == 'ok':\n return int(rsp.find('photos').ge... | <|body_start_0|>
Extractor.__init__(self, 'Flickr')
self.__apikey__ = apikey
self.__secret__ = secret
self.__flickr__ = flickrapi.FlickrAPI(apikey, secret)
<|end_body_0|>
<|body_start_1|>
rsp = self.__flickr__.photos.search(lat=lat, lon=lon, radius=radius, radius_units='km', per... | Simple flickr photo tags extractor by location @Martino Ferrari | FlickrExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlickrExtractor:
"""Simple flickr photo tags extractor by location @Martino Ferrari"""
def __init__(self, apikey, secret):
"""Init flickr extractor."""
<|body_0|>
def n_photos(self, lat, lon, radius):
"""Return number of photos in the location selected."""
... | stack_v2_sparse_classes_36k_train_002355 | 8,060 | no_license | [
{
"docstring": "Init flickr extractor.",
"name": "__init__",
"signature": "def __init__(self, apikey, secret)"
},
{
"docstring": "Return number of photos in the location selected.",
"name": "n_photos",
"signature": "def n_photos(self, lat, lon, radius)"
},
{
"docstring": "Return ... | 4 | stack_v2_sparse_classes_30k_train_000527 | Implement the Python class `FlickrExtractor` described below.
Class description:
Simple flickr photo tags extractor by location @Martino Ferrari
Method signatures and docstrings:
- def __init__(self, apikey, secret): Init flickr extractor.
- def n_photos(self, lat, lon, radius): Return number of photos in the locatio... | Implement the Python class `FlickrExtractor` described below.
Class description:
Simple flickr photo tags extractor by location @Martino Ferrari
Method signatures and docstrings:
- def __init__(self, apikey, secret): Init flickr extractor.
- def n_photos(self, lat, lon, radius): Return number of photos in the locatio... | 228c26bc694b2bd0dde5b3140d6c031824670bd0 | <|skeleton|>
class FlickrExtractor:
"""Simple flickr photo tags extractor by location @Martino Ferrari"""
def __init__(self, apikey, secret):
"""Init flickr extractor."""
<|body_0|>
def n_photos(self, lat, lon, radius):
"""Return number of photos in the location selected."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlickrExtractor:
"""Simple flickr photo tags extractor by location @Martino Ferrari"""
def __init__(self, apikey, secret):
"""Init flickr extractor."""
Extractor.__init__(self, 'Flickr')
self.__apikey__ = apikey
self.__secret__ = secret
self.__flickr__ = flickrapi.... | the_stack_v2_python_sparse | tagextractor/extraction/extractors.py | Mandarancio/tag-extractor | train | 1 |
ed41bfc5515008d62eee2b4e11ec55f39c8710c4 | [
"query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = Interface.objects.filter(id=kwargs['id']).first()\nform = InterfaceForm(instance=asearch)\nlist_inter = None\nif query:\n list_inter = Interface.objects.filter(Q(name_interface__icontains=query))\nelse:\n list_inter = Interface.o... | <|body_start_0|>
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = Interface.objects.filter(id=kwargs['id']).first()
form = InterfaceForm(instance=asearch)
list_inter = None
if query:
list_inter = Interface.objects.filter(Q(name_int... | Clase para editar las interfaces | InterfaceEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceEditView:
"""Clase para editar las interfaces"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = reque... | stack_v2_sparse_classes_36k_train_002356 | 22,221 | no_license | [
{
"docstring": "Método get",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Método post",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013310 | Implement the Python class `InterfaceEditView` described below.
Class description:
Clase para editar las interfaces
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post | Implement the Python class `InterfaceEditView` described below.
Class description:
Clase para editar las interfaces
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post
<|skeleton|>
class InterfaceEditView:
"""Clase para e... | e28e2d968372609ad396c42fb572a00c2410a117 | <|skeleton|>
class InterfaceEditView:
"""Clase para editar las interfaces"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterfaceEditView:
"""Clase para editar las interfaces"""
def get(self, request, *args, **kwargs):
"""Método get"""
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = Interface.objects.filter(id=kwargs['id']).first()
form = InterfaceForm(... | the_stack_v2_python_sparse | list/views.py | damaos/server_list2 | train | 0 |
c408a9d4952e28cfb57a0a17bb0f3821c1729b79 | [
"result = []\n\ndef dfs(root):\n if root is None:\n return\n result.append(root.val)\n if root.children:\n for child in root.children:\n dfs(child)\ndfs(root)\nreturn result",
"result = []\nstack = []\nif root:\n stack.append(root)\n while stack:\n node = stack.pop()... | <|body_start_0|>
result = []
def dfs(root):
if root is None:
return
result.append(root.val)
if root.children:
for child in root.children:
dfs(child)
dfs(root)
return result
<|end_body_0|>
<|body_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorder(self, root: 'Node') -> List[int]:
"""recursive"""
<|body_0|>
def preorder(self, root: 'Node') -> List[int]:
"""iterative"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
def dfs(root):
if root i... | stack_v2_sparse_classes_36k_train_002357 | 1,199 | no_license | [
{
"docstring": "recursive",
"name": "preorder",
"signature": "def preorder(self, root: 'Node') -> List[int]"
},
{
"docstring": "iterative",
"name": "preorder",
"signature": "def preorder(self, root: 'Node') -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_019386 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root: 'Node') -> List[int]: recursive
- def preorder(self, root: 'Node') -> List[int]: iterative | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root: 'Node') -> List[int]: recursive
- def preorder(self, root: 'Node') -> List[int]: iterative
<|skeleton|>
class Solution:
def preorder(self, root: 'N... | fce451090ecaf5471aab5a9413ac0675639ace5d | <|skeleton|>
class Solution:
def preorder(self, root: 'Node') -> List[int]:
"""recursive"""
<|body_0|>
def preorder(self, root: 'Node') -> List[int]:
"""iterative"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorder(self, root: 'Node') -> List[int]:
"""recursive"""
result = []
def dfs(root):
if root is None:
return
result.append(root.val)
if root.children:
for child in root.children:
dfs... | the_stack_v2_python_sparse | tree/589N-aryTreePreorderTraversal.py | kidexp/91leetcode | train | 0 | |
3c7995a313461ae5443ea9ad3e718f666a91374d | [
"sol = (num + 1) * [0]\nsol[1] = 1\nlastBinary = 1\nfor i in range(1, num + 1):\n if self.log2(i):\n sol[i] = 1\n lastBinary = i\n else:\n sol[i] = sol[lastBinary] + sol[i - lastBinary]\n print(i, lastBinary)\nreturn sol",
"if num % 2 != 0:\n return False\nwhile num != 1:\n ... | <|body_start_0|>
sol = (num + 1) * [0]
sol[1] = 1
lastBinary = 1
for i in range(1, num + 1):
if self.log2(i):
sol[i] = 1
lastBinary = i
else:
sol[i] = sol[lastBinary] + sol[i - lastBinary]
print(i, la... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
<|body_0|>
def log2(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sol = (num + 1) * [0]
sol[1] = 1
lastBinary = 1... | stack_v2_sparse_classes_36k_train_002358 | 1,170 | no_license | [
{
"docstring": ":type num: int :rtype: List[int]",
"name": "countBits",
"signature": "def countBits(self, num)"
},
{
"docstring": ":type num: int :rtype: bool",
"name": "log2",
"signature": "def log2(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000030 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num): :type num: int :rtype: List[int]
- def log2(self, num): :type num: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num): :type num: int :rtype: List[int]
- def log2(self, num): :type num: int :rtype: bool
<|skeleton|>
class Solution:
def countBits(self, num):
... | 61933e7c0b8d8ffef9bd9a4af4fddfdb77568b62 | <|skeleton|>
class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
<|body_0|>
def log2(self, num):
""":type num: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
sol = (num + 1) * [0]
sol[1] = 1
lastBinary = 1
for i in range(1, num + 1):
if self.log2(i):
sol[i] = 1
lastBinary = i
else:
... | the_stack_v2_python_sparse | 338-Counting-Bits.py | OhMesch/Algorithm-Problems | train | 0 | |
a012293ade129d98d8c85dc89b94c564b4280007 | [
"app_id_list = self.request.query_params.get('selectedAppList')\nif not app_id_list:\n app_id_list = get_cc_app_id_by_user()\nelse:\n app_id_list = app_id_list.split(',')\nreturn KafkaCluster.objects.filter(app_id__in=app_id_list).order_by('-create_time')",
"try:\n post_data = request.data\n bk_userna... | <|body_start_0|>
app_id_list = self.request.query_params.get('selectedAppList')
if not app_id_list:
app_id_list = get_cc_app_id_by_user()
else:
app_id_list = app_id_list.split(',')
return KafkaCluster.objects.filter(app_id__in=app_id_list).order_by('-create_time')... | kafka集群表视图 | KafkaClusterViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KafkaClusterViewSet:
"""kafka集群表视图"""
def get_queryset(self):
"""重写get_queryset方法,根据用户的业务权限来输出对应记录,用户隔离"""
<|body_0|>
def create_cluster(self, request, *args, **kwargs):
"""POST /kafka/create_cluster kafka集群创建"""
<|body_1|>
def add_broker(self, reque... | stack_v2_sparse_classes_36k_train_002359 | 12,453 | no_license | [
{
"docstring": "重写get_queryset方法,根据用户的业务权限来输出对应记录,用户隔离",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "POST /kafka/create_cluster kafka集群创建",
"name": "create_cluster",
"signature": "def create_cluster(self, request, *args, **kwargs)"
},
{
"docst... | 5 | stack_v2_sparse_classes_30k_train_021120 | Implement the Python class `KafkaClusterViewSet` described below.
Class description:
kafka集群表视图
Method signatures and docstrings:
- def get_queryset(self): 重写get_queryset方法,根据用户的业务权限来输出对应记录,用户隔离
- def create_cluster(self, request, *args, **kwargs): POST /kafka/create_cluster kafka集群创建
- def add_broker(self, request):... | Implement the Python class `KafkaClusterViewSet` described below.
Class description:
kafka集群表视图
Method signatures and docstrings:
- def get_queryset(self): 重写get_queryset方法,根据用户的业务权限来输出对应记录,用户隔离
- def create_cluster(self, request, *args, **kwargs): POST /kafka/create_cluster kafka集群创建
- def add_broker(self, request):... | 97cfac2ba94d67980d837f0b541caae70b68a595 | <|skeleton|>
class KafkaClusterViewSet:
"""kafka集群表视图"""
def get_queryset(self):
"""重写get_queryset方法,根据用户的业务权限来输出对应记录,用户隔离"""
<|body_0|>
def create_cluster(self, request, *args, **kwargs):
"""POST /kafka/create_cluster kafka集群创建"""
<|body_1|>
def add_broker(self, reque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KafkaClusterViewSet:
"""kafka集群表视图"""
def get_queryset(self):
"""重写get_queryset方法,根据用户的业务权限来输出对应记录,用户隔离"""
app_id_list = self.request.query_params.get('selectedAppList')
if not app_id_list:
app_id_list = get_cc_app_id_by_user()
else:
app_id_list = a... | the_stack_v2_python_sparse | apps/kafka/views.py | sdgdsffdsfff/bk-dop | train | 0 |
b3e8013baf549f19f2ce9183fb7124fdb56518bc | [
"nums.sort(reverse=True)\nself.nums = nums[0:k]\nself.k = k",
"if len(self.nums) == self.k and val <= self.nums[-1]:\n return self.nums[-1]\nleft, right = (0, len(self.nums))\nwhile left < right:\n mid = (left + right) // 2\n if val > self.nums[mid]:\n right = mid\n else:\n left = mid + ... | <|body_start_0|>
nums.sort(reverse=True)
self.nums = nums[0:k]
self.k = k
<|end_body_0|>
<|body_start_1|>
if len(self.nums) == self.k and val <= self.nums[-1]:
return self.nums[-1]
left, right = (0, len(self.nums))
while left < right:
mid = (left ... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort(reverse=True)
self.nums = nums[0:k]
... | stack_v2_sparse_classes_36k_train_002360 | 1,019 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015857 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | e4d3ddb3529486f99b3ba128141837e67588a177 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
nums.sort(reverse=True)
self.nums = nums[0:k]
self.k = k
def add(self, val):
""":type val: int :rtype: int"""
if len(self.nums) == self.k and val <= self.nums[-1]:
... | the_stack_v2_python_sparse | Python/703-Kth_largest_element_in_a_stream_first_1_modify.py | zhangwei1989/algorithm | train | 0 | |
6ca3259a6785bf4e58c7ec9a3cfc14a44acb3a85 | [
"if IATTopic.providedBy(context) or ICollection.providedBy(context):\n return context.queryCatalog(batch=False)\nelif IFolderish.providedBy(context):\n return context.getFolderContents(batch=False)",
"if objectimages:\n theader = '\\n <thead>\\n <tr>\\n ... | <|body_start_0|>
if IATTopic.providedBy(context) or ICollection.providedBy(context):
return context.queryCatalog(batch=False)
elif IFolderish.providedBy(context):
return context.getFolderContents(batch=False)
<|end_body_0|>
<|body_start_1|>
if objectimages:
t... | DownloadWoid_Viewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadWoid_Viewlet:
def query(self, context):
"""Make catalog query for the folder listing."""
<|body_0|>
def createTableHeader(self, objectimages):
"""Create the Header for Table"""
<|body_1|>
def createZeileFromMF(self, obj, objectimages):
""... | stack_v2_sparse_classes_36k_train_002361 | 5,467 | no_license | [
{
"docstring": "Make catalog query for the folder listing.",
"name": "query",
"signature": "def query(self, context)"
},
{
"docstring": "Create the Header for Table",
"name": "createTableHeader",
"signature": "def createTableHeader(self, objectimages)"
},
{
"docstring": "Create a... | 5 | stack_v2_sparse_classes_30k_train_006303 | Implement the Python class `DownloadWoid_Viewlet` described below.
Class description:
Implement the DownloadWoid_Viewlet class.
Method signatures and docstrings:
- def query(self, context): Make catalog query for the folder listing.
- def createTableHeader(self, objectimages): Create the Header for Table
- def create... | Implement the Python class `DownloadWoid_Viewlet` described below.
Class description:
Implement the DownloadWoid_Viewlet class.
Method signatures and docstrings:
- def query(self, context): Make catalog query for the folder listing.
- def createTableHeader(self, objectimages): Create the Header for Table
- def create... | 62203ae995bd708dc81809cc8698c0b24208735e | <|skeleton|>
class DownloadWoid_Viewlet:
def query(self, context):
"""Make catalog query for the folder listing."""
<|body_0|>
def createTableHeader(self, objectimages):
"""Create the Header for Table"""
<|body_1|>
def createZeileFromMF(self, obj, objectimages):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadWoid_Viewlet:
def query(self, context):
"""Make catalog query for the folder listing."""
if IATTopic.providedBy(context) or ICollection.providedBy(context):
return context.queryCatalog(batch=False)
elif IFolderish.providedBy(context):
return context.getF... | the_stack_v2_python_sparse | nva.flgdesktop/trunk/nva/flgdesktop/viewlets.py | witsch/novareto | train | 0 | |
2d49ffa1402dda5237cec7c61515bfc05c7662bc | [
"env = gym_atari.GymAtari('pong', seed=1)\naction_spec = env.action_spec()\nagent = AgentWithPreprocessing(num_actions=action_spec.num_values)\nagent.reset()\ntimestep = env.reset()\nactions = []\nfor _ in range(20):\n action = agent.step(timestep)\n timestep = env.step(action)\n assert not timestep.last()... | <|body_start_0|>
env = gym_atari.GymAtari('pong', seed=1)
action_spec = env.action_spec()
agent = AgentWithPreprocessing(num_actions=action_spec.num_values)
agent.reset()
timestep = env.reset()
actions = []
for _ in range(20):
action = agent.step(times... | AtariTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtariTest:
def test_can_use_in_an_agent(self):
"""Example of using Atari processor on the agent side."""
<|body_0|>
def test_default_on_fixed_input(self):
"""End-to-end test on fixed input. This is to test (mainly observation) processors do not change due to updates ... | stack_v2_sparse_classes_36k_train_002362 | 16,509 | permissive | [
{
"docstring": "Example of using Atari processor on the agent side.",
"name": "test_can_use_in_an_agent",
"signature": "def test_can_use_in_an_agent(self)"
},
{
"docstring": "End-to-end test on fixed input. This is to test (mainly observation) processors do not change due to updates in underlyin... | 2 | stack_v2_sparse_classes_30k_train_007524 | Implement the Python class `AtariTest` described below.
Class description:
Implement the AtariTest class.
Method signatures and docstrings:
- def test_can_use_in_an_agent(self): Example of using Atari processor on the agent side.
- def test_default_on_fixed_input(self): End-to-end test on fixed input. This is to test... | Implement the Python class `AtariTest` described below.
Class description:
Implement the AtariTest class.
Method signatures and docstrings:
- def test_can_use_in_an_agent(self): Example of using Atari processor on the agent side.
- def test_default_on_fixed_input(self): End-to-end test on fixed input. This is to test... | f011d683529d8d23b017a95194ebbb41a4962fe8 | <|skeleton|>
class AtariTest:
def test_can_use_in_an_agent(self):
"""Example of using Atari processor on the agent side."""
<|body_0|>
def test_default_on_fixed_input(self):
"""End-to-end test on fixed input. This is to test (mainly observation) processors do not change due to updates ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AtariTest:
def test_can_use_in_an_agent(self):
"""Example of using Atari processor on the agent side."""
env = gym_atari.GymAtari('pong', seed=1)
action_spec = env.action_spec()
agent = AgentWithPreprocessing(num_actions=action_spec.num_values)
agent.reset()
tim... | the_stack_v2_python_sparse | dqn_zoo/processors_test.py | jinghanY/dqn_zoo | train | 0 | |
9b203c29879fd6882603e4f666f807a2cc0c819e | [
"if not url_str:\n return err_resp('A url is required')\nif not isinstance(url_str, str):\n return err_resp('The \"url_str\" must be a string')\nreturn ok_resp(urlparse(url_str))",
"info = URLHelper.get_parsed_url(url_str)\nif not info.success:\n return info\nnetloc = info.result_obj.netloc\nif not netlo... | <|body_start_0|>
if not url_str:
return err_resp('A url is required')
if not isinstance(url_str, str):
return err_resp('The "url_str" must be a string')
return ok_resp(urlparse(url_str))
<|end_body_0|>
<|body_start_1|>
info = URLHelper.get_parsed_url(url_str)
... | Helper methods related to urls | URLHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLHelper:
"""Helper methods related to urls"""
def get_parsed_url(url_str):
"""Return a ParseResult object"""
<|body_0|>
def get_netloc_from_url(url_str):
"""Return the netloc from the url"""
<|body_1|>
def format_url_for_saving(url_str, remove_trai... | stack_v2_sparse_classes_36k_train_002363 | 5,027 | permissive | [
{
"docstring": "Return a ParseResult object",
"name": "get_parsed_url",
"signature": "def get_parsed_url(url_str)"
},
{
"docstring": "Return the netloc from the url",
"name": "get_netloc_from_url",
"signature": "def get_netloc_from_url(url_str)"
},
{
"docstring": "Make the url lo... | 6 | stack_v2_sparse_classes_30k_train_005292 | Implement the Python class `URLHelper` described below.
Class description:
Helper methods related to urls
Method signatures and docstrings:
- def get_parsed_url(url_str): Return a ParseResult object
- def get_netloc_from_url(url_str): Return the netloc from the url
- def format_url_for_saving(url_str, remove_trailing... | Implement the Python class `URLHelper` described below.
Class description:
Helper methods related to urls
Method signatures and docstrings:
- def get_parsed_url(url_str): Return a ParseResult object
- def get_netloc_from_url(url_str): Return the netloc from the url
- def format_url_for_saving(url_str, remove_trailing... | 9461522219f5ef0f4877f24c8f5923e462bd9557 | <|skeleton|>
class URLHelper:
"""Helper methods related to urls"""
def get_parsed_url(url_str):
"""Return a ParseResult object"""
<|body_0|>
def get_netloc_from_url(url_str):
"""Return the netloc from the url"""
<|body_1|>
def format_url_for_saving(url_str, remove_trai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class URLHelper:
"""Helper methods related to urls"""
def get_parsed_url(url_str):
"""Return a ParseResult object"""
if not url_str:
return err_resp('A url is required')
if not isinstance(url_str, str):
return err_resp('The "url_str" must be a string')
re... | the_stack_v2_python_sparse | preprocess_web/code/ravens_metadata_apps/utils/url_helper.py | TwoRavens/raven-metadata-service | train | 0 |
25ea46673f5cd6641610961618d119b9f708fb5a | [
"test_post = Post(post_title='Test Post', author=Person.objects.get(pk=1), markdown_url='https://raw.githubusercontent.com/BridgesLab/Lab-Website/master/LICENSE.md')\ntest_post.save()\nself.assertEqual(test_post.pk, 1)",
"test_post = Post(post_title='Test Post', author=Person.objects.get(pk=1), markdown_url='http... | <|body_start_0|>
test_post = Post(post_title='Test Post', author=Person.objects.get(pk=1), markdown_url='https://raw.githubusercontent.com/BridgesLab/Lab-Website/master/LICENSE.md')
test_post.save()
self.assertEqual(test_post.pk, 1)
<|end_body_0|>
<|body_start_1|>
test_post = Post(post_... | This class tests various aspects of the :class:`~papers.models.Post` model. | PostModelTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostModelTests:
"""This class tests various aspects of the :class:`~papers.models.Post` model."""
def test_create_new_post_minimum(self):
"""This test creates a :class:`~papers.models.Post` with the required information only."""
<|body_0|>
def test_create_new_post_all(se... | stack_v2_sparse_classes_36k_train_002364 | 14,526 | permissive | [
{
"docstring": "This test creates a :class:`~papers.models.Post` with the required information only.",
"name": "test_create_new_post_minimum",
"signature": "def test_create_new_post_minimum(self)"
},
{
"docstring": "This test creates a :class:`~papers.models.Post` with all fields entered.",
... | 4 | stack_v2_sparse_classes_30k_train_000646 | Implement the Python class `PostModelTests` described below.
Class description:
This class tests various aspects of the :class:`~papers.models.Post` model.
Method signatures and docstrings:
- def test_create_new_post_minimum(self): This test creates a :class:`~papers.models.Post` with the required information only.
-... | Implement the Python class `PostModelTests` described below.
Class description:
This class tests various aspects of the :class:`~papers.models.Post` model.
Method signatures and docstrings:
- def test_create_new_post_minimum(self): This test creates a :class:`~papers.models.Post` with the required information only.
-... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class PostModelTests:
"""This class tests various aspects of the :class:`~papers.models.Post` model."""
def test_create_new_post_minimum(self):
"""This test creates a :class:`~papers.models.Post` with the required information only."""
<|body_0|>
def test_create_new_post_all(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostModelTests:
"""This class tests various aspects of the :class:`~papers.models.Post` model."""
def test_create_new_post_minimum(self):
"""This test creates a :class:`~papers.models.Post` with the required information only."""
test_post = Post(post_title='Test Post', author=Person.objec... | the_stack_v2_python_sparse | communication/tests.py | BridgesLab/Lab-Website | train | 0 |
a7df8f3d5e3efa03bbe97e531dc4549b6356831e | [
"if not identifier:\n raise ValueError('A User must have an identifier')\nuser = self.model(identifier=identifier, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(identifier, password=password, **extra_fields)\nuser.is_staff = True\nuser.is_superu... | <|body_start_0|>
if not identifier:
raise ValueError('A User must have an identifier')
user = self.model(identifier=identifier, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.creat... | CalendloUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendloUserManager:
def create_user(self, identifier, password=None, **extra_fields):
"""Creates and saves a User with the given identifier and password"""
<|body_0|>
def create_superuser(self, identifier, password, **extra_fields):
"""Creates and saves a superuser ... | stack_v2_sparse_classes_36k_train_002365 | 980 | no_license | [
{
"docstring": "Creates and saves a User with the given identifier and password",
"name": "create_user",
"signature": "def create_user(self, identifier, password=None, **extra_fields)"
},
{
"docstring": "Creates and saves a superuser with the given identifier and password.",
"name": "create_... | 2 | stack_v2_sparse_classes_30k_train_003035 | Implement the Python class `CalendloUserManager` described below.
Class description:
Implement the CalendloUserManager class.
Method signatures and docstrings:
- def create_user(self, identifier, password=None, **extra_fields): Creates and saves a User with the given identifier and password
- def create_superuser(sel... | Implement the Python class `CalendloUserManager` described below.
Class description:
Implement the CalendloUserManager class.
Method signatures and docstrings:
- def create_user(self, identifier, password=None, **extra_fields): Creates and saves a User with the given identifier and password
- def create_superuser(sel... | cbc0b44dbec6a65bb8daab3745a5b116177df655 | <|skeleton|>
class CalendloUserManager:
def create_user(self, identifier, password=None, **extra_fields):
"""Creates and saves a User with the given identifier and password"""
<|body_0|>
def create_superuser(self, identifier, password, **extra_fields):
"""Creates and saves a superuser ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendloUserManager:
def create_user(self, identifier, password=None, **extra_fields):
"""Creates and saves a User with the given identifier and password"""
if not identifier:
raise ValueError('A User must have an identifier')
user = self.model(identifier=identifier, **extr... | the_stack_v2_python_sparse | accounts/managers.py | luvpreetsingh/calendlo | train | 0 | |
228758063aaab24a95a7c9e0ee9663f0c046af62 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.find('div', {'class': 'fic_title'})['title'].strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = self.absolute_url(soup.find('div', {'class': 'fic_image'}).find('img')['src'])\nlogge... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.find('div', {'class': 'fic_title'})['title'].strip()
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = self.absolute_url(soup.find('div', {'... | ScribbleHubCrawler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScribbleHubCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_list(self, page):
"""Download list of chapters and volumes."""
<|body_1|>
def download_chapter_body(self, chapter):
"""Download... | stack_v2_sparse_classes_36k_train_002366 | 3,492 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download list of chapters and volumes.",
"name": "download_chapter_list",
"signature": "def download_chapter_list(self, page)"
},
{
"docstrin... | 3 | null | Implement the Python class `ScribbleHubCrawler` described below.
Class description:
Implement the ScribbleHubCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_list(self, page): Download list of chapters and volumes.
- def download_ch... | Implement the Python class `ScribbleHubCrawler` described below.
Class description:
Implement the ScribbleHubCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_list(self, page): Download list of chapters and volumes.
- def download_ch... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class ScribbleHubCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_list(self, page):
"""Download list of chapters and volumes."""
<|body_1|>
def download_chapter_body(self, chapter):
"""Download... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScribbleHubCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.find('div', {'class': 'fic_title'})['title'].strip()
logger.info('Novel title:... | the_stack_v2_python_sparse | lncrawl/sources/scribblehub.py | NNTin/lightnovel-crawler | train | 2 | |
e2e02221f82041ec26f92af88c2f8c61deb22fa2 | [
"old_namespaced_oligotype = NamespacedOligotypesModel.query.filter((NamespacedOligotypesModel.namespace == namespaced_oligotype.namespace) & (NamespacedOligotypesModel.oligotype == namespaced_oligotype.oligotype)).first()\nif old_namespaced_oligotype:\n return (False, from_dict(NamespacedOligotype, old_namespace... | <|body_start_0|>
old_namespaced_oligotype = NamespacedOligotypesModel.query.filter((NamespacedOligotypesModel.namespace == namespaced_oligotype.namespace) & (NamespacedOligotypesModel.oligotype == namespaced_oligotype.oligotype)).first()
if old_namespaced_oligotype:
return (False, from_dict(... | A manager of Namespaced Oligotypes model. | NamespacesdOligotypeRepositoryManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NamespacesdOligotypeRepositoryManager:
"""A manager of Namespaced Oligotypes model."""
def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]:
"""Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single... | stack_v2_sparse_classes_36k_train_002367 | 3,211 | no_license | [
{
"docstring": "Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single namespaced oligotype entity. Returns: Tuple[bool, NamespacesdOligotype]: A boolean indicating if the namespace was created (True) or recovered from database (False), and a instance of the created nam... | 2 | stack_v2_sparse_classes_30k_train_018082 | Implement the Python class `NamespacesdOligotypeRepositoryManager` described below.
Class description:
A manager of Namespaced Oligotypes model.
Method signatures and docstrings:
- def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]: Insert a single record into database. A... | Implement the Python class `NamespacesdOligotypeRepositoryManager` described below.
Class description:
A manager of Namespaced Oligotypes model.
Method signatures and docstrings:
- def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]: Insert a single record into database. A... | 5d240fea783a453137c9a3697b67dae67b08a73d | <|skeleton|>
class NamespacesdOligotypeRepositoryManager:
"""A manager of Namespaced Oligotypes model."""
def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]:
"""Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NamespacesdOligotypeRepositoryManager:
"""A manager of Namespaced Oligotypes model."""
def get_or_create(namespaced_oligotype: NamespacedOligotype) -> Tuple[bool, NamespacedOligotype]:
"""Insert a single record into database. Args: namespaced_oligotype (NamespacedOligotype): A single namespaced o... | the_stack_v2_python_sparse | src/adapters/repositories/oligotype_link.py | sgelias/blu | train | 0 |
704007c62d247197840ceb0eb0c6f73d33e193dc | [
"dt1 = '2021-02-01:2,3,4,5;'\nself.assertEqual(turn_first_datetime_string_into_time_format(dt1), datetime(2021, 2, 1, 1, 0))\ndt2 = '2021-02-03:0;'\nself.assertEqual(turn_first_datetime_string_into_time_format(dt2), datetime(2021, 2, 3, 0, 0))\ndt3 = '2021-02-01:47'\nself.assertEqual(turn_first_datetime_string_into... | <|body_start_0|>
dt1 = '2021-02-01:2,3,4,5;'
self.assertEqual(turn_first_datetime_string_into_time_format(dt1), datetime(2021, 2, 1, 1, 0))
dt2 = '2021-02-03:0;'
self.assertEqual(turn_first_datetime_string_into_time_format(dt2), datetime(2021, 2, 3, 0, 0))
dt3 = '2021-02-01:47'
... | TEST_HANDY | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TEST_HANDY:
def test_turn_first_datetime_string_into_time_format(self):
"""檢查是否可以將字串化的日期區間轉為datetime格式"""
<|body_0|>
def test_turn_picture_into_jpeg_format_change_size(self):
"""測試Image的一些性質"""
<|body_1|>
def test_turn_picture_into_jpeg_format_change_siz... | stack_v2_sparse_classes_36k_train_002368 | 3,391 | no_license | [
{
"docstring": "檢查是否可以將字串化的日期區間轉為datetime格式",
"name": "test_turn_first_datetime_string_into_time_format",
"signature": "def test_turn_first_datetime_string_into_time_format(self)"
},
{
"docstring": "測試Image的一些性質",
"name": "test_turn_picture_into_jpeg_format_change_size",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_test_000725 | Implement the Python class `TEST_HANDY` described below.
Class description:
Implement the TEST_HANDY class.
Method signatures and docstrings:
- def test_turn_first_datetime_string_into_time_format(self): 檢查是否可以將字串化的日期區間轉為datetime格式
- def test_turn_picture_into_jpeg_format_change_size(self): 測試Image的一些性質
- def test_tu... | Implement the Python class `TEST_HANDY` described below.
Class description:
Implement the TEST_HANDY class.
Method signatures and docstrings:
- def test_turn_first_datetime_string_into_time_format(self): 檢查是否可以將字串化的日期區間轉為datetime格式
- def test_turn_picture_into_jpeg_format_change_size(self): 測試Image的一些性質
- def test_tu... | 7a292671a355ae58f3889036d8da199b3801d321 | <|skeleton|>
class TEST_HANDY:
def test_turn_first_datetime_string_into_time_format(self):
"""檢查是否可以將字串化的日期區間轉為datetime格式"""
<|body_0|>
def test_turn_picture_into_jpeg_format_change_size(self):
"""測試Image的一些性質"""
<|body_1|>
def test_turn_picture_into_jpeg_format_change_siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TEST_HANDY:
def test_turn_first_datetime_string_into_time_format(self):
"""檢查是否可以將字串化的日期區間轉為datetime格式"""
dt1 = '2021-02-01:2,3,4,5;'
self.assertEqual(turn_first_datetime_string_into_time_format(dt1), datetime(2021, 2, 1, 1, 0))
dt2 = '2021-02-03:0;'
self.assertEqual(tu... | the_stack_v2_python_sparse | Quikok/website_assets/handy_functions_tests.py | chikuku/QUIKOK | train | 0 | |
3b14642d85e824e6c8c389b3bc982759b68718a5 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn GoogleCloudResourceEvidence()",
"from .alert_evidence import AlertEvidence\nfrom .google_cloud_location_type import GoogleCloudLocationType\nfrom .alert_evidence import AlertEvidence\nfrom .google_cloud_location_type import GoogleCloud... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return GoogleCloudResourceEvidence()
<|end_body_0|>
<|body_start_1|>
from .alert_evidence import AlertEvidence
from .google_cloud_location_type import GoogleCloudLocationType
from .aler... | GoogleCloudResourceEvidence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleCloudResourceEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GoogleCloudResourceEvidence:
"""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 a... | stack_v2_sparse_classes_36k_train_002369 | 3,637 | 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: GoogleCloudResourceEvidence",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | null | Implement the Python class `GoogleCloudResourceEvidence` described below.
Class description:
Implement the GoogleCloudResourceEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GoogleCloudResourceEvidence: Creates a new instance of the appr... | Implement the Python class `GoogleCloudResourceEvidence` described below.
Class description:
Implement the GoogleCloudResourceEvidence class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GoogleCloudResourceEvidence: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class GoogleCloudResourceEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GoogleCloudResourceEvidence:
"""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 a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleCloudResourceEvidence:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GoogleCloudResourceEvidence:
"""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 ... | the_stack_v2_python_sparse | msgraph/generated/models/security/google_cloud_resource_evidence.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
222ea5650f62c19504934c075a6dbf4c0580bf72 | [
"if namespace is None:\n namespace = {}\nself.namespace = namespace\nif not valuedict:\n valuedict = {}\nself.values = valuedict\nself.default = default",
"if default is __notfound__:\n default = self.default\nif name in self.values:\n value = self.values[name]\nelse:\n try:\n value = self.n... | <|body_start_0|>
if namespace is None:
namespace = {}
self.namespace = namespace
if not valuedict:
valuedict = {}
self.values = valuedict
self.default = default
<|end_body_0|>
<|body_start_1|>
if default is __notfound__:
default = self... | Smart dictionary object | SmartDict | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartDict:
"""Smart dictionary object"""
def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__):
"""init"""
<|body_0|>
def __getitem__(self, name, default=__notfound__):
"""get item from values *or* namespace"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_002370 | 2,260 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__)"
},
{
"docstring": "get item from values *or* namespace",
"name": "__getitem__",
"signature": "def __getitem__(self, name, default=__notfound__)"
}... | 3 | null | Implement the Python class `SmartDict` described below.
Class description:
Smart dictionary object
Method signatures and docstrings:
- def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__): init
- def __getitem__(self, name, default=__notfound__): get item from values *or* namespace
- def ... | Implement the Python class `SmartDict` described below.
Class description:
Smart dictionary object
Method signatures and docstrings:
- def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__): init
- def __getitem__(self, name, default=__notfound__): get item from values *or* namespace
- def ... | 0f2e6a2d1c71f104b1522fd68ec01b9f9f3b92f9 | <|skeleton|>
class SmartDict:
"""Smart dictionary object"""
def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__):
"""init"""
<|body_0|>
def __getitem__(self, name, default=__notfound__):
"""get item from values *or* namespace"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmartDict:
"""Smart dictionary object"""
def __init__(self, namespace: object, valuedict: dict=None, default=__notfound__):
"""init"""
if namespace is None:
namespace = {}
self.namespace = namespace
if not valuedict:
valuedict = {}
self.valu... | the_stack_v2_python_sparse | apps/TCPB_-_Expressions/src/smartdict.py | ThreatConnect-Inc/threatconnect-playbooks | train | 76 |
f0c842f71926f58aad3f2622f4b321d0548122d2 | [
"super(PixelControl, self).__init__(name=name)\nself._num_actions = num_actions\nself._activation = activation\nself._linear = snt.Linear(32 * 7 * 7, name='linear')\nself._deconv = snt.Conv2DTranspose(output_channels=32, kernel_shape=9, padding='SAME', name='deconv', stride=3, output_shape=(20, 20))\nself._value = ... | <|body_start_0|>
super(PixelControl, self).__init__(name=name)
self._num_actions = num_actions
self._activation = activation
self._linear = snt.Linear(32 * 7 * 7, name='linear')
self._deconv = snt.Conv2DTranspose(output_channels=32, kernel_shape=9, padding='SAME', name='deconv', ... | Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representing a 5 x 5 pixel area, covering a pixel ... | PixelControl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelControl:
"""Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representi... | stack_v2_sparse_classes_36k_train_002371 | 10,989 | no_license | [
{
"docstring": "Initializes the PixelControl module. Args: num_actions: number of actions in discrete action space activation: activation function to be used (after linear and deconvolutional layer) name: name for the module",
"name": "__init__",
"signature": "def __init__(self, num_actions: int, activa... | 2 | stack_v2_sparse_classes_30k_train_017301 | Implement the Python class `PixelControl` described below.
Class description:
Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a... | Implement the Python class `PixelControl` described below.
Class description:
Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a... | 1c2b2768f2c5996c8cc998d0271f3857949bdaeb | <|skeleton|>
class PixelControl:
"""Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PixelControl:
"""Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representing a 5 x 5 pi... | the_stack_v2_python_sparse | ftw/tf/networks/auxiliary.py | RaoulDrake/ftw | train | 3 |
843626b6935d0f2012969e12bef1170acee37963 | [
"instance = db.session.query(cls).filter_by(**filter_by).with_for_update().first()\nif instance:\n return (instance, False)\ninstance = cls(**filter_by, **default_kwargs or {})\ninstance.save(commit)\nreturn (instance, True)",
"instance, created = cls.get_or_create(filter_by, update_kwargs or {})\nif not creat... | <|body_start_0|>
instance = db.session.query(cls).filter_by(**filter_by).with_for_update().first()
if instance:
return (instance, False)
instance = cls(**filter_by, **default_kwargs or {})
instance.save(commit)
return (instance, True)
<|end_body_0|>
<|body_start_1|>
... | UpsertMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpsertMixin:
def get_or_create(cls, filter_by, default_kwargs=None, commit=True):
"""Fetches one record by filter criteria and creates one with defaults if missing"""
<|body_0|>
def update_or_create(cls, filter_by, update_kwargs=None, commit=True):
"""Fetches one rec... | stack_v2_sparse_classes_36k_train_002372 | 3,836 | no_license | [
{
"docstring": "Fetches one record by filter criteria and creates one with defaults if missing",
"name": "get_or_create",
"signature": "def get_or_create(cls, filter_by, default_kwargs=None, commit=True)"
},
{
"docstring": "Fetches one record by filter criteria and updates with kwargs",
"nam... | 2 | stack_v2_sparse_classes_30k_train_015252 | Implement the Python class `UpsertMixin` described below.
Class description:
Implement the UpsertMixin class.
Method signatures and docstrings:
- def get_or_create(cls, filter_by, default_kwargs=None, commit=True): Fetches one record by filter criteria and creates one with defaults if missing
- def update_or_create(c... | Implement the Python class `UpsertMixin` described below.
Class description:
Implement the UpsertMixin class.
Method signatures and docstrings:
- def get_or_create(cls, filter_by, default_kwargs=None, commit=True): Fetches one record by filter criteria and creates one with defaults if missing
- def update_or_create(c... | da37174113392a67b1bd7cc8f33633a4c230f7b9 | <|skeleton|>
class UpsertMixin:
def get_or_create(cls, filter_by, default_kwargs=None, commit=True):
"""Fetches one record by filter criteria and creates one with defaults if missing"""
<|body_0|>
def update_or_create(cls, filter_by, update_kwargs=None, commit=True):
"""Fetches one rec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpsertMixin:
def get_or_create(cls, filter_by, default_kwargs=None, commit=True):
"""Fetches one record by filter criteria and creates one with defaults if missing"""
instance = db.session.query(cls).filter_by(**filter_by).with_for_update().first()
if instance:
return (inst... | the_stack_v2_python_sparse | app/database.py | openstate/open-rechtspraak | train | 3 | |
7ee5429d3a214d3f6300ee24185e9ed7131c99c0 | [
"docs = test_corpus.get_documents()\nself.__result = result\nself.__true = []\nfor clazz in range(len(docs)):\n for document in docs[clazz]:\n if clazz == class_index:\n self.__true.append(1)\n else:\n self.__true.append(-1)\nself.__positives = 0\nfor item in range(len(result)... | <|body_start_0|>
docs = test_corpus.get_documents()
self.__result = result
self.__true = []
for clazz in range(len(docs)):
for document in docs[clazz]:
if clazz == class_index:
self.__true.append(1)
else:
... | Implements IR evaluation tools (Precision, Recall and F1). | Measures | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Measures:
"""Implements IR evaluation tools (Precision, Recall and F1)."""
def __init__(self, test_corpus, class_index, result):
"""@param test_corpus: Corpus. Test corpus @param class_index: int. Index of 'true' (or positive) class @param result: list. Contains the classification re... | stack_v2_sparse_classes_36k_train_002373 | 2,358 | no_license | [
{
"docstring": "@param test_corpus: Corpus. Test corpus @param class_index: int. Index of 'true' (or positive) class @param result: list. Contains the classification results on the test corpus",
"name": "__init__",
"signature": "def __init__(self, test_corpus, class_index, result)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_013019 | Implement the Python class `Measures` described below.
Class description:
Implements IR evaluation tools (Precision, Recall and F1).
Method signatures and docstrings:
- def __init__(self, test_corpus, class_index, result): @param test_corpus: Corpus. Test corpus @param class_index: int. Index of 'true' (or positive) ... | Implement the Python class `Measures` described below.
Class description:
Implements IR evaluation tools (Precision, Recall and F1).
Method signatures and docstrings:
- def __init__(self, test_corpus, class_index, result): @param test_corpus: Corpus. Test corpus @param class_index: int. Index of 'true' (or positive) ... | bcd3fbd22dc16ff2476597cfd03ef80d91d5a56c | <|skeleton|>
class Measures:
"""Implements IR evaluation tools (Precision, Recall and F1)."""
def __init__(self, test_corpus, class_index, result):
"""@param test_corpus: Corpus. Test corpus @param class_index: int. Index of 'true' (or positive) class @param result: list. Contains the classification re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Measures:
"""Implements IR evaluation tools (Precision, Recall and F1)."""
def __init__(self, test_corpus, class_index, result):
"""@param test_corpus: Corpus. Test corpus @param class_index: int. Index of 'true' (or positive) class @param result: list. Contains the classification results on the ... | the_stack_v2_python_sparse | src/tclass/util/metrics.py | htaunay/TClass | train | 1 |
a52aab58d71f16daf3a946b0ef0b0fb7583617d7 | [
"self.count, self.result = (0, 0)\ntry:\n self.get_kth_smallest(root, k)\nexcept:\n return self.result",
"if root:\n self.get_kth_smallest(root.left, k)\n self.count += 1\n if self.count == k:\n self.result = root.key\n raise Exception()\n self.get_kth_smallest(root.right, k)"
] | <|body_start_0|>
self.count, self.result = (0, 0)
try:
self.get_kth_smallest(root, k)
except:
return self.result
<|end_body_0|>
<|body_start_1|>
if root:
self.get_kth_smallest(root.left, k)
self.count += 1
if self.count == k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
"""Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node"""
<|body_0|>
def get_kth_smallest(self, r... | stack_v2_sparse_classes_36k_train_002374 | 2,127 | no_license | [
{
"docstring": "Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node",
"name": "kth_smallest",
"signature": "def kth_smallest(self, root: TreeNode, k: int) -> int"
},
{
"docstring": "A... | 2 | stack_v2_sparse_classes_30k_val_001055 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kth_smallest(self, root: TreeNode, k: int) -> int: Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kth_smallest(self, root: TreeNode, k: int) -> int: Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space:... | de685690745a5a322e6233e1a3fd10a2d9539076 | <|skeleton|>
class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
"""Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node"""
<|body_0|>
def get_kth_smallest(self, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kth_smallest(self, root: TreeNode, k: int) -> int:
"""Returns the kth smallest node in a BST. :param root: root of tree :param k: number k :Time: O(H) H = height of tree :Space: O(H) :return: value of kth smallest node"""
self.count, self.result = (0, 0)
try:
... | the_stack_v2_python_sparse | questions/trees_graphs/BSTKthSmallest.py | aksh0001/algorithms-journal | train | 17 | |
153b74ffcded938ece7d9914e960907266babe8e | [
"self.coefs = {}\npass_args = {}\nif kwargs is not None:\n for key, value in kwargs.items():\n if key[0].lower() == 'a':\n idx = int(key[1:])\n self.coefs[idx] = value\n else:\n pass_args[key] = value\nsuper().__init__(**pass_args)",
"self.phase = e.zeros([self.sa... | <|body_start_0|>
self.coefs = {}
pass_args = {}
if kwargs is not None:
for key, value in kwargs.items():
if key[0].lower() == 'a':
idx = int(key[1:])
self.coefs[idx] = value
else:
pass_args[ke... | Base class with 1D Q polynomial logic. | QPolySag1D | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QPolySag1D:
"""Base class with 1D Q polynomial logic."""
def __init__(self, *args, **kwargs):
"""Initialize a new QBFS instance."""
<|body_0|>
def build(self):
"""Use the aspheric coefficients stored in this class instance to build a sag model. Returns ------- se... | stack_v2_sparse_classes_36k_train_002375 | 20,825 | permissive | [
{
"docstring": "Initialize a new QBFS instance.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Use the aspheric coefficients stored in this class instance to build a sag model. Returns ------- self : `QPolySag1D` this QPolySag1D instance`",
"name"... | 2 | stack_v2_sparse_classes_30k_train_006282 | Implement the Python class `QPolySag1D` described below.
Class description:
Base class with 1D Q polynomial logic.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize a new QBFS instance.
- def build(self): Use the aspheric coefficients stored in this class instance to build a sag mode... | Implement the Python class `QPolySag1D` described below.
Class description:
Base class with 1D Q polynomial logic.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize a new QBFS instance.
- def build(self): Use the aspheric coefficients stored in this class instance to build a sag mode... | 01fb5572b7a1ac5e3ee095f89f133166050af719 | <|skeleton|>
class QPolySag1D:
"""Base class with 1D Q polynomial logic."""
def __init__(self, *args, **kwargs):
"""Initialize a new QBFS instance."""
<|body_0|>
def build(self):
"""Use the aspheric coefficients stored in this class instance to build a sag model. Returns ------- se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QPolySag1D:
"""Base class with 1D Q polynomial logic."""
def __init__(self, *args, **kwargs):
"""Initialize a new QBFS instance."""
self.coefs = {}
pass_args = {}
if kwargs is not None:
for key, value in kwargs.items():
if key[0].lower() == 'a':... | the_stack_v2_python_sparse | prysm/qpoly.py | JakobSilbermann/prysm | train | 0 |
bcff4dc1adbac515bbe488ee9febbf6f2393d060 | [
"N = len(height)\nif N <= 1:\n return 0\nres = 0\nMax = max(height)\nfor level in range(1, Max + 1):\n left = 0\n right = N - 1\n while height[left] < level or height[right] < level:\n left += height[left] < level\n right -= height[right] < level\n for i in range(left, right + 1):\n ... | <|body_start_0|>
N = len(height)
if N <= 1:
return 0
res = 0
Max = max(height)
for level in range(1, Max + 1):
left = 0
right = N - 1
while height[left] < level or height[right] < level:
left += height[left] < level
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
"""按照行 这个方法会超时 :param height: :return:"""
<|body_0|>
def trap2(self, height):
"""使用双指针,记录最大值 :param height: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
N = len(height)
if N <= 1:
ret... | stack_v2_sparse_classes_36k_train_002376 | 1,358 | no_license | [
{
"docstring": "按照行 这个方法会超时 :param height: :return:",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": "使用双指针,记录最大值 :param height: :return:",
"name": "trap2",
"signature": "def trap2(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019259 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): 按照行 这个方法会超时 :param height: :return:
- def trap2(self, height): 使用双指针,记录最大值 :param height: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): 按照行 这个方法会超时 :param height: :return:
- def trap2(self, height): 使用双指针,记录最大值 :param height: :return:
<|skeleton|>
class Solution:
def trap(self, heigh... | d8ad2da776066ac3fd99f246cb2b41a921c21a73 | <|skeleton|>
class Solution:
def trap(self, height):
"""按照行 这个方法会超时 :param height: :return:"""
<|body_0|>
def trap2(self, height):
"""使用双指针,记录最大值 :param height: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
"""按照行 这个方法会超时 :param height: :return:"""
N = len(height)
if N <= 1:
return 0
res = 0
Max = max(height)
for level in range(1, Max + 1):
left = 0
right = N - 1
while height[left] < ... | the_stack_v2_python_sparse | Python/LeetCode/LeetCode42trap.py | 540928898/LeetCodeMe | train | 0 | |
54d6176378b1eb8ffbaccc3418d212a6be389e56 | [
"def backtrack(nums, temp_list, result):\n if len(temp_list) == len(nums):\n result.append(list(temp_list))\n else:\n for num in nums:\n if num not in temp_list:\n temp_list.append(num)\n backtrack(nums, temp_list, result)\n temp_list.pop()... | <|body_start_0|>
def backtrack(nums, temp_list, result):
if len(temp_list) == len(nums):
result.append(list(temp_list))
else:
for num in nums:
if num not in temp_list:
temp_list.append(num)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permute_2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def backtrack(nums, temp_li... | stack_v2_sparse_classes_36k_train_002377 | 1,439 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute_2",
"signature": "def permute_2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008833 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 9d9e0c08992ef7dbd9ac517821faa9de17f49b0e | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permute_2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
def backtrack(nums, temp_list, result):
if len(temp_list) == len(nums):
result.append(list(temp_list))
else:
for num in nums:
if nu... | the_stack_v2_python_sparse | 046-permutations.py | floydchenchen/leetcode | train | 0 | |
1acb9ee43170906368aa3965c522da2fa4d9435b | [
"self.constants = {self.nDimensions: nDimensions}\nself.constants.update({'k_' + str(j): k[j] for j in range(self.constants[self.nDimensions])})\nself.constants.update({'r_shift' + str(j): r_shift[j] for j in range(self.constants[self.nDimensions])})\nself.constants.update({'V_off_' + str(j): Voff[j] for j in range... | <|body_start_0|>
self.constants = {self.nDimensions: nDimensions}
self.constants.update({'k_' + str(j): k[j] for j in range(self.constants[self.nDimensions])})
self.constants.update({'r_shift' + str(j): r_shift[j] for j in range(self.constants[self.nDimensions])})
self.constants.update({... | ND harmonic oscillator potential | harmonicOscillatorPotential | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class harmonicOscillatorPotential:
"""ND harmonic oscillator potential"""
def __init__(self, k: np.array=np.array([1.0, 1.0, 1.0]), r_shift: np.array=np.array([0.0, 0.0, 0.0]), Voff: np.array=np.array([0.0, 0.0, 0.0]), nDimensions: int=3):
"""__init__ Constructs an harmonic Oscillator with... | stack_v2_sparse_classes_36k_train_002378 | 24,269 | permissive | [
{
"docstring": "__init__ Constructs an harmonic Oscillator with an on runtime defined dimensionality. Parameters ---------- k: List[float], optional force constants, as many as nDim, defaults to [1.0, 1.0, 1.0] x_shift: List[float], optional shift of the minimum in the x Axis, as many as nDim, defaults to [0.0,... | 2 | stack_v2_sparse_classes_30k_train_011940 | Implement the Python class `harmonicOscillatorPotential` described below.
Class description:
ND harmonic oscillator potential
Method signatures and docstrings:
- def __init__(self, k: np.array=np.array([1.0, 1.0, 1.0]), r_shift: np.array=np.array([0.0, 0.0, 0.0]), Voff: np.array=np.array([0.0, 0.0, 0.0]), nDimensions... | Implement the Python class `harmonicOscillatorPotential` described below.
Class description:
ND harmonic oscillator potential
Method signatures and docstrings:
- def __init__(self, k: np.array=np.array([1.0, 1.0, 1.0]), r_shift: np.array=np.array([0.0, 0.0, 0.0]), Voff: np.array=np.array([0.0, 0.0, 0.0]), nDimensions... | f8f9eb9381498d6cba21182ebfb5ee6eca2a3310 | <|skeleton|>
class harmonicOscillatorPotential:
"""ND harmonic oscillator potential"""
def __init__(self, k: np.array=np.array([1.0, 1.0, 1.0]), r_shift: np.array=np.array([0.0, 0.0, 0.0]), Voff: np.array=np.array([0.0, 0.0, 0.0]), nDimensions: int=3):
"""__init__ Constructs an harmonic Oscillator with... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class harmonicOscillatorPotential:
"""ND harmonic oscillator potential"""
def __init__(self, k: np.array=np.array([1.0, 1.0, 1.0]), r_shift: np.array=np.array([0.0, 0.0, 0.0]), Voff: np.array=np.array([0.0, 0.0, 0.0]), nDimensions: int=3):
"""__init__ Constructs an harmonic Oscillator with an on runtim... | the_stack_v2_python_sparse | ensembler/potentials/ND.py | Bio-Otto/Ensembler | train | 0 |
a744487c92965c81657725718f8310d99898b5a5 | [
"super().setUp()\nconn = get_conn(verify=False)\nfor index in conn.indices.get_alias().keys():\n if index.startswith(settings.OPENSEARCH_INDEX):\n conn.indices.delete(index)\nfrom search import indexing_api\nindexing_api._CONN = None\nindexing_api._CONN_VERIFIED = False",
"with self.assertRaises(Reindex... | <|body_start_0|>
super().setUp()
conn = get_conn(verify=False)
for index in conn.indices.get_alias().keys():
if index.startswith(settings.OPENSEARCH_INDEX):
conn.indices.delete(index)
from search import indexing_api
indexing_api._CONN = None
in... | Tests for get_conn | GetConnTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
<|body_0|>
def test_no_index(self):
"""Test that an error is raised if we don't have an index"""
<|body_1|>
def test_no_index_not_default(self):
"""Test tha... | stack_v2_sparse_classes_36k_train_002379 | 42,701 | permissive | [
{
"docstring": "Start without any index",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that an error is raised if we don't have an index",
"name": "test_no_index",
"signature": "def test_no_index(self)"
},
{
"docstring": "Test that an error is raised if... | 4 | null | Implement the Python class `GetConnTests` described below.
Class description:
Tests for get_conn
Method signatures and docstrings:
- def setUp(self): Start without any index
- def test_no_index(self): Test that an error is raised if we don't have an index
- def test_no_index_not_default(self): Test that an error is r... | Implement the Python class `GetConnTests` described below.
Class description:
Tests for get_conn
Method signatures and docstrings:
- def setUp(self): Start without any index
- def test_no_index(self): Test that an error is raised if we don't have an index
- def test_no_index_not_default(self): Test that an error is r... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
<|body_0|>
def test_no_index(self):
"""Test that an error is raised if we don't have an index"""
<|body_1|>
def test_no_index_not_default(self):
"""Test tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
super().setUp()
conn = get_conn(verify=False)
for index in conn.indices.get_alias().keys():
if index.startswith(settings.OPENSEARCH_INDEX):
conn.indices.delete... | the_stack_v2_python_sparse | search/indexing_api_test.py | mitodl/micromasters | train | 35 |
b922df153c49f845f03d8f14b6396bd3aed4da6e | [
"if not lists:\n return None\nfrom heapq import heappush, heappop\nheap = []\ntmp = 0\nfor n in lists:\n if n:\n heappush(heap, (n.val, (tmp, n)))\n tmp += 1\nif not heap:\n return None\nhead = cur = ListNode(None)\nwhile heap:\n v, (_, n) = heappop(heap)\n cur.next = n\n cur = cur.n... | <|body_start_0|>
if not lists:
return None
from heapq import heappush, heappop
heap = []
tmp = 0
for n in lists:
if n:
heappush(heap, (n.val, (tmp, n)))
tmp += 1
if not heap:
return None
head = cu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
"""08/04/2018 22:06"""
<|body_0|>
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
"""Time complexity: O(n*m*n) Space complexity: O(n)"""
<|body_1|>
def mergeKLists(self, lists: List[Op... | stack_v2_sparse_classes_36k_train_002380 | 3,955 | no_license | [
{
"docstring": "08/04/2018 22:06",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": "Time complexity: O(n*m*n) Space complexity: O(n)",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]"
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): 08/04/2018 22:06
- def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: Time complexity: O(n*m*n) Space complexity: O(n)
- ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): 08/04/2018 22:06
- def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: Time complexity: O(n*m*n) Space complexity: O(n)
- ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
"""08/04/2018 22:06"""
<|body_0|>
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
"""Time complexity: O(n*m*n) Space complexity: O(n)"""
<|body_1|>
def mergeKLists(self, lists: List[Op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
"""08/04/2018 22:06"""
if not lists:
return None
from heapq import heappush, heappop
heap = []
tmp = 0
for n in lists:
if n:
heappush(heap, (n.val, (tmp, n)))
tmp += ... | the_stack_v2_python_sparse | leetcode/solved/23_Merge_k_Sorted_Lists/solution.py | sungminoh/algorithms | train | 0 | |
dc2d63c1db9724acd31993330852deba674cd983 | [
"m = 'Setting %s, %s identify to %s' % (self.name, self.address, value)\nq = self._build_command(self.address, 'pulse', value)\nself.info(m)\nself.ask(q)",
"if typetag == 'pressure':\n s = 'PR1'\nelif typetag == 'filament':\n s = 'FS'\nelif typetag == 'setpoint_value':\n s = 'SP%i' % setpointindex\nelif ... | <|body_start_0|>
m = 'Setting %s, %s identify to %s' % (self.name, self.address, value)
q = self._build_command(self.address, 'pulse', value)
self.info(m)
self.ask(q)
<|end_body_0|>
<|body_start_1|>
if typetag == 'pressure':
s = 'PR1'
elif typetag == 'filamen... | BaseMKSGauge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseMKSGauge:
def set_transducer_identify(self, value):
"""sends command to transducer to toggle LED pulse @type value: C{str} @param value: ON or OFF @see: L{MKSComs}"""
<|body_0|>
def _build_query(self, addr, typetag, setpointindex=1):
"""build a query @type addr: ... | stack_v2_sparse_classes_36k_train_002381 | 5,075 | permissive | [
{
"docstring": "sends command to transducer to toggle LED pulse @type value: C{str} @param value: ON or OFF @see: L{MKSComs}",
"name": "set_transducer_identify",
"signature": "def set_transducer_identify(self, value)"
},
{
"docstring": "build a query @type addr: C{s} @param addr: RS-485 address ... | 4 | null | Implement the Python class `BaseMKSGauge` described below.
Class description:
Implement the BaseMKSGauge class.
Method signatures and docstrings:
- def set_transducer_identify(self, value): sends command to transducer to toggle LED pulse @type value: C{str} @param value: ON or OFF @see: L{MKSComs}
- def _build_query(... | Implement the Python class `BaseMKSGauge` described below.
Class description:
Implement the BaseMKSGauge class.
Method signatures and docstrings:
- def set_transducer_identify(self, value): sends command to transducer to toggle LED pulse @type value: C{str} @param value: ON or OFF @see: L{MKSComs}
- def _build_query(... | 8cfc8085393ace2aee6b98d36bfd6fba0bcb41c6 | <|skeleton|>
class BaseMKSGauge:
def set_transducer_identify(self, value):
"""sends command to transducer to toggle LED pulse @type value: C{str} @param value: ON or OFF @see: L{MKSComs}"""
<|body_0|>
def _build_query(self, addr, typetag, setpointindex=1):
"""build a query @type addr: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseMKSGauge:
def set_transducer_identify(self, value):
"""sends command to transducer to toggle LED pulse @type value: C{str} @param value: ON or OFF @see: L{MKSComs}"""
m = 'Setting %s, %s identify to %s' % (self.name, self.address, value)
q = self._build_command(self.address, 'pulse... | the_stack_v2_python_sparse | pychron/hardware/gauges/mks/base_mks_gauge.py | NMGRL/pychron | train | 38 | |
3f7f3dfdef9347112e6a925cf4a6e1aef9642d44 | [
"if not number:\n raise ValueError('\"number\" must not be empty.')\ntry:\n return cls.objects.create(phone_number=number)\nexcept IntegrityError:\n return None",
"if not number:\n raise ValueError('\"number\" must not be empty.')\nnumber = cls.objects.filter(phone_number=number).only('id')\nif not nu... | <|body_start_0|>
if not number:
raise ValueError('"number" must not be empty.')
try:
return cls.objects.create(phone_number=number)
except IntegrityError:
return None
<|end_body_0|>
<|body_start_1|>
if not number:
raise ValueError('"number... | SuspiciousPhoneNumbers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuspiciousPhoneNumbers:
def add(cls, number):
"""Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present i... | stack_v2_sparse_classes_36k_train_002382 | 3,941 | no_license | [
{
"docstring": "Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present in the ban. :raises: ValueError - if \"number\" is empty."... | 3 | null | Implement the Python class `SuspiciousPhoneNumbers` described below.
Class description:
Implement the SuspiciousPhoneNumbers class.
Method signatures and docstrings:
- def add(cls, number): Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns... | Implement the Python class `SuspiciousPhoneNumbers` described below.
Class description:
Implement the SuspiciousPhoneNumbers class.
Method signatures and docstrings:
- def add(cls, number): Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns... | c060941b16c36d258989206f9c2143b5179b4acd | <|skeleton|>
class SuspiciousPhoneNumbers:
def add(cls, number):
"""Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuspiciousPhoneNumbers:
def add(cls, number):
"""Creates and returns new record with banned phone number. :param number: phone number that should be added into the ban. :returns: BannedPhoneNumbers record - if number was successfully added into ban. None - if the number already present in the ban. :ra... | the_stack_v2_python_sparse | core/managing/ban/models.py | HaySayCheese/mappino | train | 0 | |
ebc4265b7bec08003fc3b39970afb794a2f91c94 | [
"size = len(nums)\nif size == 0 or k <= 0:\n return\nk = k % len(nums)\nself.__reverse(nums, 0, size - 1)\nself.__reverse(nums, 0, k - 1)\nself.__reverse(nums, k, size - 1)",
"while index1 < index2:\n nums[index1], nums[index2] = (nums[index2], nums[index1])\n index1 += 1\n index2 -= 1"
] | <|body_start_0|>
size = len(nums)
if size == 0 or k <= 0:
return
k = k % len(nums)
self.__reverse(nums, 0, size - 1)
self.__reverse(nums, 0, k - 1)
self.__reverse(nums, k, size - 1)
<|end_body_0|>
<|body_start_1|>
while index1 < index2:
nu... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def __reverse(self, nums, index1, index2):
"""将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:"""
... | stack_v2_sparse_classes_36k_train_002383 | 1,050 | permissive | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums: List[int], k: int) -> None"
},
{
"docstring": "将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:",
"name": "__reverse",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_000792 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def __reverse(self, nums, index1, index2): 将数组 [index1,index2] 区间内的元素进行... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def __reverse(self, nums, index1, index2): 将数组 [index1,index2] 区间内的元素进行... | baabdb1990fd49ab82a712e121f49c4f68b29459 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def __reverse(self, nums, index1, index2):
"""将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
size = len(nums)
if size == 0 or k <= 0:
return
k = k % len(nums)
self.__reverse(nums, 0, size - 1)
self.__reverse(nums, 0, k - 1... | the_stack_v2_python_sparse | array/Python/0189-rotate-array.py | lemonnader/LeetCode-Solution-Well-Formed | train | 1 | |
0582fe1d0c3100afd8d4baa29f0fbca1dbf47097 | [
"super(GraphNonLocal, self).__init__(activity_regularizer=activity_regularizer, **kwargs)\nself.inter_filters = inter_filters\nself.kernel_initializer = kernel_initializer\nself.bias_initializer = bias_initializer\nself.kernel_regularizer = kernel_regularizer\nself.bias_regularizer = bias_regularizer\nself.activity... | <|body_start_0|>
super(GraphNonLocal, self).__init__(activity_regularizer=activity_regularizer, **kwargs)
self.inter_filters = inter_filters
self.kernel_initializer = kernel_initializer
self.bias_initializer = bias_initializer
self.kernel_regularizer = kernel_regularizer
... | Implements graph non-local layer. Reference: Wang et al. Non-local Neural Networks. https://arxiv.org/pdf/1711.07971.pdf. | GraphNonLocal | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphNonLocal:
"""Implements graph non-local layer. Reference: Wang et al. Non-local Neural Networks. https://arxiv.org/pdf/1711.07971.pdf."""
def __init__(self, inter_filters=None, kernel_initializer='he_normal', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, acti... | stack_v2_sparse_classes_36k_train_002384 | 30,548 | permissive | [
{
"docstring": "Initializer. Args: inter_filters: An integer for the output dimension of the layer. kernel_initializer: Initializer for the kernel weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function for the kernel weights matrix. bias_regularizer: Regulari... | 3 | null | Implement the Python class `GraphNonLocal` described below.
Class description:
Implements graph non-local layer. Reference: Wang et al. Non-local Neural Networks. https://arxiv.org/pdf/1711.07971.pdf.
Method signatures and docstrings:
- def __init__(self, inter_filters=None, kernel_initializer='he_normal', bias_initi... | Implement the Python class `GraphNonLocal` described below.
Class description:
Implements graph non-local layer. Reference: Wang et al. Non-local Neural Networks. https://arxiv.org/pdf/1711.07971.pdf.
Method signatures and docstrings:
- def __init__(self, inter_filters=None, kernel_initializer='he_normal', bias_initi... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class GraphNonLocal:
"""Implements graph non-local layer. Reference: Wang et al. Non-local Neural Networks. https://arxiv.org/pdf/1711.07971.pdf."""
def __init__(self, inter_filters=None, kernel_initializer='he_normal', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, acti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphNonLocal:
"""Implements graph non-local layer. Reference: Wang et al. Non-local Neural Networks. https://arxiv.org/pdf/1711.07971.pdf."""
def __init__(self, inter_filters=None, kernel_initializer='he_normal', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regulari... | the_stack_v2_python_sparse | poem/cv_mim/models.py | Jimmy-INL/google-research | train | 1 |
2571988bd5e306c130bbfce5e690abf08c8a305b | [
"input_specs = {}\nfor level in range(model_id):\n input_specs[str(level + 1)] = tf.TensorShape([1, 128 // 2 ** level, 128 // 2 ** level, 128 // 2 ** level, 1])\nnetwork = decoders.UNet3DDecoder(model_id=model_id, input_specs=input_specs, use_sync_bn=True, use_batch_normalization=True, use_deconvolution=True)\nm... | <|body_start_0|>
input_specs = {}
for level in range(model_id):
input_specs[str(level + 1)] = tf.TensorShape([1, 128 // 2 ** level, 128 // 2 ** level, 128 // 2 ** level, 1])
network = decoders.UNet3DDecoder(model_id=model_id, input_specs=input_specs, use_sync_bn=True, use_batch_norma... | FactoryTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryTest:
def test_unet_3d_decoder_creation(self, model_id):
"""Test creation of UNet 3D decoder."""
<|body_0|>
def test_identity_creation(self):
"""Test creation of identity decoder."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
input_specs = ... | stack_v2_sparse_classes_36k_train_002385 | 3,008 | permissive | [
{
"docstring": "Test creation of UNet 3D decoder.",
"name": "test_unet_3d_decoder_creation",
"signature": "def test_unet_3d_decoder_creation(self, model_id)"
},
{
"docstring": "Test creation of identity decoder.",
"name": "test_identity_creation",
"signature": "def test_identity_creation... | 2 | null | Implement the Python class `FactoryTest` described below.
Class description:
Implement the FactoryTest class.
Method signatures and docstrings:
- def test_unet_3d_decoder_creation(self, model_id): Test creation of UNet 3D decoder.
- def test_identity_creation(self): Test creation of identity decoder. | Implement the Python class `FactoryTest` described below.
Class description:
Implement the FactoryTest class.
Method signatures and docstrings:
- def test_unet_3d_decoder_creation(self, model_id): Test creation of UNet 3D decoder.
- def test_identity_creation(self): Test creation of identity decoder.
<|skeleton|>
cl... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class FactoryTest:
def test_unet_3d_decoder_creation(self, model_id):
"""Test creation of UNet 3D decoder."""
<|body_0|>
def test_identity_creation(self):
"""Test creation of identity decoder."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactoryTest:
def test_unet_3d_decoder_creation(self, model_id):
"""Test creation of UNet 3D decoder."""
input_specs = {}
for level in range(model_id):
input_specs[str(level + 1)] = tf.TensorShape([1, 128 // 2 ** level, 128 // 2 ** level, 128 // 2 ** level, 1])
netwo... | the_stack_v2_python_sparse | official/projects/volumetric_models/modeling/decoders/factory_test.py | jianzhnie/models | train | 2 | |
f0afe8ad841327bbfd24f44be6d8dda3e0623e57 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | CybosPlusProxyServiceServicer | [
"Apache-2.0",
"GPL-1.0-or-later",
"GPL-3.0-or-later",
"GPL-3.0-only",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CybosPlusProxyServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Dispatch(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Property(self, request, context):
"""Missing associat... | stack_v2_sparse_classes_36k_train_002386 | 8,133 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Dispatch",
"signature": "def Dispatch(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Property",
"signature": "def Property(self, request, c... | 4 | null | Implement the Python class `CybosPlusProxyServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Dispatch(self, request, context): Missing associated documentation comment in .proto file.
- def Property(self, request, conte... | Implement the Python class `CybosPlusProxyServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Dispatch(self, request, context): Missing associated documentation comment in .proto file.
- def Property(self, request, conte... | 2d0e5004074f6a7f62c0301ce1a5b7b0f2037204 | <|skeleton|>
class CybosPlusProxyServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Dispatch(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Property(self, request, context):
"""Missing associat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CybosPlusProxyServiceServicer:
"""Missing associated documentation comment in .proto file."""
def Dispatch(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implem... | the_stack_v2_python_sparse | koapy/backend/daishin_cybos_plus/proxy/CybosPlusProxyService_pb2_grpc.py | gomtinQQ/koapy | train | 0 |
8669e0cf3eb4eba231b68600caf3123cc52c6bba | [
"super(MatchingEngine, self).__init__()\nself._logger = logging.getLogger(self.__class__.__name__)\nassert isinstance(matching_strategy, MatchingStrategy), type(matching_strategy)\nself.matching_strategy = matching_strategy",
"assert isinstance(order, Order), type(order)\nnow = time()\nproposed_trades = self.matc... | <|body_start_0|>
super(MatchingEngine, self).__init__()
self._logger = logging.getLogger(self.__class__.__name__)
assert isinstance(matching_strategy, MatchingStrategy), type(matching_strategy)
self.matching_strategy = matching_strategy
<|end_body_0|>
<|body_start_1|>
assert isi... | Matches ticks and orders to the order book | MatchingEngine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchingEngine:
"""Matches ticks and orders to the order book"""
def __init__(self, matching_strategy):
""":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy"""
<|body_0|>
def match_order(self, order):
""":param order: The ord... | stack_v2_sparse_classes_36k_train_002387 | 13,505 | no_license | [
{
"docstring": ":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy",
"name": "__init__",
"signature": "def __init__(self, matching_strategy)"
},
{
"docstring": ":param order: The order to match against :type order: Order :return: The proposed trades :rtype: [... | 2 | stack_v2_sparse_classes_30k_train_016945 | Implement the Python class `MatchingEngine` described below.
Class description:
Matches ticks and orders to the order book
Method signatures and docstrings:
- def __init__(self, matching_strategy): :param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy
- def match_order(self, order): ... | Implement the Python class `MatchingEngine` described below.
Class description:
Matches ticks and orders to the order book
Method signatures and docstrings:
- def __init__(self, matching_strategy): :param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy
- def match_order(self, order): ... | cc4d1c27166d68c39e5c38e77bb70093f34e19e5 | <|skeleton|>
class MatchingEngine:
"""Matches ticks and orders to the order book"""
def __init__(self, matching_strategy):
""":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy"""
<|body_0|>
def match_order(self, order):
""":param order: The ord... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatchingEngine:
"""Matches ticks and orders to the order book"""
def __init__(self, matching_strategy):
""":param matching_strategy: The strategy to use :type matching_strategy: MatchingStrategy"""
super(MatchingEngine, self).__init__()
self._logger = logging.getLogger(self.__clas... | the_stack_v2_python_sparse | market/core/matching_engine.py | devos50/decentralized-market | train | 0 |
135e3bb45694183e0d5d7638d2502879384ebd1d | [
"for integer, numeral in self.known_values:\n result = roman_numeral.to_roman(integer)\n self.assertEqual(numeral, result)",
"for integer, numeral in self.known_values:\n result = roman_numeral.from_roman(numeral)\n self.assertEqual(integer, result)"
] | <|body_start_0|>
for integer, numeral in self.known_values:
result = roman_numeral.to_roman(integer)
self.assertEqual(numeral, result)
<|end_body_0|>
<|body_start_1|>
for integer, numeral in self.known_values:
result = roman_numeral.from_roman(numeral)
se... | KnownValues | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnownValues:
def test_to_roman_known_values(self):
"""to_roman should give known result with known input"""
<|body_0|>
def test_from_roman_known_values(self):
"""from_roman should give known result with known input"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_002388 | 4,436 | permissive | [
{
"docstring": "to_roman should give known result with known input",
"name": "test_to_roman_known_values",
"signature": "def test_to_roman_known_values(self)"
},
{
"docstring": "from_roman should give known result with known input",
"name": "test_from_roman_known_values",
"signature": "d... | 2 | null | Implement the Python class `KnownValues` described below.
Class description:
Implement the KnownValues class.
Method signatures and docstrings:
- def test_to_roman_known_values(self): to_roman should give known result with known input
- def test_from_roman_known_values(self): from_roman should give known result with ... | Implement the Python class `KnownValues` described below.
Class description:
Implement the KnownValues class.
Method signatures and docstrings:
- def test_to_roman_known_values(self): to_roman should give known result with known input
- def test_from_roman_known_values(self): from_roman should give known result with ... | f6697489389406ec00e0583ffa9eb738bdbd650c | <|skeleton|>
class KnownValues:
def test_to_roman_known_values(self):
"""to_roman should give known result with known input"""
<|body_0|>
def test_from_roman_known_values(self):
"""from_roman should give known result with known input"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KnownValues:
def test_to_roman_known_values(self):
"""to_roman should give known result with known input"""
for integer, numeral in self.known_values:
result = roman_numeral.to_roman(integer)
self.assertEqual(numeral, result)
def test_from_roman_known_values(self):... | the_stack_v2_python_sparse | python/Oct22/test-roman.py | souradeepta/leetcode-practice | train | 1 | |
8fa4f5b90104a88bda3272b55b8b416b5244c9dc | [
"json_request = request.data\nsearch_text = json_request.get('search_text', None)\ntry:\n limit = int(json_request.get('limit', 10))\nexcept ValueError:\n raise InvalidParameterException('Limit request parameter is not a valid, positive integer')\nif not search_text:\n raise InvalidParameterException('Miss... | <|body_start_0|>
json_request = request.data
search_text = json_request.get('search_text', None)
try:
limit = int(json_request.get('limit', 10))
except ValueError:
raise InvalidParameterException('Limit request parameter is not a valid, positive integer')
... | BaseAutocompleteViewSet | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseAutocompleteViewSet:
def get_request_payload(request):
"""Retrieves all the request attributes needed for the autocomplete endpoints. Current attributes: * search_text : string to search for * limit : number of items to return"""
<|body_0|>
def agency_autocomplete(self, ... | stack_v2_sparse_classes_36k_train_002389 | 8,374 | permissive | [
{
"docstring": "Retrieves all the request attributes needed for the autocomplete endpoints. Current attributes: * search_text : string to search for * limit : number of items to return",
"name": "get_request_payload",
"signature": "def get_request_payload(request)"
},
{
"docstring": "Search by s... | 2 | null | Implement the Python class `BaseAutocompleteViewSet` described below.
Class description:
Implement the BaseAutocompleteViewSet class.
Method signatures and docstrings:
- def get_request_payload(request): Retrieves all the request attributes needed for the autocomplete endpoints. Current attributes: * search_text : st... | Implement the Python class `BaseAutocompleteViewSet` described below.
Class description:
Implement the BaseAutocompleteViewSet class.
Method signatures and docstrings:
- def get_request_payload(request): Retrieves all the request attributes needed for the autocomplete endpoints. Current attributes: * search_text : st... | 38f920438697930ae3ac57bbcaae9034877d8fb7 | <|skeleton|>
class BaseAutocompleteViewSet:
def get_request_payload(request):
"""Retrieves all the request attributes needed for the autocomplete endpoints. Current attributes: * search_text : string to search for * limit : number of items to return"""
<|body_0|>
def agency_autocomplete(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseAutocompleteViewSet:
def get_request_payload(request):
"""Retrieves all the request attributes needed for the autocomplete endpoints. Current attributes: * search_text : string to search for * limit : number of items to return"""
json_request = request.data
search_text = json_reque... | the_stack_v2_python_sparse | usaspending_api/references/v2/views/autocomplete.py | fedspendingtransparency/usaspending-api | train | 276 | |
727f70fb22f30954acfd58df6e8a17a5c806acab | [
"if self.action in ['list', 'retrieve']:\n permission_classes = [permissions.UserIsAuthenticated]\nelif self.action in ['partial_update', 'update']:\n permission_classes = [permissions.UserIsAuthenticated & permissions.IsUserOrganizationAdmin]\nelif self.action in ['whoami']:\n permission_classes = []\nels... | <|body_start_0|>
if self.action in ['list', 'retrieve']:
permission_classes = [permissions.UserIsAuthenticated]
elif self.action in ['partial_update', 'update']:
permission_classes = [permissions.UserIsAuthenticated & permissions.IsUserOrganizationAdmin]
elif self.action ... | ViewSet for all user-related interactions. | UserViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
"""ViewSet for all user-related interactions."""
def get_permissions(self):
"""Manage permissions for all the endpoint actions."""
<|body_0|>
def get_queryset(self):
"""Redefine the queryset to use based on the current action. For list, retrieve, upd... | stack_v2_sparse_classes_36k_train_002390 | 8,277 | permissive | [
{
"docstring": "Manage permissions for all the endpoint actions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Redefine the queryset to use based on the current action. For list, retrieve, update, it returns only the user belonging to the organizations ... | 4 | null | Implement the Python class `UserViewSet` described below.
Class description:
ViewSet for all user-related interactions.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for all the endpoint actions.
- def get_queryset(self): Redefine the queryset to use based on the current action. Fo... | Implement the Python class `UserViewSet` described below.
Class description:
ViewSet for all user-related interactions.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for all the endpoint actions.
- def get_queryset(self): Redefine the queryset to use based on the current action. Fo... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class UserViewSet:
"""ViewSet for all user-related interactions."""
def get_permissions(self):
"""Manage permissions for all the endpoint actions."""
<|body_0|>
def get_queryset(self):
"""Redefine the queryset to use based on the current action. For list, retrieve, upd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserViewSet:
"""ViewSet for all user-related interactions."""
def get_permissions(self):
"""Manage permissions for all the endpoint actions."""
if self.action in ['list', 'retrieve']:
permission_classes = [permissions.UserIsAuthenticated]
elif self.action in ['partial_... | the_stack_v2_python_sparse | src/backend/marsha/core/api/account.py | openfun/marsha | train | 92 |
77931276be47dbd7576f68f68332cb06c61dd88a | [
"re = OpenYDTReq(openYDTLogin).carInOut(send_data['parkCode'], send_data['carNum'], 0)\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = Information(userLogin).intelligenceCheckCarOut(send_data['parkName'])\nresult = re['status']\nAssertions().assert_text(result, expect['cleanC... | <|body_start_0|>
re = OpenYDTReq(openYDTLogin).carInOut(send_data['parkCode'], send_data['carNum'], 0)
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = Information(userLogin).intelligenceCheckCarOut(send_data['parkName'])
... | 按时间智能盘点,在在场车辆中查看不到该盘点车辆,在异常进场中可以查看到该车辆 | TestVemsIntelligenceCleanCarByTime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVemsIntelligenceCleanCarByTime:
"""按时间智能盘点,在在场车辆中查看不到该盘点车辆,在异常进场中可以查看到该车辆"""
def test_mockCarIn(self, openYDTLogin, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_intelligenceCheckCarOut(self, userLogin, send_data, expect):
"""选择一条进行批量盘点"""
<|bo... | stack_v2_sparse_classes_36k_train_002391 | 2,090 | no_license | [
{
"docstring": "模拟车辆进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, openYDTLogin, send_data, expect)"
},
{
"docstring": "选择一条进行批量盘点",
"name": "test_intelligenceCheckCarOut",
"signature": "def test_intelligenceCheckCarOut(self, userLogin, send_data, expect)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_014534 | Implement the Python class `TestVemsIntelligenceCleanCarByTime` described below.
Class description:
按时间智能盘点,在在场车辆中查看不到该盘点车辆,在异常进场中可以查看到该车辆
Method signatures and docstrings:
- def test_mockCarIn(self, openYDTLogin, send_data, expect): 模拟车辆进场
- def test_intelligenceCheckCarOut(self, userLogin, send_data, expect): 选择一条进... | Implement the Python class `TestVemsIntelligenceCleanCarByTime` described below.
Class description:
按时间智能盘点,在在场车辆中查看不到该盘点车辆,在异常进场中可以查看到该车辆
Method signatures and docstrings:
- def test_mockCarIn(self, openYDTLogin, send_data, expect): 模拟车辆进场
- def test_intelligenceCheckCarOut(self, userLogin, send_data, expect): 选择一条进... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestVemsIntelligenceCleanCarByTime:
"""按时间智能盘点,在在场车辆中查看不到该盘点车辆,在异常进场中可以查看到该车辆"""
def test_mockCarIn(self, openYDTLogin, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_intelligenceCheckCarOut(self, userLogin, send_data, expect):
"""选择一条进行批量盘点"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestVemsIntelligenceCleanCarByTime:
"""按时间智能盘点,在在场车辆中查看不到该盘点车辆,在异常进场中可以查看到该车辆"""
def test_mockCarIn(self, openYDTLogin, send_data, expect):
"""模拟车辆进场"""
re = OpenYDTReq(openYDTLogin).carInOut(send_data['parkCode'], send_data['carNum'], 0)
result = re
Assertions().assert_in... | the_stack_v2_python_sparse | test_suite/informationSearch/carNumSearch/test_vemsIntelligenceCleanCarByTime.py | oyebino/pomp_api | train | 1 |
48966475e1d1fa8435d560a77c1235ed4d73ef1c | [
"super().__init__(experiment_name, train_func, **kwargs)\nself.end_train_func = end_train_func\nself.delay = True",
"if isinstance(models, Recorder):\n models = [models]\nif end_train_func is None:\n end_train_func = self.end_train_func\nif experiment_name is None:\n experiment_name = self.experiment_nam... | <|body_start_0|>
super().__init__(experiment_name, train_func, **kwargs)
self.end_train_func = end_train_func
self.delay = True
<|end_body_0|>
<|body_start_1|>
if isinstance(models, Recorder):
models = [models]
if end_train_func is None:
end_train_func = ... | A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting. | DelayTrainerR | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayTrainerR:
"""A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting."""
def __init__(self, experiment_name: str=None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs):
... | stack_v2_sparse_classes_36k_train_002392 | 22,767 | permissive | [
{
"docstring": "Init TrainerRM. Args: experiment_name (str): the default name of experiment. train_func (Callable, optional): default train method. Defaults to `begin_task_train`. end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`.",
"name": "__init__",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_015739 | Implement the Python class `DelayTrainerR` described below.
Class description:
A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting.
Method signatures and docstrings:
- def __init__(self, experiment_name: str=None, tra... | Implement the Python class `DelayTrainerR` described below.
Class description:
A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting.
Method signatures and docstrings:
- def __init__(self, experiment_name: str=None, tra... | 4c30e5827b74bcc45f14cf3ae0c1715459ed09ae | <|skeleton|>
class DelayTrainerR:
"""A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting."""
def __init__(self, experiment_name: str=None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelayTrainerR:
"""A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting."""
def __init__(self, experiment_name: str=None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs):
"""In... | the_stack_v2_python_sparse | qlib/model/trainer.py | microsoft/qlib | train | 12,822 |
d04eaae615d3603073fb468d5b5dd19e2eb0fe89 | [
"if not circuit.instructions:\n return ''\ncircuit_qubits = circuit.qubits\ncircuit_qubits.sort()\ny_axis_width = len(str(int(max(circuit_qubits))))\ny_axis_str = '{0:{width}} : |\\n'.format('T', width=y_axis_width + 1)\nfor qubit in circuit_qubits:\n y_axis_str += '{0:{width}}\\n'.format(' ', width=y_axis_wi... | <|body_start_0|>
if not circuit.instructions:
return ''
circuit_qubits = circuit.qubits
circuit_qubits.sort()
y_axis_width = len(str(int(max(circuit_qubits))))
y_axis_str = '{0:{width}} : |\n'.format('T', width=y_axis_width + 1)
for qubit in circuit_qubits:
... | Builds ASCII string circuit diagrams. | AsciiCircuitDiagram | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsciiCircuitDiagram:
"""Builds ASCII string circuit diagrams."""
def build_diagram(circuit) -> str:
"""Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit for which to build a diagram. Returns: str: ASCII string circuit diagram."""
<|body_0|>
def _asc... | stack_v2_sparse_classes_36k_train_002393 | 7,014 | permissive | [
{
"docstring": "Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit for which to build a diagram. Returns: str: ASCII string circuit diagram.",
"name": "build_diagram",
"signature": "def build_diagram(circuit) -> str"
},
{
"docstring": "Group instructions in a moment for ASCI... | 4 | stack_v2_sparse_classes_30k_train_011298 | Implement the Python class `AsciiCircuitDiagram` described below.
Class description:
Builds ASCII string circuit diagrams.
Method signatures and docstrings:
- def build_diagram(circuit) -> str: Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit for which to build a diagram. Returns: str: ASCII st... | Implement the Python class `AsciiCircuitDiagram` described below.
Class description:
Builds ASCII string circuit diagrams.
Method signatures and docstrings:
- def build_diagram(circuit) -> str: Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit for which to build a diagram. Returns: str: ASCII st... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class AsciiCircuitDiagram:
"""Builds ASCII string circuit diagrams."""
def build_diagram(circuit) -> str:
"""Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit for which to build a diagram. Returns: str: ASCII string circuit diagram."""
<|body_0|>
def _asc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsciiCircuitDiagram:
"""Builds ASCII string circuit diagrams."""
def build_diagram(circuit) -> str:
"""Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit for which to build a diagram. Returns: str: ASCII string circuit diagram."""
if not circuit.instructions:
... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/amazon-braket-sdk-python/amazon-braket-sdk-python#44/after/ascii_circuit_diagram.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
dab66747f99efec64d74c1cede6f186d34234b7c | [
"rows = len(grid)\ncols = len(grid[0])\n\ndef isValid(i, j, marked):\n return i >= 0 and i < rows and (j >= 0) and (j < cols) and (grid[i][j] == 1) and (marked[i][j] == False)\narea = [0]\n\ndef dfs(i, j, marked):\n if not isValid(i, j, marked):\n return\n marked[i][j] = True\n area[0] += 1\n ... | <|body_start_0|>
rows = len(grid)
cols = len(grid[0])
def isValid(i, j, marked):
return i >= 0 and i < rows and (j >= 0) and (j < cols) and (grid[i][j] == 1) and (marked[i][j] == False)
area = [0]
def dfs(i, j, marked):
if not isValid(i, j, marked):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def largestIsland2(self, grid):
"""union find"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rows = len(grid)
cols = len(grid[0])
def... | stack_v2_sparse_classes_36k_train_002394 | 3,884 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "largestIsland",
"signature": "def largestIsland(self, grid)"
},
{
"docstring": "union find",
"name": "largestIsland2",
"signature": "def largestIsland2(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestIsland(self, grid): :type grid: List[List[int]] :rtype: int
- def largestIsland2(self, grid): union find | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestIsland(self, grid): :type grid: List[List[int]] :rtype: int
- def largestIsland2(self, grid): union find
<|skeleton|>
class Solution:
def largestIsland(self, gri... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def largestIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def largestIsland2(self, grid):
"""union find"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
rows = len(grid)
cols = len(grid[0])
def isValid(i, j, marked):
return i >= 0 and i < rows and (j >= 0) and (j < cols) and (grid[i][j] == 1) and (marked[i][j] == False)
a... | the_stack_v2_python_sparse | BiliBili/最大人工岛_H.py | 2226171237/Algorithmpractice | train | 0 | |
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"self.num_damage_bins = num_damage_bins\nself.dtypes = OrderedDict([('bin_index', 'i'), ('bin_from', 'f'), ('bin_to', 'f'), ('interpolation', 'f'), ('interval_type', 'i')])\nself.start_stats = None\nself.data_length = num_damage_bins\nself.file_name = os.path.join(directory, 'damage_bin_dict.bin')",
"bin_indexes ... | <|body_start_0|>
self.num_damage_bins = num_damage_bins
self.dtypes = OrderedDict([('bin_index', 'i'), ('bin_from', 'f'), ('bin_to', 'f'), ('interpolation', 'f'), ('interval_type', 'i')])
self.start_stats = None
self.data_length = num_damage_bins
self.file_name = os.path.join(dir... | Generate data for Damage Bin Dictionary dummy model file. This file shows the discretisation of the effective damageability cumulative distribution function. Attributes: generate_data: Generate Damage Bin Dictionary dummy model file data. | DamageBinDictFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DamageBinDictFile:
"""Generate data for Damage Bin Dictionary dummy model file. This file shows the discretisation of the effective damageability cumulative distribution function. Attributes: generate_data: Generate Damage Bin Dictionary dummy model file data."""
def __init__(self, num_damag... | stack_v2_sparse_classes_36k_train_002395 | 39,722 | permissive | [
{
"docstring": "Initialise Damage Bin Dictionary file class. Args: num_damage_bins (int): number of damage bins. directory (str): dummy model file destination.",
"name": "__init__",
"signature": "def __init__(self, num_damage_bins, directory)"
},
{
"docstring": "Generate Damage Bin Dictionary du... | 2 | null | Implement the Python class `DamageBinDictFile` described below.
Class description:
Generate data for Damage Bin Dictionary dummy model file. This file shows the discretisation of the effective damageability cumulative distribution function. Attributes: generate_data: Generate Damage Bin Dictionary dummy model file dat... | Implement the Python class `DamageBinDictFile` described below.
Class description:
Generate data for Damage Bin Dictionary dummy model file. This file shows the discretisation of the effective damageability cumulative distribution function. Attributes: generate_data: Generate Damage Bin Dictionary dummy model file dat... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class DamageBinDictFile:
"""Generate data for Damage Bin Dictionary dummy model file. This file shows the discretisation of the effective damageability cumulative distribution function. Attributes: generate_data: Generate Damage Bin Dictionary dummy model file data."""
def __init__(self, num_damag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DamageBinDictFile:
"""Generate data for Damage Bin Dictionary dummy model file. This file shows the discretisation of the effective damageability cumulative distribution function. Attributes: generate_data: Generate Damage Bin Dictionary dummy model file data."""
def __init__(self, num_damage_bins, direc... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
1616e44c90fd3f1d113306e930b1e487630c1ebd | [
"yield from cls.decorations\nyield from super().variableDerivation(record)\nreturn",
"yield from cls.decorations\nyield from super().operatorDerivation(record)\nreturn"
] | <|body_start_0|>
yield from cls.decorations
yield from super().variableDerivation(record)
return
<|end_body_0|>
<|body_start_1|>
yield from cls.decorations
yield from super().operatorDerivation(record)
return
<|end_body_1|>
| Metaclass that decorates descriptors with a name and a type | Decorator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decorator:
"""Metaclass that decorates descriptors with a name and a type"""
def variableDerivation(cls, record):
"""Inject the local decorations to the variable inheritance hierarchy"""
<|body_0|>
def operatorDerivation(cls, record):
"""Inject the local decorati... | stack_v2_sparse_classes_36k_train_002396 | 1,161 | permissive | [
{
"docstring": "Inject the local decorations to the variable inheritance hierarchy",
"name": "variableDerivation",
"signature": "def variableDerivation(cls, record)"
},
{
"docstring": "Inject the local decorations to the operator inheritance hierarcrhy",
"name": "operatorDerivation",
"si... | 2 | stack_v2_sparse_classes_30k_val_000222 | Implement the Python class `Decorator` described below.
Class description:
Metaclass that decorates descriptors with a name and a type
Method signatures and docstrings:
- def variableDerivation(cls, record): Inject the local decorations to the variable inheritance hierarchy
- def operatorDerivation(cls, record): Inje... | Implement the Python class `Decorator` described below.
Class description:
Metaclass that decorates descriptors with a name and a type
Method signatures and docstrings:
- def variableDerivation(cls, record): Inject the local decorations to the variable inheritance hierarchy
- def operatorDerivation(cls, record): Inje... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Decorator:
"""Metaclass that decorates descriptors with a name and a type"""
def variableDerivation(cls, record):
"""Inject the local decorations to the variable inheritance hierarchy"""
<|body_0|>
def operatorDerivation(cls, record):
"""Inject the local decorati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decorator:
"""Metaclass that decorates descriptors with a name and a type"""
def variableDerivation(cls, record):
"""Inject the local decorations to the variable inheritance hierarchy"""
yield from cls.decorations
yield from super().variableDerivation(record)
return
d... | the_stack_v2_python_sparse | packages/pyre/descriptors/Decorator.py | pyre/pyre | train | 27 |
96c56b5e1318bb37994c1186f8e6027a9be4ca12 | [
"if 'watts_rsp.auth.WattsBackend' in settings.AUTHENTICATION_BACKENDS:\n logger.debug('Redirect to home/rsp/login/init...')\n return redirect('vfw_home:watts_rsp:login_init')\nelif settings.DEBUG:\n return redirect('vfw_home:login')\nelse:\n raise Http404",
"if not request.user.is_authenticated:\n ... | <|body_start_0|>
if 'watts_rsp.auth.WattsBackend' in settings.AUTHENTICATION_BACKENDS:
logger.debug('Redirect to home/rsp/login/init...')
return redirect('vfw_home:watts_rsp:login_init')
elif settings.DEBUG:
return redirect('vfw_home:login')
else:
... | LoginView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
def post(self, request):
""":param request: :type request: :return: :rtype:"""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""When clicked on login, this is the first(?) function to access. If not user.is_authenticated, next function is post a... | stack_v2_sparse_classes_36k_train_002397 | 37,263 | permissive | [
{
"docstring": ":param request: :type request: :return: :rtype:",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "When clicked on login, this is the first(?) function to access. If not user.is_authenticated, next function is post and redirect to watts (django-watts-rsp/... | 2 | stack_v2_sparse_classes_30k_train_003428 | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def post(self, request): :param request: :type request: :return: :rtype:
- def dispatch(self, request, *args, **kwargs): When clicked on login, this is the first(?) function to... | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def post(self, request): :param request: :type request: :return: :rtype:
- def dispatch(self, request, *args, **kwargs): When clicked on login, this is the first(?) function to... | 9055095cbe796d6d6e2ce744d727ff60e27e09ed | <|skeleton|>
class LoginView:
def post(self, request):
""":param request: :type request: :return: :rtype:"""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""When clicked on login, this is the first(?) function to access. If not user.is_authenticated, next function is post a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginView:
def post(self, request):
""":param request: :type request: :return: :rtype:"""
if 'watts_rsp.auth.WattsBackend' in settings.AUTHENTICATION_BACKENDS:
logger.debug('Redirect to home/rsp/login/init...')
return redirect('vfw_home:watts_rsp:login_init')
el... | the_stack_v2_python_sparse | vfw_home/views.py | VForWaTer/vforwater-portal | train | 8 | |
298afdd04d0898da81cdb976541ed34dd2aba2d9 | [
"self.net = net\nself.dataset = dataset\nself.loader = loader\nself.device = device\nself.opt = opt\nself.grad_clip = grad_clip\nself.lr_func = lr_func\nself.step = 0\nself.epoch = 0",
"lr = -1\nfor i, (img, bbox, label, loc, scale) in enumerate(self.loader):\n if self.lr_func is not None:\n lr = self.l... | <|body_start_0|>
self.net = net
self.dataset = dataset
self.loader = loader
self.device = device
self.opt = opt
self.grad_clip = grad_clip
self.lr_func = lr_func
self.step = 0
self.epoch = 0
<|end_body_0|>
<|body_start_1|>
lr = -1
... | Trainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
def __init__(self, net, dataset, loader, device, opt, grad_clip=3, lr_func=None):
"""external initialization structure: net(DataParallel), dataset(Dataset), loader(DataLoader), device(List), opt(Optimizer) grad_clip: limit the gradient size of each iteration lr_func: lr_func(ste... | stack_v2_sparse_classes_36k_train_002398 | 8,178 | permissive | [
{
"docstring": "external initialization structure: net(DataParallel), dataset(Dataset), loader(DataLoader), device(List), opt(Optimizer) grad_clip: limit the gradient size of each iteration lr_func: lr_func(step) -> float self.step, self.epoch for outside use",
"name": "__init__",
"signature": "def __in... | 2 | stack_v2_sparse_classes_30k_train_015339 | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, net, dataset, loader, device, opt, grad_clip=3, lr_func=None): external initialization structure: net(DataParallel), dataset(Dataset), loader(DataLoader), device... | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, net, dataset, loader, device, opt, grad_clip=3, lr_func=None): external initialization structure: net(DataParallel), dataset(Dataset), loader(DataLoader), device... | 4f62f7754cf3f408b785a5ef410d5ca452d9cabf | <|skeleton|>
class Trainer:
def __init__(self, net, dataset, loader, device, opt, grad_clip=3, lr_func=None):
"""external initialization structure: net(DataParallel), dataset(Dataset), loader(DataLoader), device(List), opt(Optimizer) grad_clip: limit the gradient size of each iteration lr_func: lr_func(ste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trainer:
def __init__(self, net, dataset, loader, device, opt, grad_clip=3, lr_func=None):
"""external initialization structure: net(DataParallel), dataset(Dataset), loader(DataLoader), device(List), opt(Optimizer) grad_clip: limit the gradient size of each iteration lr_func: lr_func(step) -> float se... | the_stack_v2_python_sparse | api.py | Cuzzan/fcos | train | 1 | |
e0b32925aee455ca49a8ba47f6d45a72e7d74ee0 | [
"super().__init__()\nself.self_attn_layer_norm = nn.LayerNorm(hid_dim)\nself.enc_attn_layer_norm = nn.LayerNorm(hid_dim)\nself.ff_layer_norm = nn.LayerNorm(hid_dim)\nself.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout)\nself.encoder_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout)\... | <|body_start_0|>
super().__init__()
self.self_attn_layer_norm = nn.LayerNorm(hid_dim)
self.enc_attn_layer_norm = nn.LayerNorm(hid_dim)
self.ff_layer_norm = nn.LayerNorm(hid_dim)
self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout)
self.encoder_attentio... | TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the dropout value device: the device on which the model ... | TransformerDecoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDecoderLayer:
"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the d... | stack_v2_sparse_classes_36k_train_002399 | 10,223 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, hid_dim, n_heads, pf_dim, dropout)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, trg, enc_src, trg_mask, src_mask)"
... | 2 | stack_v2_sparse_classes_30k_train_007302 | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the f... | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the f... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class TransformerDecoderLayer:
"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerDecoderLayer:
"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the dropout value ... | the_stack_v2_python_sparse | caspr/models/transformer.py | microsoft/CASPR | train | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.