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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
98873d5345d3d53bc5c66ba402ff2eda49787fb5 | [
"self.v2d = vec2d\nself.i = 0\nself.j = 0",
"if self.hasNext():\n tmp = self.v2d[self.i][self.j]\n self.j += 1\n return tmp\nreturn -1",
"while self.i < len(self.v2d) and self.j == len(self.v2d[self.i]):\n self.i += 1\n self.j = 0\nreturn self.i < len(self.v2d)"
] | <|body_start_0|>
self.v2d = vec2d
self.i = 0
self.j = 0
<|end_body_0|>
<|body_start_1|>
if self.hasNext():
tmp = self.v2d[self.i][self.j]
self.j += 1
return tmp
return -1
<|end_body_1|>
<|body_start_2|>
while self.i < len(self.v2d) an... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_025300 | 833 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | null | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | 832f6a8c0deb0569d3fe0dc03e4564c2d850f067 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.v2d = vec2d
self.i = 0
self.j = 0
def next(self):
""":rtype: int"""
if self.hasNext():
tmp = self.v2d[self.i][self.j]
s... | the_stack_v2_python_sparse | leetcode/251_flattenedl2dvector.py | hwillmott/csfundamentals | train | 0 | |
62d6584c2b47f966c964d1875f06e83e47e3bdfa | [
"trie = Trie()\nfor p in products:\n trie.add(p)\nres = []\nprefix = ''\nfor c in searchWord:\n prefix += c\n l = trie.findAll(prefix)\n res.append(sorted(l)[:3])\nreturn res",
"products.sort()\nprefix = ''\nres = []\nfor c in searchWord:\n temp = []\n prefix += c\n i = bisect.bisect_left(pro... | <|body_start_0|>
trie = Trie()
for p in products:
trie.add(p)
res = []
prefix = ''
for c in searchWord:
prefix += c
l = trie.findAll(prefix)
res.append(sorted(l)[:3])
return res
<|end_body_0|>
<|body_start_1|>
produ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
"""Trie 구현."""
<|body_0|>
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
"""sort 후 binary search."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_025301 | 1,844 | no_license | [
{
"docstring": "Trie 구현.",
"name": "suggestedProducts",
"signature": "def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]"
},
{
"docstring": "sort 후 binary search.",
"name": "suggestedProducts",
"signature": "def suggestedProducts(self, products: List[str... | 2 | stack_v2_sparse_classes_30k_val_000738 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: Trie 구현.
- def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[st... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: Trie 구현.
- def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[st... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
"""Trie 구현."""
<|body_0|>
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
"""sort 후 binary search."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
"""Trie 구현."""
trie = Trie()
for p in products:
trie.add(p)
res = []
prefix = ''
for c in searchWord:
prefix += c
l = trie.findAll... | the_stack_v2_python_sparse | Leetcode/1268.py | hanwgyu/algorithm_problem_solving | train | 5 | |
2a40489ad8b58252b40a7400decb84c1d0b5ec2b | [
"Nourriture.__init__(self, cle)\nself.nourrissant = 3\nself.niveau_peche = 5\nself.etendre_editeur('ni', 'niveau', Entier, self, 'niveau_peche', 1, 100)",
"Nourriture.travailler_enveloppes(self, enveloppes)\nniveau = enveloppes['ni']\nniveau.apercu = '{objet.niveau_peche}'\nniveau.prompt = 'Niveau pêche du poisso... | <|body_start_0|>
Nourriture.__init__(self, cle)
self.nourrissant = 3
self.niveau_peche = 5
self.etendre_editeur('ni', 'niveau', Entier, self, 'niveau_peche', 1, 100)
<|end_body_0|>
<|body_start_1|>
Nourriture.travailler_enveloppes(self, enveloppes)
niveau = enveloppes['n... | Type d'objet: poisson. | Poisson | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Type d'objet: poisson."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Nourriture.__in... | stack_v2_sparse_classes_36k_train_025302 | 3,156 | permissive | [
{
"docstring": "Constructeur de l'objet",
"name": "__init__",
"signature": "def __init__(self, cle='')"
},
{
"docstring": "Travail sur les enveloppes",
"name": "travailler_enveloppes",
"signature": "def travailler_enveloppes(self, enveloppes)"
}
] | 2 | null | Implement the Python class `Poisson` described below.
Class description:
Type d'objet: poisson.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes | Implement the Python class `Poisson` described below.
Class description:
Type d'objet: poisson.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
<|skeleton|>
class Poisson:
"""Type d'objet: poisson.""... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class Poisson:
"""Type d'objet: poisson."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poisson:
"""Type d'objet: poisson."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
Nourriture.__init__(self, cle)
self.nourrissant = 3
self.niveau_peche = 5
self.etendre_editeur('ni', 'niveau', Entier, self, 'niveau_peche', 1, 100)
def travailler_... | the_stack_v2_python_sparse | src/secondaires/peche/types/poisson.py | vincent-lg/tsunami | train | 5 |
634f4bdc8758b11a597d8affefd13e27a1b2636a | [
"if country:\n tracks = cls.lfm().get_top_tracks_geo(country)\nelse:\n tracks = cls.lfm().get_top_tracks_global()\nrandom.shuffle(tracks)\nfor track in cls.tracks_with_prefetch(tracks):\n if cls.get_exit():\n break\n cls.play_full_track(track)",
"rs = RS500Requestor()\ntracks = [u'{0!s} - {1!s}... | <|body_start_0|>
if country:
tracks = cls.lfm().get_top_tracks_geo(country)
else:
tracks = cls.lfm().get_top_tracks_global()
random.shuffle(tracks)
for track in cls.tracks_with_prefetch(tracks):
if cls.get_exit():
break
cls.... | Play top tracks from different services | TopTracksTask | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopTracksTask:
"""Play top tracks from different services"""
def run_top_tracks_geo(cls, country):
"""Shuffle top tracks global or for specific country"""
<|body_0|>
def run_rs500(cls, *args):
"""Shuffle Rolling stone 500 tracks"""
<|body_1|>
def run... | stack_v2_sparse_classes_36k_train_025303 | 7,415 | permissive | [
{
"docstring": "Shuffle top tracks global or for specific country",
"name": "run_top_tracks_geo",
"signature": "def run_top_tracks_geo(cls, country)"
},
{
"docstring": "Shuffle Rolling stone 500 tracks",
"name": "run_rs500",
"signature": "def run_rs500(cls, *args)"
},
{
"docstrin... | 5 | null | Implement the Python class `TopTracksTask` described below.
Class description:
Play top tracks from different services
Method signatures and docstrings:
- def run_top_tracks_geo(cls, country): Shuffle top tracks global or for specific country
- def run_rs500(cls, *args): Shuffle Rolling stone 500 tracks
- def run_bb1... | Implement the Python class `TopTracksTask` described below.
Class description:
Play top tracks from different services
Method signatures and docstrings:
- def run_top_tracks_geo(cls, country): Shuffle top tracks global or for specific country
- def run_rs500(cls, *args): Shuffle Rolling stone 500 tracks
- def run_bb1... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class TopTracksTask:
"""Play top tracks from different services"""
def run_top_tracks_geo(cls, country):
"""Shuffle top tracks global or for specific country"""
<|body_0|>
def run_rs500(cls, *args):
"""Shuffle Rolling stone 500 tracks"""
<|body_1|>
def run... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopTracksTask:
"""Play top tracks from different services"""
def run_top_tracks_geo(cls, country):
"""Shuffle top tracks global or for specific country"""
if country:
tracks = cls.lfm().get_top_tracks_geo(country)
else:
tracks = cls.lfm().get_top_tracks_glo... | the_stack_v2_python_sparse | voiceplay/player/tasks/top.py | tb0hdan/voiceplay | train | 4 |
39161beb9277f2b131f7aa339b1315786a0b6813 | [
"maxSum, pre = (nums[0], nums[0])\nfor i in range(1, len(nums)):\n pre = max(nums[i], nums[i] + pre)\n maxSum = max(pre, maxSum)\nreturn maxSum",
"maxSum, pre = (nums[0], nums[0])\nbegin, end = (0, 0)\ntemp_begin = 0\nfor i in range(1, len(nums)):\n if nums[i] < nums[i] + pre:\n pre += nums[i]\n ... | <|body_start_0|>
maxSum, pre = (nums[0], nums[0])
for i in range(1, len(nums)):
pre = max(nums[i], nums[i] + pre)
maxSum = max(pre, maxSum)
return maxSum
<|end_body_0|>
<|body_start_1|>
maxSum, pre = (nums[0], nums[0])
begin, end = (0, 0)
temp_beg... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""53. 最大子序和f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}"""
<|body_0|>
def maxSubArrayPos(self, nums: List[int]) -> int:
"""53. 最大子序和的位置 f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}"... | stack_v2_sparse_classes_36k_train_025304 | 2,905 | no_license | [
{
"docstring": "53. 最大子序和f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums: List[int]) -> int"
},
{
"docstring": "53. 最大子序和的位置 f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}",
"name": "maxSubArrayPos",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums: List[int]) -> int: 53. 最大子序和f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}
- def maxSubArrayPos(self, nums: List[int]) -> int: 53. 最大子序和的位... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums: List[int]) -> int: 53. 最大子序和f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}
- def maxSubArrayPos(self, nums: List[int]) -> int: 53. 最大子序和的位... | 3fd69b85f52af861ff7e2c74d8aacc515b192615 | <|skeleton|>
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""53. 最大子序和f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}"""
<|body_0|>
def maxSubArrayPos(self, nums: List[int]) -> int:
"""53. 最大子序和的位置 f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""53. 最大子序和f(i)代表以第 i个数结尾的「连续子数组的最大和」f(i)=max{f(i−1)+nums[i],nums[i]}"""
maxSum, pre = (nums[0], nums[0])
for i in range(1, len(nums)):
pre = max(nums[i], nums[i] + pre)
maxSum = max(pre, maxSum)
... | the_stack_v2_python_sparse | Array/SubArray.py | helloprogram6/leetcode_Cookbook_python | train | 0 | |
d2926680a4d160ec8c0321cc0f676cf974b69fd0 | [
"with db.connection as connection:\n services_color = ColorService(connection)\n color = services_color.read_all_color()\n return (jsonify(color), 200)",
"with db.connection as connection:\n name = request.json.get('name')\n hex_id = request.json.get('hex')\n services_color = ColorService(connec... | <|body_start_0|>
with db.connection as connection:
services_color = ColorService(connection)
color = services_color.read_all_color()
return (jsonify(color), 200)
<|end_body_0|>
<|body_start_1|>
with db.connection as connection:
name = request.json.get('na... | ColorView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorView:
def get(self):
"""Получение списка всех цветов"""
<|body_0|>
def post(self):
"""Создание цвета"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with db.connection as connection:
services_color = ColorService(connection)
... | stack_v2_sparse_classes_36k_train_025305 | 942 | no_license | [
{
"docstring": "Получение списка всех цветов",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Создание цвета",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011276 | Implement the Python class `ColorView` described below.
Class description:
Implement the ColorView class.
Method signatures and docstrings:
- def get(self): Получение списка всех цветов
- def post(self): Создание цвета | Implement the Python class `ColorView` described below.
Class description:
Implement the ColorView class.
Method signatures and docstrings:
- def get(self): Получение списка всех цветов
- def post(self): Создание цвета
<|skeleton|>
class ColorView:
def get(self):
"""Получение списка всех цветов"""
... | 79b0563f654016f7d56d988988ddc4bfdb0f1474 | <|skeleton|>
class ColorView:
def get(self):
"""Получение списка всех цветов"""
<|body_0|>
def post(self):
"""Создание цвета"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorView:
def get(self):
"""Получение списка всех цветов"""
with db.connection as connection:
services_color = ColorService(connection)
color = services_color.read_all_color()
return (jsonify(color), 200)
def post(self):
"""Создание цвета"""
... | the_stack_v2_python_sparse | Lesson 13/final v 2.0/src/blueprints/colors.py | Alexey7953/antida-school | train | 0 | |
7b17739a8ef79c19e0e2e4e0a5f8b5ee02f5b313 | [
"obj = cls(api_url=api_url, api_name=api_name, desc=desc)\ntry:\n obj.save()\nexcept IntegrityError as e:\n print(e)\n s = e.args[1]\n if 'Duplicate entry' in s and 'api_url' in s:\n raise RuleRegisterException('重复的api_url: {}'.format(api_url))\n elif 'Duplicate entry' in s and 'api_name' in s... | <|body_start_0|>
obj = cls(api_url=api_url, api_name=api_name, desc=desc)
try:
obj.save()
except IntegrityError as e:
print(e)
s = e.args[1]
if 'Duplicate entry' in s and 'api_url' in s:
raise RuleRegisterException('重复的api_url: {}'.... | (业务接口的)权限规则模板, 权限规则和api视图路由是1:1的关系 | RawRule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawRule:
"""(业务接口的)权限规则模板, 权限规则和api视图路由是1:1的关系"""
def register_rule(cls, api_url: str, api_name: str, desc: str=''):
"""注册业务权限接口路由.此接口应该有视图类/函数自动调用进行注册 :param api_url: 接口地址,唯一. :param api_name: 接口名字,唯一 :param desc: :return: 注册失败会抛出异常"""
<|body_0|>
def get_all(cls) -> dic... | stack_v2_sparse_classes_36k_train_025306 | 25,579 | no_license | [
{
"docstring": "注册业务权限接口路由.此接口应该有视图类/函数自动调用进行注册 :param api_url: 接口地址,唯一. :param api_name: 接口名字,唯一 :param desc: :return: 注册失败会抛出异常",
"name": "register_rule",
"signature": "def register_rule(cls, api_url: str, api_name: str, desc: str='')"
},
{
"docstring": "获取所有可用来编辑权限的接口视图路由 :return:",
"name... | 2 | stack_v2_sparse_classes_30k_train_005096 | Implement the Python class `RawRule` described below.
Class description:
(业务接口的)权限规则模板, 权限规则和api视图路由是1:1的关系
Method signatures and docstrings:
- def register_rule(cls, api_url: str, api_name: str, desc: str=''): 注册业务权限接口路由.此接口应该有视图类/函数自动调用进行注册 :param api_url: 接口地址,唯一. :param api_name: 接口名字,唯一 :param desc: :return: 注册失... | Implement the Python class `RawRule` described below.
Class description:
(业务接口的)权限规则模板, 权限规则和api视图路由是1:1的关系
Method signatures and docstrings:
- def register_rule(cls, api_url: str, api_name: str, desc: str=''): 注册业务权限接口路由.此接口应该有视图类/函数自动调用进行注册 :param api_url: 接口地址,唯一. :param api_name: 接口名字,唯一 :param desc: :return: 注册失... | 3a2bdfd1598bfcdfe56386ec0c46fcede772cbfe | <|skeleton|>
class RawRule:
"""(业务接口的)权限规则模板, 权限规则和api视图路由是1:1的关系"""
def register_rule(cls, api_url: str, api_name: str, desc: str=''):
"""注册业务权限接口路由.此接口应该有视图类/函数自动调用进行注册 :param api_url: 接口地址,唯一. :param api_name: 接口名字,唯一 :param desc: :return: 注册失败会抛出异常"""
<|body_0|>
def get_all(cls) -> dic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawRule:
"""(业务接口的)权限规则模板, 权限规则和api视图路由是1:1的关系"""
def register_rule(cls, api_url: str, api_name: str, desc: str=''):
"""注册业务权限接口路由.此接口应该有视图类/函数自动调用进行注册 :param api_url: 接口地址,唯一. :param api_name: 接口名字,唯一 :param desc: :return: 注册失败会抛出异常"""
obj = cls(api_url=api_url, api_name=api_name, desc=d... | the_stack_v2_python_sparse | NewISpider/authorization_package/permission_module.py | SYYDSN/py_projects | train | 0 |
8f7ed02b839ca89722a76f6178ce9f1327203cbc | [
"super(ProblemMultiObjective, self).__init__(n_var=1, n_obj=3, n_constr=0)\nself.n_refactorings_lowerbound = n_refactorings_lowerbound\nself.n_refactorings_upperbound = n_refactorings_upperbound\nself.evaluate_in_parallel = evaluate_in_parallel\nself.n_obj_virtual = n_objectives",
"objective_values = []\nfor k, i... | <|body_start_0|>
super(ProblemMultiObjective, self).__init__(n_var=1, n_obj=3, n_constr=0)
self.n_refactorings_lowerbound = n_refactorings_lowerbound
self.n_refactorings_upperbound = n_refactorings_upperbound
self.evaluate_in_parallel = evaluate_in_parallel
self.n_obj_virtual = n... | The CodART multi-objective optimization work with three objective: * Objective 1: Mean value of QMOOD metrics * Objective 2: Testability * Objective 3: Modularity | ProblemMultiObjective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProblemMultiObjective:
"""The CodART multi-objective optimization work with three objective: * Objective 1: Mean value of QMOOD metrics * Objective 2: Testability * Objective 3: Modularity"""
def __init__(self, n_objectives=8, n_refactorings_lowerbound=10, n_refactorings_upperbound=50, evalu... | stack_v2_sparse_classes_36k_train_025307 | 48,683 | permissive | [
{
"docstring": "Args: n_objectives (int): Number of objectives n_refactorings_lowerbound (int): The lower bound of the refactoring sequences n_refactorings_upperbound (int): The upper bound of the refactoring sequences evaluate_in_parallel (bool): Whether the objectives evaluate in parallel",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_004132 | Implement the Python class `ProblemMultiObjective` described below.
Class description:
The CodART multi-objective optimization work with three objective: * Objective 1: Mean value of QMOOD metrics * Objective 2: Testability * Objective 3: Modularity
Method signatures and docstrings:
- def __init__(self, n_objectives=... | Implement the Python class `ProblemMultiObjective` described below.
Class description:
The CodART multi-objective optimization work with three objective: * Objective 1: Mean value of QMOOD metrics * Objective 2: Testability * Objective 3: Modularity
Method signatures and docstrings:
- def __init__(self, n_objectives=... | 9e1031dbfda3b76fa1781be261bc4083ec8b5323 | <|skeleton|>
class ProblemMultiObjective:
"""The CodART multi-objective optimization work with three objective: * Objective 1: Mean value of QMOOD metrics * Objective 2: Testability * Objective 3: Modularity"""
def __init__(self, n_objectives=8, n_refactorings_lowerbound=10, n_refactorings_upperbound=50, evalu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProblemMultiObjective:
"""The CodART multi-objective optimization work with three objective: * Objective 1: Mean value of QMOOD metrics * Objective 2: Testability * Objective 3: Modularity"""
def __init__(self, n_objectives=8, n_refactorings_lowerbound=10, n_refactorings_upperbound=50, evaluate_in_parall... | the_stack_v2_python_sparse | codart/sbse/search_based_refactoring2.py | m-zakeri/CodART | train | 39 |
70a01effe26b707d0bbcff6e32d86cba430724c1 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.w_Q = pytorch_linear(d_model, d_model)\nself.w_K = pytorch_linear(d_model, d_model)\nself.w_V = pytorch_linear(d_model, d_model)\nself.w_O = pytorch_linear(d_model, d_model)\nself.attn_fn = scaled_dot_p... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.w_Q = pytorch_linear(d_model, d_model)
self.w_K = pytorch_linear(d_model, d_model)
self.w_V = pytorch_linear(d_model, d_model)
sel... | Multi-headed attention from https://arxiv.org/abs/1706.03762 via http://nlp.seas.harvard.edu/2018/04/03/attention.html Multi-headed attention provides multiple looks of low-order projections K, Q and V using an attention function (specifically `scaled_dot_product_attention` in the paper. This allows multiple relationsh... | MultiHeadedAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-headed attention from https://arxiv.org/abs/1706.03762 via http://nlp.seas.harvard.edu/2018/04/03/attention.html Multi-headed attention provides multiple looks of low-order projections K, Q and V using an attention function (specifically `scaled_dot_product_attentio... | stack_v2_sparse_classes_36k_train_025308 | 8,810 | permissive | [
{
"docstring": "Constructor for multi-headed attention :param h: The number of heads :param d_model: The model hidden size :param dropout (``float``): The amount of dropout to use :param attn_fn: A function to apply attention, defaults to SDP",
"name": "__init__",
"signature": "def __init__(self, h, d_m... | 2 | stack_v2_sparse_classes_30k_train_000693 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-headed attention from https://arxiv.org/abs/1706.03762 via http://nlp.seas.harvard.edu/2018/04/03/attention.html Multi-headed attention provides multiple looks of low-order projections K, Q and V using an attention function (sp... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Multi-headed attention from https://arxiv.org/abs/1706.03762 via http://nlp.seas.harvard.edu/2018/04/03/attention.html Multi-headed attention provides multiple looks of low-order projections K, Q and V using an attention function (sp... | 2261abfb7e770cc6f3d63a7f6e0015238d0e11f8 | <|skeleton|>
class MultiHeadedAttention:
"""Multi-headed attention from https://arxiv.org/abs/1706.03762 via http://nlp.seas.harvard.edu/2018/04/03/attention.html Multi-headed attention provides multiple looks of low-order projections K, Q and V using an attention function (specifically `scaled_dot_product_attentio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
"""Multi-headed attention from https://arxiv.org/abs/1706.03762 via http://nlp.seas.harvard.edu/2018/04/03/attention.html Multi-headed attention provides multiple looks of low-order projections K, Q and V using an attention function (specifically `scaled_dot_product_attention` in the pap... | the_stack_v2_python_sparse | python/baseline/pytorch/transformer.py | ijindal/baseline | train | 0 |
e31f151dab2c7d9930477060d71e9169aeb674d8 | [
"self.bin_size = 1.0 / M\nself.conf = []\nself.upper_bounds = np.arange(self.bin_size, 1 + self.bin_size, self.bin_size)",
"filtered = [x[0] for x in zip(true, probs) if x[1] > conf_thresh_lower and x[1] <= conf_thresh_upper]\nnr_elems = len(filtered)\nif nr_elems < 1:\n return 0\nelse:\n conf = sum(filtere... | <|body_start_0|>
self.bin_size = 1.0 / M
self.conf = []
self.upper_bounds = np.arange(self.bin_size, 1 + self.bin_size, self.bin_size)
<|end_body_0|>
<|body_start_1|>
filtered = [x[0] for x in zip(true, probs) if x[1] > conf_thresh_lower and x[1] <= conf_thresh_upper]
nr_elems =... | Histogram Binning as a calibration method. The bins are divided into equal lengths. The class contains two methods: - fit(probs, true), that should be used with validation data to train the calibration model. - predict(probs), this method is used to calibrate the confidences. | HistogramBinning | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistogramBinning:
"""Histogram Binning as a calibration method. The bins are divided into equal lengths. The class contains two methods: - fit(probs, true), that should be used with validation data to train the calibration model. - predict(probs), this method is used to calibrate the confidences.... | stack_v2_sparse_classes_36k_train_025309 | 3,285 | no_license | [
{
"docstring": "M (int): the number of equal-length bins used",
"name": "__init__",
"signature": "def __init__(self, M=15)"
},
{
"docstring": "Inner method to calculate optimal confidence for certain probability range Params: - conf_thresh_lower (float): start of the interval (not included) - co... | 4 | stack_v2_sparse_classes_30k_train_003534 | Implement the Python class `HistogramBinning` described below.
Class description:
Histogram Binning as a calibration method. The bins are divided into equal lengths. The class contains two methods: - fit(probs, true), that should be used with validation data to train the calibration model. - predict(probs), this metho... | Implement the Python class `HistogramBinning` described below.
Class description:
Histogram Binning as a calibration method. The bins are divided into equal lengths. The class contains two methods: - fit(probs, true), that should be used with validation data to train the calibration model. - predict(probs), this metho... | 75a40649c3ab3b551546cd5deb7093d6cbcf01e0 | <|skeleton|>
class HistogramBinning:
"""Histogram Binning as a calibration method. The bins are divided into equal lengths. The class contains two methods: - fit(probs, true), that should be used with validation data to train the calibration model. - predict(probs), this method is used to calibrate the confidences.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HistogramBinning:
"""Histogram Binning as a calibration method. The bins are divided into equal lengths. The class contains two methods: - fit(probs, true), that should be used with validation data to train the calibration model. - predict(probs), this method is used to calibrate the confidences."""
def ... | the_stack_v2_python_sparse | data/1516_data/Uncertainty4VerificationModels-master/Twitter 15:16/model/analysisTw1516/calibration/cal_methods.py | zzunebye/Capstone-code-data | train | 0 |
e48bc926d375e8894f5cc53c25dbde2882cce452 | [
"number_dict = {}\nfor num in nums:\n if num in number_dict:\n number_dict[num] += 1\n else:\n number_dict[num] = 1\nfor num in number_dict.values():\n if num > 1:\n return True\nreturn False",
"number_set = set()\nfor num in nums:\n if num in number_set:\n return True\n ... | <|body_start_0|>
number_dict = {}
for num in nums:
if num in number_dict:
number_dict[num] += 1
else:
number_dict[num] = 1
for num in number_dict.values():
if num > 1:
return True
return False
<|end_body_... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
"""判断是否有重复的数 Args: nums: 数组 Returns: 布尔值"""
<|body_0|>
def contains_duplicate2(self, nums: List[int]) -> bool:
"""判断是否有重复的数 Args: nums: 数组 Returns: 布尔值"""
<|body_1|>
def contains_duplicate3... | stack_v2_sparse_classes_36k_train_025310 | 2,354 | permissive | [
{
"docstring": "判断是否有重复的数 Args: nums: 数组 Returns: 布尔值",
"name": "contains_duplicate",
"signature": "def contains_duplicate(self, nums: List[int]) -> bool"
},
{
"docstring": "判断是否有重复的数 Args: nums: 数组 Returns: 布尔值",
"name": "contains_duplicate2",
"signature": "def contains_duplicate2(self,... | 3 | stack_v2_sparse_classes_30k_train_003595 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def contains_duplicate(self, nums: List[int]) -> bool: 判断是否有重复的数 Args: nums: 数组 Returns: 布尔值
- def contains_duplicate2(self, nums: List[int]) -> bool: 判断是否有重复的数 Args: nums: 数组 Re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def contains_duplicate(self, nums: List[int]) -> bool: 判断是否有重复的数 Args: nums: 数组 Returns: 布尔值
- def contains_duplicate2(self, nums: List[int]) -> bool: 判断是否有重复的数 Args: nums: 数组 Re... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
"""判断是否有重复的数 Args: nums: 数组 Returns: 布尔值"""
<|body_0|>
def contains_duplicate2(self, nums: List[int]) -> bool:
"""判断是否有重复的数 Args: nums: 数组 Returns: 布尔值"""
<|body_1|>
def contains_duplicate3... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
"""判断是否有重复的数 Args: nums: 数组 Returns: 布尔值"""
number_dict = {}
for num in nums:
if num in number_dict:
number_dict[num] += 1
else:
number_dict[num] = 1
for num... | the_stack_v2_python_sparse | src/leetcodepython/array/contains_duplicate_217.py | zhangyu345293721/leetcode | train | 101 | |
6835d2e1c68cb97d0d6132c3be1697ea8d8bfaa0 | [
"super(ec3poDriver, self).__init__(interface, params)\nself._logger = logging.getLogger('EC3PO Driver')\nself._interface = interface",
"if self._interface is not None:\n self._interface.set_interp_connect(state)\nelse:\n self._logger.debug('There is no UART on this servo for this specific interface.')",
"... | <|body_start_0|>
super(ec3poDriver, self).__init__(interface, params)
self._logger = logging.getLogger('EC3PO Driver')
self._interface = interface
<|end_body_0|>
<|body_start_1|>
if self._interface is not None:
self._interface.set_interp_connect(state)
else:
... | ec3poDriver | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ec3poDriver:
def __init__(self, interface, params):
"""Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init."""
<|body_0|>
def _Set_in... | stack_v2_sparse_classes_36k_train_025311 | 1,960 | permissive | [
{
"docstring": "Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init.",
"name": "__init__",
"signature": "def __init__(self, interface, params)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_004306 | Implement the Python class `ec3poDriver` described below.
Class description:
Implement the ec3poDriver class.
Method signatures and docstrings:
- def __init__(self, interface, params): Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpret... | Implement the Python class `ec3poDriver` described below.
Class description:
Implement the ec3poDriver class.
Method signatures and docstrings:
- def __init__(self, interface, params): Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpret... | c7d50190837497dafc45f6efe18bf01d6e70cfd2 | <|skeleton|>
class ec3poDriver:
def __init__(self, interface, params):
"""Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init."""
<|body_0|>
def _Set_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ec3poDriver:
def __init__(self, interface, params):
"""Creates the driver for EC-3PO console interpreter. Args: interface: An EC3PO instance which is the interface to the console interpreter. params: A dictionary of params passed to HwDriver's init."""
super(ec3poDriver, self).__init__(interfa... | the_stack_v2_python_sparse | servo/drv/ec3po_driver.py | mmind/servo-hdctools | train | 2 | |
1240eccf34db3be9def27235298a60f485818d5b | [
"if user.is_authenticated:\n qs = self.filter(Q(author=user.profile) | Q(is_visible=Diary.ALL_CHOICE))\n qs = qs.distinct()\nelse:\n qs = self.filter(is_visible=Diary.ALL_CHOICE)\nqs = qs.select_related('author')\nreturn qs",
"followed_profiles = profile.followed_profiles.all()\nqs = self.filter(author__... | <|body_start_0|>
if user.is_authenticated:
qs = self.filter(Q(author=user.profile) | Q(is_visible=Diary.ALL_CHOICE))
qs = qs.distinct()
else:
qs = self.filter(is_visible=Diary.ALL_CHOICE)
qs = qs.select_related('author')
return qs
<|end_body_0|>
<|bod... | DiaryQuerySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiaryQuerySet:
def active(self, user):
"""Returns only the diaries that user should be able to see If the user isn't authenticated, he should only see public diaries If he's authencated he can also see his private diaries"""
<|body_0|>
def by_followed_profiles(self, profile)... | stack_v2_sparse_classes_36k_train_025312 | 8,420 | no_license | [
{
"docstring": "Returns only the diaries that user should be able to see If the user isn't authenticated, he should only see public diaries If he's authencated he can also see his private diaries",
"name": "active",
"signature": "def active(self, user)"
},
{
"docstring": "Returns diaries of foll... | 3 | stack_v2_sparse_classes_30k_train_012741 | Implement the Python class `DiaryQuerySet` described below.
Class description:
Implement the DiaryQuerySet class.
Method signatures and docstrings:
- def active(self, user): Returns only the diaries that user should be able to see If the user isn't authenticated, he should only see public diaries If he's authencated ... | Implement the Python class `DiaryQuerySet` described below.
Class description:
Implement the DiaryQuerySet class.
Method signatures and docstrings:
- def active(self, user): Returns only the diaries that user should be able to see If the user isn't authenticated, he should only see public diaries If he's authencated ... | 11fcc2ae12f6f89a10da3e8c50e7d75003476165 | <|skeleton|>
class DiaryQuerySet:
def active(self, user):
"""Returns only the diaries that user should be able to see If the user isn't authenticated, he should only see public diaries If he's authencated he can also see his private diaries"""
<|body_0|>
def by_followed_profiles(self, profile)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiaryQuerySet:
def active(self, user):
"""Returns only the diaries that user should be able to see If the user isn't authenticated, he should only see public diaries If he's authencated he can also see his private diaries"""
if user.is_authenticated:
qs = self.filter(Q(author=user.... | the_stack_v2_python_sparse | diaries/models.py | ahmed2fathy/yawm | train | 0 | |
bb6c633d9ec00d5fb94a280bae6db656ba706cf5 | [
"try:\n url = 'https://api.short.io/api/domains'\n api_secret = config['secret_key']\n domain_id = int(config['domain_id'])\n headers = {'Accept': 'application/json', 'Authorization': api_secret}\n response = requests.request('GET', url, headers=headers)\n response.raise_for_status()\n for doma... | <|body_start_0|>
try:
url = 'https://api.short.io/api/domains'
api_secret = config['secret_key']
domain_id = int(config['domain_id'])
headers = {'Accept': 'application/json', 'Authorization': api_secret}
response = requests.request('GET', url, headers=... | SourceShortio | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"Elastic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceShortio:
def check_connection(self, logger, config) -> Tuple[bool, any]:
"""CHeck whether configuration is correct. :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input c... | stack_v2_sparse_classes_36k_train_025313 | 8,527 | permissive | [
{
"docstring": "CHeck whether configuration is correct. :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input config can be used to connect to the API successfully, (False, error) otherwise.",
"nam... | 2 | null | Implement the Python class `SourceShortio` described below.
Class description:
Implement the SourceShortio class.
Method signatures and docstrings:
- def check_connection(self, logger, config) -> Tuple[bool, any]: CHeck whether configuration is correct. :param config: the user-input config object conforming to the co... | Implement the Python class `SourceShortio` described below.
Class description:
Implement the SourceShortio class.
Method signatures and docstrings:
- def check_connection(self, logger, config) -> Tuple[bool, any]: CHeck whether configuration is correct. :param config: the user-input config object conforming to the co... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SourceShortio:
def check_connection(self, logger, config) -> Tuple[bool, any]:
"""CHeck whether configuration is correct. :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceShortio:
def check_connection(self, logger, config) -> Tuple[bool, any]:
"""CHeck whether configuration is correct. :param config: the user-input config object conforming to the connector's spec.json :param logger: logger object :return Tuple[bool, any]: (True, None) if the input config can be u... | the_stack_v2_python_sparse | dts/airbyte/airbyte-integrations/connectors/source-shortio/source_shortio/source.py | alldatacenter/alldata | train | 774 | |
95fd912b122e2bd5c66da6e20fa3d2b6f9e625f7 | [
"@tf.function(**tf_function_kwargs)\n@functools.wraps(function)\ndef with_summaries(*args, **kwargs):\n with _soft_device_placement():\n return function(*args, **kwargs)\n\n@tf.function(**tf_function_kwargs)\n@functools.wraps(function)\ndef without_summaries(*args, **kwargs):\n with tf.summary.record_i... | <|body_start_0|>
@tf.function(**tf_function_kwargs)
@functools.wraps(function)
def with_summaries(*args, **kwargs):
with _soft_device_placement():
return function(*args, **kwargs)
@tf.function(**tf_function_kwargs)
@functools.wraps(function)
d... | Wrapper that provides versions of a function with and without summaries. This is a utility class for implementing optimized summary recording via a two-function approach, specifically important for TPUs. Two `tf.function` versions of a given `function` are created: one with soft device placement enabled (for use on ste... | OptionalSummariesFunction | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionalSummariesFunction:
"""Wrapper that provides versions of a function with and without summaries. This is a utility class for implementing optimized summary recording via a two-function approach, specifically important for TPUs. Two `tf.function` versions of a given `function` are created: o... | stack_v2_sparse_classes_36k_train_025314 | 5,630 | permissive | [
{
"docstring": "Constructs an instance wrapping the given `function`. The given `function` is wrapped twice: Once in a \"soft device placement\" context (allowing summaries to also run on TPU), and once with summary recording entirely disabled. Both of these versions are compiled via `tf.function` (optionally u... | 2 | null | Implement the Python class `OptionalSummariesFunction` described below.
Class description:
Wrapper that provides versions of a function with and without summaries. This is a utility class for implementing optimized summary recording via a two-function approach, specifically important for TPUs. Two `tf.function` versio... | Implement the Python class `OptionalSummariesFunction` described below.
Class description:
Wrapper that provides versions of a function with and without summaries. This is a utility class for implementing optimized summary recording via a two-function approach, specifically important for TPUs. Two `tf.function` versio... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class OptionalSummariesFunction:
"""Wrapper that provides versions of a function with and without summaries. This is a utility class for implementing optimized summary recording via a two-function approach, specifically important for TPUs. Two `tf.function` versions of a given `function` are created: o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionalSummariesFunction:
"""Wrapper that provides versions of a function with and without summaries. This is a utility class for implementing optimized summary recording via a two-function approach, specifically important for TPUs. Two `tf.function` versions of a given `function` are created: one with soft ... | the_stack_v2_python_sparse | models/orbit/utils/tpu_summaries.py | aboerzel/German_License_Plate_Recognition | train | 34 |
c2f5c2275fefe544786ff5cb8c5e467a62467ed8 | [
"meta = super(EventSerializerTemplate, self).get_meta(obj)\nmeta['is_ended'] = is_ended_event(obj)\nreturn meta",
"errors = super(EventSerializerTemplate, self).validate(data, get_errors=True)\nvalidate_profanity_serializer(data, 'location', errors, field_name='Event location')\nif not field_exists(data, 'start_d... | <|body_start_0|>
meta = super(EventSerializerTemplate, self).get_meta(obj)
meta['is_ended'] = is_ended_event(obj)
return meta
<|end_body_0|>
<|body_start_1|>
errors = super(EventSerializerTemplate, self).validate(data, get_errors=True)
validate_profanity_serializer(data, 'locati... | EventSerializerTemplate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventSerializerTemplate:
def get_meta(self, obj):
"""Retrieve meta data"""
<|body_0|>
def validate(self, data, get_errors=False):
"""Validate data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
meta = super(EventSerializerTemplate, self).get_meta(o... | stack_v2_sparse_classes_36k_train_025315 | 25,313 | permissive | [
{
"docstring": "Retrieve meta data",
"name": "get_meta",
"signature": "def get_meta(self, obj)"
},
{
"docstring": "Validate data",
"name": "validate",
"signature": "def validate(self, data, get_errors=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016444 | Implement the Python class `EventSerializerTemplate` described below.
Class description:
Implement the EventSerializerTemplate class.
Method signatures and docstrings:
- def get_meta(self, obj): Retrieve meta data
- def validate(self, data, get_errors=False): Validate data | Implement the Python class `EventSerializerTemplate` described below.
Class description:
Implement the EventSerializerTemplate class.
Method signatures and docstrings:
- def get_meta(self, obj): Retrieve meta data
- def validate(self, data, get_errors=False): Validate data
<|skeleton|>
class EventSerializerTemplate:... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class EventSerializerTemplate:
def get_meta(self, obj):
"""Retrieve meta data"""
<|body_0|>
def validate(self, data, get_errors=False):
"""Validate data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventSerializerTemplate:
def get_meta(self, obj):
"""Retrieve meta data"""
meta = super(EventSerializerTemplate, self).get_meta(obj)
meta['is_ended'] = is_ended_event(obj)
return meta
def validate(self, data, get_errors=False):
"""Validate data"""
errors = ... | the_stack_v2_python_sparse | community/serializers.py | 810Teams/clubs-and-events-backend | train | 3 | |
8e15159a1d1f72f24f04bba85111ed10c5f38789 | [
"try:\n return KnowVideo.objects.filter(knowledge=int(self.kwargs['pk']))\nexcept:\n return KnowVideo.objects.all()",
"instance = self.get_queryset()\nserializer = self.get_serializer(instance, many=True)\nreturn Response(serializer.data)"
] | <|body_start_0|>
try:
return KnowVideo.objects.filter(knowledge=int(self.kwargs['pk']))
except:
return KnowVideo.objects.all()
<|end_body_0|>
<|body_start_1|>
instance = self.get_queryset()
serializer = self.get_serializer(instance, many=True)
return Resp... | 知识点视频 | KnowledgeVideoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnowledgeVideoViewSet:
"""知识点视频"""
def get_queryset(self):
"""获取知识点视频 根据知识点id查询视频 :return:"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""url请求 http://127.0.0.1:8000/know_video/1/ 其中的1代表知识点的id号 返回该知识点对应的所有视频 :param request: :param args: :param kwa... | stack_v2_sparse_classes_36k_train_025316 | 7,211 | no_license | [
{
"docstring": "获取知识点视频 根据知识点id查询视频 :return:",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "url请求 http://127.0.0.1:8000/know_video/1/ 其中的1代表知识点的id号 返回该知识点对应的所有视频 :param request: :param args: :param kwargs: :return:",
"name": "retrieve",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_013103 | Implement the Python class `KnowledgeVideoViewSet` described below.
Class description:
知识点视频
Method signatures and docstrings:
- def get_queryset(self): 获取知识点视频 根据知识点id查询视频 :return:
- def retrieve(self, request, *args, **kwargs): url请求 http://127.0.0.1:8000/know_video/1/ 其中的1代表知识点的id号 返回该知识点对应的所有视频 :param request: :p... | Implement the Python class `KnowledgeVideoViewSet` described below.
Class description:
知识点视频
Method signatures and docstrings:
- def get_queryset(self): 获取知识点视频 根据知识点id查询视频 :return:
- def retrieve(self, request, *args, **kwargs): url请求 http://127.0.0.1:8000/know_video/1/ 其中的1代表知识点的id号 返回该知识点对应的所有视频 :param request: :p... | 9205dfd8dd0c822a9f5352db845fc12c319db3e3 | <|skeleton|>
class KnowledgeVideoViewSet:
"""知识点视频"""
def get_queryset(self):
"""获取知识点视频 根据知识点id查询视频 :return:"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""url请求 http://127.0.0.1:8000/know_video/1/ 其中的1代表知识点的id号 返回该知识点对应的所有视频 :param request: :param args: :param kwa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KnowledgeVideoViewSet:
"""知识点视频"""
def get_queryset(self):
"""获取知识点视频 根据知识点id查询视频 :return:"""
try:
return KnowVideo.objects.filter(knowledge=int(self.kwargs['pk']))
except:
return KnowVideo.objects.all()
def retrieve(self, request, *args, **kwargs):
... | the_stack_v2_python_sparse | apps/library/views.py | bbright3493/gz_v1.0.0 | train | 0 |
f92a3e2f707a8af65f66bb923b044c36e3c64b51 | [
"Idevice.__init__(self, x_(u'Java Applet'), x_(u'University of Auckland'), u'', u'', u'', parentNode)\nself.emphasis = Idevice.NoEmphasis\nself.appletCode = u''\nself.fileInstruc = u''\nself.codeInstruc = u''",
"log.debug(u'uploadFile ' + unicode(filePath))\nresourceFile = Path(filePath)\nassert (self.parentNode,... | <|body_start_0|>
Idevice.__init__(self, x_(u'Java Applet'), x_(u'University of Auckland'), u'', u'', u'', parentNode)
self.emphasis = Idevice.NoEmphasis
self.appletCode = u''
self.fileInstruc = u''
self.codeInstruc = u''
<|end_body_0|>
<|body_start_1|>
log.debug(u'upload... | Java Applet Idevice. Enables you to embed java applet in the browser | AppletIdevice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppletIdevice:
"""Java Applet Idevice. Enables you to embed java applet in the browser"""
def __init__(self, parentNode=None):
"""Sets up the idevice title and instructions etc"""
<|body_0|>
def uploadFile(self, filePath):
"""Store the upload files in the package... | stack_v2_sparse_classes_36k_train_025317 | 2,070 | no_license | [
{
"docstring": "Sets up the idevice title and instructions etc",
"name": "__init__",
"signature": "def __init__(self, parentNode=None)"
},
{
"docstring": "Store the upload files in the package Needs to be in a package to work.",
"name": "uploadFile",
"signature": "def uploadFile(self, fi... | 3 | null | Implement the Python class `AppletIdevice` described below.
Class description:
Java Applet Idevice. Enables you to embed java applet in the browser
Method signatures and docstrings:
- def __init__(self, parentNode=None): Sets up the idevice title and instructions etc
- def uploadFile(self, filePath): Store the upload... | Implement the Python class `AppletIdevice` described below.
Class description:
Java Applet Idevice. Enables you to embed java applet in the browser
Method signatures and docstrings:
- def __init__(self, parentNode=None): Sets up the idevice title and instructions etc
- def uploadFile(self, filePath): Store the upload... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class AppletIdevice:
"""Java Applet Idevice. Enables you to embed java applet in the browser"""
def __init__(self, parentNode=None):
"""Sets up the idevice title and instructions etc"""
<|body_0|>
def uploadFile(self, filePath):
"""Store the upload files in the package... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppletIdevice:
"""Java Applet Idevice. Enables you to embed java applet in the browser"""
def __init__(self, parentNode=None):
"""Sets up the idevice title and instructions etc"""
Idevice.__init__(self, x_(u'Java Applet'), x_(u'University of Auckland'), u'', u'', u'', parentNode)
... | the_stack_v2_python_sparse | eXe/rev1889-1952/left-trunk-1952/exe/idevices/appletidevice.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
a9e64e69fb3e1ccffd7c6b2938afb6c82c67c5e5 | [
"self.num_days_to_keep = num_days_to_keep\nself.num_secs_to_keep = num_secs_to_keep\nself.worm_retention = worm_retention",
"if dictionary is None:\n return None\nnum_days_to_keep = dictionary.get('numDaysToKeep')\nnum_secs_to_keep = dictionary.get('numSecsToKeep')\nworm_retention = cohesity_management_sdk.mod... | <|body_start_0|>
self.num_days_to_keep = num_days_to_keep
self.num_secs_to_keep = num_secs_to_keep
self.worm_retention = worm_retention
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
num_days_to_keep = dictionary.get('numDaysToKeep')
num_s... | Implementation of the 'RetentionPolicyProto' model. Message that specifies the retention policy for backup snapshots. Attributes: num_days_to_keep (long|int): The number of days to keep the snapshots for a backup run. num_secs_to_keep (int): The number of seconds to keep the snapshots for a backup run. worm_retention (... | RetentionPolicyProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetentionPolicyProto:
"""Implementation of the 'RetentionPolicyProto' model. Message that specifies the retention policy for backup snapshots. Attributes: num_days_to_keep (long|int): The number of days to keep the snapshots for a backup run. num_secs_to_keep (int): The number of seconds to keep ... | stack_v2_sparse_classes_36k_train_025318 | 2,976 | permissive | [
{
"docstring": "Constructor for the RetentionPolicyProto class",
"name": "__init__",
"signature": "def __init__(self, num_days_to_keep=None, num_secs_to_keep=None, worm_retention=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio... | 2 | null | Implement the Python class `RetentionPolicyProto` described below.
Class description:
Implementation of the 'RetentionPolicyProto' model. Message that specifies the retention policy for backup snapshots. Attributes: num_days_to_keep (long|int): The number of days to keep the snapshots for a backup run. num_secs_to_kee... | Implement the Python class `RetentionPolicyProto` described below.
Class description:
Implementation of the 'RetentionPolicyProto' model. Message that specifies the retention policy for backup snapshots. Attributes: num_days_to_keep (long|int): The number of days to keep the snapshots for a backup run. num_secs_to_kee... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RetentionPolicyProto:
"""Implementation of the 'RetentionPolicyProto' model. Message that specifies the retention policy for backup snapshots. Attributes: num_days_to_keep (long|int): The number of days to keep the snapshots for a backup run. num_secs_to_keep (int): The number of seconds to keep ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetentionPolicyProto:
"""Implementation of the 'RetentionPolicyProto' model. Message that specifies the retention policy for backup snapshots. Attributes: num_days_to_keep (long|int): The number of days to keep the snapshots for a backup run. num_secs_to_keep (int): The number of seconds to keep the snapshots... | the_stack_v2_python_sparse | cohesity_management_sdk/models/retention_policy_proto.py | cohesity/management-sdk-python | train | 24 |
5fb83e5a5a3f67df233eb30e8b4390e94e8ab460 | [
"_diff = np.abs(self.dataset['TAT_DI_R'].array - self.dataset['TAT_ND_R'].array)\nmask = pd.Series(np.zeros_like(self.dataset['TAT_DI_R'].array), index=self.dataset['TAT_DI_R'].index)\nmask.loc[_diff > TEMPERATURE_THRESHOLD] = MASKED\nreturn mask",
"if test:\n flag = self.test_flag\nelse:\n flag = self._get... | <|body_start_0|>
_diff = np.abs(self.dataset['TAT_DI_R'].array - self.dataset['TAT_ND_R'].array)
mask = pd.Series(np.zeros_like(self.dataset['TAT_DI_R'].array), index=self.dataset['TAT_DI_R'].index)
mask.loc[_diff > TEMPERATURE_THRESHOLD] = MASKED
return mask
<|end_body_0|>
<|body_start... | This class adds a flag to the rosemount temperatures if the two temperatures disagree by more than a given absolute value. This is given by the module constant TEMPERATURE_THRESHOLD. | RosemountTempDeltaFlag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RosemountTempDeltaFlag:
"""This class adds a flag to the rosemount temperatures if the two temperatures disagree by more than a given absolute value. This is given by the module constant TEMPERATURE_THRESHOLD."""
def _get_flag(self):
"""Get the flag value for the new flag"""
... | stack_v2_sparse_classes_36k_train_025319 | 3,355 | no_license | [
{
"docstring": "Get the flag value for the new flag",
"name": "_get_flag",
"signature": "def _get_flag(self)"
},
{
"docstring": "Entry point for the flagging module.",
"name": "_flag",
"signature": "def _flag(self, test=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010645 | Implement the Python class `RosemountTempDeltaFlag` described below.
Class description:
This class adds a flag to the rosemount temperatures if the two temperatures disagree by more than a given absolute value. This is given by the module constant TEMPERATURE_THRESHOLD.
Method signatures and docstrings:
- def _get_fl... | Implement the Python class `RosemountTempDeltaFlag` described below.
Class description:
This class adds a flag to the rosemount temperatures if the two temperatures disagree by more than a given absolute value. This is given by the module constant TEMPERATURE_THRESHOLD.
Method signatures and docstrings:
- def _get_fl... | e8c54f78a97166c5f66b2196ea4d6eb7a33a0bc4 | <|skeleton|>
class RosemountTempDeltaFlag:
"""This class adds a flag to the rosemount temperatures if the two temperatures disagree by more than a given absolute value. This is given by the module constant TEMPERATURE_THRESHOLD."""
def _get_flag(self):
"""Get the flag value for the new flag"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RosemountTempDeltaFlag:
"""This class adds a flag to the rosemount temperatures if the two temperatures disagree by more than a given absolute value. This is given by the module constant TEMPERATURE_THRESHOLD."""
def _get_flag(self):
"""Get the flag value for the new flag"""
_diff = np.ab... | the_stack_v2_python_sparse | ppodd/flags/p_rosemount_temps.py | FAAM-146/decades-ppandas | train | 0 |
4072fcdc01f9cbdfec09d1200b0ec7ec86ad7b8f | [
"if author.has_perm('social.add_score'):\n score = self.get_or_create(author=author, user=user, axis=axis)\n score.score = count\n score.save()",
"points = self.filter(axis=axis)\nresult = points.aggregate(average=Avg('score'))\nreturn result['average']",
"points = self.filter(axis=axis)\nresult = poin... | <|body_start_0|>
if author.has_perm('social.add_score'):
score = self.get_or_create(author=author, user=user, axis=axis)
score.score = count
score.save()
<|end_body_0|>
<|body_start_1|>
points = self.filter(axis=axis)
result = points.aggregate(average=Avg('sc... | Manager de points | ScoreManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScoreManager:
"""Manager de points"""
def add(self, author, user, count=1, axis=0):
"""Ajouter des points à un utilisateur sur un axe"""
<|body_0|>
def get_average(self, user, axis=0):
"""Renvoyer le score moyen d'un utilisateur sur un axe"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_025320 | 2,106 | no_license | [
{
"docstring": "Ajouter des points à un utilisateur sur un axe",
"name": "add",
"signature": "def add(self, author, user, count=1, axis=0)"
},
{
"docstring": "Renvoyer le score moyen d'un utilisateur sur un axe",
"name": "get_average",
"signature": "def get_average(self, user, axis=0)"
... | 3 | null | Implement the Python class `ScoreManager` described below.
Class description:
Manager de points
Method signatures and docstrings:
- def add(self, author, user, count=1, axis=0): Ajouter des points à un utilisateur sur un axe
- def get_average(self, user, axis=0): Renvoyer le score moyen d'un utilisateur sur un axe
- ... | Implement the Python class `ScoreManager` described below.
Class description:
Manager de points
Method signatures and docstrings:
- def add(self, author, user, count=1, axis=0): Ajouter des points à un utilisateur sur un axe
- def get_average(self, user, axis=0): Renvoyer le score moyen d'un utilisateur sur un axe
- ... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class ScoreManager:
"""Manager de points"""
def add(self, author, user, count=1, axis=0):
"""Ajouter des points à un utilisateur sur un axe"""
<|body_0|>
def get_average(self, user, axis=0):
"""Renvoyer le score moyen d'un utilisateur sur un axe"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScoreManager:
"""Manager de points"""
def add(self, author, user, count=1, axis=0):
"""Ajouter des points à un utilisateur sur un axe"""
if author.has_perm('social.add_score'):
score = self.get_or_create(author=author, user=user, axis=axis)
score.score = count
... | the_stack_v2_python_sparse | scoop/user/social/models/rating/score.py | artscoop/scoop | train | 0 |
15a33f3fd93703409a0fe7597f24a7ee84e5a6f6 | [
"if self.is_active(global_step):\n tic = self._compute(global_step, params, batch_loss).item()\n if self._verbose:\n print(f'[Step {global_step}] TICTrace: {tic:.4f}')\n self.output[global_step]['tic_trace'] = tic\n if self._check:\n self.__run_check(global_step, params, batch_loss)",
"s... | <|body_start_0|>
if self.is_active(global_step):
tic = self._compute(global_step, params, batch_loss).item()
if self._verbose:
print(f'[Step {global_step}] TICTrace: {tic:.4f}')
self.output[global_step]['tic_trace'] = tic
if self._check:
... | TIC approximation using the trace of curvature and gradient covariance. | TICTrace | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TICTrace:
"""TIC approximation using the trace of curvature and gradient covariance."""
def compute(self, global_step, params, batch_loss):
"""Compute TICTrace. Args: global_step (int): The current iteration number. params ([torch.Tensor]): List of torch.Tensors holding the network's... | stack_v2_sparse_classes_36k_train_025321 | 9,326 | permissive | [
{
"docstring": "Compute TICTrace. Args: global_step (int): The current iteration number. params ([torch.Tensor]): List of torch.Tensors holding the network's parameters. batch_loss (torch.Tensor): Mini-batch loss from current step.",
"name": "compute",
"signature": "def compute(self, global_step, params... | 3 | stack_v2_sparse_classes_30k_test_000512 | Implement the Python class `TICTrace` described below.
Class description:
TIC approximation using the trace of curvature and gradient covariance.
Method signatures and docstrings:
- def compute(self, global_step, params, batch_loss): Compute TICTrace. Args: global_step (int): The current iteration number. params ([to... | Implement the Python class `TICTrace` described below.
Class description:
TIC approximation using the trace of curvature and gradient covariance.
Method signatures and docstrings:
- def compute(self, global_step, params, batch_loss): Compute TICTrace. Args: global_step (int): The current iteration number. params ([to... | 5bd5ab3cda03eda0b0bf276f29d5c28b83d70b06 | <|skeleton|>
class TICTrace:
"""TIC approximation using the trace of curvature and gradient covariance."""
def compute(self, global_step, params, batch_loss):
"""Compute TICTrace. Args: global_step (int): The current iteration number. params ([torch.Tensor]): List of torch.Tensors holding the network's... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TICTrace:
"""TIC approximation using the trace of curvature and gradient covariance."""
def compute(self, global_step, params, batch_loss):
"""Compute TICTrace. Args: global_step (int): The current iteration number. params ([torch.Tensor]): List of torch.Tensors holding the network's parameters. ... | the_stack_v2_python_sparse | cockpit/quantities/tic.py | MeNicefellow/cockpit | train | 0 |
4b025ec185b853b251073e616ac9ff5582563a30 | [
"tf.config.run_functions_eagerly(True)\nself.batch_size = batch_size\nself.latent_dim = latent_dim\nself.intermediate_dim = intermediate_dim\nself.epochs = epochs\nself.epsilon_std = epsilon_std\nself.beta = beta\nself.validation_split = validation_split\nself.verbose = verbose\nself.name = f'VAE_latent_dim={latent... | <|body_start_0|>
tf.config.run_functions_eagerly(True)
self.batch_size = batch_size
self.latent_dim = latent_dim
self.intermediate_dim = intermediate_dim
self.epochs = epochs
self.epsilon_std = epsilon_std
self.beta = beta
self.validation_split = validatio... | VAE class wrapping `VAEModel`, exposing an interface friendly to CbAS/DbAS. | VAE | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VAE:
"""VAE class wrapping `VAEModel`, exposing an interface friendly to CbAS/DbAS."""
def __init__(self, seq_length: int, alphabet: str, batch_size: int=10, latent_dim: int=2, intermediate_dim: int=250, epochs: int=10, epsilon_std: float=1.0, beta: float=1, validation_split: float=0.2, verb... | stack_v2_sparse_classes_36k_train_025322 | 8,578 | permissive | [
{
"docstring": "Create the VAE.",
"name": "__init__",
"signature": "def __init__(self, seq_length: int, alphabet: str, batch_size: int=10, latent_dim: int=2, intermediate_dim: int=250, epochs: int=10, epsilon_std: float=1.0, beta: float=1, validation_split: float=0.2, verbose: bool=True)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_val_000650 | Implement the Python class `VAE` described below.
Class description:
VAE class wrapping `VAEModel`, exposing an interface friendly to CbAS/DbAS.
Method signatures and docstrings:
- def __init__(self, seq_length: int, alphabet: str, batch_size: int=10, latent_dim: int=2, intermediate_dim: int=250, epochs: int=10, epsi... | Implement the Python class `VAE` described below.
Class description:
VAE class wrapping `VAEModel`, exposing an interface friendly to CbAS/DbAS.
Method signatures and docstrings:
- def __init__(self, seq_length: int, alphabet: str, batch_size: int=10, latent_dim: int=2, intermediate_dim: int=250, epochs: int=10, epsi... | 744e792456d93e8c48fc58220689c0b4cff6ded9 | <|skeleton|>
class VAE:
"""VAE class wrapping `VAEModel`, exposing an interface friendly to CbAS/DbAS."""
def __init__(self, seq_length: int, alphabet: str, batch_size: int=10, latent_dim: int=2, intermediate_dim: int=250, epochs: int=10, epsilon_std: float=1.0, beta: float=1, validation_split: float=0.2, verb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VAE:
"""VAE class wrapping `VAEModel`, exposing an interface friendly to CbAS/DbAS."""
def __init__(self, seq_length: int, alphabet: str, batch_size: int=10, latent_dim: int=2, intermediate_dim: int=250, epochs: int=10, epsilon_std: float=1.0, beta: float=1, validation_split: float=0.2, verbose: bool=Tru... | the_stack_v2_python_sparse | flexs/utils/VAE_utils.py | jonshao/FLEXS | train | 0 |
6b360c4356e4d2034743c94f923b69f34a512380 | [
"self.mapping = {}\nself.capacity = capacity\nself.head = DLLNode(-1, -1)\nself.tail = DLLNode(-1, -1)\nself.head.next = self.tail\nself.tail.prev = self.head",
"if key not in self.mapping:\n return -1\ncurrNode = self.mapping[key]\nself._remove(currNode)\nself._add(currNode)\nreturn currNode.val",
"if key i... | <|body_start_0|>
self.mapping = {}
self.capacity = capacity
self.head = DLLNode(-1, -1)
self.tail = DLLNode(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
<|end_body_0|>
<|body_start_1|>
if key not in self.mapping:
return -1
cur... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int Need a data structure that will support insert and deletes Keep a hashtable that maps the key to the node in the LRU have 2 ends of the ds - head -> LRU - tail -> MRU so any puts will be done on the tail - as they will be the... | stack_v2_sparse_classes_36k_train_025323 | 3,451 | no_license | [
{
"docstring": ":type capacity: int Need a data structure that will support insert and deletes Keep a hashtable that maps the key to the node in the LRU have 2 ends of the ds - head -> LRU - tail -> MRU so any puts will be done on the tail - as they will be the most recently used objects any retirevals - should... | 5 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int Need a data structure that will support insert and deletes Keep a hashtable that maps the key to the node in the LRU have 2 ends... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int Need a data structure that will support insert and deletes Keep a hashtable that maps the key to the node in the LRU have 2 ends... | bbfee57ae89d23cd4f4132fbb62d8931ea654a0e | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int Need a data structure that will support insert and deletes Keep a hashtable that maps the key to the node in the LRU have 2 ends of the ds - head -> LRU - tail -> MRU so any puts will be done on the tail - as they will be the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int Need a data structure that will support insert and deletes Keep a hashtable that maps the key to the node in the LRU have 2 ends of the ds - head -> LRU - tail -> MRU so any puts will be done on the tail - as they will be the most recently... | the_stack_v2_python_sparse | Data Structures/LRU Cache.py | timpark0807/self-taught-swe | train | 1 | |
22916b161aac9f6f9970358de2a1e00e38c9de18 | [
"pygame.sprite.Sprite.__init__(self)\nself.width = 75\nself.height = 15\nself.image = pygame.Surface([self.width, self.height])\nself.image.fill(white)\nself.rect = self.image.get_rect()\nself.screenheight = pygame.display.get_surface().get_height()\nself.screenwidth = pygame.display.get_surface().get_width()\nself... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
self.width = 75
self.height = 15
self.image = pygame.Surface([self.width, self.height])
self.image.fill(white)
self.rect = self.image.get_rect()
self.screenheight = pygame.display.get_surface().get_height()
... | This class represents the bar at the bottom that the player controls. | Player | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""This class represents the bar at the bottom that the player controls."""
def __init__(self):
"""Constructor for Player."""
<|body_0|>
def update(self):
"""Update the player position."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pyg... | stack_v2_sparse_classes_36k_train_025324 | 7,974 | permissive | [
{
"docstring": "Constructor for Player.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update the player position.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018026 | Implement the Python class `Player` described below.
Class description:
This class represents the bar at the bottom that the player controls.
Method signatures and docstrings:
- def __init__(self): Constructor for Player.
- def update(self): Update the player position. | Implement the Python class `Player` described below.
Class description:
This class represents the bar at the bottom that the player controls.
Method signatures and docstrings:
- def __init__(self): Constructor for Player.
- def update(self): Update the player position.
<|skeleton|>
class Player:
"""This class re... | 50219d3884fdf9380436965c456f15dbcd16d207 | <|skeleton|>
class Player:
"""This class represents the bar at the bottom that the player controls."""
def __init__(self):
"""Constructor for Player."""
<|body_0|>
def update(self):
"""Update the player position."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Player:
"""This class represents the bar at the bottom that the player controls."""
def __init__(self):
"""Constructor for Player."""
pygame.sprite.Sprite.__init__(self)
self.width = 75
self.height = 15
self.image = pygame.Surface([self.width, self.height])
... | the_stack_v2_python_sparse | pygame/simple-breakout-example.py | CoderDojoLu/py-club | train | 0 |
55a8d31018ec74d8722fc0afe894a7a192e2d665 | [
"audit = AuditResource.get_by_id(audit_uuid=audit_uuid, withContacts=False, withScans=False)\nif audit['approved'] == True:\n abort(400, 'Already approved')\nschema = AuditUpdateSchema(only=['approved', 'submitted'])\nparams, _errors = schema.load({'approved': True, 'submitted': True})\nwith db.database.atomic()... | <|body_start_0|>
audit = AuditResource.get_by_id(audit_uuid=audit_uuid, withContacts=False, withScans=False)
if audit['approved'] == True:
abort(400, 'Already approved')
schema = AuditUpdateSchema(only=['approved', 'submitted'])
params, _errors = schema.load({'approved': True... | AuditApproval | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditApproval:
def post(self, audit_uuid):
"""Approve the specified audit submission"""
<|body_0|>
def delete(self, audit_uuid):
"""Withdraw the approval of the specified audit submission"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
audit = Audit... | stack_v2_sparse_classes_36k_train_025325 | 18,857 | no_license | [
{
"docstring": "Approve the specified audit submission",
"name": "post",
"signature": "def post(self, audit_uuid)"
},
{
"docstring": "Withdraw the approval of the specified audit submission",
"name": "delete",
"signature": "def delete(self, audit_uuid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016025 | Implement the Python class `AuditApproval` described below.
Class description:
Implement the AuditApproval class.
Method signatures and docstrings:
- def post(self, audit_uuid): Approve the specified audit submission
- def delete(self, audit_uuid): Withdraw the approval of the specified audit submission | Implement the Python class `AuditApproval` described below.
Class description:
Implement the AuditApproval class.
Method signatures and docstrings:
- def post(self, audit_uuid): Approve the specified audit submission
- def delete(self, audit_uuid): Withdraw the approval of the specified audit submission
<|skeleton|>... | 7b67aa682d73c8a8d7f0f19b2a90e69c40761c58 | <|skeleton|>
class AuditApproval:
def post(self, audit_uuid):
"""Approve the specified audit submission"""
<|body_0|>
def delete(self, audit_uuid):
"""Withdraw the approval of the specified audit submission"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditApproval:
def post(self, audit_uuid):
"""Approve the specified audit submission"""
audit = AuditResource.get_by_id(audit_uuid=audit_uuid, withContacts=False, withScans=False)
if audit['approved'] == True:
abort(400, 'Already approved')
schema = AuditUpdateSchem... | the_stack_v2_python_sparse | rem/apis/audit.py | recruit-tech/casval | train | 6 | |
85f596e6c859893db0d0019b8ffb20508bf7ef9e | [
"if isinstance(item, cls):\n return item\nif not type(item) in (str, int):\n raise TypeError(f'Source type ({type(item)}) for casting not handled.')\nfor i in list(cls):\n if i == item:\n return i\nif silent_fail:\n return None\nraise ValueError(f'`{cls.__qualname__}` casting failed. Item: {item}... | <|body_start_0|>
if isinstance(item, cls):
return item
if not type(item) in (str, int):
raise TypeError(f'Source type ({type(item)}) for casting not handled.')
for i in list(cls):
if i == item:
return i
if silent_fail:
retur... | Mixin for some extend enum functionality. | FlagEnumMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlagEnumMixin:
"""Mixin for some extend enum functionality."""
def cast(cls, item: Union[str, int], *, silent_fail=False):
"""Cast ``item`` to the corresponding :class:`FlagEnumMixin`. ``item`` can only be either ``code`` (:class:`str`) or ``name`` (:class:`int`). If ``silent_fail`` ... | stack_v2_sparse_classes_36k_train_025326 | 11,828 | permissive | [
{
"docstring": "Cast ``item`` to the corresponding :class:`FlagEnumMixin`. ``item`` can only be either ``code`` (:class:`str`) or ``name`` (:class:`int`). If ``silent_fail`` is ``True``, returns ``None`` if not found. Otherwise, raises :class:`ValueError`. :param item: item to be casted :param silent_fail: if t... | 2 | stack_v2_sparse_classes_30k_train_013798 | Implement the Python class `FlagEnumMixin` described below.
Class description:
Mixin for some extend enum functionality.
Method signatures and docstrings:
- def cast(cls, item: Union[str, int], *, silent_fail=False): Cast ``item`` to the corresponding :class:`FlagEnumMixin`. ``item`` can only be either ``code`` (:cla... | Implement the Python class `FlagEnumMixin` described below.
Class description:
Mixin for some extend enum functionality.
Method signatures and docstrings:
- def cast(cls, item: Union[str, int], *, silent_fail=False): Cast ``item`` to the corresponding :class:`FlagEnumMixin`. ``item`` can only be either ``code`` (:cla... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class FlagEnumMixin:
"""Mixin for some extend enum functionality."""
def cast(cls, item: Union[str, int], *, silent_fail=False):
"""Cast ``item`` to the corresponding :class:`FlagEnumMixin`. ``item`` can only be either ``code`` (:class:`str`) or ``name`` (:class:`int`). If ``silent_fail`` ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlagEnumMixin:
"""Mixin for some extend enum functionality."""
def cast(cls, item: Union[str, int], *, silent_fail=False):
"""Cast ``item`` to the corresponding :class:`FlagEnumMixin`. ``item`` can only be either ``code`` (:class:`str`) or ``name`` (:class:`int`). If ``silent_fail`` is ``True``, ... | the_stack_v2_python_sparse | extutils/flags/main.py | RxJellyBot/Jelly-Bot | train | 5 |
6ce5c4a7122a3635ffa1c02d3ba6fc41e2e35804 | [
"self.request_user = kwargs.pop('user', None)\nself.workflow = kwargs.pop('workflow')\nself.user_obj = None\nsuper().__init__(*args, **kwargs)",
"form_data = super().clean()\nself.user_obj = get_user_model().objects.filter(email__iexact=form_data['user_email']).first()\nif not self.user_obj:\n self.add_error('... | <|body_start_0|>
self.request_user = kwargs.pop('user', None)
self.workflow = kwargs.pop('workflow')
self.user_obj = None
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
form_data = super().clean()
self.user_obj = get_user_model().objects.filter(email__... | Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list) | SharedForm | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedForm:
"""Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)"""
def __init__(self, *args, **kwargs... | stack_v2_sparse_classes_36k_train_025327 | 3,730 | permissive | [
{
"docstring": "Set the request user, workflow.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check that the request has the correct user.",
"name": "clean",
"signature": "def clean(self) -> Dict"
}
] | 2 | null | Implement the Python class `SharedForm` described below.
Class description:
Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)
Me... | Implement the Python class `SharedForm` described below.
Class description:
Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)
Me... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class SharedForm:
"""Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)"""
def __init__(self, *args, **kwargs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SharedForm:
"""Form to ask for a user email to add to those sharing the workflow. The form uses two parameters: :param user: The user making the request (to detect self-sharing) :param workflow: The workflow to share (to detect users already in the list)"""
def __init__(self, *args, **kwargs):
""... | the_stack_v2_python_sparse | ontask/workflow/forms/attribute_shared.py | abelardopardo/ontask_b | train | 43 |
21703d416a3d715ae2205e74a456ac197f1b2f17 | [
"my_stack = []\nlength = len(nums)\nres = [-1] * length\nfor i in range(length):\n while my_stack and nums[my_stack[-1]] < nums[i]:\n res[my_stack.pop()] = nums[i]\n my_stack.append(i)\nfor i in range(length):\n while my_stack and nums[my_stack[-1]] < nums[i]:\n res[my_stack.pop()] = nums[i]\... | <|body_start_0|>
my_stack = []
length = len(nums)
res = [-1] * length
for i in range(length):
while my_stack and nums[my_stack[-1]] < nums[i]:
res[my_stack.pop()] = nums[i]
my_stack.append(i)
for i in range(length):
while my_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElements(self, nums):
"""Stack solution O(n) :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements2(self, nums):
"""Naive solution O(n^2) :type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_025328 | 1,122 | no_license | [
{
"docstring": "Stack solution O(n) :type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements",
"signature": "def nextGreaterElements(self, nums)"
},
{
"docstring": "Naive solution O(n^2) :type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements2",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_008709 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements(self, nums): Stack solution O(n) :type nums: List[int] :rtype: List[int]
- def nextGreaterElements2(self, nums): Naive solution O(n^2) :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements(self, nums): Stack solution O(n) :type nums: List[int] :rtype: List[int]
- def nextGreaterElements2(self, nums): Naive solution O(n^2) :type nums: List[in... | c14d8829c95f61ff6691816e8c0de76b9319f389 | <|skeleton|>
class Solution:
def nextGreaterElements(self, nums):
"""Stack solution O(n) :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements2(self, nums):
"""Naive solution O(n^2) :type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElements(self, nums):
"""Stack solution O(n) :type nums: List[int] :rtype: List[int]"""
my_stack = []
length = len(nums)
res = [-1] * length
for i in range(length):
while my_stack and nums[my_stack[-1]] < nums[i]:
res... | the_stack_v2_python_sparse | medium/next-greater-element-ii/solution.py | hsuanhauliu/leetcode-solutions | train | 0 | |
3545c354c44c4530a2c80f72bfc52dd304b99010 | [
"user_id = token_auth.current_user()\nfavorited = ProjectService.is_favorited(project_id, user_id)\nif favorited is True:\n return ({'favorited': True}, 200)\nreturn ({'favorited': False}, 200)",
"authenticated_user_id = token_auth.current_user()\nfavorite_dto = ProjectFavoriteDTO()\nfavorite_dto.project_id = ... | <|body_start_0|>
user_id = token_auth.current_user()
favorited = ProjectService.is_favorited(project_id, user_id)
if favorited is True:
return ({'favorited': True}, 200)
return ({'favorited': False}, 200)
<|end_body_0|>
<|body_start_1|>
authenticated_user_id = token_... | ProjectsFavoritesAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsFavoritesAPI:
def get(self, project_id: int):
"""Validate that project is favorited --- tags: - favorites produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHer... | stack_v2_sparse_classes_36k_train_025329 | 3,833 | permissive | [
{
"docstring": "Validate that project is favorited --- tags: - favorites produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: project_id in: path description: Unique project ID re... | 3 | null | Implement the Python class `ProjectsFavoritesAPI` described below.
Class description:
Implement the ProjectsFavoritesAPI class.
Method signatures and docstrings:
- def get(self, project_id: int): Validate that project is favorited --- tags: - favorites produces: - application/json parameters: - in: header name: Autho... | Implement the Python class `ProjectsFavoritesAPI` described below.
Class description:
Implement the ProjectsFavoritesAPI class.
Method signatures and docstrings:
- def get(self, project_id: int): Validate that project is favorited --- tags: - favorites produces: - application/json parameters: - in: header name: Autho... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class ProjectsFavoritesAPI:
def get(self, project_id: int):
"""Validate that project is favorited --- tags: - favorites produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectsFavoritesAPI:
def get(self, project_id: int):
"""Validate that project is favorited --- tags: - favorites produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: pr... | the_stack_v2_python_sparse | backend/api/projects/favorites.py | hotosm/tasking-manager | train | 526 | |
8413b45f0f4d872fe6755e67ff45a7e0316747ae | [
"self.nums = []\nself.values = []\nfor i in range(0, len(A), 2):\n self.nums.append(A[i])\n self.values.append(A[i + 1])\nself.off = 0\nfor i in range(1, len(self.nums)):\n self.nums[i] += self.nums[i - 1]\nself.lo = 0",
"if self.off > self.nums[-1]:\n return -1\nself.off += n\nif self.off > self.nums... | <|body_start_0|>
self.nums = []
self.values = []
for i in range(0, len(A), 2):
self.nums.append(A[i])
self.values.append(A[i + 1])
self.off = 0
for i in range(1, len(self.nums)):
self.nums[i] += self.nums[i - 1]
self.lo = 0
<|end_body_0... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums = []
self.values = []
for i in range(0, len(A), 2):
... | stack_v2_sparse_classes_36k_train_025330 | 827 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015705 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | c026f2969c784827fac702b34b07a9268b70b62a | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.nums = []
self.values = []
for i in range(0, len(A), 2):
self.nums.append(A[i])
self.values.append(A[i + 1])
self.off = 0
for i in range(1, len(self.nums)):
sel... | the_stack_v2_python_sparse | codes/contest/leetcode/rle-iterator.py | jiluhu/dirtysalt.github.io | train | 0 | |
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"super().__init__(num_locations, coverages_per_location)\nself.num_layers = num_layers\nself.dtypes = OrderedDict([('output_id', 'i'), ('summary_id', 'i'), ('summaryset_id', 'i')])\nself.data_length = num_locations * coverages_per_location * num_layers\nself.file_name = os.path.join(directory, 'fmsummaryxref.bin')"... | <|body_start_0|>
super().__init__(num_locations, coverages_per_location)
self.num_layers = num_layers
self.dtypes = OrderedDict([('output_id', 'i'), ('summary_id', 'i'), ('summaryset_id', 'i')])
self.data_length = num_locations * coverages_per_location * num_layers
self.file_name... | Generate data for Financial Model Summary Cross Reference dummy model Oasis file. This file shows how insurance losses are summed together at various levels by summarycalc. Attributes: generate_data: Generate Financial Model Summary Cross Reference dummy model Oasis file data. | FMSummaryXrefFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FMSummaryXrefFile:
"""Generate data for Financial Model Summary Cross Reference dummy model Oasis file. This file shows how insurance losses are summed together at various levels by summarycalc. Attributes: generate_data: Generate Financial Model Summary Cross Reference dummy model Oasis file dat... | stack_v2_sparse_classes_36k_train_025331 | 39,722 | permissive | [
{
"docstring": "Initialise Financial Model Summary Cross Reference file class. Args: num_locations (int): number of locations. coverages_per_location (int): number of coverage types per location. num_layers (int): number of layers. directory (str): dummy model file destination.",
"name": "__init__",
"si... | 2 | null | Implement the Python class `FMSummaryXrefFile` described below.
Class description:
Generate data for Financial Model Summary Cross Reference dummy model Oasis file. This file shows how insurance losses are summed together at various levels by summarycalc. Attributes: generate_data: Generate Financial Model Summary Cro... | Implement the Python class `FMSummaryXrefFile` described below.
Class description:
Generate data for Financial Model Summary Cross Reference dummy model Oasis file. This file shows how insurance losses are summed together at various levels by summarycalc. Attributes: generate_data: Generate Financial Model Summary Cro... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class FMSummaryXrefFile:
"""Generate data for Financial Model Summary Cross Reference dummy model Oasis file. This file shows how insurance losses are summed together at various levels by summarycalc. Attributes: generate_data: Generate Financial Model Summary Cross Reference dummy model Oasis file dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FMSummaryXrefFile:
"""Generate data for Financial Model Summary Cross Reference dummy model Oasis file. This file shows how insurance losses are summed together at various levels by summarycalc. Attributes: generate_data: Generate Financial Model Summary Cross Reference dummy model Oasis file data."""
de... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
9465ff91f06e42642b4fa5dcff5e9cde89d29a0b | [
"self.max_rank = max_rank\nself.problems = problems\nself.languages = languages\nself.results = results\nself.acc_result = acc_result",
"content = ''\nscore_tuple = [(score, userid) for userid, score in score_dict.items()]\nscore_tuple.sort()\nscore_tuple.reverse()\nfor score, userid in score_tuple:\n pr_statu... | <|body_start_0|>
self.max_rank = max_rank
self.problems = problems
self.languages = languages
self.results = results
self.acc_result = acc_result
<|end_body_0|>
<|body_start_1|>
content = ''
score_tuple = [(score, userid) for userid, score in score_dict.items()]
... | Generate rankings list Columns: teamname, pr. solved, score | RankingsGen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RankingsGen:
"""Generate rankings list Columns: teamname, pr. solved, score"""
def __init__(self, max_rank, problems, languages, results, acc_result):
"""@param max_rank: Last rank to be denerated @param problems: List of problems (@see profile/) @param languages: Dict of languages (... | stack_v2_sparse_classes_36k_train_025332 | 3,763 | no_license | [
{
"docstring": "@param max_rank: Last rank to be denerated @param problems: List of problems (@see profile/) @param languages: Dict of languages (@see profile/) @param results: List of Results (@see profile/) @param acc_result: Index of acc result",
"name": "__init__",
"signature": "def __init__(self, m... | 2 | stack_v2_sparse_classes_30k_val_000141 | Implement the Python class `RankingsGen` described below.
Class description:
Generate rankings list Columns: teamname, pr. solved, score
Method signatures and docstrings:
- def __init__(self, max_rank, problems, languages, results, acc_result): @param max_rank: Last rank to be denerated @param problems: List of probl... | Implement the Python class `RankingsGen` described below.
Class description:
Generate rankings list Columns: teamname, pr. solved, score
Method signatures and docstrings:
- def __init__(self, max_rank, problems, languages, results, acc_result): @param max_rank: Last rank to be denerated @param problems: List of probl... | f9b426ebb76eb7321da691a96db2aedb53c5265c | <|skeleton|>
class RankingsGen:
"""Generate rankings list Columns: teamname, pr. solved, score"""
def __init__(self, max_rank, problems, languages, results, acc_result):
"""@param max_rank: Last rank to be denerated @param problems: List of problems (@see profile/) @param languages: Dict of languages (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RankingsGen:
"""Generate rankings list Columns: teamname, pr. solved, score"""
def __init__(self, max_rank, problems, languages, results, acc_result):
"""@param max_rank: Last rank to be denerated @param problems: List of problems (@see profile/) @param languages: Dict of languages (@see profile/... | the_stack_v2_python_sparse | trunk/lib/codehack/server/scoregen.py | BackupTheBerlios/codehack-svn | train | 0 |
30428a56d72072c009f913377ac00609a9bb0946 | [
"self.morse_tree = BinaryTree('')\nwith open(file_in) as morse_file:\n for line in morse_file:\n letter, code = line.split()\n self.follow_and_insert(code, letter)",
"current = self.morse_tree\nfor symbol in code_str:\n 'if _dot_, go to to the left child, else go to the right child'\n \"cre... | <|body_start_0|>
self.morse_tree = BinaryTree('')
with open(file_in) as morse_file:
for line in morse_file:
letter, code = line.split()
self.follow_and_insert(code, letter)
<|end_body_0|>
<|body_start_1|>
current = self.morse_tree
for symbol i... | Morse Code Encoder/Decoder | Coder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coder:
"""Morse Code Encoder/Decoder"""
def __init__(self, file_in: str):
"""Constructor"""
<|body_0|>
def follow_and_insert(self, code_str: str, letter: str):
"""Follow the tree and insert a letter"""
<|body_1|>
def follow_and_retrieve(self, code_st... | stack_v2_sparse_classes_36k_train_025333 | 5,460 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, file_in: str)"
},
{
"docstring": "Follow the tree and insert a letter",
"name": "follow_and_insert",
"signature": "def follow_and_insert(self, code_str: str, letter: str)"
},
{
"docstring": "Follow... | 6 | stack_v2_sparse_classes_30k_train_005253 | Implement the Python class `Coder` described below.
Class description:
Morse Code Encoder/Decoder
Method signatures and docstrings:
- def __init__(self, file_in: str): Constructor
- def follow_and_insert(self, code_str: str, letter: str): Follow the tree and insert a letter
- def follow_and_retrieve(self, code_str: s... | Implement the Python class `Coder` described below.
Class description:
Morse Code Encoder/Decoder
Method signatures and docstrings:
- def __init__(self, file_in: str): Constructor
- def follow_and_insert(self, code_str: str, letter: str): Follow the tree and insert a letter
- def follow_and_retrieve(self, code_str: s... | da880c6c805508c60f92c29cfba65ba2ca922415 | <|skeleton|>
class Coder:
"""Morse Code Encoder/Decoder"""
def __init__(self, file_in: str):
"""Constructor"""
<|body_0|>
def follow_and_insert(self, code_str: str, letter: str):
"""Follow the tree and insert a letter"""
<|body_1|>
def follow_and_retrieve(self, code_st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Coder:
"""Morse Code Encoder/Decoder"""
def __init__(self, file_in: str):
"""Constructor"""
self.morse_tree = BinaryTree('')
with open(file_in) as morse_file:
for line in morse_file:
letter, code = line.split()
self.follow_and_insert(cod... | the_stack_v2_python_sparse | projects/morse/morse.py | thu2pham/DataStructures | train | 0 |
9c52cc6e4a5c6a6dd4c6a1ba19eb2676952f572e | [
"try:\n raw_version = self.client.get('/version')['version']\nexcept KeyError:\n raise VersionNotFoundException('Cannot Find Version at api/v1/version')\nreturn get_version_from_string(raw_version)",
"logger.debug('Validating client and server versions')\nserver_version = self.get_server_version()\nclient_v... | <|body_start_0|>
try:
raw_version = self.client.get('/version')['version']
except KeyError:
raise VersionNotFoundException('Cannot Find Version at api/v1/version')
return get_version_from_string(raw_version)
<|end_body_0|>
<|body_start_1|>
logger.debug('Validatin... | OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata | OMetaServerMixin | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OMetaServerMixin:
"""OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata"""
def get_server_version(self) -> str:
"""Run endpoint /version to check server version :return: Server version"""
<|body_0|>
def validate_versions(self) -> None... | stack_v2_sparse_classes_36k_train_025334 | 2,191 | permissive | [
{
"docstring": "Run endpoint /version to check server version :return: Server version",
"name": "get_server_version",
"signature": "def get_server_version(self) -> str"
},
{
"docstring": "Validate Server & Client versions. They should match. Otherwise, raise VersionMismatchException",
"name"... | 2 | null | Implement the Python class `OMetaServerMixin` described below.
Class description:
OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata
Method signatures and docstrings:
- def get_server_version(self) -> str: Run endpoint /version to check server version :return: Server version
- def... | Implement the Python class `OMetaServerMixin` described below.
Class description:
OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata
Method signatures and docstrings:
- def get_server_version(self) -> str: Run endpoint /version to check server version :return: Server version
- def... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class OMetaServerMixin:
"""OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata"""
def get_server_version(self) -> str:
"""Run endpoint /version to check server version :return: Server version"""
<|body_0|>
def validate_versions(self) -> None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OMetaServerMixin:
"""OpenMetadata API methods related to the Pipeline Entity To be inherited by OpenMetadata"""
def get_server_version(self) -> str:
"""Run endpoint /version to check server version :return: Server version"""
try:
raw_version = self.client.get('/version')['vers... | the_stack_v2_python_sparse | govern/data-meta/OpenMetadata/ingestion/src/metadata/ingestion/ometa/mixins/server_mixin.py | alldatacenter/alldata | train | 774 |
7928b5fa75cbac7c096d66e218533bdeeee3fafa | [
"self.votefunc = votefunc\nself.trackstats = trackstats\nself.clear()",
"zeros = lambda: [0, 0, 0, 0, 0]\nself.samplestats = defaultdict(zeros)\nself.locusstats = defaultdict(zeros)",
"concordclass, geno = self.votefunc(model, genos)\nif self.trackstats:\n self.samplestats[sample][concordclass] += 1\n sel... | <|body_start_0|>
self.votefunc = votefunc
self.trackstats = trackstats
self.clear()
<|end_body_0|>
<|body_start_1|>
zeros = lambda: [0, 0, 0, 0, 0]
self.samplestats = defaultdict(zeros)
self.locusstats = defaultdict(zeros)
<|end_body_1|>
<|body_start_2|>
concord... | Object to form consensus/merged genotypes and track statistics on genotypes that have been processed. Two statistics objects are maintained, samplestats and locustats. They are dictionaries from sample and locus, respectively, to a five element list containing the following genotype counts: 0) unambiguous: exactly one ... | GenotypeMerger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenotypeMerger:
"""Object to form consensus/merged genotypes and track statistics on genotypes that have been processed. Two statistics objects are maintained, samplestats and locustats. They are dictionaries from sample and locus, respectively, to a five element list containing the following gen... | stack_v2_sparse_classes_36k_train_025335 | 30,193 | no_license | [
{
"docstring": "Create a new GenotypeMerger object",
"name": "__init__",
"signature": "def __init__(self, votefunc, trackstats=True)"
},
{
"docstring": "Clear concordance statistics",
"name": "clear",
"signature": "def clear(self)"
},
{
"docstring": "Merge a group of genotypes in... | 5 | null | Implement the Python class `GenotypeMerger` described below.
Class description:
Object to form consensus/merged genotypes and track statistics on genotypes that have been processed. Two statistics objects are maintained, samplestats and locustats. They are dictionaries from sample and locus, respectively, to a five el... | Implement the Python class `GenotypeMerger` described below.
Class description:
Object to form consensus/merged genotypes and track statistics on genotypes that have been processed. Two statistics objects are maintained, samplestats and locustats. They are dictionaries from sample and locus, respectively, to a five el... | dcbbbf67a308d35e157b20a9c76373530510379a | <|skeleton|>
class GenotypeMerger:
"""Object to form consensus/merged genotypes and track statistics on genotypes that have been processed. Two statistics objects are maintained, samplestats and locustats. They are dictionaries from sample and locus, respectively, to a five element list containing the following gen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenotypeMerger:
"""Object to form consensus/merged genotypes and track statistics on genotypes that have been processed. Two statistics objects are maintained, samplestats and locustats. They are dictionaries from sample and locus, respectively, to a five element list containing the following genotype counts:... | the_stack_v2_python_sparse | glu/lib/genolib/merge.py | PiRSquared17/glu-genetics | train | 0 |
96d8cd5eac88153f219915c168ab62a2a67e77bd | [
"if self._cauchy_point is None:\n g = self.jac\n Bg = self.hessp(g)\n self._cauchy_point = -(np.dot(g, g) / np.dot(g, Bg)) * g\nreturn self._cauchy_point",
"if self._newton_point is None:\n g = self.jac\n B = self.hess\n cho_info = scipy.linalg.cho_factor(B)\n self._newton_point = -scipy.lina... | <|body_start_0|>
if self._cauchy_point is None:
g = self.jac
Bg = self.hessp(g)
self._cauchy_point = -(np.dot(g, g) / np.dot(g, Bg)) * g
return self._cauchy_point
<|end_body_0|>
<|body_start_1|>
if self._newton_point is None:
g = self.jac
... | Quadratic subproblem solved by the dogleg method | DoglegSubproblem | [
"Python-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Qhull",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoglegSubproblem:
"""Quadratic subproblem solved by the dogleg method"""
def cauchy_point(self):
"""The Cauchy point is minimal along the direction of steepest descent."""
<|body_0|>
def newton_point(self):
"""The Newton point is a global minimum of the approxima... | stack_v2_sparse_classes_36k_train_025336 | 4,449 | permissive | [
{
"docstring": "The Cauchy point is minimal along the direction of steepest descent.",
"name": "cauchy_point",
"signature": "def cauchy_point(self)"
},
{
"docstring": "The Newton point is a global minimum of the approximate function.",
"name": "newton_point",
"signature": "def newton_poi... | 3 | null | Implement the Python class `DoglegSubproblem` described below.
Class description:
Quadratic subproblem solved by the dogleg method
Method signatures and docstrings:
- def cauchy_point(self): The Cauchy point is minimal along the direction of steepest descent.
- def newton_point(self): The Newton point is a global min... | Implement the Python class `DoglegSubproblem` described below.
Class description:
Quadratic subproblem solved by the dogleg method
Method signatures and docstrings:
- def cauchy_point(self): The Cauchy point is minimal along the direction of steepest descent.
- def newton_point(self): The Newton point is a global min... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class DoglegSubproblem:
"""Quadratic subproblem solved by the dogleg method"""
def cauchy_point(self):
"""The Cauchy point is minimal along the direction of steepest descent."""
<|body_0|>
def newton_point(self):
"""The Newton point is a global minimum of the approxima... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoglegSubproblem:
"""Quadratic subproblem solved by the dogleg method"""
def cauchy_point(self):
"""The Cauchy point is minimal along the direction of steepest descent."""
if self._cauchy_point is None:
g = self.jac
Bg = self.hessp(g)
self._cauchy_point... | the_stack_v2_python_sparse | contrib/python/scipy/py2/scipy/optimize/_trustregion_dogleg.py | catboost/catboost | train | 8,012 |
860a5feddcdaabb4085c774926af5462b3d09d7e | [
"self.path = path\nself.quantization = quantize\nself.deviceid = Models.deviceid(gpu)\nself.device = Models.reference(self.deviceid)\nself.batchsize = batch",
"if self.deviceid == -1 and self.quantization:\n model = self.quantize(model)\nreturn model",
"batch, positions = ([], [])\nfor x, text in enumerate(t... | <|body_start_0|>
self.path = path
self.quantization = quantize
self.deviceid = Models.deviceid(gpu)
self.device = Models.reference(self.deviceid)
self.batchsize = batch
<|end_body_0|>
<|body_start_1|>
if self.deviceid == -1 and self.quantization:
model = self... | Pipeline backed by a Hugging Face Transformers model. | HFModel | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HFModel:
"""Pipeline backed by a Hugging Face Transformers model."""
def __init__(self, path=None, quantize=False, gpu=False, batch=64):
"""Creates a new HFModel. Args: path: optional path to model, accepts Hugging Face model hub id or local path, uses default model for task if not p... | stack_v2_sparse_classes_36k_train_025337 | 3,687 | permissive | [
{
"docstring": "Creates a new HFModel. Args: path: optional path to model, accepts Hugging Face model hub id or local path, uses default model for task if not provided quantize: if model should be quantized, defaults to False gpu: True/False if GPU should be enabled, also supports a GPU device id batch: batch s... | 3 | null | Implement the Python class `HFModel` described below.
Class description:
Pipeline backed by a Hugging Face Transformers model.
Method signatures and docstrings:
- def __init__(self, path=None, quantize=False, gpu=False, batch=64): Creates a new HFModel. Args: path: optional path to model, accepts Hugging Face model h... | Implement the Python class `HFModel` described below.
Class description:
Pipeline backed by a Hugging Face Transformers model.
Method signatures and docstrings:
- def __init__(self, path=None, quantize=False, gpu=False, batch=64): Creates a new HFModel. Args: path: optional path to model, accepts Hugging Face model h... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class HFModel:
"""Pipeline backed by a Hugging Face Transformers model."""
def __init__(self, path=None, quantize=False, gpu=False, batch=64):
"""Creates a new HFModel. Args: path: optional path to model, accepts Hugging Face model hub id or local path, uses default model for task if not p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HFModel:
"""Pipeline backed by a Hugging Face Transformers model."""
def __init__(self, path=None, quantize=False, gpu=False, batch=64):
"""Creates a new HFModel. Args: path: optional path to model, accepts Hugging Face model hub id or local path, uses default model for task if not provided quant... | the_stack_v2_python_sparse | src/python/txtai/pipeline/hfmodel.py | neuml/txtai | train | 4,804 |
c94a2880a63fbaf3791d26f5efd26b8bc47132d7 | [
"self.keyword = keyword\nself.keyvalue = keyvalue\nself.comment = comment",
"rstring = self.keyword + ' ' + str(self.keyvalue)\nif self.comment != None:\n rstring = rstring + ' ; ' + self.comment\nrstring += '\\n'\nreturn rstring"
] | <|body_start_0|>
self.keyword = keyword
self.keyvalue = keyvalue
self.comment = comment
<|end_body_0|>
<|body_start_1|>
rstring = self.keyword + ' ' + str(self.keyvalue)
if self.comment != None:
rstring = rstring + ' ; ' + self.comment
rstring += '\n'
... | Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configuration file. All important values are direct ly read from the object attributes. | ConfKey | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfKey:
"""Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configuration file. All important values are direct ly read from the object attributes."""
def __init__(self, keyword, keyvalue, comment... | stack_v2_sparse_classes_36k_train_025338 | 48,172 | permissive | [
{
"docstring": "Constructor for the keyword class Initializer for the keyword class. The keyword instance is created using all input values. @param keyword: the keword name @type keyword: string @param keyvalue: the keyword value @type keyvalue: string @param comment: the keyword comment @type comment: string",... | 2 | null | Implement the Python class `ConfKey` described below.
Class description:
Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configuration file. All important values are direct ly read from the object attributes.
Method signat... | Implement the Python class `ConfKey` described below.
Class description:
Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configuration file. All important values are direct ly read from the object attributes.
Method signat... | 043c173fd5497c18c2b1bfe8bcff65180bca3996 | <|skeleton|>
class ConfKey:
"""Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configuration file. All important values are direct ly read from the object attributes."""
def __init__(self, keyword, keyvalue, comment... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfKey:
"""Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configuration file. All important values are direct ly read from the object attributes."""
def __init__(self, keyword, keyvalue, comment=None):
... | the_stack_v2_python_sparse | stsdas/pkg/analysis/slitless/axe/axesrc/configfile.py | spacetelescope/stsdas_stripped | train | 1 |
03b9daaeaced139a1295729fe64118e8f1babffa | [
"cases = dict(((unicode(x.id), x) for x in model.Case.objects.filter(pk__in=self.cleaned_data['cases'])))\ntry:\n clean_cases = []\n for case_id in self.cleaned_data['cases']:\n case = cases[case_id]\n if case not in clean_cases:\n clean_cases.append(case)\n if 'cases' in self.init... | <|body_start_0|>
cases = dict(((unicode(x.id), x) for x in model.Case.objects.filter(pk__in=self.cleaned_data['cases'])))
try:
clean_cases = []
for case_id in self.cleaned_data['cases']:
case = cases[case_id]
if case not in clean_cases:
... | Base form for adding/editing suites. | SuiteForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuiteForm:
"""Base form for adding/editing suites."""
def clean_cases(self):
"""Make sure all the ids for the cases are valid and populate self.cleaned_data with the real objects."""
<|body_0|>
def save(self, user=None):
"""Save the suite and case associations.""... | stack_v2_sparse_classes_36k_train_025339 | 4,045 | permissive | [
{
"docstring": "Make sure all the ids for the cases are valid and populate self.cleaned_data with the real objects.",
"name": "clean_cases",
"signature": "def clean_cases(self)"
},
{
"docstring": "Save the suite and case associations.",
"name": "save",
"signature": "def save(self, user=N... | 2 | stack_v2_sparse_classes_30k_train_004380 | Implement the Python class `SuiteForm` described below.
Class description:
Base form for adding/editing suites.
Method signatures and docstrings:
- def clean_cases(self): Make sure all the ids for the cases are valid and populate self.cleaned_data with the real objects.
- def save(self, user=None): Save the suite and... | Implement the Python class `SuiteForm` described below.
Class description:
Base form for adding/editing suites.
Method signatures and docstrings:
- def clean_cases(self): Make sure all the ids for the cases are valid and populate self.cleaned_data with the real objects.
- def save(self, user=None): Save the suite and... | ee54db2fe8ffbf2216d359b7a093b51f2574878e | <|skeleton|>
class SuiteForm:
"""Base form for adding/editing suites."""
def clean_cases(self):
"""Make sure all the ids for the cases are valid and populate self.cleaned_data with the real objects."""
<|body_0|>
def save(self, user=None):
"""Save the suite and case associations.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuiteForm:
"""Base form for adding/editing suites."""
def clean_cases(self):
"""Make sure all the ids for the cases are valid and populate self.cleaned_data with the real objects."""
cases = dict(((unicode(x.id), x) for x in model.Case.objects.filter(pk__in=self.cleaned_data['cases'])))
... | the_stack_v2_python_sparse | moztrap/view/manage/suites/forms.py | isakib/moztrap | train | 1 |
3408aef63c52837c9be1ee4ac3cd129624709f39 | [
"if isinstance(select_template, str):\n self._select_template = lambda _: _select_template_or_default(_, default=select_template)\nelif callable(select_template):\n self._select_template = select_template\nelse:\n raise lena.core.LenaTypeError('select_template must be a string or a callable, {}'.format(sel... | <|body_start_0|>
if isinstance(select_template, str):
self._select_template = lambda _: _select_template_or_default(_, default=select_template)
elif callable(select_template):
self._select_template = select_template
else:
raise lena.core.LenaTypeError('select_... | Create LaTeX from templates and data. | RenderLaTeX | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenderLaTeX:
"""Create LaTeX from templates and data."""
def __init__(self, select_template='', template_dir='.', select_data=None, verbose=0):
"""*select_template* is a string or a callable. If a string, it is the name of the template to be used (unless *context.output.template* ove... | stack_v2_sparse_classes_36k_train_025340 | 5,772 | permissive | [
{
"docstring": "*select_template* is a string or a callable. If a string, it is the name of the template to be used (unless *context.output.template* overwrites that). If *select_template* is a callable, it must accept a value from the flow and return template name. If *select_template* is an empty string (defa... | 2 | null | Implement the Python class `RenderLaTeX` described below.
Class description:
Create LaTeX from templates and data.
Method signatures and docstrings:
- def __init__(self, select_template='', template_dir='.', select_data=None, verbose=0): *select_template* is a string or a callable. If a string, it is the name of the ... | Implement the Python class `RenderLaTeX` described below.
Class description:
Create LaTeX from templates and data.
Method signatures and docstrings:
- def __init__(self, select_template='', template_dir='.', select_data=None, verbose=0): *select_template* is a string or a callable. If a string, it is the name of the ... | 8b85a93e3c15a69d58521332aac3202a077aa7ba | <|skeleton|>
class RenderLaTeX:
"""Create LaTeX from templates and data."""
def __init__(self, select_template='', template_dir='.', select_data=None, verbose=0):
"""*select_template* is a string or a callable. If a string, it is the name of the template to be used (unless *context.output.template* ove... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RenderLaTeX:
"""Create LaTeX from templates and data."""
def __init__(self, select_template='', template_dir='.', select_data=None, verbose=0):
"""*select_template* is a string or a callable. If a string, it is the name of the template to be used (unless *context.output.template* overwrites that)... | the_stack_v2_python_sparse | lena/output/render_latex.py | ynikitenko/lena | train | 4 |
a62603223a5b094fab78054ad5e96eb2c276dda1 | [
"serializer_class = WellListSerializerV1\nif self.request.user and self.request.user.is_authenticated and self.request.user.groups.filter(name=WELLS_VIEWER_ROLE).exists():\n serializer_class = WellListAdminSerializerV1\nreturn serializer_class",
"if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists(... | <|body_start_0|>
serializer_class = WellListSerializerV1
if self.request.user and self.request.user.is_authenticated and self.request.user.groups.filter(name=WELLS_VIEWER_ROLE).exists():
serializer_class = WellListAdminSerializerV1
return serializer_class
<|end_body_0|>
<|body_start... | List and create wells get: returns a list of wells | WellListAPIViewV1 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellListAPIViewV1:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
<|body_0|>
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permiss... | stack_v2_sparse_classes_36k_train_025341 | 32,335 | permissive | [
{
"docstring": "Returns a different serializer class for admin users.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Excludes Unpublished wells for users without edit permissions",
"name": "get_queryset",
"signature": "def get_queryset(... | 2 | null | Implement the Python class `WellListAPIViewV1` described below.
Class description:
List and create wells get: returns a list of wells
Method signatures and docstrings:
- def get_serializer_class(self): Returns a different serializer class for admin users.
- def get_queryset(self): Excludes Unpublished wells for users... | Implement the Python class `WellListAPIViewV1` described below.
Class description:
List and create wells get: returns a list of wells
Method signatures and docstrings:
- def get_serializer_class(self): Returns a different serializer class for admin users.
- def get_queryset(self): Excludes Unpublished wells for users... | 6be3701a8e0085d0c6fa199b2672b7f9f1266a03 | <|skeleton|>
class WellListAPIViewV1:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
<|body_0|>
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permiss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WellListAPIViewV1:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
serializer_class = WellListSerializerV1
if self.request.user and self.request.user.is_authenticated and self.requ... | the_stack_v2_python_sparse | app/backend/wells/views.py | bcgov/gwells | train | 39 |
88d7c4ce1a6fe3cb9d6490788a0ed17eef1ecec9 | [
"res = [0] * len(T)\ncurrentPeak = []\nfor i in range(len(T) - 1, -1, -1):\n while currentPeak and T[i] >= T[currentPeak[-1]]:\n currentPeak.pop()\n if currentPeak:\n res[i] = currentPeak[-1] - i\n currentPeak.append(i)\nreturn res",
"res = []\nfor i in range(len(T)):\n count = 0\n fo... | <|body_start_0|>
res = [0] * len(T)
currentPeak = []
for i in range(len(T) - 1, -1, -1):
while currentPeak and T[i] >= T[currentPeak[-1]]:
currentPeak.pop()
if currentPeak:
res[i] = currentPeak[-1] - i
currentPeak.append(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int] #quadratic solution. exceeds time limit"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_025342 | 1,206 | no_license | [
{
"docstring": ":type T: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, T)"
},
{
"docstring": ":type T: List[int] :rtype: List[int] #quadratic solution. exceeds time limit",
"name": "dailyTemperatures2",
"signature": "def dailyTempera... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] #quadratic solution. exceeds time lim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] #quadratic solution. exceeds time lim... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int] #quadratic solution. exceeds time limit"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
res = [0] * len(T)
currentPeak = []
for i in range(len(T) - 1, -1, -1):
while currentPeak and T[i] >= T[currentPeak[-1]]:
currentPeak.pop()
if currentPea... | the_stack_v2_python_sparse | 12.STACK/739_daily_temperature/solution.py | kimmyoo/python_leetcode | train | 1 | |
48b118cc6f7b44a1e713e841a8471b8289be64bd | [
"self.symbol = symbol\nself.x = x\nself.y = y\nself.velocity = (0, 0)",
"if isinstance(self.symbol, list):\n renderer.render_composite(self.x, self.y, self.symbol, layer)\nelse:\n renderer.render(self.x, self.y, self.symbol, layer)"
] | <|body_start_0|>
self.symbol = symbol
self.x = x
self.y = y
self.velocity = (0, 0)
<|end_body_0|>
<|body_start_1|>
if isinstance(self.symbol, list):
renderer.render_composite(self.x, self.y, self.symbol, layer)
else:
renderer.render(self.x, self.y... | A generic object in the game world, such as a creature or item. | GameplayObject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameplayObject:
"""A generic object in the game world, such as a creature or item."""
def __init__(self, symbol, x, y):
"""Create a new GameplayObject at the given location."""
<|body_0|>
def render(self, renderer, layer):
"""Render this gameplay object."""
... | stack_v2_sparse_classes_36k_train_025343 | 577 | no_license | [
{
"docstring": "Create a new GameplayObject at the given location.",
"name": "__init__",
"signature": "def __init__(self, symbol, x, y)"
},
{
"docstring": "Render this gameplay object.",
"name": "render",
"signature": "def render(self, renderer, layer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003626 | Implement the Python class `GameplayObject` described below.
Class description:
A generic object in the game world, such as a creature or item.
Method signatures and docstrings:
- def __init__(self, symbol, x, y): Create a new GameplayObject at the given location.
- def render(self, renderer, layer): Render this game... | Implement the Python class `GameplayObject` described below.
Class description:
A generic object in the game world, such as a creature or item.
Method signatures and docstrings:
- def __init__(self, symbol, x, y): Create a new GameplayObject at the given location.
- def render(self, renderer, layer): Render this game... | ad5806685041545ed61d50034f9adc8a520fe62e | <|skeleton|>
class GameplayObject:
"""A generic object in the game world, such as a creature or item."""
def __init__(self, symbol, x, y):
"""Create a new GameplayObject at the given location."""
<|body_0|>
def render(self, renderer, layer):
"""Render this gameplay object."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameplayObject:
"""A generic object in the game world, such as a creature or item."""
def __init__(self, symbol, x, y):
"""Create a new GameplayObject at the given location."""
self.symbol = symbol
self.x = x
self.y = y
self.velocity = (0, 0)
def render(self, ... | the_stack_v2_python_sparse | gameplay_object.py | Ben-Lall/AnotherTentativelyNamedRoguelike | train | 0 |
8abd285109d8349c758c7a75eb6690ec3132f4d6 | [
"obj.save()\nfrom celery_tasks.html.tasks import generate_static_list_search_html\ngenerate_static_list_search_html.delay()",
"obj.delete()\nfrom celery_tasks.html.tasks import generate_static_list_search_html\ngenerate_static_list_search_html.delay()"
] | <|body_start_0|>
obj.save()
from celery_tasks.html.tasks import generate_static_list_search_html
generate_static_list_search_html.delay()
<|end_body_0|>
<|body_start_1|>
obj.delete()
from celery_tasks.html.tasks import generate_static_list_search_html
generate_static_lis... | 商品类别模型站点管理类 | GoodsCategoryAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsCategoryAdmin:
"""商品类别模型站点管理类"""
def save_model(self, request, obj, form, change):
"""当点击admin中的保存按钮时会来调用此方法 :param request:保存时本次请求对象 :param obj:本次要保存的模型对象 :param form:admin中的表单 :param change: 是否更改 bool"""
<|body_0|>
def delete_model(self, request, obj):
"""... | stack_v2_sparse_classes_36k_train_025344 | 2,663 | no_license | [
{
"docstring": "当点击admin中的保存按钮时会来调用此方法 :param request:保存时本次请求对象 :param obj:本次要保存的模型对象 :param form:admin中的表单 :param change: 是否更改 bool",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "当点击admin中的删除按钮时会来调此方法 :param request: 删除时本次请求对象 :param o... | 2 | null | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
商品类别模型站点管理类
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 当点击admin中的保存按钮时会来调用此方法 :param request:保存时本次请求对象 :param obj:本次要保存的模型对象 :param form:admin中的表单 :param change: 是否更改 bool
- def delete_model(... | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
商品类别模型站点管理类
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): 当点击admin中的保存按钮时会来调用此方法 :param request:保存时本次请求对象 :param obj:本次要保存的模型对象 :param form:admin中的表单 :param change: 是否更改 bool
- def delete_model(... | 61798f2c3624bfde540cfb7469d42564ffe674a6 | <|skeleton|>
class GoodsCategoryAdmin:
"""商品类别模型站点管理类"""
def save_model(self, request, obj, form, change):
"""当点击admin中的保存按钮时会来调用此方法 :param request:保存时本次请求对象 :param obj:本次要保存的模型对象 :param form:admin中的表单 :param change: 是否更改 bool"""
<|body_0|>
def delete_model(self, request, obj):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoodsCategoryAdmin:
"""商品类别模型站点管理类"""
def save_model(self, request, obj, form, change):
"""当点击admin中的保存按钮时会来调用此方法 :param request:保存时本次请求对象 :param obj:本次要保存的模型对象 :param form:admin中的表单 :param change: 是否更改 bool"""
obj.save()
from celery_tasks.html.tasks import generate_static_list_se... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/goods/admin.py | MEGALO-JOE/meiduo | train | 0 |
7929cd678260c83e3ef6142c56b17ab169d28e72 | [
"requestor = Requestor(local_api_key=api_key)\nurl = cls.class_url()\nwrapped_params = {cls.snakecase_name(): params}\nif verify:\n wrapped_params['verify'] = verify\nif verify_strict:\n wrapped_params['verify_strict'] = verify_strict\nresponse, api_key = requestor.request(method=RequestMethod.POST, url=url, ... | <|body_start_0|>
requestor = Requestor(local_api_key=api_key)
url = cls.class_url()
wrapped_params = {cls.snakecase_name(): params}
if verify:
wrapped_params['verify'] = verify
if verify_strict:
wrapped_params['verify_strict'] = verify_strict
respo... | Address | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Address:
def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address':
"""Create an address."""
<|body_0|>
def create_and_verify(cls, api_key: Opti... | stack_v2_sparse_classes_36k_train_025345 | 1,988 | permissive | [
{
"docstring": "Create an address.",
"name": "create",
"signature": "def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address'"
},
{
"docstring": "Create and verify ... | 3 | stack_v2_sparse_classes_30k_test_000345 | Implement the Python class `Address` described below.
Class description:
Implement the Address class.
Method signatures and docstrings:
- def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> '... | Implement the Python class `Address` described below.
Class description:
Implement the Address class.
Method signatures and docstrings:
- def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> '... | c8f7a3f2472ae5fea13a5b596b4618bd55f3be0c | <|skeleton|>
class Address:
def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address':
"""Create an address."""
<|body_0|>
def create_and_verify(cls, api_key: Opti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Address:
def create(cls, api_key: Optional[str]=None, verify: Optional[Union[Dict[str, Any], str, bool]]=None, verify_strict: Optional[Union[Dict[str, Any], str, bool]]=None, **params) -> 'Address':
"""Create an address."""
requestor = Requestor(local_api_key=api_key)
url = cls.class_u... | the_stack_v2_python_sparse | easypost/address.py | dsanders11/easypost-python | train | 0 | |
4801e77db8b0bbef6c5f9abbd3cf226706bc1bae | [
"executor_group = parser.add_argument_group(title='Task Graph Executor')\nexecutor_group.add_argument('-j', '--jobs', type=int, default=None, help='Number of jobs to run in parallel. Defaults to the number of processors on the machine')\nexecutor_group.add_argument('-N', '--dask-cluster-name', '--dcn', dest='dask_c... | <|body_start_0|>
executor_group = parser.add_argument_group(title='Task Graph Executor')
executor_group.add_argument('-j', '--jobs', type=int, default=None, help='Number of jobs to run in parallel. Defaults to the number of processors on the machine')
executor_group.add_argument('-N', '--dask-cl... | Takes care of creating a task graph executor and executing a graph. | TaskGraphCli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGraphCli:
"""Takes care of creating a task graph executor and executing a graph."""
def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None:
"""Add arguments needed to execute a task graph."... | stack_v2_sparse_classes_36k_train_025346 | 6,088 | permissive | [
{
"docstring": "Add arguments needed to execute a task graph.",
"name": "add_arguments",
"signature": "def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None"
},
{
"docstring": "Create a task graph executo... | 3 | null | Implement the Python class `TaskGraphCli` described below.
Class description:
Takes care of creating a task graph executor and executing a graph.
Method signatures and docstrings:
- def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True... | Implement the Python class `TaskGraphCli` described below.
Class description:
Takes care of creating a task graph executor and executing a graph.
Method signatures and docstrings:
- def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True... | 21c8d4d32f632431704556f8bcb158f9bb686239 | <|skeleton|>
class TaskGraphCli:
"""Takes care of creating a task graph executor and executing a graph."""
def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None:
"""Add arguments needed to execute a task graph."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskGraphCli:
"""Takes care of creating a task graph executor and executing a graph."""
def add_arguments(parser: argparse.ArgumentParser, force_mode: str='optional', default_task_status_dir: str='.', use_commands: bool=True) -> None:
"""Add arguments needed to execute a task graph."""
ex... | the_stack_v2_python_sparse | dae/dae/task_graph/cli_tools.py | iossifovlab/gpf | train | 5 |
fd9e69a1e0267622952ebbd5197db9263ae2de90 | [
"if not params.get('resource_id'):\n return resp\naim = []\nresource_ids = params.get('resource_id').split(',')\nfor dct in resp:\n if dct['Id'] in resource_ids:\n aim.append(dct)\nreturn aim",
"pattern_image_name = params.get('patternImageName')\nif not pattern_image_name:\n return resp\naim = []... | <|body_start_0|>
if not params.get('resource_id'):
return resp
aim = []
resource_ids = params.get('resource_id').split(',')
for dct in resp:
if dct['Id'] in resource_ids:
aim.append(dct)
return aim
<|end_body_0|>
<|body_start_1|>
p... | FilterResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterResponse:
def filter_resource(cls, params, resp):
"""Filter one or multi resource(s) according to resource_id, use at: params doesn't support filter"""
<|body_0|>
def filter_image_name(cls, params, resp):
"""Filter one or multi resource(s) according to resource... | stack_v2_sparse_classes_36k_train_025347 | 19,553 | permissive | [
{
"docstring": "Filter one or multi resource(s) according to resource_id, use at: params doesn't support filter",
"name": "filter_resource",
"signature": "def filter_resource(cls, params, resp)"
},
{
"docstring": "Filter one or multi resource(s) according to resource_id, use at: params doesn't s... | 4 | null | Implement the Python class `FilterResponse` described below.
Class description:
Implement the FilterResponse class.
Method signatures and docstrings:
- def filter_resource(cls, params, resp): Filter one or multi resource(s) according to resource_id, use at: params doesn't support filter
- def filter_image_name(cls, p... | Implement the Python class `FilterResponse` described below.
Class description:
Implement the FilterResponse class.
Method signatures and docstrings:
- def filter_resource(cls, params, resp): Filter one or multi resource(s) according to resource_id, use at: params doesn't support filter
- def filter_image_name(cls, p... | a890e2eb96cc537db131e7ca8a0e6e1edc0b6ebd | <|skeleton|>
class FilterResponse:
def filter_resource(cls, params, resp):
"""Filter one or multi resource(s) according to resource_id, use at: params doesn't support filter"""
<|body_0|>
def filter_image_name(cls, params, resp):
"""Filter one or multi resource(s) according to resource... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterResponse:
def filter_resource(cls, params, resp):
"""Filter one or multi resource(s) according to resource_id, use at: params doesn't support filter"""
if not params.get('resource_id'):
return resp
aim = []
resource_ids = params.get('resource_id').split(',')
... | the_stack_v2_python_sparse | cloudentries/commoncloud/query/response.py | CloudChef/cloud-entries | train | 1 | |
2d767cc1b07c540793974ce34d78e32a20c0ed1d | [
"c_error = 'content_image must be a numpy.ndarray with shape (h, w, 3)'\nif not isinstance(style_image, np.ndarray):\n raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')\nif len(style_image.shape) != 3:\n raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')\nif ... | <|body_start_0|>
c_error = 'content_image must be a numpy.ndarray with shape (h, w, 3)'
if not isinstance(style_image, np.ndarray):
raise TypeError('style_image must be a numpy.ndarray with shape (h, w, 3)')
if len(style_image.shape) != 3:
raise TypeError('style_image mus... | performs tasks for neural style transfer Class atributes: - Content layer where will pull our feature maps - Style layer we are interested in | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""performs tasks for neural style transfer Class atributes: - Content layer where will pull our feature maps - Style layer we are interested in"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""initializing the varibles Arg: - style_image: img used as... | stack_v2_sparse_classes_36k_train_025348 | 3,618 | no_license | [
{
"docstring": "initializing the varibles Arg: - style_image: img used as a style reference, numpy.ndarray - content_image: image used as a content reference, numpy.ndarray - alpha: the weight for content cost - beta: the weight for style cost Enviornment: Eager execution: TensorFlow’s imperative programming en... | 2 | stack_v2_sparse_classes_30k_train_014220 | Implement the Python class `NST` described below.
Class description:
performs tasks for neural style transfer Class atributes: - Content layer where will pull our feature maps - Style layer we are interested in
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): ... | Implement the Python class `NST` described below.
Class description:
performs tasks for neural style transfer Class atributes: - Content layer where will pull our feature maps - Style layer we are interested in
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): ... | 1d86c9606371697854878b833b810d73c9af7ee7 | <|skeleton|>
class NST:
"""performs tasks for neural style transfer Class atributes: - Content layer where will pull our feature maps - Style layer we are interested in"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""initializing the varibles Arg: - style_image: img used as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NST:
"""performs tasks for neural style transfer Class atributes: - Content layer where will pull our feature maps - Style layer we are interested in"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""initializing the varibles Arg: - style_image: img used as a style refe... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/0-neural_style.py | macoyulloa/holbertonschool-machine_learning | train | 0 |
5dd2d773e19da4a06c39730ad37300db03d08472 | [
"chosen_row = random.choice(range(len(array2D)))\nchosen_column = random.choice(array2D[chosen_row])\narray2D[chosen_row].remove(chosen_column)\nreturn (chosen_row, chosen_column)",
"dungeon_map = [[DungeonCell.EMPTY] * map_size for i in range(map_size)]\nfree_map_cells = [list(range(map_size)) for i in range(map... | <|body_start_0|>
chosen_row = random.choice(range(len(array2D)))
chosen_column = random.choice(array2D[chosen_row])
array2D[chosen_row].remove(chosen_column)
return (chosen_row, chosen_column)
<|end_body_0|>
<|body_start_1|>
dungeon_map = [[DungeonCell.EMPTY] * map_size for i in... | DungeonGameMapGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DungeonGameMapGenerator:
def __choose_random_index_and_remove(self, array2D):
"""Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :... | stack_v2_sparse_classes_36k_train_025349 | 2,235 | permissive | [
{
"docstring": "Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :rtype: a tuple of 2 integers.",
"name": "__choose_random_index_and_remove",
"sign... | 2 | null | Implement the Python class `DungeonGameMapGenerator` described below.
Class description:
Implement the DungeonGameMapGenerator class.
Method signatures and docstrings:
- def __choose_random_index_and_remove(self, array2D): Function chooses a random row and column in 2D array, returns it and removed it's cell from the... | Implement the Python class `DungeonGameMapGenerator` described below.
Class description:
Implement the DungeonGameMapGenerator class.
Method signatures and docstrings:
- def __choose_random_index_and_remove(self, array2D): Function chooses a random row and column in 2D array, returns it and removed it's cell from the... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class DungeonGameMapGenerator:
def __choose_random_index_and_remove(self, array2D):
"""Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DungeonGameMapGenerator:
def __choose_random_index_and_remove(self, array2D):
"""Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :rtype: a tuple... | the_stack_v2_python_sparse | Tihran_Katolikian/10/TKDungeonGamePkg/TKDungeonGamePkg/DungeonGameMapGenerator.py | SmischenkoB/campus_2018_python | train | 0 | |
6ece163b83039ae1ed6aeea51783be6a8583832f | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('user_id', required=False, type=int, store_missing=False, location=['form', 'json'])\nself.reqparser.add_argument('widget_id', required=True, type=int, help='widget Id missing', location=['form', 'json'])\nself.reqparser.add_argument('activated... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('user_id', required=False, type=int, store_missing=False, location=['form', 'json'])
self.reqparser.add_argument('widget_id', required=True, type=int, help='widget Id missing', location=['form', 'json'])
... | Create an alert. Takes a minimum and maximum threshold value, an attribute id, widget id and a optional user id. | CreateAlert | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAlert:
"""Create an alert. Takes a minimum and maximum threshold value, an attribute id, widget id and a optional user id."""
def __init__(self) -> None:
"""Instantiate reparse for POST request."""
<|body_0|>
def post(self) -> (dict, HTTPStatus):
"""Create ... | stack_v2_sparse_classes_36k_train_025350 | 3,942 | permissive | [
{
"docstring": "Instantiate reparse for POST request.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Create an alert. :return: On success return the new alert Id and an HTTP status code 201 (Created), Otherwise return an error with the appropriate HTTP status ... | 2 | stack_v2_sparse_classes_30k_train_011591 | Implement the Python class `CreateAlert` described below.
Class description:
Create an alert. Takes a minimum and maximum threshold value, an attribute id, widget id and a optional user id.
Method signatures and docstrings:
- def __init__(self) -> None: Instantiate reparse for POST request.
- def post(self) -> (dict,... | Implement the Python class `CreateAlert` described below.
Class description:
Create an alert. Takes a minimum and maximum threshold value, an attribute id, widget id and a optional user id.
Method signatures and docstrings:
- def __init__(self) -> None: Instantiate reparse for POST request.
- def post(self) -> (dict,... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class CreateAlert:
"""Create an alert. Takes a minimum and maximum threshold value, an attribute id, widget id and a optional user id."""
def __init__(self) -> None:
"""Instantiate reparse for POST request."""
<|body_0|>
def post(self) -> (dict, HTTPStatus):
"""Create ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateAlert:
"""Create an alert. Takes a minimum and maximum threshold value, an attribute id, widget id and a optional user id."""
def __init__(self) -> None:
"""Instantiate reparse for POST request."""
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('user_i... | the_stack_v2_python_sparse | Analytics/resources/alerts/create_alert.py | thanosbnt/SharingCitiesDashboard | train | 0 |
098e9c483b1d043e0920697eab1885c3b8f972eb | [
"self.logger = logging.getLogger(__name__)\nself.Name = name\nself.Drawing_type = drawing_type\nself.Text_presentation = {}\nself.Underlays = set()\nself.Shape_presentation = {}\nself.Closed_shape_fill = {}\nself.Corner_spec = {}\nself.logger.info(f'Loading assets for Presentation [{self.Name}]')\nself.load_text_pr... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.Name = name
self.Drawing_type = drawing_type
self.Text_presentation = {}
self.Underlays = set()
self.Shape_presentation = {}
self.Closed_shape_fill = {}
self.Corner_spec = {}
self.logg... | A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly different colors for transient and non-trans... | Presentation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Presentation:
"""A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly diff... | stack_v2_sparse_classes_36k_train_025351 | 3,484 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, name: str, drawing_type: str)"
},
{
"docstring": "For each text Asset in this Presentation, load its Text Presentation",
"name": "load_text_presentations",
"signature": "def load_text_presentations(self)"
... | 3 | stack_v2_sparse_classes_30k_train_004583 | Implement the Python class `Presentation` described below.
Class description:
A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain ... | Implement the Python class `Presentation` described below.
Class description:
A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain ... | 088e27cded9eca2cacba2c6168c03caf4b43ef72 | <|skeleton|>
class Presentation:
"""A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly diff... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Presentation:
"""A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly different colors ... | the_stack_v2_python_sparse | flatland/drawing_domain/presentation.py | Laurelinex/flatland-model-diagram-editor | train | 0 |
950450753bc401bd9ca57ec4d80d73d9828ca8cd | [
"user = self.model(name=name, surname=surname, full_name=full_name, badge=badge, location=location)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(name=name, surname=surname, full_name=full_name, badge=badge, location=location, password=password)\nuser.is_admin = T... | <|body_start_0|>
user = self.model(name=name, surname=surname, full_name=full_name, badge=badge, location=location)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.create_user(name=name, surname=surname, full_name=ful... | MyUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, name, surname, full_name, badge, location, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, full_name, name=None, surname=None, badge=None, location=Non... | stack_v2_sparse_classes_36k_train_025352 | 2,259 | permissive | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, name, surname, full_name, badge, location, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth ... | 2 | stack_v2_sparse_classes_30k_train_005302 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, name, surname, full_name, badge, location, password=None): Creates and saves a User with the given email, date of birth and password.
- def create... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, name, surname, full_name, badge, location, password=None): Creates and saves a User with the given email, date of birth and password.
- def create... | 80b8c9e33653bf703362dfc60e7a252610a5d6f1 | <|skeleton|>
class MyUserManager:
def create_user(self, name, surname, full_name, badge, location, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, full_name, name=None, surname=None, badge=None, location=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, name, surname, full_name, badge, location, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
user = self.model(name=name, surname=surname, full_name=full_name, badge=badge, location=location)
user.set_p... | the_stack_v2_python_sparse | src/users/models.py | EpicKiwi/nuit-info-2019 | train | 0 | |
f17675f40d03e21acb517b6ae8fcdbe11b0c8865 | [
"image_id = 'invalid'\nwith self.assertRaises(ItemNotFound):\n self.images_client.list_members(image_id)",
"image_id = ''\nwith self.assertRaises(ItemNotFound):\n self.images_client.list_members(image_id)",
"member_id = self.alt_tenant_id\nimage = self.images_behavior.create_image_via_task()\nresponse = s... | <|body_start_0|>
image_id = 'invalid'
with self.assertRaises(ItemNotFound):
self.images_client.list_members(image_id)
<|end_body_0|>
<|body_start_1|>
image_id = ''
with self.assertRaises(ItemNotFound):
self.images_client.list_members(image_id)
<|end_body_1|>
<|b... | TestGetImageMembersNegative | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetImageMembersNegative:
def test_get_image_members_using_invalid_image_id(self):
"""@summary: Get image members using invalid image id 1) Get image members using invalid image id 2) Verify that the response code is 404"""
<|body_0|>
def test_get_image_members_using_blan... | stack_v2_sparse_classes_36k_train_025353 | 2,950 | permissive | [
{
"docstring": "@summary: Get image members using invalid image id 1) Get image members using invalid image id 2) Verify that the response code is 404",
"name": "test_get_image_members_using_invalid_image_id",
"signature": "def test_get_image_members_using_invalid_image_id(self)"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_train_014396 | Implement the Python class `TestGetImageMembersNegative` described below.
Class description:
Implement the TestGetImageMembersNegative class.
Method signatures and docstrings:
- def test_get_image_members_using_invalid_image_id(self): @summary: Get image members using invalid image id 1) Get image members using inval... | Implement the Python class `TestGetImageMembersNegative` described below.
Class description:
Implement the TestGetImageMembersNegative class.
Method signatures and docstrings:
- def test_get_image_members_using_invalid_image_id(self): @summary: Get image members using invalid image id 1) Get image members using inval... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class TestGetImageMembersNegative:
def test_get_image_members_using_invalid_image_id(self):
"""@summary: Get image members using invalid image id 1) Get image members using invalid image id 2) Verify that the response code is 404"""
<|body_0|>
def test_get_image_members_using_blan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetImageMembersNegative:
def test_get_image_members_using_invalid_image_id(self):
"""@summary: Get image members using invalid image id 1) Get image members using invalid image id 2) Verify that the response code is 404"""
image_id = 'invalid'
with self.assertRaises(ItemNotFound):
... | the_stack_v2_python_sparse | cloudroast/images/v2/functional/test_get_image_members_negative.py | RULCSoft/cloudroast | train | 1 | |
4a8492c096c9d8a81a791419b1df3f2b2149a972 | [
"self.path_parts = module.split('.')\nif template_path:\n self.path_parts.append(template_path)",
"path_parts = copy.copy(self.path_parts)\npath_parts.append(template_name)\ntemplate_name = '/'.join(path_parts)\nreturn render(request, template_name, context, content_type, status, using)"
] | <|body_start_0|>
self.path_parts = module.split('.')
if template_path:
self.path_parts.append(template_path)
<|end_body_0|>
<|body_start_1|>
path_parts = copy.copy(self.path_parts)
path_parts.append(template_name)
template_name = '/'.join(path_parts)
return r... | app 渲染模板,用于app子模块的模板路由 | AppRender | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppRender:
"""app 渲染模板,用于app子模块的模板路由"""
def __init__(self, module, template_path=None):
"""初始化渲染器 :param module: 所在模块 :param template_path: 模板路径"""
<|body_0|>
def render(self, request, template_name, context=None, content_type=None, status=None, using=None):
"""重... | stack_v2_sparse_classes_36k_train_025354 | 1,439 | no_license | [
{
"docstring": "初始化渲染器 :param module: 所在模块 :param template_path: 模板路径",
"name": "__init__",
"signature": "def __init__(self, module, template_path=None)"
},
{
"docstring": "重载渲染方法,寻找自定义模板路径 :param request: 请求对象 :param template_name: 模板名称 :param context: 模板上下文 :param content_type: http内容类型 :param... | 2 | stack_v2_sparse_classes_30k_train_021504 | Implement the Python class `AppRender` described below.
Class description:
app 渲染模板,用于app子模块的模板路由
Method signatures and docstrings:
- def __init__(self, module, template_path=None): 初始化渲染器 :param module: 所在模块 :param template_path: 模板路径
- def render(self, request, template_name, context=None, content_type=None, status... | Implement the Python class `AppRender` described below.
Class description:
app 渲染模板,用于app子模块的模板路由
Method signatures and docstrings:
- def __init__(self, module, template_path=None): 初始化渲染器 :param module: 所在模块 :param template_path: 模板路径
- def render(self, request, template_name, context=None, content_type=None, status... | a4502d14652c6a926e74be6d0f53b2b50ada9c3c | <|skeleton|>
class AppRender:
"""app 渲染模板,用于app子模块的模板路由"""
def __init__(self, module, template_path=None):
"""初始化渲染器 :param module: 所在模块 :param template_path: 模板路径"""
<|body_0|>
def render(self, request, template_name, context=None, content_type=None, status=None, using=None):
"""重... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppRender:
"""app 渲染模板,用于app子模块的模板路由"""
def __init__(self, module, template_path=None):
"""初始化渲染器 :param module: 所在模块 :param template_path: 模板路径"""
self.path_parts = module.split('.')
if template_path:
self.path_parts.append(template_path)
def render(self, request... | the_stack_v2_python_sparse | sv/sv_base/extensions/project/render.py | xianzhishenqie/project_template | train | 1 |
b691324c0b744ef61293ed58666d12ae927dc5d2 | [
"if not take_key_as_arg:\n self.missing_value_creator = lambda k: missing_value_creator()\nelse:\n self.missing_value_creator = missing_value_creator",
"value = self.missing_value_creator(k)\nself[k] = value\nreturn value"
] | <|body_start_0|>
if not take_key_as_arg:
self.missing_value_creator = lambda k: missing_value_creator()
else:
self.missing_value_creator = missing_value_creator
<|end_body_0|>
<|body_start_1|>
value = self.missing_value_creator(k)
self[k] = value
return v... | A dictionary where missing values are created by an __init__ time supplied function. | DictOf | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictOf:
"""A dictionary where missing values are created by an __init__ time supplied function."""
def __init__(self, missing_value_creator, take_key_as_arg=False):
"""@arg missing_value_creator: Function to create missing values in the dictionary"""
<|body_0|>
def __mis... | stack_v2_sparse_classes_36k_train_025355 | 3,293 | permissive | [
{
"docstring": "@arg missing_value_creator: Function to create missing values in the dictionary",
"name": "__init__",
"signature": "def __init__(self, missing_value_creator, take_key_as_arg=False)"
},
{
"docstring": "Called when there is no value for a given key, k.",
"name": "__missing__",
... | 2 | stack_v2_sparse_classes_30k_train_014371 | Implement the Python class `DictOf` described below.
Class description:
A dictionary where missing values are created by an __init__ time supplied function.
Method signatures and docstrings:
- def __init__(self, missing_value_creator, take_key_as_arg=False): @arg missing_value_creator: Function to create missing valu... | Implement the Python class `DictOf` described below.
Class description:
A dictionary where missing values are created by an __init__ time supplied function.
Method signatures and docstrings:
- def __init__(self, missing_value_creator, take_key_as_arg=False): @arg missing_value_creator: Function to create missing valu... | 02db81f3e7c87c9497c527d3dc4ea5e3592a58cb | <|skeleton|>
class DictOf:
"""A dictionary where missing values are created by an __init__ time supplied function."""
def __init__(self, missing_value_creator, take_key_as_arg=False):
"""@arg missing_value_creator: Function to create missing values in the dictionary"""
<|body_0|>
def __mis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DictOf:
"""A dictionary where missing values are created by an __init__ time supplied function."""
def __init__(self, missing_value_creator, take_key_as_arg=False):
"""@arg missing_value_creator: Function to create missing values in the dictionary"""
if not take_key_as_arg:
se... | the_stack_v2_python_sparse | python/cookbook/dicts.py | JohnReid/Cookbook | train | 1 |
0ad5bced8e5021e4b7e6ebb70d7a74a284885f84 | [
"if num <= 0 or num & num - 1 != 0:\n return False\nreturn bool(1431655765 & num)",
"if num <= 0 or num & num - 1 != 0:\n return False\nt = num & -num\nreturn num & 1431655765 and num == t",
"if num <= 0:\n return False\nnum_bin = bin(num)[2:]\nif len(num_bin) % 2 != 0 and num_bin[0] == '1':\n if nu... | <|body_start_0|>
if num <= 0 or num & num - 1 != 0:
return False
return bool(1431655765 & num)
<|end_body_0|>
<|body_start_1|>
if num <= 0 or num & num - 1 != 0:
return False
t = num & -num
return num & 1431655765 and num == t
<|end_body_1|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num: int) -> bool:
"""理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:"""
<|body_0|>
def isPowerOfFour5(self, num: int) -> bool:
""":param num: :ret... | stack_v2_sparse_classes_36k_train_025356 | 2,318 | no_license | [
{
"docstring": "理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:",
"name": "isPowerOfFour",
"signature": "def isPowerOfFour(self, num: int) -> bool"
},
{
"docstring": ":param num: :return:",
"name": "isPower... | 5 | stack_v2_sparse_classes_30k_train_003561 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num: int) -> bool: 理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num: int) -> bool: 理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:
-... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num: int) -> bool:
"""理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:"""
<|body_0|>
def isPowerOfFour5(self, num: int) -> bool:
""":param num: :ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfFour(self, num: int) -> bool:
"""理论上数字4幂的二进制类似于100,10000,1000000,etc...形式。可以有如下结论: 4的幂一定是2的。 2的幂减1与原数做与运算结果一定是0 4的幂和2的幂一样,只会出现一位1。但是,4的1总是出现在奇数位。 :param num: :return:"""
if num <= 0 or num & num - 1 != 0:
return False
return bool(1431655765 & num)
... | the_stack_v2_python_sparse | 342_4的幂.py | lovehhf/LeetCode | train | 0 | |
d8867a2bdc58722c5ce95cf4555e9c4c6b326771 | [
"length = len(nums)\nfor i in range(0, length):\n for j in range(i + 1, length):\n sum = nums[i] + nums[j]\n if sum == target:\n return (i, j)",
"dic = {}\nfor i, num in enumerate(nums):\n dic[num] = i\nfor i, num in enumerate(nums):\n j = target - num\n if j in dic and dic[j]... | <|body_start_0|>
length = len(nums)
for i in range(0, length):
for j in range(i + 1, length):
sum = nums[i] + nums[j]
if sum == target:
return (i, j)
<|end_body_0|>
<|body_start_1|>
dic = {}
for i, num in enumerate(nums):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def two_sum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def two_pass_dict(self, nums, target):
""":param nums: List[int] :param target: int :return: List[int]"""
<|body_1|>
def one_pass_dict(s... | stack_v2_sparse_classes_36k_train_025357 | 1,077 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "two_sum",
"signature": "def two_sum(self, nums, target)"
},
{
"docstring": ":param nums: List[int] :param target: int :return: List[int]",
"name": "two_pass_dict",
"signature": "def two_pass_dict(self, n... | 3 | stack_v2_sparse_classes_30k_train_008830 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def two_sum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def two_pass_dict(self, nums, target): :param nums: List[int] :param target: int :ret... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def two_sum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def two_pass_dict(self, nums, target): :param nums: List[int] :param target: int :ret... | f234bd7b62cb7bc2150faa764bf05a9095e19192 | <|skeleton|>
class Solution:
def two_sum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def two_pass_dict(self, nums, target):
""":param nums: List[int] :param target: int :return: List[int]"""
<|body_1|>
def one_pass_dict(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def two_sum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
length = len(nums)
for i in range(0, length):
for j in range(i + 1, length):
sum = nums[i] + nums[j]
if sum == target:
... | the_stack_v2_python_sparse | alg/two_sum.py | nyannko/leetcode-python | train | 0 | |
c11acba97f2c7613636fd7a3701b449dcca903db | [
"lq_sms_key = get_lq_sms_key(tid)\nlq_interval_key = get_lq_interval_key(tid)\nself.redis.setvalue(lq_interval_key, int(time.time()), interval * 60 - 160)\nif not self.redis.getvalue(lq_sms_key):\n sms = SMSCode.SMS_LQ % interval\n biz_type = QueryHelper.get_biz_type_by_tmobile(sim, self.db)\n if biz_type ... | <|body_start_0|>
lq_sms_key = get_lq_sms_key(tid)
lq_interval_key = get_lq_interval_key(tid)
self.redis.setvalue(lq_interval_key, int(time.time()), interval * 60 - 160)
if not self.redis.getvalue(lq_sms_key):
sms = SMSCode.SMS_LQ % interval
biz_type = QueryHelper.... | BaseMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseMixin:
def send_lq_sms(self, sim, tid, interval):
"""Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the per... | stack_v2_sparse_classes_36k_train_025358 | 4,444 | no_license | [
{
"docstring": "Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the period of interval, terminal is been awaken. when the period of inte... | 3 | null | Implement the Python class `BaseMixin` described below.
Class description:
Implement the BaseMixin class.
Method signatures and docstrings:
- def send_lq_sms(self, sim, tid, interval): Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq s... | Implement the Python class `BaseMixin` described below.
Class description:
Implement the BaseMixin class.
Method signatures and docstrings:
- def send_lq_sms(self, sim, tid, interval): Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq s... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class BaseMixin:
def send_lq_sms(self, sim, tid, interval):
"""Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the per... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseMixin:
def send_lq_sms(self, sim, tid, interval):
"""Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the period of interva... | the_stack_v2_python_sparse | apps/uweb/mixin/base.py | jcsy521/ydws | train | 0 | |
d7452d39b3aea6fcba83321b674513f9dfd6029b | [
"request = DescribeInstancesRequest()\nrequest.set_accept_format('json')\nrequest.set_PageNumber(page_num)\nrequest.set_PageSize(page_size)\ndata = self._request(request)\ntotal = data.get('TotalCount')\ndata = data.get('Instances')\ndata_list = data.get('KVStoreInstance')\ndata = {'total': total, 'data_list': data... | <|body_start_0|>
request = DescribeInstancesRequest()
request.set_accept_format('json')
request.set_PageNumber(page_num)
request.set_PageSize(page_size)
data = self._request(request)
total = data.get('TotalCount')
data = data.get('Instances')
data_list = d... | 阿里云redis | AliyunRedis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliyunRedis:
"""阿里云redis"""
def get_redises(self, page_num=1, page_size=30):
"""获取Redis列表"""
<|body_0|>
def get_redis_accounts(self, instance_id):
"""获取Redis账户列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
request = DescribeInstancesRequest(... | stack_v2_sparse_classes_36k_train_025359 | 1,351 | no_license | [
{
"docstring": "获取Redis列表",
"name": "get_redises",
"signature": "def get_redises(self, page_num=1, page_size=30)"
},
{
"docstring": "获取Redis账户列表",
"name": "get_redis_accounts",
"signature": "def get_redis_accounts(self, instance_id)"
}
] | 2 | null | Implement the Python class `AliyunRedis` described below.
Class description:
阿里云redis
Method signatures and docstrings:
- def get_redises(self, page_num=1, page_size=30): 获取Redis列表
- def get_redis_accounts(self, instance_id): 获取Redis账户列表 | Implement the Python class `AliyunRedis` described below.
Class description:
阿里云redis
Method signatures and docstrings:
- def get_redises(self, page_num=1, page_size=30): 获取Redis列表
- def get_redis_accounts(self, instance_id): 获取Redis账户列表
<|skeleton|>
class AliyunRedis:
"""阿里云redis"""
def get_redises(self, p... | 3539cab6e73571f84b7f17391d9a363a756f12e1 | <|skeleton|>
class AliyunRedis:
"""阿里云redis"""
def get_redises(self, page_num=1, page_size=30):
"""获取Redis列表"""
<|body_0|>
def get_redis_accounts(self, instance_id):
"""获取Redis账户列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AliyunRedis:
"""阿里云redis"""
def get_redises(self, page_num=1, page_size=30):
"""获取Redis列表"""
request = DescribeInstancesRequest()
request.set_accept_format('json')
request.set_PageNumber(page_num)
request.set_PageSize(page_size)
data = self._request(request... | the_stack_v2_python_sparse | utils/aliyun/redis.py | cuijianzhe/cow | train | 2 |
d5611ccc5e9af9c484a78036e497b02b4145911b | [
"self.db_name = db_name\nself.host_dict: host_type = ConfigFilesManager().get_hosts() if not host_dict else host_dict\nif not self.host_dict or 'mysql' not in self.host_dict:\n raise MissingFlavor('No databases available for mysql', None)\nself.host_dict = self.host_dict.get('mysql').get(self.db_name, {})\nif no... | <|body_start_0|>
self.db_name = db_name
self.host_dict: host_type = ConfigFilesManager().get_hosts() if not host_dict else host_dict
if not self.host_dict or 'mysql' not in self.host_dict:
raise MissingFlavor('No databases available for mysql', None)
self.host_dict = self.hos... | Mysql | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mysql:
def __init__(self, db_name: str, host_dict: host_type=None):
""":param db_name: database name :param host_dict: optional database info with host, ports etc"""
<|body_0|>
def create_engine(self, user: str=None, pwd: str=None, **kwargs):
""":param user: username... | stack_v2_sparse_classes_36k_train_025360 | 2,257 | permissive | [
{
"docstring": ":param db_name: database name :param host_dict: optional database info with host, ports etc",
"name": "__init__",
"signature": "def __init__(self, db_name: str, host_dict: host_type=None)"
},
{
"docstring": ":param user: username :param pwd: password :param kwargs: for compatibil... | 2 | stack_v2_sparse_classes_30k_train_014035 | Implement the Python class `Mysql` described below.
Class description:
Implement the Mysql class.
Method signatures and docstrings:
- def __init__(self, db_name: str, host_dict: host_type=None): :param db_name: database name :param host_dict: optional database info with host, ports etc
- def create_engine(self, user:... | Implement the Python class `Mysql` described below.
Class description:
Implement the Mysql class.
Method signatures and docstrings:
- def __init__(self, db_name: str, host_dict: host_type=None): :param db_name: database name :param host_dict: optional database info with host, ports etc
- def create_engine(self, user:... | 9abb7b14e44be2d9f6d80a0dff412e0e1382aab8 | <|skeleton|>
class Mysql:
def __init__(self, db_name: str, host_dict: host_type=None):
""":param db_name: database name :param host_dict: optional database info with host, ports etc"""
<|body_0|>
def create_engine(self, user: str=None, pwd: str=None, **kwargs):
""":param user: username... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mysql:
def __init__(self, db_name: str, host_dict: host_type=None):
""":param db_name: database name :param host_dict: optional database info with host, ports etc"""
self.db_name = db_name
self.host_dict: host_type = ConfigFilesManager().get_hosts() if not host_dict else host_dict
... | the_stack_v2_python_sparse | dsdbmanager/mysql_.py | jojoduquartier/dsdbmanager | train | 8 | |
abe8d3058ece639f5e75f8f22e0649d94d1399a5 | [
"import numpy as np\nself.positions = np.array(positions)\nself.position_value = 1000 / self.positions\nself.num_trials = num_trials",
"import numpy as np\np = 0.51\ncumu_ret = []\nfor i, position in enumerate(self.positions):\n position_return = 2 * self.position_value[i] * np.random.binomial(position, p)\n ... | <|body_start_0|>
import numpy as np
self.positions = np.array(positions)
self.position_value = 1000 / self.positions
self.num_trials = num_trials
<|end_body_0|>
<|body_start_1|>
import numpy as np
p = 0.51
cumu_ret = []
for i, position in enumerate(self.p... | Class represents a string of $1000 investments and their daily returns | investment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment:
"""Class represents a string of $1000 investments and their daily returns"""
def __init__(self, positions=[1], num_trials=1):
"""Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trial... | stack_v2_sparse_classes_36k_train_025361 | 1,980 | no_license | [
{
"docstring": "Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trials: An integer representing the number of days to simulate investment",
"name": "__init__",
"signature": "def __init__(self, positions=[1], num_tr... | 3 | stack_v2_sparse_classes_30k_train_011943 | Implement the Python class `investment` described below.
Class description:
Class represents a string of $1000 investments and their daily returns
Method signatures and docstrings:
- def __init__(self, positions=[1], num_trials=1): Constructor for interval class inputs: positions: A list of integers of number of shar... | Implement the Python class `investment` described below.
Class description:
Class represents a string of $1000 investments and their daily returns
Method signatures and docstrings:
- def __init__(self, positions=[1], num_trials=1): Constructor for interval class inputs: positions: A list of integers of number of shar... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment:
"""Class represents a string of $1000 investments and their daily returns"""
def __init__(self, positions=[1], num_trials=1):
"""Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class investment:
"""Class represents a string of $1000 investments and their daily returns"""
def __init__(self, positions=[1], num_trials=1):
"""Constructor for interval class inputs: positions: A list of integers of number of shares to buy. Each entry must be a factor of 1000. num_trials: An integer... | the_stack_v2_python_sparse | jt2276/investment_package/investment.py | ds-ga-1007/assignment8 | train | 1 |
d4ba13de3f572778d6e6658310ab8ce208ee13d0 | [
"args = self.theses_filter.parse_args()\nitems_per_page = 20\npage_number = args['page']\nif page_number < 1:\n return abort(HTTPStatus.BAD_REQUEST, message=\"'page' must be > 0\")\nitems_query = Thesis.query.join(Thesis.argument_thesis).filter(ArgumentThesis.argument_id == argument_id, not_(Thesis.is_comment)).... | <|body_start_0|>
args = self.theses_filter.parse_args()
items_per_page = 20
page_number = args['page']
if page_number < 1:
return abort(HTTPStatus.BAD_REQUEST, message="'page' must be > 0")
items_query = Thesis.query.join(Thesis.argument_thesis).filter(ArgumentThesis.... | ArgumentThesesResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentThesesResource:
def get(self, argument_id):
"""Get all argument theses * User can view theses of argument * View with pagination"""
<|body_0|>
def post(self, argument_id):
"""Create a new argument thesis * User with permission to **"create theses"** can creat... | stack_v2_sparse_classes_36k_train_025362 | 2,961 | permissive | [
{
"docstring": "Get all argument theses * User can view theses of argument * View with pagination",
"name": "get",
"signature": "def get(self, argument_id)"
},
{
"docstring": "Create a new argument thesis * User with permission to **\"create theses\"** can create a new thesis (in argument of not... | 2 | null | Implement the Python class `ArgumentThesesResource` described below.
Class description:
Implement the ArgumentThesesResource class.
Method signatures and docstrings:
- def get(self, argument_id): Get all argument theses * User can view theses of argument * View with pagination
- def post(self, argument_id): Create a ... | Implement the Python class `ArgumentThesesResource` described below.
Class description:
Implement the ArgumentThesesResource class.
Method signatures and docstrings:
- def get(self, argument_id): Get all argument theses * User can view theses of argument * View with pagination
- def post(self, argument_id): Create a ... | dce87ffe395ae4bd08b47f28e07594e1889da819 | <|skeleton|>
class ArgumentThesesResource:
def get(self, argument_id):
"""Get all argument theses * User can view theses of argument * View with pagination"""
<|body_0|>
def post(self, argument_id):
"""Create a new argument thesis * User with permission to **"create theses"** can creat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgumentThesesResource:
def get(self, argument_id):
"""Get all argument theses * User can view theses of argument * View with pagination"""
args = self.theses_filter.parse_args()
items_per_page = 20
page_number = args['page']
if page_number < 1:
return abort... | the_stack_v2_python_sparse | src/backend/app/api/public/arguments/argument/argument_theses.py | aimanow/sft | train | 0 | |
30bb0fc51cb65232d6e68a25e1cf7f75f874c680 | [
"super().__init__()\nallowed = ('conv', 'linear')\nif mlp_type not in allowed:\n raise ValueError(f'Illegal `mlp_type` given. Got: {mlp_type}. Allowed: {allowed}.')\nnorm_kwargs = norm_kwargs if norm_kwargs is not None else {}\nact_kwargs = act_kwargs if act_kwargs is not None else {}\nself.norm = Norm(normaliza... | <|body_start_0|>
super().__init__()
allowed = ('conv', 'linear')
if mlp_type not in allowed:
raise ValueError(f'Illegal `mlp_type` given. Got: {mlp_type}. Allowed: {allowed}.')
norm_kwargs = norm_kwargs if norm_kwargs is not None else {}
act_kwargs = act_kwargs if act... | MlpBlock | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MlpBlock:
def __init__(self, in_channels: int, mlp_type: str='linear', mlp_ratio: int=2, activation: str='star_relu', act_kwargs: Dict[str, Any]=None, dropout: float=0.0, bias: bool=False, normalization: str='ln', norm_kwargs: Dict[str, Any]=None) -> None:
"""Residual Mlp block. I.e. nor... | stack_v2_sparse_classes_36k_train_025363 | 6,969 | permissive | [
{
"docstring": "Residual Mlp block. I.e. norm -> mlp -> residual Parameters ---------- in_channels : int Number of input features. mlp_type : str, default=\"linear\" Flag for either nn.Linear or nn.Conv2d mlp-layer. One of \"conv\", \"linear\". mlp_ratio : int, default=2 Scaling factor to get the number hidden ... | 2 | null | Implement the Python class `MlpBlock` described below.
Class description:
Implement the MlpBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, mlp_type: str='linear', mlp_ratio: int=2, activation: str='star_relu', act_kwargs: Dict[str, Any]=None, dropout: float=0.0, bias: bool=False,... | Implement the Python class `MlpBlock` described below.
Class description:
Implement the MlpBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, mlp_type: str='linear', mlp_ratio: int=2, activation: str='star_relu', act_kwargs: Dict[str, Any]=None, dropout: float=0.0, bias: bool=False,... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class MlpBlock:
def __init__(self, in_channels: int, mlp_type: str='linear', mlp_ratio: int=2, activation: str='star_relu', act_kwargs: Dict[str, Any]=None, dropout: float=0.0, bias: bool=False, normalization: str='ln', norm_kwargs: Dict[str, Any]=None) -> None:
"""Residual Mlp block. I.e. nor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MlpBlock:
def __init__(self, in_channels: int, mlp_type: str='linear', mlp_ratio: int=2, activation: str='star_relu', act_kwargs: Dict[str, Any]=None, dropout: float=0.0, bias: bool=False, normalization: str='ln', norm_kwargs: Dict[str, Any]=None) -> None:
"""Residual Mlp block. I.e. norm -> mlp -> re... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/mlp.py | okunator/cellseg_models.pytorch | train | 43 | |
591292c85b964332f06cc0d06447f267977ac71f | [
"super().__init__()\nself.cost_class = cost_class\nself.cost_bbox = cost_bbox\nself.cost_giou = cost_giou\nassert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'",
"with torch.no_grad():\n targets = [targets[1]]\n out_bbox = outputs['pred_boxes'].flatten(0, 1)\n out_bbox = out_... | <|body_start_0|>
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'
<|end_body_0|>
<|body_start_1|>
with torch.no_grad():
targ... | SimpleMatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleMatcher:
def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1):
"""Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding b... | stack_v2_sparse_classes_36k_train_025364 | 2,835 | no_license | [
{
"docstring": "Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_giou: This is the relative weight of the giou loss of the bounding... | 2 | stack_v2_sparse_classes_30k_train_012955 | Implement the Python class `SimpleMatcher` described below.
Class description:
Implement the SimpleMatcher class.
Method signatures and docstrings:
- def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1): Creates the matcher Params: cost_class: This is the relative weight of the classificati... | Implement the Python class `SimpleMatcher` described below.
Class description:
Implement the SimpleMatcher class.
Method signatures and docstrings:
- def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1): Creates the matcher Params: cost_class: This is the relative weight of the classificati... | 24e1f80b24fb786039932603232b4c5801de1e37 | <|skeleton|>
class SimpleMatcher:
def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1):
"""Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleMatcher:
def __init__(self, cost_class: float=1, cost_bbox: float=1, cost_giou: float=1):
"""Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates... | the_stack_v2_python_sparse | utils/simple_matcher.py | ZYWZ/rltracking | train | 1 | |
408f31d4a76092b15536b32d5ea4b6ced7fc7b75 | [
"self.logger = logger\nself.datasets = datasets\nself.parameters = parameters\nself.experiment_name = parameters['experiment_name']\nself.dataset_name = parameters['dataset']\nself.dataset = datasets[parameters['dataset']]\nself.iterations = parameters['iterations']\nself.partions_number = parameters['partions_numb... | <|body_start_0|>
self.logger = logger
self.datasets = datasets
self.parameters = parameters
self.experiment_name = parameters['experiment_name']
self.dataset_name = parameters['dataset']
self.dataset = datasets[parameters['dataset']]
self.iterations = parameters['... | An aggregator module for import by AMLE | Aggregator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aggregator:
"""An aggregator module for import by AMLE"""
def __init__(self, logger, datasets, parameters):
"""Initialise the aggregator"""
<|body_0|>
def run(self):
"""Run cross validation of the experiment"""
<|body_1|>
def _cross_validate(self):
... | stack_v2_sparse_classes_36k_train_025365 | 2,888 | permissive | [
{
"docstring": "Initialise the aggregator",
"name": "__init__",
"signature": "def __init__(self, logger, datasets, parameters)"
},
{
"docstring": "Run cross validation of the experiment",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Perform a cross validation te... | 3 | stack_v2_sparse_classes_30k_train_015423 | Implement the Python class `Aggregator` described below.
Class description:
An aggregator module for import by AMLE
Method signatures and docstrings:
- def __init__(self, logger, datasets, parameters): Initialise the aggregator
- def run(self): Run cross validation of the experiment
- def _cross_validate(self): Perfo... | Implement the Python class `Aggregator` described below.
Class description:
An aggregator module for import by AMLE
Method signatures and docstrings:
- def __init__(self, logger, datasets, parameters): Initialise the aggregator
- def run(self): Run cross validation of the experiment
- def _cross_validate(self): Perfo... | 90d1baa21b1dfe58144c17f10e984b46ef0dec99 | <|skeleton|>
class Aggregator:
"""An aggregator module for import by AMLE"""
def __init__(self, logger, datasets, parameters):
"""Initialise the aggregator"""
<|body_0|>
def run(self):
"""Run cross validation of the experiment"""
<|body_1|>
def _cross_validate(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Aggregator:
"""An aggregator module for import by AMLE"""
def __init__(self, logger, datasets, parameters):
"""Initialise the aggregator"""
self.logger = logger
self.datasets = datasets
self.parameters = parameters
self.experiment_name = parameters['experiment_name... | the_stack_v2_python_sparse | amle/aggregators/samples/cross_validator_1/cross_validator_1.py | mattjhayes/amle | train | 0 |
eb61fcc3acc3bd9619406313a1e48c7f64e90ef5 | [
"self.task_controller = task_controller\nself.clear_before = clear_before\nself.clear_after = clear_after\nself.retries = retries\nself.recovery_task = recovery_task\nself.depend = depend\nself.block = block",
"max_len = max((len(s) for s in sequences))\nfor s in sequences:\n if len(s) != max_len:\n rai... | <|body_start_0|>
self.task_controller = task_controller
self.clear_before = clear_before
self.clear_after = clear_after
self.retries = retries
self.recovery_task = recovery_task
self.depend = depend
self.block = block
<|end_body_0|>
<|body_start_1|>
max_l... | Make an `IBlockingTaskClient` look like an `IMapper`. This class provides a load balanced version of `map`. | SynchronousTaskMapper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SynchronousTaskMapper:
"""Make an `IBlockingTaskClient` look like an `IMapper`. This class provides a load balanced version of `map`."""
def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=None, depend=None, block=True):
"""Create a `IM... | stack_v2_sparse_classes_36k_train_025366 | 8,554 | permissive | [
{
"docstring": "Create a `IMapper` given a `IBlockingTaskClient` and arguments. The additional arguments are those that are common to all types of tasks and are described in the documentation for `IPython.kernel.task.BaseTask`. :Parameters: task_controller : an `IBlockingTaskClient` implementer The `TaskControl... | 2 | stack_v2_sparse_classes_30k_train_007408 | Implement the Python class `SynchronousTaskMapper` described below.
Class description:
Make an `IBlockingTaskClient` look like an `IMapper`. This class provides a load balanced version of `map`.
Method signatures and docstrings:
- def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, r... | Implement the Python class `SynchronousTaskMapper` described below.
Class description:
Make an `IBlockingTaskClient` look like an `IMapper`. This class provides a load balanced version of `map`.
Method signatures and docstrings:
- def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, r... | 1cf44de3833929a4cf9e0069e8c75ef9086eeaca | <|skeleton|>
class SynchronousTaskMapper:
"""Make an `IBlockingTaskClient` look like an `IMapper`. This class provides a load balanced version of `map`."""
def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=None, depend=None, block=True):
"""Create a `IM... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SynchronousTaskMapper:
"""Make an `IBlockingTaskClient` look like an `IMapper`. This class provides a load balanced version of `map`."""
def __init__(self, task_controller, clear_before=False, clear_after=False, retries=0, recovery_task=None, depend=None, block=True):
"""Create a `IMapper` given ... | the_stack_v2_python_sparse | IPython/kernel/mapper.py | omazapa/ipython | train | 3 |
0472d7093a90e3c34e739000e1c51a7bd167fd65 | [
"self.name = name\nself.items = []\nself.load()",
"db = TinyDB(f'maxchess_db.json')\ntable = db.table(self.name)\ntable.truncate()\ntable.insert_multiple(self.items)",
"db = TinyDB(f'maxchess_db.json')\ntable = db.table(self.name)\nself.items = table.all()"
] | <|body_start_0|>
self.name = name
self.items = []
self.load()
<|end_body_0|>
<|body_start_1|>
db = TinyDB(f'maxchess_db.json')
table = db.table(self.name)
table.truncate()
table.insert_multiple(self.items)
<|end_body_1|>
<|body_start_2|>
db = TinyDB(f'ma... | Table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
def __init__(self, name):
"""Charge le nom de table joueurs/matchs/tournois depuis la base de donnée"""
<|body_0|>
def save(self):
"""Save all table items to the persistant db"""
<|body_1|>
def load(self):
"""Load all items from the persis... | stack_v2_sparse_classes_36k_train_025367 | 828 | no_license | [
{
"docstring": "Charge le nom de table joueurs/matchs/tournois depuis la base de donnée",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Save all table items to the persistant db",
"name": "save",
"signature": "def save(self)"
},
{
"docstring": "Lo... | 3 | stack_v2_sparse_classes_30k_train_008196 | Implement the Python class `Table` described below.
Class description:
Implement the Table class.
Method signatures and docstrings:
- def __init__(self, name): Charge le nom de table joueurs/matchs/tournois depuis la base de donnée
- def save(self): Save all table items to the persistant db
- def load(self): Load all... | Implement the Python class `Table` described below.
Class description:
Implement the Table class.
Method signatures and docstrings:
- def __init__(self, name): Charge le nom de table joueurs/matchs/tournois depuis la base de donnée
- def save(self): Save all table items to the persistant db
- def load(self): Load all... | 38ac2de90e891acdd9af42aab53488dd8db5b691 | <|skeleton|>
class Table:
def __init__(self, name):
"""Charge le nom de table joueurs/matchs/tournois depuis la base de donnée"""
<|body_0|>
def save(self):
"""Save all table items to the persistant db"""
<|body_1|>
def load(self):
"""Load all items from the persis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
def __init__(self, name):
"""Charge le nom de table joueurs/matchs/tournois depuis la base de donnée"""
self.name = name
self.items = []
self.load()
def save(self):
"""Save all table items to the persistant db"""
db = TinyDB(f'maxchess_db.json')
... | the_stack_v2_python_sparse | model/database.py | maximesoydas/maxchess | train | 0 | |
08986a8fb6c9317dadbcbb669f6b2ada2d72173f | [
"self.image = np.zeros(1)\nself.mask = np.zeros(1)\nself.x_tt = 0\nself.x_yy = 0",
"if xxx == 0 or yyy == 0 or xxx == self.image.width - 1 or (yyy == self.image.height - 1):\n return False\nif self.image[xxx][yyy] != 0 and self.image[xxx - 1][yyy] and (self.mask[xxx][yyy] == 0) or self.image[xxx + 1][yyy] != 0... | <|body_start_0|>
self.image = np.zeros(1)
self.mask = np.zeros(1)
self.x_tt = 0
self.x_yy = 0
<|end_body_0|>
<|body_start_1|>
if xxx == 0 or yyy == 0 or xxx == self.image.width - 1 or (yyy == self.image.height - 1):
return False
if self.image[xxx][yyy] != 0 a... | The threshold tracker is responsible for determining a set of threshold points for an image. Given a 2D array of points, it analyses these points and returns a set of threshold points for the image. The Threshold Tracker implements the following algorithm: (1)Scan the image from left to right and from top to bottom unt... | ThresholdTracker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThresholdTracker:
"""The threshold tracker is responsible for determining a set of threshold points for an image. Given a 2D array of points, it analyses these points and returns a set of threshold points for the image. The Threshold Tracker implements the following algorithm: (1)Scan the image f... | stack_v2_sparse_classes_36k_train_025368 | 4,966 | no_license | [
{
"docstring": "Initializes the member values",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Determines whether point is already within other points Parameters ---------- xxx, yyy : int Coordinates of point Returns ------- bool Whether point is on boundary or not",
... | 6 | stack_v2_sparse_classes_30k_train_021516 | Implement the Python class `ThresholdTracker` described below.
Class description:
The threshold tracker is responsible for determining a set of threshold points for an image. Given a 2D array of points, it analyses these points and returns a set of threshold points for the image. The Threshold Tracker implements the f... | Implement the Python class `ThresholdTracker` described below.
Class description:
The threshold tracker is responsible for determining a set of threshold points for an image. Given a 2D array of points, it analyses these points and returns a set of threshold points for the image. The Threshold Tracker implements the f... | f130a9e9904d6d2350300486524b53e6282a26f2 | <|skeleton|>
class ThresholdTracker:
"""The threshold tracker is responsible for determining a set of threshold points for an image. Given a 2D array of points, it analyses these points and returns a set of threshold points for the image. The Threshold Tracker implements the following algorithm: (1)Scan the image f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThresholdTracker:
"""The threshold tracker is responsible for determining a set of threshold points for an image. Given a 2D array of points, it analyses these points and returns a set of threshold points for the image. The Threshold Tracker implements the following algorithm: (1)Scan the image from left to r... | the_stack_v2_python_sparse | src/image_definition/ThresholdTracker.py | mcverter/Python_Image_Segmentation | train | 0 |
f248eac9f36bc4d6a12d2fac1da5921e30bc91da | [
"ax, ay = (a // 6, a % 6)\nbx, by = (b // 6, b % 6)\nreturn abs(ax - bx) + abs(ay - by)",
"dp = [[[-1] * 30 for _ in range(30)] for _ in range(310)]\ndp[0][26][26] = 0\nn = len(word)\nfor i in range(1, n + 1):\n c = word[i - 1]\n v = ord(c) - ord('A')\n for a in range(0, 27):\n for b in range(0, 2... | <|body_start_0|>
ax, ay = (a // 6, a % 6)
bx, by = (b // 6, b % 6)
return abs(ax - bx) + abs(ay - by)
<|end_body_0|>
<|body_start_1|>
dp = [[[-1] * 30 for _ in range(30)] for _ in range(310)]
dp[0][26][26] = 0
n = len(word)
for i in range(1, n + 1):
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_dis(self, a, b):
"""获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:"""
<|body_0|>
def minimumDistance(self, word: str) -> int:
"""dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距离 状态表示: i: 输入到第i个字符 a或b = -1: 表示没有放置手指, 0~25: 表示手指放在字母'A'-'Z'... | stack_v2_sparse_classes_36k_train_025369 | 4,418 | no_license | [
{
"docstring": "获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:",
"name": "get_dis",
"signature": "def get_dis(self, a, b)"
},
{
"docstring": "dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距离 状态表示: i: 输入到第i个字符 a或b = -1: 表示没有放置手指, 0~25: 表示手指放在字母'A'-'Z'上 26: 表示手指还没有开始输入 状态转移: i-1的状态手指放在... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_dis(self, a, b): 获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:
- def minimumDistance(self, word: str) -> int: dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_dis(self, a, b): 获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:
- def minimumDistance(self, word: str) -> int: dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def get_dis(self, a, b):
"""获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:"""
<|body_0|>
def minimumDistance(self, word: str) -> int:
"""dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距离 状态表示: i: 输入到第i个字符 a或b = -1: 表示没有放置手指, 0~25: 表示手指放在字母'A'-'Z'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_dis(self, a, b):
"""获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:"""
ax, ay = (a // 6, a % 6)
bx, by = (b // 6, b % 6)
return abs(ax - bx) + abs(ay - by)
def minimumDistance(self, word: str) -> int:
"""dp[i][a][b] 表示输入完第i个字符时手指1放在A上,... | the_stack_v2_python_sparse | 1320. 二指输入的的最小距离.py | lovehhf/LeetCode | train | 0 | |
e4bedae8495bbce80d2d746ae8f836050f96e429 | [
"aux = []\nacc = 0\nfor num in nums:\n aux.append(acc)\n acc += num\naux.append(acc)\nresult = 0\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums) + 1):\n if aux[j] - aux[i] == k:\n result += 1\nreturn result",
"acc = 0\naux = defaultdict(lambda: 0)\naux[0] += 1\nresult = 0\... | <|body_start_0|>
aux = []
acc = 0
for num in nums:
aux.append(acc)
acc += num
aux.append(acc)
result = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums) + 1):
if aux[j] - aux[i] == k:
resul... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def first_solution(self, nums: List[int], k: int) -> int:
"""O(n^2)"""
<|body_0|>
def subarraySum(self, nums: List[int], k: int) -> int:
"""O(n) inspired by the other solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
aux = []
... | stack_v2_sparse_classes_36k_train_025370 | 870 | no_license | [
{
"docstring": "O(n^2)",
"name": "first_solution",
"signature": "def first_solution(self, nums: List[int], k: int) -> int"
},
{
"docstring": "O(n) inspired by the other solution",
"name": "subarraySum",
"signature": "def subarraySum(self, nums: List[int], k: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def first_solution(self, nums: List[int], k: int) -> int: O(n^2)
- def subarraySum(self, nums: List[int], k: int) -> int: O(n) inspired by the other solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def first_solution(self, nums: List[int], k: int) -> int: O(n^2)
- def subarraySum(self, nums: List[int], k: int) -> int: O(n) inspired by the other solution
<|skeleton|>
class ... | d4d44e6dfd3df4cb47b855ad30e6849038cea0a5 | <|skeleton|>
class Solution:
def first_solution(self, nums: List[int], k: int) -> int:
"""O(n^2)"""
<|body_0|>
def subarraySum(self, nums: List[int], k: int) -> int:
"""O(n) inspired by the other solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def first_solution(self, nums: List[int], k: int) -> int:
"""O(n^2)"""
aux = []
acc = 0
for num in nums:
aux.append(acc)
acc += num
aux.append(acc)
result = 0
for i in range(len(nums)):
for j in range(i + 1, ... | the_stack_v2_python_sparse | leetcode/30_days_challange/subarray_sum_equals_k.py | alvaronaschez/amazon | train | 0 | |
b0885d3fa034851753d0eeb9698a7f22fb479700 | [
"self.__sql_db_path = sql_db_path\nself.__mapper = table_mapper_method\nself.__connection = sqlite3.connect(self.__sql_db_path)\nself.__c_names, self.__c_types, self.__c_tables, self.__tables_keys = ([], [], [], {})\nself.__generate_tables_dict()",
"cur = self.__connection.cursor()\nquery = \"SELECT name FROM sql... | <|body_start_0|>
self.__sql_db_path = sql_db_path
self.__mapper = table_mapper_method
self.__connection = sqlite3.connect(self.__sql_db_path)
self.__c_names, self.__c_types, self.__c_tables, self.__tables_keys = ([], [], [], {})
self.__generate_tables_dict()
<|end_body_0|>
<|bod... | SqlInterfaceGeneric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqlInterfaceGeneric:
def __init__(self, sql_db_path, table_mapper_method):
""":param sql_db_path: The path to the sql_db_path. :type sql_db_path: str :param table_mapper_method: The method that maps all the table names of the db to there corresponding PRAGMA queries. :type table_mapper_m... | stack_v2_sparse_classes_36k_train_025371 | 10,669 | permissive | [
{
"docstring": ":param sql_db_path: The path to the sql_db_path. :type sql_db_path: str :param table_mapper_method: The method that maps all the table names of the db to there corresponding PRAGMA queries. :type table_mapper_method: function()",
"name": "__init__",
"signature": "def __init__(self, sql_d... | 5 | stack_v2_sparse_classes_30k_train_000226 | Implement the Python class `SqlInterfaceGeneric` described below.
Class description:
Implement the SqlInterfaceGeneric class.
Method signatures and docstrings:
- def __init__(self, sql_db_path, table_mapper_method): :param sql_db_path: The path to the sql_db_path. :type sql_db_path: str :param table_mapper_method: Th... | Implement the Python class `SqlInterfaceGeneric` described below.
Class description:
Implement the SqlInterfaceGeneric class.
Method signatures and docstrings:
- def __init__(self, sql_db_path, table_mapper_method): :param sql_db_path: The path to the sql_db_path. :type sql_db_path: str :param table_mapper_method: Th... | 09cecfb795cd9df33773a3095ff855d1c2eb396d | <|skeleton|>
class SqlInterfaceGeneric:
def __init__(self, sql_db_path, table_mapper_method):
""":param sql_db_path: The path to the sql_db_path. :type sql_db_path: str :param table_mapper_method: The method that maps all the table names of the db to there corresponding PRAGMA queries. :type table_mapper_m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqlInterfaceGeneric:
def __init__(self, sql_db_path, table_mapper_method):
""":param sql_db_path: The path to the sql_db_path. :type sql_db_path: str :param table_mapper_method: The method that maps all the table names of the db to there corresponding PRAGMA queries. :type table_mapper_method: functio... | the_stack_v2_python_sparse | data_models/sql_provider/sql_interface_generic.py | imldresden/mcv-displaywall | train | 2 | |
bc403fcdd9722d84dd2b72e1f64e8c21370e268f | [
"self.graph = graph\nself.point_dict = dict()\nself.radius = 1.0",
"if root is None:\n algorithm = TreeCenter(self.graph)\n algorithm.run()\n root = algorithm.tree_center[0]\nself.plot(root, 0.0, 2.0 * math.pi, level=0)",
"angle = 0.5 * (left + right)\nx = self.radius * level * math.cos(angle)\ny = sel... | <|body_start_0|>
self.graph = graph
self.point_dict = dict()
self.radius = 1.0
<|end_body_0|>
<|body_start_1|>
if root is None:
algorithm = TreeCenter(self.graph)
algorithm.run()
root = algorithm.tree_center[0]
self.plot(root, 0.0, 2.0 * math.... | Finding the positions of tree nodes in the plane. This is not suitable for large trees (|V| > 1e4) due to numerical errors. For large trees use TreePlotRadiusAngle with fractions. | TreePlot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreePlot:
"""Finding the positions of tree nodes in the plane. This is not suitable for large trees (|V| > 1e4) due to numerical errors. For large trees use TreePlotRadiusAngle with fractions."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_025372 | 3,663 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, root=None)"
},
{
"docstring": "Find node positions. Parameters ---------- source : c... | 3 | stack_v2_sparse_classes_30k_train_015971 | Implement the Python class `TreePlot` described below.
Class description:
Finding the positions of tree nodes in the plane. This is not suitable for large trees (|V| > 1e4) due to numerical errors. For large trees use TreePlotRadiusAngle with fractions.
Method signatures and docstrings:
- def __init__(self, graph): T... | Implement the Python class `TreePlot` described below.
Class description:
Finding the positions of tree nodes in the plane. This is not suitable for large trees (|V| > 1e4) due to numerical errors. For large trees use TreePlotRadiusAngle with fractions.
Method signatures and docstrings:
- def __init__(self, graph): T... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class TreePlot:
"""Finding the positions of tree nodes in the plane. This is not suitable for large trees (|V| > 1e4) due to numerical errors. For large trees use TreePlotRadiusAngle with fractions."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreePlot:
"""Finding the positions of tree nodes in the plane. This is not suitable for large trees (|V| > 1e4) due to numerical errors. For large trees use TreePlotRadiusAngle with fractions."""
def __init__(self, graph):
"""The algorithm initialization."""
self.graph = graph
sel... | the_stack_v2_python_sparse | graphtheory/forests/treeplot.py | kgashok/graphs-dict | train | 0 |
dc567f115c6c5b7cddfe34479fb43d311958bb73 | [
"self.app = app\nself.migrate_from = [(app, migrate_from)]\nself.executor = MigrationExecutor(connection)\nself.executor.migrate(self.migrate_from)\nself._old_apps = self.executor.loader.project_state(self.migrate_from).apps\nreturn self._old_apps",
"self.migrate_to = [(app, migrate_to)]\nself.executor.loader.bui... | <|body_start_0|>
self.app = app
self.migrate_from = [(app, migrate_from)]
self.executor = MigrationExecutor(connection)
self.executor.migrate(self.migrate_from)
self._old_apps = self.executor.loader.project_state(self.migrate_from).apps
return self._old_apps
<|end_body_0|... | Migrator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migrator:
def before(self, app, migrate_from):
"""Specify app and starting migration name as in: before('app', '0001_before') => app/migrations/0001_before.py"""
<|body_0|>
def apply(self, app, migrate_to):
"""Migrate forwards to the "migrate_to" migration"""
... | stack_v2_sparse_classes_36k_train_025373 | 2,736 | permissive | [
{
"docstring": "Specify app and starting migration name as in: before('app', '0001_before') => app/migrations/0001_before.py",
"name": "before",
"signature": "def before(self, app, migrate_from)"
},
{
"docstring": "Migrate forwards to the \"migrate_to\" migration",
"name": "apply",
"sign... | 2 | stack_v2_sparse_classes_30k_train_004058 | Implement the Python class `Migrator` described below.
Class description:
Implement the Migrator class.
Method signatures and docstrings:
- def before(self, app, migrate_from): Specify app and starting migration name as in: before('app', '0001_before') => app/migrations/0001_before.py
- def apply(self, app, migrate_t... | Implement the Python class `Migrator` described below.
Class description:
Implement the Migrator class.
Method signatures and docstrings:
- def before(self, app, migrate_from): Specify app and starting migration name as in: before('app', '0001_before') => app/migrations/0001_before.py
- def apply(self, app, migrate_t... | 408f3fa3d36542d8fc1236ba1cac804de6f14b0c | <|skeleton|>
class Migrator:
def before(self, app, migrate_from):
"""Specify app and starting migration name as in: before('app', '0001_before') => app/migrations/0001_before.py"""
<|body_0|>
def apply(self, app, migrate_to):
"""Migrate forwards to the "migrate_to" migration"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migrator:
def before(self, app, migrate_from):
"""Specify app and starting migration name as in: before('app', '0001_before') => app/migrations/0001_before.py"""
self.app = app
self.migrate_from = [(app, migrate_from)]
self.executor = MigrationExecutor(connection)
self.... | the_stack_v2_python_sparse | hard-gists/b3e6f9b5d95af8ba2cc46f2ba6eae5e2/snippet.py | dockerizeme/dockerizeme | train | 24 | |
525988558be984e2b23360b9d8f0fac1739b3ee7 | [
"super().__init__(trinity.god, config.NGOD, trinity, config)\nself.config = config\nself.net = Model(projekt.ANN, config)\nif config.POPOPT:\n self.opt = PopulationOptimizer(self.net, config)\nelse:\n self.opt = GradientOptimizer(self.net, config)\nif config.LOAD or config.BEST:\n self.net.load(self.opt, c... | <|body_start_0|>
super().__init__(trinity.god, config.NGOD, trinity, config)
self.config = config
self.net = Model(projekt.ANN, config)
if config.POPOPT:
self.opt = PopulationOptimizer(self.net, config)
else:
self.opt = GradientOptimizer(self.net, config)
... | Cluster level Pantheon API demo This cluster level module aggregrates gradients across all server level optimizer nodes and updates model weights using Adam. Also demonstrates logging and snapshotting functionality through the Quill and Model libraries, respectively. | Pantheon | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pantheon:
"""Cluster level Pantheon API demo This cluster level module aggregrates gradients across all server level optimizer nodes and updates model weights using Adam. Also demonstrates logging and snapshotting functionality through the Quill and Model libraries, respectively."""
def __in... | stack_v2_sparse_classes_36k_train_025374 | 2,041 | permissive | [
{
"docstring": "Initializes a copy of the model, which keeps track of a copy of the weights for the optimizer.",
"name": "__init__",
"signature": "def __init__(self, trinity, config, idx)"
},
{
"docstring": "Broadcasts updated weights to server level God optimizer nodes. Performs an Adam step on... | 2 | stack_v2_sparse_classes_30k_train_013458 | Implement the Python class `Pantheon` described below.
Class description:
Cluster level Pantheon API demo This cluster level module aggregrates gradients across all server level optimizer nodes and updates model weights using Adam. Also demonstrates logging and snapshotting functionality through the Quill and Model li... | Implement the Python class `Pantheon` described below.
Class description:
Cluster level Pantheon API demo This cluster level module aggregrates gradients across all server level optimizer nodes and updates model weights using Adam. Also demonstrates logging and snapshotting functionality through the Quill and Model li... | cde2c666225d1382abb33243735f60e37113a267 | <|skeleton|>
class Pantheon:
"""Cluster level Pantheon API demo This cluster level module aggregrates gradients across all server level optimizer nodes and updates model weights using Adam. Also demonstrates logging and snapshotting functionality through the Quill and Model libraries, respectively."""
def __in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pantheon:
"""Cluster level Pantheon API demo This cluster level module aggregrates gradients across all server level optimizer nodes and updates model weights using Adam. Also demonstrates logging and snapshotting functionality through the Quill and Model libraries, respectively."""
def __init__(self, tr... | the_stack_v2_python_sparse | projekt/pantheon.py | Justin-Yuan/neural-mmo | train | 0 |
7ec2c3516e7ea63437bc9d8e69daf24d5cfbf277 | [
"super().__init__()\nself.layout = initial_layout\nself.coupling_map = coupling_map",
"if self.layout is None:\n if self.property_set['layout']:\n self.layout = self.property_set['layout']\n else:\n self.layout = Layout.generate_trivial_layout(*dag.qregs.values())\nself.property_set['is_swap_m... | <|body_start_0|>
super().__init__()
self.layout = initial_layout
self.coupling_map = coupling_map
<|end_body_0|>
<|body_start_1|>
if self.layout is None:
if self.property_set['layout']:
self.layout = self.property_set['layout']
else:
... | Checks if a DAGCircuit is mapped to `coupling_map`, setting `is_swap_mapped` in the property set as True if mapped. False otherwise. | CheckMap | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckMap:
"""Checks if a DAGCircuit is mapped to `coupling_map`, setting `is_swap_mapped` in the property set as True if mapped. False otherwise."""
def __init__(self, coupling_map, initial_layout=None):
"""Checks if a DAGCircuit is mapped to `coupling_map`. Args: coupling_map (Coupl... | stack_v2_sparse_classes_36k_train_025375 | 2,239 | permissive | [
{
"docstring": "Checks if a DAGCircuit is mapped to `coupling_map`. Args: coupling_map (CouplingMap): Directed graph representing a coupling map. initial_layout (Layout): The initial layout of the DAG to analyze.",
"name": "__init__",
"signature": "def __init__(self, coupling_map, initial_layout=None)"
... | 2 | null | Implement the Python class `CheckMap` described below.
Class description:
Checks if a DAGCircuit is mapped to `coupling_map`, setting `is_swap_mapped` in the property set as True if mapped. False otherwise.
Method signatures and docstrings:
- def __init__(self, coupling_map, initial_layout=None): Checks if a DAGCircu... | Implement the Python class `CheckMap` described below.
Class description:
Checks if a DAGCircuit is mapped to `coupling_map`, setting `is_swap_mapped` in the property set as True if mapped. False otherwise.
Method signatures and docstrings:
- def __init__(self, coupling_map, initial_layout=None): Checks if a DAGCircu... | abf6c23d4ab6c63f9c01c7434fb46321e6a69200 | <|skeleton|>
class CheckMap:
"""Checks if a DAGCircuit is mapped to `coupling_map`, setting `is_swap_mapped` in the property set as True if mapped. False otherwise."""
def __init__(self, coupling_map, initial_layout=None):
"""Checks if a DAGCircuit is mapped to `coupling_map`. Args: coupling_map (Coupl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckMap:
"""Checks if a DAGCircuit is mapped to `coupling_map`, setting `is_swap_mapped` in the property set as True if mapped. False otherwise."""
def __init__(self, coupling_map, initial_layout=None):
"""Checks if a DAGCircuit is mapped to `coupling_map`. Args: coupling_map (CouplingMap): Dire... | the_stack_v2_python_sparse | qiskit/transpiler/passes/mapping/check_map.py | indian-institute-of-science-qc/qiskit-aakash | train | 37 |
e083f14572016be6f50ad39511fe4df16569b19b | [
"def isPalindrome(i, j):\n while i < j:\n if s[i] != s[j]:\n return False\n i = i + 1\n j = j - 1\n return True\ni = 0\nj = len(s) - 1\nwhile i < j:\n if s[i] != s[j]:\n return isPalindrome(i + 1, j) or isPalindrome(i, j - 1)\n i += 1\n j -= 1\nreturn True",
"... | <|body_start_0|>
def isPalindrome(i, j):
while i < j:
if s[i] != s[j]:
return False
i = i + 1
j = j - 1
return True
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
"""给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool"""
<|body_0|>
def validPalindrome1(self, s):
"""leetcode最快实例 :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_025376 | 1,167 | no_license | [
{
"docstring": "给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s)"
},
{
"docstring": "leetcode最快实例 :param s: :return:",
"name": "validPalindrome1",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_016853 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): 给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool
- def validPalindrome1(self, s): leetcode最快实例 :p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): 给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool
- def validPalindrome1(self, s): leetcode最快实例 :p... | b2228230c90d7c91b0a40399fa631520c290b61d | <|skeleton|>
class Solution:
def validPalindrome(self, s):
"""给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool"""
<|body_0|>
def validPalindrome1(self, s):
"""leetcode最快实例 :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validPalindrome(self, s):
"""给定一个非空字符串 s,最多删除一个字符。 判断是否能成为回文字符串。 首先从字符串的首尾推进,如果不相等,那么可能删除的位置就在不等的两个位置中 :type s: str :rtype: bool"""
def isPalindrome(i, j):
while i < j:
if s[i] != s[j]:
return False
i = i + 1
... | the_stack_v2_python_sparse | 字符串/判断回文字符串2_680.py | Xiaoctw/LeetCode1_python | train | 0 | |
d8b7e5049481d013cf8bec0ffa5b371ec8b886ac | [
"self.suits = {}\nfor card in self.cards:\n self.suits[card.suit] = self.suits.get(card.suit, 0) + 1",
"self.suit_hist()\nfor val in self.suits.values():\n if val >= 5:\n return True\nreturn False"
] | <|body_start_0|>
self.suits = {}
for card in self.cards:
self.suits[card.suit] = self.suits.get(card.suit, 0) + 1
<|end_body_0|>
<|body_start_1|>
self.suit_hist()
for val in self.suits.values():
if val >= 5:
return True
return False
<|end_... | Represents a poker hand. | PokerHand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PokerHand:
"""Represents a poker hand."""
def suit_hist(self):
"""Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits."""
<|body_0|>
def has_flush(self):
"""Returns True if the hand has a flush, False otherwise. Note that... | stack_v2_sparse_classes_36k_train_025377 | 1,245 | permissive | [
{
"docstring": "Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits.",
"name": "suit_hist",
"signature": "def suit_hist(self)"
},
{
"docstring": "Returns True if the hand has a flush, False otherwise. Note that this works correctly for hands with more th... | 2 | null | Implement the Python class `PokerHand` described below.
Class description:
Represents a poker hand.
Method signatures and docstrings:
- def suit_hist(self): Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits.
- def has_flush(self): Returns True if the hand has a flush, False... | Implement the Python class `PokerHand` described below.
Class description:
Represents a poker hand.
Method signatures and docstrings:
- def suit_hist(self): Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits.
- def has_flush(self): Returns True if the hand has a flush, False... | 7961de5ba9923512bd50c579c37f1dadf070b692 | <|skeleton|>
class PokerHand:
"""Represents a poker hand."""
def suit_hist(self):
"""Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits."""
<|body_0|>
def has_flush(self):
"""Returns True if the hand has a flush, False otherwise. Note that... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PokerHand:
"""Represents a poker hand."""
def suit_hist(self):
"""Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits."""
self.suits = {}
for card in self.cards:
self.suits[card.suit] = self.suits.get(card.suit, 0) + 1
def... | the_stack_v2_python_sparse | thinkpython/18/PokerHand.py | Hellorelei/oc-2018 | train | 0 |
315df24e6511007db2b3f5cabccbe5a6aebd6654 | [
"if root is None:\n return ''\nif root.left is None and root.right is None:\n return str(root.val) + ''\nelif root.left is None:\n return str(root.val) + '()' + '(' + self.serialize(root.right) + ')'\nelif root.right is None:\n return str(root.val) + '(' + self.serialize(root.left) + ')'\nreturn str(roo... | <|body_start_0|>
if root is None:
return ''
if root.left is None and root.right is None:
return str(root.val) + ''
elif root.left is None:
return str(root.val) + '()' + '(' + self.serialize(root.right) + ')'
elif root.right is None:
return ... | Codec | [
"Apache-2.0"
] | 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, s):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_025378 | 1,638 | permissive | [
{
"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_002776 | 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, s): Decodes your encoded data to tree. :type data: str :rtype: Tr... | 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, s): Decodes your encoded data to tree. :type data: str :rtype: Tr... | 3a288b3d0cc3ec09bcb57480f6360dff95455679 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, s):
"""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 root is None:
return ''
if root.left is None and root.right is None:
return str(root.val) + ''
elif root.left is None:
return str(r... | the_stack_v2_python_sparse | leetcode_python/serialize_and_deserialize_bst.py | wanglikun7342/Leetcode-Python | train | 0 | |
de79394367eb2867ee1648c79d85687459982d9c | [
"super(KineticPooling, self).__init__()\nself.configs = configs\nself.nconfs = len(configs[0])\nself.nup = mol.nup\nself.ndown = mol.ndown\nself.nelec = self.nup + self.ndown\nself.orb_proj = OrbitalProjector(configs, mol, cuda=cuda)\nself.device = torch.device('cpu')\nif cuda:\n self.device = torch.device('cuda... | <|body_start_0|>
super(KineticPooling, self).__init__()
self.configs = configs
self.nconfs = len(configs[0])
self.nup = mol.nup
self.ndown = mol.ndown
self.nelec = self.nup + self.ndown
self.orb_proj = OrbitalProjector(configs, mol, cuda=cuda)
self.device ... | KineticPooling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KineticPooling:
def __init__(self, configs, mol, cuda=False):
"""Computes the kinetic energy using the Jacobi formula WARNING : This is very memory intesive as it stores explicit projector matrices to extract submatrices. Prefer the pooling methods implemented in slater_pooling.py Args: ... | stack_v2_sparse_classes_36k_train_025379 | 2,646 | permissive | [
{
"docstring": "Computes the kinetic energy using the Jacobi formula WARNING : This is very memory intesive as it stores explicit projector matrices to extract submatrices. Prefer the pooling methods implemented in slater_pooling.py Args: configs (list): list of slater determinants mol (Molecule): instance of a... | 2 | stack_v2_sparse_classes_30k_train_006473 | Implement the Python class `KineticPooling` described below.
Class description:
Implement the KineticPooling class.
Method signatures and docstrings:
- def __init__(self, configs, mol, cuda=False): Computes the kinetic energy using the Jacobi formula WARNING : This is very memory intesive as it stores explicit projec... | Implement the Python class `KineticPooling` described below.
Class description:
Implement the KineticPooling class.
Method signatures and docstrings:
- def __init__(self, configs, mol, cuda=False): Computes the kinetic energy using the Jacobi formula WARNING : This is very memory intesive as it stores explicit projec... | 7ad217168fc5083b55977dfdaf964d355986d001 | <|skeleton|>
class KineticPooling:
def __init__(self, configs, mol, cuda=False):
"""Computes the kinetic energy using the Jacobi formula WARNING : This is very memory intesive as it stores explicit projector matrices to extract submatrices. Prefer the pooling methods implemented in slater_pooling.py Args: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KineticPooling:
def __init__(self, configs, mol, cuda=False):
"""Computes the kinetic energy using the Jacobi formula WARNING : This is very memory intesive as it stores explicit projector matrices to extract submatrices. Prefer the pooling methods implemented in slater_pooling.py Args: configs (list)... | the_stack_v2_python_sparse | qmctorch/wavefunction/pooling/kinetic_pooling.py | ScorpJD/QMCTorch | train | 0 | |
38778efe560f097e41e37a2c8ed85b2deed50d2d | [
"self._logger = logger\nself.operation = event['cmd']\nself.pod_task_uuid = event['cid']\nself.domain_name = ''\nself.project_name = ''\nself.node_name = ''\nself.node_ip = ''\nself.networks = None\nself.pod_subnets = None\nself.security_groups = ''\nself.floating_ips = ''\nself._extract_values(event)",
"labels =... | <|body_start_0|>
self._logger = logger
self.operation = event['cmd']
self.pod_task_uuid = event['cid']
self.domain_name = ''
self.project_name = ''
self.node_name = ''
self.node_ip = ''
self.networks = None
self.pod_subnets = None
self.secu... | Handle label processing | MesosCniLabels | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MesosCniLabels:
"""Handle label processing"""
def __init__(self, event, logger):
"""Initialize all labels to default vaule"""
<|body_0|>
def _extract_values(self, event):
"""Extract values from args"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_025380 | 12,359 | permissive | [
{
"docstring": "Initialize all labels to default vaule",
"name": "__init__",
"signature": "def __init__(self, event, logger)"
},
{
"docstring": "Extract values from args",
"name": "_extract_values",
"signature": "def _extract_values(self, event)"
}
] | 2 | null | Implement the Python class `MesosCniLabels` described below.
Class description:
Handle label processing
Method signatures and docstrings:
- def __init__(self, event, logger): Initialize all labels to default vaule
- def _extract_values(self, event): Extract values from args | Implement the Python class `MesosCniLabels` described below.
Class description:
Handle label processing
Method signatures and docstrings:
- def __init__(self, event, logger): Initialize all labels to default vaule
- def _extract_values(self, event): Extract values from args
<|skeleton|>
class MesosCniLabels:
"""... | f825fde287f4eb2089aba2225ca73eeab3888040 | <|skeleton|>
class MesosCniLabels:
"""Handle label processing"""
def __init__(self, event, logger):
"""Initialize all labels to default vaule"""
<|body_0|>
def _extract_values(self, event):
"""Extract values from args"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MesosCniLabels:
"""Handle label processing"""
def __init__(self, event, logger):
"""Initialize all labels to default vaule"""
self._logger = logger
self.operation = event['cmd']
self.pod_task_uuid = event['cid']
self.domain_name = ''
self.project_name = ''
... | the_stack_v2_python_sparse | src/container/mesos-manager/mesos_manager/vnc/vnc_pod_task.py | tungstenfabric/tf-controller | train | 55 |
3aa64e72cc636517ca89109166efc8580f0b3bfc | [
"if 'id_user' in request.data:\n id_user = request.data['id_user']\n del request.data['id_user']\n user = User.objects.get(id=id_user)\n queryset = Prompt.objects.filter(creater=user)\n serializer = MockPromptSerializer(queryset, many=True)\n return Response({'result': serializer.data})\nelse:\n ... | <|body_start_0|>
if 'id_user' in request.data:
id_user = request.data['id_user']
del request.data['id_user']
user = User.objects.get(id=id_user)
queryset = Prompt.objects.filter(creater=user)
serializer = MockPromptSerializer(queryset, many=True)
... | PromptViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PromptViewSet:
def my_prompts(self, request, *args, **kwargs):
"""Action to get your prompts."""
<|body_0|>
def others_prompts(self, request, *args, **kwargs):
"""Action to get prompts when you added in prompt."""
<|body_1|>
def all_prompts(self, request... | stack_v2_sparse_classes_36k_train_025381 | 2,872 | permissive | [
{
"docstring": "Action to get your prompts.",
"name": "my_prompts",
"signature": "def my_prompts(self, request, *args, **kwargs)"
},
{
"docstring": "Action to get prompts when you added in prompt.",
"name": "others_prompts",
"signature": "def others_prompts(self, request, *args, **kwargs... | 4 | stack_v2_sparse_classes_30k_train_014116 | Implement the Python class `PromptViewSet` described below.
Class description:
Implement the PromptViewSet class.
Method signatures and docstrings:
- def my_prompts(self, request, *args, **kwargs): Action to get your prompts.
- def others_prompts(self, request, *args, **kwargs): Action to get prompts when you added i... | Implement the Python class `PromptViewSet` described below.
Class description:
Implement the PromptViewSet class.
Method signatures and docstrings:
- def my_prompts(self, request, *args, **kwargs): Action to get your prompts.
- def others_prompts(self, request, *args, **kwargs): Action to get prompts when you added i... | b7c0ec39a01631f822035786d76aebbb96ba077c | <|skeleton|>
class PromptViewSet:
def my_prompts(self, request, *args, **kwargs):
"""Action to get your prompts."""
<|body_0|>
def others_prompts(self, request, *args, **kwargs):
"""Action to get prompts when you added in prompt."""
<|body_1|>
def all_prompts(self, request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PromptViewSet:
def my_prompts(self, request, *args, **kwargs):
"""Action to get your prompts."""
if 'id_user' in request.data:
id_user = request.data['id_user']
del request.data['id_user']
user = User.objects.get(id=id_user)
queryset = Prompt.obj... | the_stack_v2_python_sparse | backend/api/views_api.py | ZayJob/Mnemosyne | train | 3 | |
b912dbe5da6fc486dfb8d615f7c3c836236f9376 | [
"if field is None:\n return field\nelif field is '':\n return None\nelif isinstance(field, basestring):\n result = dateutil.parser.parse(field)\n if result.tzinfo is None:\n result = result.replace(tzinfo=UTC())\n return result\nelif isinstance(field, (int, long, float)):\n return datetime.... | <|body_start_0|>
if field is None:
return field
elif field is '':
return None
elif isinstance(field, basestring):
result = dateutil.parser.parse(field)
if result.tzinfo is None:
result = result.replace(tzinfo=UTC())
retu... | Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes. | Date | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Date:
"""Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes."""
def from_json(self, field):
"""Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid."""
... | stack_v2_sparse_classes_36k_train_025382 | 3,123 | no_license | [
{
"docstring": "Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid.",
"name": "from_json",
"signature": "def from_json(self, field)"
},
{
"docstring": "Convert a time struct to a string",
"name": "to_json",
"s... | 2 | stack_v2_sparse_classes_30k_train_003320 | Implement the Python class `Date` described below.
Class description:
Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes.
Method signatures and docstrings:
- def from_json(self, field): Parse an optional metadata key containing a time: if present, complain if it do... | Implement the Python class `Date` described below.
Class description:
Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes.
Method signatures and docstrings:
- def from_json(self, field): Parse an optional metadata key containing a time: if present, complain if it do... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class Date:
"""Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes."""
def from_json(self, field):
"""Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Date:
"""Date fields know how to parse and produce json (iso) compatible formats. Converts to tz aware datetimes."""
def from_json(self, field):
"""Parse an optional metadata key containing a time: if present, complain if it doesn't parse. Return None if not present or invalid."""
if fiel... | the_stack_v2_python_sparse | ExtractFeatures/Data/pratik98/fields.py | vivekaxl/LexisNexis | train | 9 |
3be8d7d9a61a6c4d31bfb4718c69827b0279d4d3 | [
"if slt_num == 0:\n self.MF_root = os.path.join(data_path, 'U_V', mode)\nelse:\n self.MF_root = os.path.join(data_path, 'U_V', str(slt_num) + '_' + mode)\nif not os.path.exists(self.MF_root):\n os.makedirs(self.MF_root)\nself.mashup_emb_df, self.api_emb_df = (None, None)",
"if self.mashup_emb_df is None ... | <|body_start_0|>
if slt_num == 0:
self.MF_root = os.path.join(data_path, 'U_V', mode)
else:
self.MF_root = os.path.join(data_path, 'U_V', str(slt_num) + '_' + mode)
if not os.path.exists(self.MF_root):
os.makedirs(self.MF_root)
self.mashup_emb_df, self... | MF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MF:
def __init__(self, data_path, mode, slt_num=0):
"""根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法"""
<|body_0|>
def get_mf_embedding(self, train_mashup_api_list, mode):
""":param train_mashup_api_list: 训练集 :param mode: :re... | stack_v2_sparse_classes_36k_train_025383 | 6,194 | no_license | [
{
"docstring": "根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法",
"name": "__init__",
"signature": "def __init__(self, data_path, mode, slt_num=0)"
},
{
"docstring": ":param train_mashup_api_list: 训练集 :param mode: :return: df形式,id是其索引, embedding列的列名是embedd... | 2 | stack_v2_sparse_classes_30k_train_000290 | Implement the Python class `MF` described below.
Class description:
Implement the MF class.
Method signatures and docstrings:
- def __init__(self, data_path, mode, slt_num=0): 根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法
- def get_mf_embedding(self, train_mashup_api_list, mo... | Implement the Python class `MF` described below.
Class description:
Implement the MF class.
Method signatures and docstrings:
- def __init__(self, data_path, mode, slt_num=0): 根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法
- def get_mf_embedding(self, train_mashup_api_list, mo... | 8acad55835cce1c76eac44e5694c89741bba12dc | <|skeleton|>
class MF:
def __init__(self, data_path, mode, slt_num=0):
"""根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法"""
<|body_0|>
def get_mf_embedding(self, train_mashup_api_list, mode):
""":param train_mashup_api_list: 训练集 :param mode: :re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MF:
def __init__(self, data_path, mode, slt_num=0):
"""根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法"""
if slt_num == 0:
self.MF_root = os.path.join(data_path, 'U_V', mode)
else:
self.MF_root = os.path.join(data_path, 'U... | the_stack_v2_python_sparse | mf/get_mf_embedding.py | xiaotret/DLISR | train | 0 | |
e53f989c318f09dc4283c2c5933a5b0d739d83ef | [
"if not product_id:\n products = product_db.Product.all()\n products_result = [{'product_id': p.key().name()} for p in products]\n result = {'products': products_result}\nelse:\n product = product_db.Product.get_by_key_name(product_id)\n if not product:\n self.error(httplib.NOT_FOUND)\n ... | <|body_start_0|>
if not product_id:
products = product_db.Product.all()
products_result = [{'product_id': p.key().name()} for p in products]
result = {'products': products_result}
else:
product = product_db.Product.get_by_key_name(product_id)
i... | A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the handler. Note that PUT is not handled beca... | ProductHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductHandler:
"""A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the ... | stack_v2_sparse_classes_36k_train_025384 | 3,664 | no_license | [
{
"docstring": "Responds with information about all products or a specific product. /products/ Responds with a JSON encoded object that contains a list of product IDs. /products/<product> Responds with a JSON encoded object of the product ID and its child client IDs for the given product. Args: product_id. The ... | 3 | stack_v2_sparse_classes_30k_train_011617 | Implement the Python class `ProductHandler` described below.
Class description:
A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so t... | Implement the Python class `ProductHandler` described below.
Class description:
A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so t... | 4fe608d3225f38e765928c137214428cb60c3cd1 | <|skeleton|>
class ProductHandler:
"""A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductHandler:
"""A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the handler. Note... | the_stack_v2_python_sparse | syzygy/dashboard/handler/product.py | TheRyuu/sawbuck | train | 4 |
6d5ed1d2eb359dbfbee3cac333e9e97acd6e0ad6 | [
"self.height = max(availheight, self.CODEBARHEIGHT)\nself.border = border\nif len(subtype) != 1 or subtype not in ascii_uppercase + string_digits:\n raise ValueError(\"Invalid subtype '%s'\" % subtype)\nif not number and len(prefix) > 6 or not prefix.isalnum():\n raise ValueError(\"Invalid prefix '%s'\" % pre... | <|body_start_0|>
self.height = max(availheight, self.CODEBARHEIGHT)
self.border = border
if len(subtype) != 1 or subtype not in ascii_uppercase + string_digits:
raise ValueError("Invalid subtype '%s'" % subtype)
if not number and len(prefix) > 6 or not prefix.isalnum():
... | Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en | BaseLTOLabel | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseLTOLabel:
"""Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en"""
def __... | stack_v2_sparse_classes_36k_train_025385 | 7,377 | permissive | [
{
"docstring": "Initializes an LTO label. prefix : Up to six characters from [A-Z][0-9]. Defaults to \"\". number : Label's number or None. Defaults to None. subtype : LTO subtype string , e.g. \"1\" for LTO1. Defaults to \"1\". border : None, or the width of the label's border. Defaults to None. checksum : Boo... | 2 | stack_v2_sparse_classes_30k_train_013174 | Implement the Python class `BaseLTOLabel` described below.
Class description:
Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=e... | Implement the Python class `BaseLTOLabel` described below.
Class description:
Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=e... | c28aa50e2d6d3451b47e114094a86c03c87d4c50 | <|skeleton|>
class BaseLTOLabel:
"""Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en"""
def __... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseLTOLabel:
"""Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en"""
def __init__(self, ... | the_stack_v2_python_sparse | src/reportlab/graphics/barcode/lto.py | MrBitBucket/reportlab-mirror | train | 64 |
62b278e698dcc63d35fb6278c98efd01e123734b | [
"exit_flag = False\nwhile not exit_flag:\n try:\n first_name, middle_name, last_name = fake.name().split(' ')\n exit_flag = True\n except ValueError:\n continue\nreturn (first_name, middle_name, last_name)",
"result = ''\nfor _ in range(n):\n result += str(random.choice(range(10)))\n... | <|body_start_0|>
exit_flag = False
while not exit_flag:
try:
first_name, middle_name, last_name = fake.name().split(' ')
exit_flag = True
except ValueError:
continue
return (first_name, middle_name, last_name)
<|end_body_0|>... | Класс утилит с доп методами | Util | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
"""Класс утилит с доп методами"""
def gen_name(fake: Faker):
"""Генерация имени пользователя"""
<|body_0|>
def get_number_range(n) -> str:
"""Отдает n рандомных цифр"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
exit_flag = False
... | stack_v2_sparse_classes_36k_train_025386 | 11,458 | permissive | [
{
"docstring": "Генерация имени пользователя",
"name": "gen_name",
"signature": "def gen_name(fake: Faker)"
},
{
"docstring": "Отдает n рандомных цифр",
"name": "get_number_range",
"signature": "def get_number_range(n) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_006100 | Implement the Python class `Util` described below.
Class description:
Класс утилит с доп методами
Method signatures and docstrings:
- def gen_name(fake: Faker): Генерация имени пользователя
- def get_number_range(n) -> str: Отдает n рандомных цифр | Implement the Python class `Util` described below.
Class description:
Класс утилит с доп методами
Method signatures and docstrings:
- def gen_name(fake: Faker): Генерация имени пользователя
- def get_number_range(n) -> str: Отдает n рандомных цифр
<|skeleton|>
class Util:
"""Класс утилит с доп методами"""
d... | 9575c43fa01c261ea1ed573df9b5686b5a6f4211 | <|skeleton|>
class Util:
"""Класс утилит с доп методами"""
def gen_name(fake: Faker):
"""Генерация имени пользователя"""
<|body_0|>
def get_number_range(n) -> str:
"""Отдает n рандомных цифр"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Util:
"""Класс утилит с доп методами"""
def gen_name(fake: Faker):
"""Генерация имени пользователя"""
exit_flag = False
while not exit_flag:
try:
first_name, middle_name, last_name = fake.name().split(' ')
exit_flag = True
ex... | the_stack_v2_python_sparse | Course_II/Python_SQL/pract/pract3/control/control.py | GeorgiyDemo/FA | train | 46 |
137739884ac6cd9409207f4ed45e4d3379e15636 | [
"url = self.ip + '/api/scm/auth/scm/scmPurchaseApplyH/saveOrUpdate.do'\nparams = purchase_apply_save_params\nbody = purchase_apply_body\nr = self.s.post(url=url, params=params, data=body)\nreturn r.json()",
"url = self.ip + '/api/scm/auth/scm/scmPurchaseApplyH/getDetailByOrderNo.do'\nparams = {'orderNo': purchase... | <|body_start_0|>
url = self.ip + '/api/scm/auth/scm/scmPurchaseApplyH/saveOrUpdate.do'
params = purchase_apply_save_params
body = purchase_apply_body
r = self.s.post(url=url, params=params, data=body)
return r.json()
<|end_body_0|>
<|body_start_1|>
url = self.ip + '/api/... | PurchaseApply | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PurchaseApply:
def purchase_apply_save(self):
"""申购单:保存,状态为草稿 :return:"""
<|body_0|>
def get_purchase_apply_detail(self, purchase_apply_order_no):
"""获取申购单物料明细 :return:"""
<|body_1|>
def get_purchase_apply_submit_body(self, purchase_apply_order_no):
... | stack_v2_sparse_classes_36k_train_025387 | 3,732 | no_license | [
{
"docstring": "申购单:保存,状态为草稿 :return:",
"name": "purchase_apply_save",
"signature": "def purchase_apply_save(self)"
},
{
"docstring": "获取申购单物料明细 :return:",
"name": "get_purchase_apply_detail",
"signature": "def get_purchase_apply_detail(self, purchase_apply_order_no)"
},
{
"docst... | 5 | stack_v2_sparse_classes_30k_test_000778 | Implement the Python class `PurchaseApply` described below.
Class description:
Implement the PurchaseApply class.
Method signatures and docstrings:
- def purchase_apply_save(self): 申购单:保存,状态为草稿 :return:
- def get_purchase_apply_detail(self, purchase_apply_order_no): 获取申购单物料明细 :return:
- def get_purchase_apply_submit_... | Implement the Python class `PurchaseApply` described below.
Class description:
Implement the PurchaseApply class.
Method signatures and docstrings:
- def purchase_apply_save(self): 申购单:保存,状态为草稿 :return:
- def get_purchase_apply_detail(self, purchase_apply_order_no): 获取申购单物料明细 :return:
- def get_purchase_apply_submit_... | 26d2ae773a999fd8446e18f9c0719d46402b19aa | <|skeleton|>
class PurchaseApply:
def purchase_apply_save(self):
"""申购单:保存,状态为草稿 :return:"""
<|body_0|>
def get_purchase_apply_detail(self, purchase_apply_order_no):
"""获取申购单物料明细 :return:"""
<|body_1|>
def get_purchase_apply_submit_body(self, purchase_apply_order_no):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PurchaseApply:
def purchase_apply_save(self):
"""申购单:保存,状态为草稿 :return:"""
url = self.ip + '/api/scm/auth/scm/scmPurchaseApplyH/saveOrUpdate.do'
params = purchase_apply_save_params
body = purchase_apply_body
r = self.s.post(url=url, params=params, data=body)
retu... | the_stack_v2_python_sparse | api/purchase_apply_api.py | Leofighting/dimi_api_test | train | 0 | |
b4b73a3eb0780d1918f7538d17cddc4caee4d936 | [
"acl.enforce('event_triggers:get', auth_ctx.ctx())\nLOG.debug('Fetch event trigger [id=%s]', id)\nif fields and 'id' not in fields:\n fields.insert(0, 'id')\nr = rest_utils.create_db_retry_object()\ndb_model = r.call(db_api.get_event_trigger, id, fields=fields)\nif fields:\n return resources.EventTrigger.from... | <|body_start_0|>
acl.enforce('event_triggers:get', auth_ctx.ctx())
LOG.debug('Fetch event trigger [id=%s]', id)
if fields and 'id' not in fields:
fields.insert(0, 'id')
r = rest_utils.create_db_retry_object()
db_model = r.call(db_api.get_event_trigger, id, fields=fiel... | EventTriggersController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTriggersController:
def get(self, id, fields=''):
"""Returns the specified event_trigger."""
<|body_0|>
def post(self, event_trigger):
"""Creates a new event trigger."""
<|body_1|>
def put(self, id, event_trigger):
"""Updates an existing eve... | stack_v2_sparse_classes_36k_train_025388 | 6,476 | permissive | [
{
"docstring": "Returns the specified event_trigger.",
"name": "get",
"signature": "def get(self, id, fields='')"
},
{
"docstring": "Creates a new event trigger.",
"name": "post",
"signature": "def post(self, event_trigger)"
},
{
"docstring": "Updates an existing event trigger. T... | 5 | null | Implement the Python class `EventTriggersController` described below.
Class description:
Implement the EventTriggersController class.
Method signatures and docstrings:
- def get(self, id, fields=''): Returns the specified event_trigger.
- def post(self, event_trigger): Creates a new event trigger.
- def put(self, id,... | Implement the Python class `EventTriggersController` described below.
Class description:
Implement the EventTriggersController class.
Method signatures and docstrings:
- def get(self, id, fields=''): Returns the specified event_trigger.
- def post(self, event_trigger): Creates a new event trigger.
- def put(self, id,... | 7baff017d0cf01d19c44055ad201ca59131b9f94 | <|skeleton|>
class EventTriggersController:
def get(self, id, fields=''):
"""Returns the specified event_trigger."""
<|body_0|>
def post(self, event_trigger):
"""Creates a new event trigger."""
<|body_1|>
def put(self, id, event_trigger):
"""Updates an existing eve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventTriggersController:
def get(self, id, fields=''):
"""Returns the specified event_trigger."""
acl.enforce('event_triggers:get', auth_ctx.ctx())
LOG.debug('Fetch event trigger [id=%s]', id)
if fields and 'id' not in fields:
fields.insert(0, 'id')
r = rest... | the_stack_v2_python_sparse | mistral/api/controllers/v2/event_trigger.py | openstack/mistral | train | 214 | |
c72a8531932e3950463046dd6733c84a0563bbde | [
"url = utils.urljoin(self.base_path, self.id, 'members')\nendpoint_override = self.service.get_endpoint_override()\nresponse = session.post(url, endpoint_filter=self.service, endpoint_override=endpoint_override, json=members, headers={})\njob = OperateMemberJob()\njob._translate_response(response)\nreturn job",
"... | <|body_start_0|>
url = utils.urljoin(self.base_path, self.id, 'members')
endpoint_override = self.service.get_endpoint_override()
response = session.post(url, endpoint_filter=self.service, endpoint_override=endpoint_override, json=members, headers={})
job = OperateMemberJob()
job... | Listener | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Listener:
def add_members(self, session, members):
"""Add backend members :param session: openstack session :param members: list of dicts which contain the server_id and address. server_id is ECS service id, address is ECS server internal IP. [{"server_id": "dbecb618-2259-405f-ab17-9b68c... | stack_v2_sparse_classes_36k_train_025389 | 8,259 | permissive | [
{
"docstring": "Add backend members :param session: openstack session :param members: list of dicts which contain the server_id and address. server_id is ECS service id, address is ECS server internal IP. [{\"server_id\": \"dbecb618-2259-405f-ab17-9b68c4f541b0\", \"address\": \"172.16.0.31\"}] for example. :ret... | 2 | null | Implement the Python class `Listener` described below.
Class description:
Implement the Listener class.
Method signatures and docstrings:
- def add_members(self, session, members): Add backend members :param session: openstack session :param members: list of dicts which contain the server_id and address. server_id is... | Implement the Python class `Listener` described below.
Class description:
Implement the Listener class.
Method signatures and docstrings:
- def add_members(self, session, members): Add backend members :param session: openstack session :param members: list of dicts which contain the server_id and address. server_id is... | 60d75438d71ffb7998f5dc407ffa890cc98d3171 | <|skeleton|>
class Listener:
def add_members(self, session, members):
"""Add backend members :param session: openstack session :param members: list of dicts which contain the server_id and address. server_id is ECS service id, address is ECS server internal IP. [{"server_id": "dbecb618-2259-405f-ab17-9b68c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Listener:
def add_members(self, session, members):
"""Add backend members :param session: openstack session :param members: list of dicts which contain the server_id and address. server_id is ECS service id, address is ECS server internal IP. [{"server_id": "dbecb618-2259-405f-ab17-9b68c4f541b0", "add... | the_stack_v2_python_sparse | openstack/load_balancer/v1/listener.py | huaweicloudsdk/sdk-python | train | 20 | |
df950e94fce7fb25dacd5b2153c85d514654b546 | [
"value = attrs[source]\nif value.upper() not in (QuestionCatalogue.SEEVCAM_SCOPE, QuestionCatalogue.PRIVATE_SCOPE):\n raise serializers.ValidationError('Invalid catalogue scope specified')\nreturn attrs",
"value = attrs[source]\nif QuestionCatalogue.objects.filter(catalogue_name=value).count() > 0:\n raise ... | <|body_start_0|>
value = attrs[source]
if value.upper() not in (QuestionCatalogue.SEEVCAM_SCOPE, QuestionCatalogue.PRIVATE_SCOPE):
raise serializers.ValidationError('Invalid catalogue scope specified')
return attrs
<|end_body_0|>
<|body_start_1|>
value = attrs[source]
... | QuestionCatalogueSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionCatalogueSerializer:
def validate_catalogue_scope(attrs, source):
"""Check that the scope specified is one of the two values allowed"""
<|body_0|>
def validate_catalogue_name(attrs, source):
"""Check that a catalogue with that name already exist"""
<|... | stack_v2_sparse_classes_36k_train_025390 | 1,270 | no_license | [
{
"docstring": "Check that the scope specified is one of the two values allowed",
"name": "validate_catalogue_scope",
"signature": "def validate_catalogue_scope(attrs, source)"
},
{
"docstring": "Check that a catalogue with that name already exist",
"name": "validate_catalogue_name",
"si... | 2 | stack_v2_sparse_classes_30k_train_003511 | Implement the Python class `QuestionCatalogueSerializer` described below.
Class description:
Implement the QuestionCatalogueSerializer class.
Method signatures and docstrings:
- def validate_catalogue_scope(attrs, source): Check that the scope specified is one of the two values allowed
- def validate_catalogue_name(a... | Implement the Python class `QuestionCatalogueSerializer` described below.
Class description:
Implement the QuestionCatalogueSerializer class.
Method signatures and docstrings:
- def validate_catalogue_scope(attrs, source): Check that the scope specified is one of the two values allowed
- def validate_catalogue_name(a... | e060f294fccc49e289dd5fdcd1cc85ab53e8b679 | <|skeleton|>
class QuestionCatalogueSerializer:
def validate_catalogue_scope(attrs, source):
"""Check that the scope specified is one of the two values allowed"""
<|body_0|>
def validate_catalogue_name(attrs, source):
"""Check that a catalogue with that name already exist"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionCatalogueSerializer:
def validate_catalogue_scope(attrs, source):
"""Check that the scope specified is one of the two values allowed"""
value = attrs[source]
if value.upper() not in (QuestionCatalogue.SEEVCAM_SCOPE, QuestionCatalogue.PRIVATE_SCOPE):
raise serializer... | the_stack_v2_python_sparse | seeVcam/questions/serializers.py | giuse88/seevcam | train | 0 | |
7dacb85accedb807b19396bd44da07a6394dcd67 | [
"self.AddObserver('LeftButtonPressEvent', self._left_button_press_event)\nself.parent = parent\nself.highlight_button = self.parent.actions['highlight']\nself.is_eids = is_eids\nself.is_nids = is_nids\nself.representation = representation\nassert is_eids or is_nids, 'is_eids=%r is_nids=%r, must not both be False' %... | <|body_start_0|>
self.AddObserver('LeftButtonPressEvent', self._left_button_press_event)
self.parent = parent
self.highlight_button = self.parent.actions['highlight']
self.is_eids = is_eids
self.is_nids = is_nids
self.representation = representation
assert is_eids... | Highlights nodes & elements | HighlightStyle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighlightStyle:
"""Highlights nodes & elements"""
def __init__(self, parent=None, is_eids=True, is_nids=True, representation='wire', name=None, callback=None):
"""Creates the HighlightStyle instance Parameters ---------- is_eids/is_nids : bool; default=True should elements/nodes be h... | stack_v2_sparse_classes_36k_train_025391 | 6,337 | no_license | [
{
"docstring": "Creates the HighlightStyle instance Parameters ---------- is_eids/is_nids : bool; default=True should elements/nodes be highlighted representation : str; default='wire' allowed = {'wire', 'points', 'surface'} name : str; default=None the name of the actor callback : function fill up a QLineEdit ... | 5 | stack_v2_sparse_classes_30k_train_011596 | Implement the Python class `HighlightStyle` described below.
Class description:
Highlights nodes & elements
Method signatures and docstrings:
- def __init__(self, parent=None, is_eids=True, is_nids=True, representation='wire', name=None, callback=None): Creates the HighlightStyle instance Parameters ---------- is_eid... | Implement the Python class `HighlightStyle` described below.
Class description:
Highlights nodes & elements
Method signatures and docstrings:
- def __init__(self, parent=None, is_eids=True, is_nids=True, representation='wire', name=None, callback=None): Creates the HighlightStyle instance Parameters ---------- is_eid... | d9ffdb4ac845b13bcf6aea96ff5d37cc026c5267 | <|skeleton|>
class HighlightStyle:
"""Highlights nodes & elements"""
def __init__(self, parent=None, is_eids=True, is_nids=True, representation='wire', name=None, callback=None):
"""Creates the HighlightStyle instance Parameters ---------- is_eids/is_nids : bool; default=True should elements/nodes be h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HighlightStyle:
"""Highlights nodes & elements"""
def __init__(self, parent=None, is_eids=True, is_nids=True, representation='wire', name=None, callback=None):
"""Creates the HighlightStyle instance Parameters ---------- is_eids/is_nids : bool; default=True should elements/nodes be highlighted re... | the_stack_v2_python_sparse | pyNastran/gui/styles/highlight_style.py | ratalex/pyNastran | train | 0 |
0efeb5b55cc15394fb1b8155c21eb00b4877974b | [
"multi = a\nres = 1\nwhile k:\n if k & 1 == 1:\n res = res % 1337 * (multi % 1337) % 1337\n multi = multi % 1337 * (multi % 1337) % 1337\n k >>= 1\nreturn res",
"if not b:\n return 1\nn = len(b)\nlast_digit = b.pop()\nleft = self.fast_pow(a, last_digit)\nright = self.fast_pow(self.superPow(a, b... | <|body_start_0|>
multi = a
res = 1
while k:
if k & 1 == 1:
res = res % 1337 * (multi % 1337) % 1337
multi = multi % 1337 * (multi % 1337) % 1337
k >>= 1
return res
<|end_body_0|>
<|body_start_1|>
if not b:
return 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fast_pow(self, a, k):
"""快速幂,以及乘法的模运算"""
<|body_0|>
def superPow(self, a: int, b: List[int]) -> int:
"""数学 math 快速幂 exponentiating by squaring 递归 https://leetcode.cn/problems/super-pow/solution/you-qian-ru-shen-kuai-su-mi-suan-fa-xiang-jie-by-l/"""
... | stack_v2_sparse_classes_36k_train_025392 | 1,339 | no_license | [
{
"docstring": "快速幂,以及乘法的模运算",
"name": "fast_pow",
"signature": "def fast_pow(self, a, k)"
},
{
"docstring": "数学 math 快速幂 exponentiating by squaring 递归 https://leetcode.cn/problems/super-pow/solution/you-qian-ru-shen-kuai-su-mi-suan-fa-xiang-jie-by-l/",
"name": "superPow",
"signature": "... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fast_pow(self, a, k): 快速幂,以及乘法的模运算
- def superPow(self, a: int, b: List[int]) -> int: 数学 math 快速幂 exponentiating by squaring 递归 https://leetcode.cn/problems/super-pow/solutio... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fast_pow(self, a, k): 快速幂,以及乘法的模运算
- def superPow(self, a: int, b: List[int]) -> int: 数学 math 快速幂 exponentiating by squaring 递归 https://leetcode.cn/problems/super-pow/solutio... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution:
def fast_pow(self, a, k):
"""快速幂,以及乘法的模运算"""
<|body_0|>
def superPow(self, a: int, b: List[int]) -> int:
"""数学 math 快速幂 exponentiating by squaring 递归 https://leetcode.cn/problems/super-pow/solution/you-qian-ru-shen-kuai-su-mi-suan-fa-xiang-jie-by-l/"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fast_pow(self, a, k):
"""快速幂,以及乘法的模运算"""
multi = a
res = 1
while k:
if k & 1 == 1:
res = res % 1337 * (multi % 1337) % 1337
multi = multi % 1337 * (multi % 1337) % 1337
k >>= 1
return res
def superPo... | the_stack_v2_python_sparse | Super_Pow_372.py | jay6413682/Leetcode | train | 0 | |
331b488c0e43b372c4ca11e093614ab9ecb0d485 | [
"self.n = nums\nimport random\nself.r = random.Random()",
"c = 0\nr = -1\nfor i, n in enumerate(self.n):\n if n != target:\n continue\n if self.r.randint(0, c) == 0:\n r = i\n c = 1\nreturn r"
] | <|body_start_0|>
self.n = nums
import random
self.r = random.Random()
<|end_body_0|>
<|body_start_1|>
c = 0
r = -1
for i, n in enumerate(self.n):
if n != target:
continue
if self.r.randint(0, c) == 0:
r = i
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.n = nums
import random
self.... | stack_v2_sparse_classes_36k_train_025393 | 645 | no_license | [
{
"docstring": ":type nums: List[int] :type numsSize: int",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type target: int :rtype: int",
"name": "pick",
"signature": "def pick(self, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010765 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type numsSize: int
- def pick(self, target): :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type numsSize: int
- def pick(self, target): :type target: int :rtype: int
<|skeleton|>
class Solution:
def __init__(self, ... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
self.n = nums
import random
self.r = random.Random()
def pick(self, target):
""":type target: int :rtype: int"""
c = 0
r = -1
for i, n in enumerate(self.n):
... | the_stack_v2_python_sparse | py/leetcode/398.py | wfeng1991/learnpy | train | 0 | |
2ae1bf7118a0e407bcfd215da6c9f87518f22f02 | [
"def build_string(root):\n if not root:\n return ['#']\n return [str(root.val)] + build_string(root.left) + build_string(root.right)\nreturn ','.join(build_string(root))",
"def build_tree(values):\n value = values.popleft()\n if value == '#':\n return None\n root = TreeNode(value)\n ... | <|body_start_0|>
def build_string(root):
if not root:
return ['#']
return [str(root.val)] + build_string(root.left) + build_string(root.right)
return ','.join(build_string(root))
<|end_body_0|>
<|body_start_1|>
def build_tree(values):
value = ... | 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_025394 | 1,884 | 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_015084 | 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:... | 086b7c9b3651a0e70c5794f6c264eb975cc90363 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def build_string(root):
if not root:
return ['#']
return [str(root.val)] + build_string(root.left) + build_string(root.right)
return ','.j... | the_stack_v2_python_sparse | serialize_and_deserialize_binary_tree.py | chunweiliu/leetcode2 | train | 4 | |
c27babc0057be0c31ec606289f469f2d26918727 | [
"with new_session() as session:\n for filter_ in filters:\n f = models.Filter_log_group(filter_id=filter_.id, filter_version=filter_.version, log_group_id=log_group_id)\n session.merge(f)\n try:\n session.commit()\n return True\n except IntegrityError as e:\n logging.exce... | <|body_start_0|>
with new_session() as session:
for filter_ in filters:
f = models.Filter_log_group(filter_id=filter_.id, filter_version=filter_.version, log_group_id=log_group_id)
session.merge(f)
try:
session.commit()
retu... | Log_group_filters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log_group_filters:
def add(cls, filters, log_group_id):
"""Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean"""
<|body_0|>
def get(cls, log_group_id):
"""Returns a list of filters ... | stack_v2_sparse_classes_36k_train_025395 | 10,222 | no_license | [
{
"docstring": "Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean",
"name": "add",
"signature": "def add(cls, filters, log_group_id)"
},
{
"docstring": "Returns a list of filters by `log_group_id`. :param log_... | 2 | stack_v2_sparse_classes_30k_train_020169 | Implement the Python class `Log_group_filters` described below.
Class description:
Implement the Log_group_filters class.
Method signatures and docstrings:
- def add(cls, filters, log_group_id): Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :ret... | Implement the Python class `Log_group_filters` described below.
Class description:
Implement the Log_group_filters class.
Method signatures and docstrings:
- def add(cls, filters, log_group_id): Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :ret... | 3f331c7169c90d1fac0d1922b011b56eebbd086a | <|skeleton|>
class Log_group_filters:
def add(cls, filters, log_group_id):
"""Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean"""
<|body_0|>
def get(cls, log_group_id):
"""Returns a list of filters ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Log_group_filters:
def add(cls, filters, log_group_id):
"""Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean"""
with new_session() as session:
for filter_ in filters:
f = models.F... | the_stack_v2_python_sparse | src/tlog/base/log_group.py | thomaserlang/TLog | train | 2 | |
2ef984b3a5210a5b63f2ef9e337335e054edf591 | [
"i = 0\nwhile i <= len(nums):\n if i + nums[i] >= len(nums) - 1:\n return True\n if i == len(nums) - 2 or nums[i] == 0:\n return False\n max = nums[i + 1] + i + 1\n temp = i + 1\n if nums[i] != 0:\n for j in range(1, nums[i] + 1):\n if nums[i + j] + i + j >= max:\n ... | <|body_start_0|>
i = 0
while i <= len(nums):
if i + nums[i] >= len(nums) - 1:
return True
if i == len(nums) - 2 or nums[i] == 0:
return False
max = nums[i + 1] + i + 1
temp = i + 1
if nums[i] != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
"""高端解法 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
while i <= len(nums):
if i + num... | stack_v2_sparse_classes_36k_train_025396 | 1,696 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": "高端解法 :param nums: :return:",
"name": "canJump2",
"signature": "def canJump2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000193 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): 高端解法 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): 高端解法 :param nums: :return:
<|skeleton|>
class Solution:
def canJump(self, nums):
... | beabfd31379f44ffd767fc676912db5022495b53 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
"""高端解法 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
i = 0
while i <= len(nums):
if i + nums[i] >= len(nums) - 1:
return True
if i == len(nums) - 2 or nums[i] == 0:
return False
max = nums[i + 1]... | the_stack_v2_python_sparse | leetCode/top100/055canJump.py | fatezy/Algorithm | train | 1 | |
2728892b7ba6fd6b27ec780f36189d263c7864f1 | [
"ret_val = cls(*args, **kwargs)\nret_val.full_clean()\nret_val.save()\nreturn ret_val",
"try:\n return (cls.objects.get(*args, **kwargs), False)\nexcept cls.DoesNotExist:\n return (cls.create_with_validation(*args, **kwargs), True)"
] | <|body_start_0|>
ret_val = cls(*args, **kwargs)
ret_val.full_clean()
ret_val.save()
return ret_val
<|end_body_0|>
<|body_start_1|>
try:
return (cls.objects.get(*args, **kwargs), False)
except cls.DoesNotExist:
return (cls.create_with_validation(*a... | A Model mixin that provides validation-based factory methods. | ModelFactoryWithValidation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelFactoryWithValidation:
"""A Model mixin that provides validation-based factory methods."""
def create_with_validation(cls, *args, **kwargs):
"""Factory method that creates and validates the model object before it is saved."""
<|body_0|>
def get_or_create_with_valida... | stack_v2_sparse_classes_36k_train_025397 | 13,066 | no_license | [
{
"docstring": "Factory method that creates and validates the model object before it is saved.",
"name": "create_with_validation",
"signature": "def create_with_validation(cls, *args, **kwargs)"
},
{
"docstring": "Factory method that gets or creates-and-validates the model object before it is sa... | 2 | stack_v2_sparse_classes_30k_train_011657 | Implement the Python class `ModelFactoryWithValidation` described below.
Class description:
A Model mixin that provides validation-based factory methods.
Method signatures and docstrings:
- def create_with_validation(cls, *args, **kwargs): Factory method that creates and validates the model object before it is saved.... | Implement the Python class `ModelFactoryWithValidation` described below.
Class description:
A Model mixin that provides validation-based factory methods.
Method signatures and docstrings:
- def create_with_validation(cls, *args, **kwargs): Factory method that creates and validates the model object before it is saved.... | 73fec97eb2850e67e5f57e391641116465424d88 | <|skeleton|>
class ModelFactoryWithValidation:
"""A Model mixin that provides validation-based factory methods."""
def create_with_validation(cls, *args, **kwargs):
"""Factory method that creates and validates the model object before it is saved."""
<|body_0|>
def get_or_create_with_valida... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelFactoryWithValidation:
"""A Model mixin that provides validation-based factory methods."""
def create_with_validation(cls, *args, **kwargs):
"""Factory method that creates and validates the model object before it is saved."""
ret_val = cls(*args, **kwargs)
ret_val.full_clean(... | the_stack_v2_python_sparse | edx/app/edxapp/venvs/edxapp/lib/python2.7/site-packages/edxval/models.py | AlaaSwedan/edx | train | 0 |
44fcf95ca7d56b5aa84685f597220ae6e042903f | [
"try:\n location = Location.objects.get(pk=pk)\n serializer = LocationsSerializer(location, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"get_state = self.request.query_params.get('get_state')\nif get_state:\n all_l... | <|body_start_0|>
try:
location = Location.objects.get(pk=pk)
serializer = LocationsSerializer(location, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end_body_0|>
<|body_start_1... | Locations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Locations:
def retrieve(self, request, pk=None):
"""Handle GET requests for single word Returns: Response -- JSON serialized word instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to words resource Returns: Response -- JSON serialized list of wor... | stack_v2_sparse_classes_36k_train_025398 | 2,029 | no_license | [
{
"docstring": "Handle GET requests for single word Returns: Response -- JSON serialized word instance",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to words resource Returns: Response -- JSON serialized list of words",
"name... | 2 | stack_v2_sparse_classes_30k_train_001884 | Implement the Python class `Locations` described below.
Class description:
Implement the Locations class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single word Returns: Response -- JSON serialized word instance
- def list(self, request): Handle GET requests to w... | Implement the Python class `Locations` described below.
Class description:
Implement the Locations class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single word Returns: Response -- JSON serialized word instance
- def list(self, request): Handle GET requests to w... | 582048dafa7e354fffdc0478ec68088e8bbf42b1 | <|skeleton|>
class Locations:
def retrieve(self, request, pk=None):
"""Handle GET requests for single word Returns: Response -- JSON serialized word instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to words resource Returns: Response -- JSON serialized list of wor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Locations:
def retrieve(self, request, pk=None):
"""Handle GET requests for single word Returns: Response -- JSON serialized word instance"""
try:
location = Location.objects.get(pk=pk)
serializer = LocationsSerializer(location, context={'request': request})
... | the_stack_v2_python_sparse | genieioapp/views/locations.py | cherkesky/GenieIO | train | 1 | |
02787cf21447367a93a11764d58285a29207fdb2 | [
"if self.env['ir.config_parameter'].sudo().get_param('generate_payslip'):\n if self.env['ir.config_parameter'].sudo().get_param('option', 'first') == 'first':\n self.month_first()\n elif self.env['ir.config_parameter'].sudo().get_param('option', 'specific') == 'specific':\n self.specific_date()\... | <|body_start_0|>
if self.env['ir.config_parameter'].sudo().get_param('generate_payslip'):
if self.env['ir.config_parameter'].sudo().get_param('option', 'first') == 'first':
self.month_first()
elif self.env['ir.config_parameter'].sudo().get_param('option', 'specific') == '... | Automate payslip generation 1.Month First 2.Specific Date 3.Month End | HrPayslipRunCron | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HrPayslipRunCron:
"""Automate payslip generation 1.Month First 2.Specific Date 3.Month End"""
def _check(self):
"""Check the options and call the corresponding methods"""
<|body_0|>
def month_first(self):
"""Method for automate month first option"""
<|bod... | stack_v2_sparse_classes_36k_train_025399 | 5,128 | no_license | [
{
"docstring": "Check the options and call the corresponding methods",
"name": "_check",
"signature": "def _check(self)"
},
{
"docstring": "Method for automate month first option",
"name": "month_first",
"signature": "def month_first(self)"
},
{
"docstring": "Method for automate ... | 5 | null | Implement the Python class `HrPayslipRunCron` described below.
Class description:
Automate payslip generation 1.Month First 2.Specific Date 3.Month End
Method signatures and docstrings:
- def _check(self): Check the options and call the corresponding methods
- def month_first(self): Method for automate month first op... | Implement the Python class `HrPayslipRunCron` described below.
Class description:
Automate payslip generation 1.Month First 2.Specific Date 3.Month End
Method signatures and docstrings:
- def _check(self): Check the options and call the corresponding methods
- def month_first(self): Method for automate month first op... | 4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14 | <|skeleton|>
class HrPayslipRunCron:
"""Automate payslip generation 1.Month First 2.Specific Date 3.Month End"""
def _check(self):
"""Check the options and call the corresponding methods"""
<|body_0|>
def month_first(self):
"""Method for automate month first option"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HrPayslipRunCron:
"""Automate payslip generation 1.Month First 2.Specific Date 3.Month End"""
def _check(self):
"""Check the options and call the corresponding methods"""
if self.env['ir.config_parameter'].sudo().get_param('generate_payslip'):
if self.env['ir.config_parameter'... | the_stack_v2_python_sparse | automatic_payroll/models/auto_generate_payslips.py | CybroOdoo/CybroAddons | train | 209 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.