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
80c2eaddcd0ec49f6763834b695024faf6c9aa13
[ "self.create_review_request(summary='Test 1', publish=True)\nself.create_review_request(summary='Test 2', publish=True)\nself.create_review_request(summary='Test 3', publish=True)\nself.client.login(username='grumpy', password='grumpy')\nresponse = self.client.get('/r/')\nself.assertEqual(response.status_code, 200)...
<|body_start_0|> self.create_review_request(summary='Test 1', publish=True) self.create_review_request(summary='Test 2', publish=True) self.create_review_request(summary='Test 3', publish=True) self.client.login(username='grumpy', password='grumpy') response = self.client.get('/r...
Unit tests for the all_review_requests view.
AllReviewRequestViewTests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllReviewRequestViewTests: """Unit tests for the all_review_requests view.""" def test_with_access(self): """Testing all_review_requests view""" <|body_0|> def test_as_anonymous_and_redirect(self): """Testing all_review_requests view as anonymous user with anonym...
stack_v2_sparse_classes_36k_train_002400
49,494
permissive
[ { "docstring": "Testing all_review_requests view", "name": "test_with_access", "signature": "def test_with_access(self)" }, { "docstring": "Testing all_review_requests view as anonymous user with anonymous access disabled", "name": "test_as_anonymous_and_redirect", "signature": "def test...
4
null
Implement the Python class `AllReviewRequestViewTests` described below. Class description: Unit tests for the all_review_requests view. Method signatures and docstrings: - def test_with_access(self): Testing all_review_requests view - def test_as_anonymous_and_redirect(self): Testing all_review_requests view as anony...
Implement the Python class `AllReviewRequestViewTests` described below. Class description: Unit tests for the all_review_requests view. Method signatures and docstrings: - def test_with_access(self): Testing all_review_requests view - def test_as_anonymous_and_redirect(self): Testing all_review_requests view as anony...
563c1e8d4dfd860f372281dc0f380a0809f6ae15
<|skeleton|> class AllReviewRequestViewTests: """Unit tests for the all_review_requests view.""" def test_with_access(self): """Testing all_review_requests view""" <|body_0|> def test_as_anonymous_and_redirect(self): """Testing all_review_requests view as anonymous user with anonym...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllReviewRequestViewTests: """Unit tests for the all_review_requests view.""" def test_with_access(self): """Testing all_review_requests view""" self.create_review_request(summary='Test 1', publish=True) self.create_review_request(summary='Test 2', publish=True) self.creat...
the_stack_v2_python_sparse
reviewboard/datagrids/tests.py
LloydFinch/reviewboard
train
2
dd35b01847f28840fdcbcf459a3066856aa5a064
[ "options = {'shapeOptions': {'color': color.info}}\nkwargs.setdefault('marker', {})\nkwargs.setdefault('circlemarker', {})\nkwargs.setdefault('polyline', {})\nkwargs.setdefault('rectangle', options)\nkwargs.setdefault('circle', options)\nkwargs.setdefault('polygon', options)\nself.m = m\nsuper().__init__(**kwargs)"...
<|body_start_0|> options = {'shapeOptions': {'color': color.info}} kwargs.setdefault('marker', {}) kwargs.setdefault('circlemarker', {}) kwargs.setdefault('polyline', {}) kwargs.setdefault('rectangle', options) kwargs.setdefault('circle', options) kwargs.setdefaul...
DrawControl
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DrawControl: def __init__(self, m: ipl.Map, **kwargs) -> None: """A custom DrawingControl object to handle edition of features. Args: m: the map on which he drawControl is displayed kwargs: any available arguments from a ipyleaflet.DrawingControl""" <|body_0|> def show(self)...
stack_v2_sparse_classes_36k_train_002401
3,000
permissive
[ { "docstring": "A custom DrawingControl object to handle edition of features. Args: m: the map on which he drawControl is displayed kwargs: any available arguments from a ipyleaflet.DrawingControl", "name": "__init__", "signature": "def __init__(self, m: ipl.Map, **kwargs) -> None" }, { "docstri...
5
stack_v2_sparse_classes_30k_train_010132
Implement the Python class `DrawControl` described below. Class description: Implement the DrawControl class. Method signatures and docstrings: - def __init__(self, m: ipl.Map, **kwargs) -> None: A custom DrawingControl object to handle edition of features. Args: m: the map on which he drawControl is displayed kwargs...
Implement the Python class `DrawControl` described below. Class description: Implement the DrawControl class. Method signatures and docstrings: - def __init__(self, m: ipl.Map, **kwargs) -> None: A custom DrawingControl object to handle edition of features. Args: m: the map on which he drawControl is displayed kwargs...
b26c7d698659d5c5a2029d02fc94dcd9daf0df98
<|skeleton|> class DrawControl: def __init__(self, m: ipl.Map, **kwargs) -> None: """A custom DrawingControl object to handle edition of features. Args: m: the map on which he drawControl is displayed kwargs: any available arguments from a ipyleaflet.DrawingControl""" <|body_0|> def show(self)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DrawControl: def __init__(self, m: ipl.Map, **kwargs) -> None: """A custom DrawingControl object to handle edition of features. Args: m: the map on which he drawControl is displayed kwargs: any available arguments from a ipyleaflet.DrawingControl""" options = {'shapeOptions': {'color': color.i...
the_stack_v2_python_sparse
sepal_ui/mapping/draw_control.py
12rambau/sepal_ui
train
17
45e097b058a055f0532f0b050cadb8a66a953407
[ "tool_sheds = []\nfor name, url in trans.app.tool_shed_registry.tool_sheds.items():\n tool_sheds.append(dict(name=name, url=quote(url, '')))\nreturn tool_sheds", "tool_shed_url = params.pop('tool_shed_url')\ncontroller = params.pop('controller')\nif controller is None:\n raise MessageException('Please provi...
<|body_start_0|> tool_sheds = [] for name, url in trans.app.tool_shed_registry.tool_sheds.items(): tool_sheds.append(dict(name=name, url=quote(url, ''))) return tool_sheds <|end_body_0|> <|body_start_1|> tool_shed_url = params.pop('tool_shed_url') controller = params...
RESTful controller for interactions with Toolsheds.
ToolShedController
[ "CC-BY-2.5", "MIT", "CC-BY-3.0", "AFL-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ToolShedController: """RESTful controller for interactions with Toolsheds.""" def index(self, trans, **kwd): """GET /api/tool_shed Interact with the Toolshed registry of this instance.""" <|body_0|> def request(self, trans, **params): """GET /api/tool_shed/reques...
stack_v2_sparse_classes_36k_train_002402
1,840
permissive
[ { "docstring": "GET /api/tool_shed Interact with the Toolshed registry of this instance.", "name": "index", "signature": "def index(self, trans, **kwd)" }, { "docstring": "GET /api/tool_shed/request", "name": "request", "signature": "def request(self, trans, **params)" } ]
2
null
Implement the Python class `ToolShedController` described below. Class description: RESTful controller for interactions with Toolsheds. Method signatures and docstrings: - def index(self, trans, **kwd): GET /api/tool_shed Interact with the Toolshed registry of this instance. - def request(self, trans, **params): GET ...
Implement the Python class `ToolShedController` described below. Class description: RESTful controller for interactions with Toolsheds. Method signatures and docstrings: - def index(self, trans, **kwd): GET /api/tool_shed Interact with the Toolshed registry of this instance. - def request(self, trans, **params): GET ...
b9ae7a16ba0465995e880ae9701b7e87226b9bab
<|skeleton|> class ToolShedController: """RESTful controller for interactions with Toolsheds.""" def index(self, trans, **kwd): """GET /api/tool_shed Interact with the Toolshed registry of this instance.""" <|body_0|> def request(self, trans, **params): """GET /api/tool_shed/reques...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ToolShedController: """RESTful controller for interactions with Toolsheds.""" def index(self, trans, **kwd): """GET /api/tool_shed Interact with the Toolshed registry of this instance.""" tool_sheds = [] for name, url in trans.app.tool_shed_registry.tool_sheds.items(): ...
the_stack_v2_python_sparse
lib/galaxy/webapps/galaxy/api/toolshed.py
galaxyproject/galaxy
train
1,277
24bbd862e6f5aed15cc110a244bfcd359a75c93f
[ "self.__current_state = initial_state\nself.__text = ''\nself.__game_state = game_state", "self.__current_state = self.__current_state.get_next_state(selection)\nself.__text = ''\nreturn self.run_until_next_result()", "self.__text += self.__current_state.text\nif self.__current_state.type == StateTypes.FINAL_ST...
<|body_start_0|> self.__current_state = initial_state self.__text = '' self.__game_state = game_state <|end_body_0|> <|body_start_1|> self.__current_state = self.__current_state.get_next_state(selection) self.__text = '' return self.run_until_next_result() <|end_body_1|>...
StateMachine
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StateMachine: def __init__(self, initial_state, game_state): """:type initial_state: State :type game_state: src.main.Model.gameState.GameState""" <|body_0|> def pick(self, selection): """:type selection: int :rtype: StateMachineResult""" <|body_1|> def ...
stack_v2_sparse_classes_36k_train_002403
7,081
no_license
[ { "docstring": ":type initial_state: State :type game_state: src.main.Model.gameState.GameState", "name": "__init__", "signature": "def __init__(self, initial_state, game_state)" }, { "docstring": ":type selection: int :rtype: StateMachineResult", "name": "pick", "signature": "def pick(s...
4
null
Implement the Python class `StateMachine` described below. Class description: Implement the StateMachine class. Method signatures and docstrings: - def __init__(self, initial_state, game_state): :type initial_state: State :type game_state: src.main.Model.gameState.GameState - def pick(self, selection): :type selectio...
Implement the Python class `StateMachine` described below. Class description: Implement the StateMachine class. Method signatures and docstrings: - def __init__(self, initial_state, game_state): :type initial_state: State :type game_state: src.main.Model.gameState.GameState - def pick(self, selection): :type selectio...
b16ba9786d4a03deef5b87f470302164e8e2b669
<|skeleton|> class StateMachine: def __init__(self, initial_state, game_state): """:type initial_state: State :type game_state: src.main.Model.gameState.GameState""" <|body_0|> def pick(self, selection): """:type selection: int :rtype: StateMachineResult""" <|body_1|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StateMachine: def __init__(self, initial_state, game_state): """:type initial_state: State :type game_state: src.main.Model.gameState.GameState""" self.__current_state = initial_state self.__text = '' self.__game_state = game_state def pick(self, selection): """:ty...
the_stack_v2_python_sparse
src/main/Logic/stateMachine.py
moritztiedje/lionfish
train
0
be1d3bd09743c18c4cd936444994012b2d68197d
[ "self.origin_file = origin_file\nself.new_data_path = new_data_path\nparser = SafeConfigParser()\nparser.read([conf_path])\nsingle_info = parser.get('common', 'single').strip().split(';')\nself.single = []\nfor info in single_info:\n begin_end = info.split('-')\n if len(begin_end) == 2:\n self.single.a...
<|body_start_0|> self.origin_file = origin_file self.new_data_path = new_data_path parser = SafeConfigParser() parser.read([conf_path]) single_info = parser.get('common', 'single').strip().split(';') self.single = [] for info in single_info: begin_end ...
repalce column
ReplaceColumn
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReplaceColumn: """repalce column""" def __init__(self, origin_file, conf_path, new_data_path): """init""" <|body_0|> def read_file(self): """read file to fill content content_bak val_set""" <|body_1|> def shuffle_print(self): """shuffle and p...
stack_v2_sparse_classes_36k_train_002404
3,679
permissive
[ { "docstring": "init", "name": "__init__", "signature": "def __init__(self, origin_file, conf_path, new_data_path)" }, { "docstring": "read file to fill content content_bak val_set", "name": "read_file", "signature": "def read_file(self)" }, { "docstring": "shuffle and print to f...
4
null
Implement the Python class `ReplaceColumn` described below. Class description: repalce column Method signatures and docstrings: - def __init__(self, origin_file, conf_path, new_data_path): init - def read_file(self): read file to fill content content_bak val_set - def shuffle_print(self): shuffle and print to file - ...
Implement the Python class `ReplaceColumn` described below. Class description: repalce column Method signatures and docstrings: - def __init__(self, origin_file, conf_path, new_data_path): init - def read_file(self): read file to fill content content_bak val_set - def shuffle_print(self): shuffle and print to file - ...
b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd
<|skeleton|> class ReplaceColumn: """repalce column""" def __init__(self, origin_file, conf_path, new_data_path): """init""" <|body_0|> def read_file(self): """read file to fill content content_bak val_set""" <|body_1|> def shuffle_print(self): """shuffle and p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReplaceColumn: """repalce column""" def __init__(self, origin_file, conf_path, new_data_path): """init""" self.origin_file = origin_file self.new_data_path = new_data_path parser = SafeConfigParser() parser.read([conf_path]) single_info = parser.get('common...
the_stack_v2_python_sparse
ST_DM/KDD2021-MSTPAC/code/MST-PAC/utils/feature_imp/replace_column.py
sserdoubleh/Research
train
10
07a0a8ff6a0fd768e565a03bf00231dc88aa3c91
[ "int1 = interval('[-8,-6]')\nint2 = interval('(-4,1]')\nint3 = interval('[4,8)')\nint4 = interval('(3,6)')\nself.assertEqual(int1.comma_interval, [-8, -7, -6])\nself.assertEqual(int2.comma_interval, [-3, -2, -1, 0, 1])\nself.assertEqual(int3.comma_interval, [4, 5, 6, 7])\nself.assertEqual(int4.comma_interval, [4, 5...
<|body_start_0|> int1 = interval('[-8,-6]') int2 = interval('(-4,1]') int3 = interval('[4,8)') int4 = interval('(3,6)') self.assertEqual(int1.comma_interval, [-8, -7, -6]) self.assertEqual(int2.comma_interval, [-3, -2, -1, 0, 1]) self.assertEqual(int3.comma_interv...
Test
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test: def test_valid(self): """test for interval function, test the range of integers it represents""" <|body_0|> def test_invalidsample(self): """test for invalid interval input""" <|body_1|> def test_mergeable(self): """test the mergeInterval f...
stack_v2_sparse_classes_36k_train_002405
3,135
no_license
[ { "docstring": "test for interval function, test the range of integers it represents", "name": "test_valid", "signature": "def test_valid(self)" }, { "docstring": "test for invalid interval input", "name": "test_invalidsample", "signature": "def test_invalidsample(self)" }, { "do...
6
stack_v2_sparse_classes_30k_train_005503
Implement the Python class `Test` described below. Class description: Implement the Test class. Method signatures and docstrings: - def test_valid(self): test for interval function, test the range of integers it represents - def test_invalidsample(self): test for invalid interval input - def test_mergeable(self): tes...
Implement the Python class `Test` described below. Class description: Implement the Test class. Method signatures and docstrings: - def test_valid(self): test for interval function, test the range of integers it represents - def test_invalidsample(self): test for invalid interval input - def test_mergeable(self): tes...
33c7a3e579c37ce3096099a350a7c8135b302ea4
<|skeleton|> class Test: def test_valid(self): """test for interval function, test the range of integers it represents""" <|body_0|> def test_invalidsample(self): """test for invalid interval input""" <|body_1|> def test_mergeable(self): """test the mergeInterval f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test: def test_valid(self): """test for interval function, test the range of integers it represents""" int1 = interval('[-8,-6]') int2 = interval('(-4,1]') int3 = interval('[4,8)') int4 = interval('(3,6)') self.assertEqual(int1.comma_interval, [-8, -7, -6]) ...
the_stack_v2_python_sparse
bz866/Interval_assignment/test.py
ds-ga-1007/assignment7
train
0
e2ac8c6d73d64d13a2a867a527fb4b8478e53d7e
[ "i = int(len(nums) > 0)\nfor n in nums:\n if n > nums[i - 1]:\n nums[i] = n\n i += 1\nreturn i", "i, j = (0, 1)\nwhile j < len(nums):\n if nums[i] == nums[j]:\n j += 1\n else:\n i += 1\n nums[i] = nums[j]\n j += 1\nreturn i + 1" ]
<|body_start_0|> i = int(len(nums) > 0) for n in nums: if n > nums[i - 1]: nums[i] = n i += 1 return i <|end_body_0|> <|body_start_1|> i, j = (0, 1) while j < len(nums): if nums[i] == nums[j]: j += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def remove_duplicates(self, nums): """:type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每...
stack_v2_sparse_classes_36k_train_002406
2,169
no_license
[ { "docstring": ":type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每次在前后值不等时,i 后移了一位,直接返回 i 的值即为 有效数组长度", "name": "remov...
2
stack_v2_sparse_classes_30k_test_000716
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def remove_duplicates(self, nums): :type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def remove_duplicates(self, nums): :type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始...
2b7f4a9fefbfd358f8ff31362d60e2007641ca29
<|skeleton|> class Solution: def remove_duplicates(self, nums): """:type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def remove_duplicates(self, nums): """:type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每次在前后值不等时,i 后移了...
the_stack_v2_python_sparse
Week_01/G20190343020166/LeetCode_26_0166.py
algorithm005-class01/algorithm005-class01
train
27
a7bd68f593c7015d2231c31a28a2facd43e1703d
[ "i, p0, p2 = (0, 0, len(nums) - 1)\nwhile i <= p2:\n while nums[i] == 2 and i < p2:\n nums[p2], nums[i] = (nums[i], nums[p2])\n p2 -= 1\n if nums[i] == 0:\n nums[p0], nums[i] = (nums[i], nums[p0])\n p0 += 1\n i += 1", "head = 0\nfor i in range(0, len(nums)):\n if nums[i] ==...
<|body_start_0|> i, p0, p2 = (0, 0, len(nums) - 1) while i <= p2: while nums[i] == 2 and i < p2: nums[p2], nums[i] = (nums[i], nums[p2]) p2 -= 1 if nums[i] == 0: nums[p0], nums[i] = (nums[i], nums[p0]) p0 += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortColors(self, nums: List[int]) -> None: """75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。""" <|body_0|> def sortColors2(self, nums: List[int]) -> None: """75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元...
stack_v2_sparse_classes_36k_train_002407
1,674
no_license
[ { "docstring": "75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。", "name": "sortColors", "signature": "def sortColors(self, nums: List[int]) -> None" }, { "docstring": "75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白...
2
stack_v2_sparse_classes_30k_train_009744
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums: List[int]) -> None: 75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 - def sortColors2(sel...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums: List[int]) -> None: 75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 - def sortColors2(sel...
d74389704de4ce519a22061191b626b7204d4dbc
<|skeleton|> class Solution: def sortColors(self, nums: List[int]) -> None: """75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。""" <|body_0|> def sortColors2(self, nums: List[int]) -> None: """75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def sortColors(self, nums: List[int]) -> None: """75. 颜色分类: 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。""" i, p0, p2 = (0, 0, len(nums) - 1) while i <= p2: while nums[i] == 2 and i < p2: nums[...
the_stack_v2_python_sparse
05_doublepoint/middle_75_sortColors.py
MrLW/algorithm
train
0
14f73d388dce505acb8f30bb623fd6d540791ffe
[ "print('Testing that spatial_correlation returns a float')\nsc_result = spatial_correlation(5, 5, 5, 5, 5, 5, 5, 5, 5, 5)\nself.assertTrue(isinstance(sc_result, float), 'spatial correlation is not a float')", "print('Testing that spatial_correlation returns an array')\nhist_long = [53.195, 51.954, 53.107]\nfloat_...
<|body_start_0|> print('Testing that spatial_correlation returns a float') sc_result = spatial_correlation(5, 5, 5, 5, 5, 5, 5, 5, 5, 5) self.assertTrue(isinstance(sc_result, float), 'spatial correlation is not a float') <|end_body_0|> <|body_start_1|> print('Testing that spatial_correl...
Test cases for "spatial_correlation" function
MyTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyTestCase: """Test cases for "spatial_correlation" function""" def test_spatial_correlation_returns_float(self): """Check that spatial_correlation returns a float if given a float :return: Nothing""" <|body_0|> def test_spatial_correlation_returns_array(self): "...
stack_v2_sparse_classes_36k_train_002408
5,068
no_license
[ { "docstring": "Check that spatial_correlation returns a float if given a float :return: Nothing", "name": "test_spatial_correlation_returns_float", "signature": "def test_spatial_correlation_returns_float(self)" }, { "docstring": "Check that spatial_correlation returns an array if given an arra...
4
stack_v2_sparse_classes_30k_train_020597
Implement the Python class `MyTestCase` described below. Class description: Test cases for "spatial_correlation" function Method signatures and docstrings: - def test_spatial_correlation_returns_float(self): Check that spatial_correlation returns a float if given a float :return: Nothing - def test_spatial_correlatio...
Implement the Python class `MyTestCase` described below. Class description: Test cases for "spatial_correlation" function Method signatures and docstrings: - def test_spatial_correlation_returns_float(self): Check that spatial_correlation returns a float if given a float :return: Nothing - def test_spatial_correlatio...
3944e9783d58422d2d10bbc95f9706e168550034
<|skeleton|> class MyTestCase: """Test cases for "spatial_correlation" function""" def test_spatial_correlation_returns_float(self): """Check that spatial_correlation returns a float if given a float :return: Nothing""" <|body_0|> def test_spatial_correlation_returns_array(self): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyTestCase: """Test cases for "spatial_correlation" function""" def test_spatial_correlation_returns_float(self): """Check that spatial_correlation returns a float if given a float :return: Nothing""" print('Testing that spatial_correlation returns a float') sc_result = spatial_co...
the_stack_v2_python_sparse
ow_calibration/find_besthist/spatial_correlation/spatial_correlation_test.py
gmaze/argodmqc_owc
train
0
2b2fd3c7305379f2d1e963645bbe1b960fe1ff2d
[ "super(Attn, self).__init__()\nself.score_type = score_type\nself.hidden_size = hidden_size\nif score_type == 'general':\n self.attn = nn.Linear(hidden_size, hidden_size)\nelif score_type == 'concat':\n self.attn = nn.Linear(hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_...
<|body_start_0|> super(Attn, self).__init__() self.score_type = score_type self.hidden_size = hidden_size if score_type == 'general': self.attn = nn.Linear(hidden_size, hidden_size) elif score_type == 'concat': self.attn = nn.Linear(hidden_size * 2, hidden...
计算对齐向量,只有general可以使用
Attn
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Attn: """计算对齐向量,只有general可以使用""" def __init__(self, score_type, hidden_size): """Args: score_type: 计算score的方法,'dot', 'general', 'concat' hidden_size: Encoder和Decoder的hidden_size""" <|body_0|> def score(self, decoder_rnn_output, encoder_output): """计算Decoder中yt与En...
stack_v2_sparse_classes_36k_train_002409
12,285
no_license
[ { "docstring": "Args: score_type: 计算score的方法,'dot', 'general', 'concat' hidden_size: Encoder和Decoder的hidden_size", "name": "__init__", "signature": "def __init__(self, score_type, hidden_size)" }, { "docstring": "计算Decoder中yt与Encoder中hs的打分。算出所有得分,再softmax就可以算出对齐向量。 下面均是单个batch Args: decoder_rnn_...
3
stack_v2_sparse_classes_30k_train_017790
Implement the Python class `Attn` described below. Class description: 计算对齐向量,只有general可以使用 Method signatures and docstrings: - def __init__(self, score_type, hidden_size): Args: score_type: 计算score的方法,'dot', 'general', 'concat' hidden_size: Encoder和Decoder的hidden_size - def score(self, decoder_rnn_output, encoder_out...
Implement the Python class `Attn` described below. Class description: 计算对齐向量,只有general可以使用 Method signatures and docstrings: - def __init__(self, score_type, hidden_size): Args: score_type: 计算score的方法,'dot', 'general', 'concat' hidden_size: Encoder和Decoder的hidden_size - def score(self, decoder_rnn_output, encoder_out...
c54079e1b6bb84654ec3e3fc08597ba493f50d5e
<|skeleton|> class Attn: """计算对齐向量,只有general可以使用""" def __init__(self, score_type, hidden_size): """Args: score_type: 计算score的方法,'dot', 'general', 'concat' hidden_size: Encoder和Decoder的hidden_size""" <|body_0|> def score(self, decoder_rnn_output, encoder_output): """计算Decoder中yt与En...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Attn: """计算对齐向量,只有general可以使用""" def __init__(self, score_type, hidden_size): """Args: score_type: 计算score的方法,'dot', 'general', 'concat' hidden_size: Encoder和Decoder的hidden_size""" super(Attn, self).__init__() self.score_type = score_type self.hidden_size = hidden_size ...
the_stack_v2_python_sparse
en-zh-translation/model.py
JeremyKwok666/NLP-Demos
train
0
e0de74640c8a2f55e739fb3e847216fc118d0330
[ "r, c = left_filter.shape\nassert left_filter.shape == right_filter.shape\nself.left_filter = left_filter\nself.right_filter = right_filter\nself.left_filter_dft = cv2.dft(left_filter)\nself.right_filter_dft = cv2.dft(right_filter)\nself.image = np.zeros((r, c), dtype=np.float32)\nself.image = np.zeros((r, c), dtyp...
<|body_start_0|> r, c = left_filter.shape assert left_filter.shape == right_filter.shape self.left_filter = left_filter self.right_filter = right_filter self.left_filter_dft = cv2.dft(left_filter) self.right_filter_dft = cv2.dft(right_filter) self.image = np.zeros...
This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only using OpenCV and is much faster than the ASEF class. For details see the paper: David S. ...
OpenCVFilterEyeLocator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpenCVFilterEyeLocator: """This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only using OpenCV and is much faster than th...
stack_v2_sparse_classes_36k_train_002410
14,116
permissive
[ { "docstring": "@param left_filter: is in the Fourier domain where the left eye corresponds to the real output and the right eye corresponds to the imaginary output", "name": "__init__", "signature": "def __init__(self, left_filter, right_filter, left_rect, right_rect)" }, { "docstring": "@param...
4
stack_v2_sparse_classes_30k_train_007802
Implement the Python class `OpenCVFilterEyeLocator` described below. Class description: This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only ...
Implement the Python class `OpenCVFilterEyeLocator` described below. Class description: This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only ...
caa4e0254f55c5c8f3464807556b9414ea731293
<|skeleton|> class OpenCVFilterEyeLocator: """This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only using OpenCV and is much faster than th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OpenCVFilterEyeLocator: """This class is used for someone only interested in locating the eyes in an image using correlation filters. This class does not include any support for training correlation filters. For training see ASEF. This class is written only using OpenCV and is much faster than the ASEF class....
the_stack_v2_python_sparse
src/pyvision/face/FilterEyeLocator.py
bolme/pyvision
train
47
3105ed6f503b70f2bae10d6d9514d5ab6ff4d960
[ "self._templates = {}\nself.add_path_template(config)\npass", "if 'templates' in config:\n for template in config['templates']:\n self._templates[template['name']] = template['template']\npass", "if template_name in self._templates:\n if 'time_format' in param:\n str = param['time_format'].s...
<|body_start_0|> self._templates = {} self.add_path_template(config) pass <|end_body_0|> <|body_start_1|> if 'templates' in config: for template in config['templates']: self._templates[template['name']] = template['template'] pass <|end_body_1|> <|bo...
generate path with template & runtime variables
PathGenerator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PathGenerator: """generate path with template & runtime variables""" def __init__(self, config): """R""" <|body_0|> def add_path_template(self, config): """R""" <|body_1|> def generate_path(self, template_name, param): """R""" <|body_...
stack_v2_sparse_classes_36k_train_002411
6,040
permissive
[ { "docstring": "R", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "R", "name": "add_path_template", "signature": "def add_path_template(self, config)" }, { "docstring": "R", "name": "generate_path", "signature": "def generate_path(self, t...
3
null
Implement the Python class `PathGenerator` described below. Class description: generate path with template & runtime variables Method signatures and docstrings: - def __init__(self, config): R - def add_path_template(self, config): R - def generate_path(self, template_name, param): R
Implement the Python class `PathGenerator` described below. Class description: generate path with template & runtime variables Method signatures and docstrings: - def __init__(self, config): R - def add_path_template(self, config): R - def generate_path(self, template_name, param): R <|skeleton|> class PathGenerator...
98872470969ab640de1a76d295b93ae155519ecd
<|skeleton|> class PathGenerator: """generate path with template & runtime variables""" def __init__(self, config): """R""" <|body_0|> def add_path_template(self, config): """R""" <|body_1|> def generate_path(self, template_name, param): """R""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PathGenerator: """generate path with template & runtime variables""" def __init__(self, config): """R""" self._templates = {} self.add_path_template(config) pass def add_path_template(self, config): """R""" if 'templates' in config: for tem...
the_stack_v2_python_sparse
core/utils/util.py
frankwhzhang/PaddleRec
train
3
a9beb82e56f0b8ee7a2bf550c126d906789ddf08
[ "self.X_train = None\nself.y_train = None\nself.priors = None\nself.posteriors = None", "self.X_train = X_train\nself.y_train = y_train\nself.priors = myutils.get_priors(y_train)\nself.posteriors = myutils.get_posteriors(X_train, y_train, self.priors)", "y_predicted = []\nfor test in X_test:\n probs = myutil...
<|body_start_0|> self.X_train = None self.y_train = None self.priors = None self.posteriors = None <|end_body_0|> <|body_start_1|> self.X_train = X_train self.y_train = y_train self.priors = myutils.get_priors(y_train) self.posteriors = myutils.get_poster...
Represents a Naive Bayes classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_samples priors(YOU CHOOSE THE MOST APPROPRIATE TYPE): ...
MyNaiveBayesClassifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyNaiveBayesClassifier: """Represents a Naive Bayes classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_samp...
stack_v2_sparse_classes_36k_train_002412
10,235
no_license
[ { "docstring": "Initializer for MyNaiveBayesClassifier.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Fits a Naive Bayes classifier to X_train and y_train. Args: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_...
3
stack_v2_sparse_classes_30k_train_010380
Implement the Python class `MyNaiveBayesClassifier` described below. Class description: Represents a Naive Bayes classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X...
Implement the Python class `MyNaiveBayesClassifier` described below. Class description: Represents a Naive Bayes classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X...
e1c9bd77026dadb993361e79514a295edd5775f3
<|skeleton|> class MyNaiveBayesClassifier: """Represents a Naive Bayes classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_samp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyNaiveBayesClassifier: """Represents a Naive Bayes classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_samples priors(YO...
the_stack_v2_python_sparse
mysklearn/myclassifiers.py
CarterKekoa/SpotifyRecommendationApp
train
1
d37be7fe6b82b7b17c5bd0e911423c2ed07a19d0
[ "query_seller_id = request.args.get('seller_id')\nquery_tags = request.args.get('tags')\nquery_make = request.args.get('make')\nquery_model = request.args.get('model')\nwith db.connection as connection:\n ad_service = AdsService(connection)\n asd_id = ad_service.generation_id(seller_id=query_seller_id)\nads =...
<|body_start_0|> query_seller_id = request.args.get('seller_id') query_tags = request.args.get('tags') query_make = request.args.get('make') query_model = request.args.get('model') with db.connection as connection: ad_service = AdsService(connection) asd_i...
AdsView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdsView: def get(self): """Получение списка объявлений""" <|body_0|> def post(self, user): """Создание нового объявления""" <|body_1|> <|end_skeleton|> <|body_start_0|> query_seller_id = request.args.get('seller_id') query_tags = request.arg...
stack_v2_sparse_classes_36k_train_002413
5,760
no_license
[ { "docstring": "Получение списка объявлений", "name": "get", "signature": "def get(self)" }, { "docstring": "Создание нового объявления", "name": "post", "signature": "def post(self, user)" } ]
2
stack_v2_sparse_classes_30k_train_016779
Implement the Python class `AdsView` described below. Class description: Implement the AdsView class. Method signatures and docstrings: - def get(self): Получение списка объявлений - def post(self, user): Создание нового объявления
Implement the Python class `AdsView` described below. Class description: Implement the AdsView class. Method signatures and docstrings: - def get(self): Получение списка объявлений - def post(self, user): Создание нового объявления <|skeleton|> class AdsView: def get(self): """Получение списка объявлени...
79b0563f654016f7d56d988988ddc4bfdb0f1474
<|skeleton|> class AdsView: def get(self): """Получение списка объявлений""" <|body_0|> def post(self, user): """Создание нового объявления""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdsView: def get(self): """Получение списка объявлений""" query_seller_id = request.args.get('seller_id') query_tags = request.args.get('tags') query_make = request.args.get('make') query_model = request.args.get('model') with db.connection as connection: ...
the_stack_v2_python_sparse
Lesson 13/final v 2.0/src/blueprints/ads.py
Alexey7953/antida-school
train
0
b5bddce0d29beccca91238e0419841b737b54dd1
[ "self.w = w\nself.n = len(w)\nself.s = sum(self.w)\nfor i in range(1, self.n):\n w[i] += w[i - 1]", "seed = randint(1, self.s)\nl, r = (0, self.n - 1)\nwhile l < r:\n mid = (l + r) // 2\n if seed <= self.w[mid]:\n r = mid\n else:\n l = mid + 1\nreturn l" ]
<|body_start_0|> self.w = w self.n = len(w) self.s = sum(self.w) for i in range(1, self.n): w[i] += w[i - 1] <|end_body_0|> <|body_start_1|> seed = randint(1, self.s) l, r = (0, self.n - 1) while l < r: mid = (l + r) // 2 if se...
Solution2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution2: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.w = w self.n = len(w) self.s = sum(self.w) for i in range(1, self....
stack_v2_sparse_classes_36k_train_002414
2,037
no_license
[ { "docstring": ":type w: List[int]", "name": "__init__", "signature": "def __init__(self, w)" }, { "docstring": ":rtype: int", "name": "pickIndex", "signature": "def pickIndex(self)" } ]
2
null
Implement the Python class `Solution2` described below. Class description: Implement the Solution2 class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int
Implement the Python class `Solution2` described below. Class description: Implement the Solution2 class. Method signatures and docstrings: - def __init__(self, w): :type w: List[int] - def pickIndex(self): :rtype: int <|skeleton|> class Solution2: def __init__(self, w): """:type w: List[int]""" ...
340ae58fb65b97aa6c6ab2daa8cbd82d1093deae
<|skeleton|> class Solution2: def __init__(self, w): """:type w: List[int]""" <|body_0|> def pickIndex(self): """:rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution2: def __init__(self, w): """:type w: List[int]""" self.w = w self.n = len(w) self.s = sum(self.w) for i in range(1, self.n): w[i] += w[i - 1] def pickIndex(self): """:rtype: int""" seed = randint(1, self.s) l, r = (0, se...
the_stack_v2_python_sparse
learnpythonthehardway/random-pick-with-weight.py
dgpllc/leetcode-python
train
0
c3ab3343f885921a1f304ed06ae72fc85ccc6777
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn B2xIdentityUserFlow()", "from .identity_provider import IdentityProvider\nfrom .identity_provider_base import IdentityProviderBase\nfrom .identity_user_flow import IdentityUserFlow\nfrom .identity_user_flow_attribute_assignment import ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return B2xIdentityUserFlow() <|end_body_0|> <|body_start_1|> from .identity_provider import IdentityProvider from .identity_provider_base import IdentityProviderBase from .identity_user...
B2xIdentityUserFlow
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class B2xIdentityUserFlow: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> B2xIdentityUserFlow: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob...
stack_v2_sparse_classes_36k_train_002415
5,224
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: B2xIdentityUserFlow", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator...
3
null
Implement the Python class `B2xIdentityUserFlow` described below. Class description: Implement the B2xIdentityUserFlow class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> B2xIdentityUserFlow: Creates a new instance of the appropriate class based on d...
Implement the Python class `B2xIdentityUserFlow` described below. Class description: Implement the B2xIdentityUserFlow class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> B2xIdentityUserFlow: Creates a new instance of the appropriate class based on d...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class B2xIdentityUserFlow: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> B2xIdentityUserFlow: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class B2xIdentityUserFlow: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> B2xIdentityUserFlow: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ...
the_stack_v2_python_sparse
msgraph/generated/models/b2x_identity_user_flow.py
microsoftgraph/msgraph-sdk-python
train
135
34cf7eaf13e5ddd7a3f842239df3205ec206b19b
[ "p_list = list(p)\np[0] = p[1]\np[0]['base_type'] = p[2]\np[0]['properties'] = {}\nif p[0]['base_type'] == 'ENUM':\n p[0]['properties']['values'] = p_list[4]", "p_list = list(p)\np[0] = {}\nif '.' not in p_list:\n p[0]['schema'] = None\nelse:\n p[0]['schema'] = p[3]\np[0]['domain_name'] = p_list[-2]" ]
<|body_start_0|> p_list = list(p) p[0] = p[1] p[0]['base_type'] = p[2] p[0]['properties'] = {} if p[0]['base_type'] == 'ENUM': p[0]['properties']['values'] = p_list[4] <|end_body_0|> <|body_start_1|> p_list = list(p) p[0] = {} if '.' not in p_...
Domain
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Domain: def p_expression_domain_as(self, p: List) -> None: """expr : domain_name id LP pid RP""" <|body_0|> def p_domain_name(self, p: List) -> None: """domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DOT id AS | CREATE DOMAIN id DOT id | CREATE DOMAIN id""" ...
stack_v2_sparse_classes_36k_train_002416
42,571
permissive
[ { "docstring": "expr : domain_name id LP pid RP", "name": "p_expression_domain_as", "signature": "def p_expression_domain_as(self, p: List) -> None" }, { "docstring": "domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DOT id AS | CREATE DOMAIN id DOT id | CREATE DOMAIN id", "name": "p_dom...
2
stack_v2_sparse_classes_30k_train_017854
Implement the Python class `Domain` described below. Class description: Implement the Domain class. Method signatures and docstrings: - def p_expression_domain_as(self, p: List) -> None: expr : domain_name id LP pid RP - def p_domain_name(self, p: List) -> None: domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DO...
Implement the Python class `Domain` described below. Class description: Implement the Domain class. Method signatures and docstrings: - def p_expression_domain_as(self, p: List) -> None: expr : domain_name id LP pid RP - def p_domain_name(self, p: List) -> None: domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DO...
8f69c9c3b58990f0d47dbe868fe4a572d51e2de7
<|skeleton|> class Domain: def p_expression_domain_as(self, p: List) -> None: """expr : domain_name id LP pid RP""" <|body_0|> def p_domain_name(self, p: List) -> None: """domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DOT id AS | CREATE DOMAIN id DOT id | CREATE DOMAIN id""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Domain: def p_expression_domain_as(self, p: List) -> None: """expr : domain_name id LP pid RP""" p_list = list(p) p[0] = p[1] p[0]['base_type'] = p[2] p[0]['properties'] = {} if p[0]['base_type'] == 'ENUM': p[0]['properties']['values'] = p_list[4] ...
the_stack_v2_python_sparse
simple_ddl_parser/dialects/sql.py
bjmc/simple-ddl-parser
train
0
20aed971f3bb7445ad2c9a3e20d95781008e47a3
[ "if 'comm' not in problem_params:\n problem_params['comm'] = None\nessential_keys = ['nvars', 'nu', 'freq', 'comm']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))\n raise ParameterError(msg)\ni...
<|body_start_0|> if 'comm' not in problem_params: problem_params['comm'] = None essential_keys = ['nvars', 'nu', 'freq', 'comm'] for key in essential_keys: if key not in problem_params: msg = 'need %s to instantiate problem, only got %s' % (key, str(proble...
Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus
heat2d_dedalus_forced
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class heat2d_dedalus_forced: """Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus""" def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """Initialization routine Args: problem_params (dict): custom ...
stack_v2_sparse_classes_36k_train_002417
4,280
permissive
[ { "docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class)", "name": "__init__", "signature": "def __init__(self, problem_params, dtype_u=dedalus_field, ...
4
null
Implement the Python class `heat2d_dedalus_forced` described below. Class description: Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus Method signatures and docstrings: - def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): In...
Implement the Python class `heat2d_dedalus_forced` described below. Class description: Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus Method signatures and docstrings: - def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): In...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class heat2d_dedalus_forced: """Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus""" def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """Initialization routine Args: problem_params (dict): custom ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class heat2d_dedalus_forced: """Example implementing the forced 2D heat equation with periodic BC in [0,1], discretized using Dedalus""" def __init__(self, problem_params, dtype_u=dedalus_field, dtype_f=rhs_imex_dedalus_field): """Initialization routine Args: problem_params (dict): custom parameters fo...
the_stack_v2_python_sparse
pySDC/playgrounds/deprecated/Dedalus/HeatEquation_2D_Dedalus_forced.py
Parallel-in-Time/pySDC
train
30
0e33882061183007bbad4171bbf91e2cab303005
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
AgentServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AgentServicer: def start_consensus(self, request, context): """start the admm algorithm on the agent""" <|body_0|> def remote_shutdown(self, request, context): """start the admm algorithm on the agent""" <|body_1|> def set_values(self, request, context):...
stack_v2_sparse_classes_36k_train_002418
5,251
no_license
[ { "docstring": "start the admm algorithm on the agent", "name": "start_consensus", "signature": "def start_consensus(self, request, context)" }, { "docstring": "start the admm algorithm on the agent", "name": "remote_shutdown", "signature": "def remote_shutdown(self, request, context)" ...
6
stack_v2_sparse_classes_30k_train_013442
Implement the Python class `AgentServicer` described below. Class description: Implement the AgentServicer class. Method signatures and docstrings: - def start_consensus(self, request, context): start the admm algorithm on the agent - def remote_shutdown(self, request, context): start the admm algorithm on the agent ...
Implement the Python class `AgentServicer` described below. Class description: Implement the AgentServicer class. Method signatures and docstrings: - def start_consensus(self, request, context): start the admm algorithm on the agent - def remote_shutdown(self, request, context): start the admm algorithm on the agent ...
a83e8709dd12e5965ef4a5b413d056a434dd1245
<|skeleton|> class AgentServicer: def start_consensus(self, request, context): """start the admm algorithm on the agent""" <|body_0|> def remote_shutdown(self, request, context): """start the admm algorithm on the agent""" <|body_1|> def set_values(self, request, context):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AgentServicer: def start_consensus(self, request, context): """start the admm algorithm on the agent""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def remote_shutdown(s...
the_stack_v2_python_sparse
source_NTU_pnp/finite_consensus_pb2_grpc.py
missinglpf/MAS_finite_consenus
train
3
d1b1b95274f6365fc0d09e8e73afac04e4e390fe
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
NamespaceServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NamespaceServiceServicer: """Missing associated documentation comment in .proto file.""" def ReadConfig(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def WriteConfig(self, request, context): """Missing associat...
stack_v2_sparse_classes_36k_train_002419
6,392
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "ReadConfig", "signature": "def ReadConfig(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "WriteConfig", "signature": "def WriteConfig(self, ...
3
stack_v2_sparse_classes_30k_train_010200
Implement the Python class `NamespaceServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def ReadConfig(self, request, context): Missing associated documentation comment in .proto file. - def WriteConfig(self, request, conte...
Implement the Python class `NamespaceServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def ReadConfig(self, request, context): Missing associated documentation comment in .proto file. - def WriteConfig(self, request, conte...
b94598eca5db7dd1746cc6f49c5cd0c76961b9c2
<|skeleton|> class NamespaceServiceServicer: """Missing associated documentation comment in .proto file.""" def ReadConfig(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def WriteConfig(self, request, context): """Missing associat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NamespaceServiceServicer: """Missing associated documentation comment in .proto file.""" def ReadConfig(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implement...
the_stack_v2_python_sparse
authzed/api/v0/namespace_service_pb2_grpc.py
hercules261188/authzed-py
train
0
1169bf240529f94428de44cebaa6591999db49b8
[ "super(StEmb, self).__init__()\nself.col_names = col_names\nself.max_idxs = max_idxs\nself.embedding_size = embedding_size\nself.use_cuda = use_cuda\nself.embeddings = nn.ModuleList([Meta_Embedding(max_idx + 1, self.embedding_size) for max_idx in self.max_idxs.values()])", "concat_embeddings = []\nbatch_size = st...
<|body_start_0|> super(StEmb, self).__init__() self.col_names = col_names self.max_idxs = max_idxs self.embedding_size = embedding_size self.use_cuda = use_cuda self.embeddings = nn.ModuleList([Meta_Embedding(max_idx + 1, self.embedding_size) for max_idx in self.max_idxs....
StEmb
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StEmb: def __init__(self, col_names, max_idxs, embedding_size=4, use_cuda=True): """fnames: feature names max_idxs: array of max_idx of each feature embedding_size: size of embedding dropout: prob for dropout, set None if no dropout use_cuda: bool, True for gpu or False for cpu""" ...
stack_v2_sparse_classes_36k_train_002420
9,497
permissive
[ { "docstring": "fnames: feature names max_idxs: array of max_idx of each feature embedding_size: size of embedding dropout: prob for dropout, set None if no dropout use_cuda: bool, True for gpu or False for cpu", "name": "__init__", "signature": "def __init__(self, col_names, max_idxs, embedding_size=4,...
2
stack_v2_sparse_classes_30k_val_001090
Implement the Python class `StEmb` described below. Class description: Implement the StEmb class. Method signatures and docstrings: - def __init__(self, col_names, max_idxs, embedding_size=4, use_cuda=True): fnames: feature names max_idxs: array of max_idx of each feature embedding_size: size of embedding dropout: pr...
Implement the Python class `StEmb` described below. Class description: Implement the StEmb class. Method signatures and docstrings: - def __init__(self, col_names, max_idxs, embedding_size=4, use_cuda=True): fnames: feature names max_idxs: array of max_idx of each feature embedding_size: size of embedding dropout: pr...
2969ed6c740d04283aa54af4e2c267cb980c96fe
<|skeleton|> class StEmb: def __init__(self, col_names, max_idxs, embedding_size=4, use_cuda=True): """fnames: feature names max_idxs: array of max_idx of each feature embedding_size: size of embedding dropout: prob for dropout, set None if no dropout use_cuda: bool, True for gpu or False for cpu""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StEmb: def __init__(self, col_names, max_idxs, embedding_size=4, use_cuda=True): """fnames: feature names max_idxs: array of max_idx of each feature embedding_size: size of embedding dropout: prob for dropout, set None if no dropout use_cuda: bool, True for gpu or False for cpu""" super(StEmb,...
the_stack_v2_python_sparse
Application/audience expansion/model.py
easezyc/deep-transfer-learning
train
801
894c40fb8a81e17513e1a2ff550dcc933dc8edd0
[ "sonar.database.init()\nsrc_dir = os.path.join(os.path.dirname(__file__), 'files_to_copy/home')\ncopy_tree(src_dir, str(Constants.SONAR_PATH))\nwith open(Path.home().joinpath('.bashrc'), 'r+') as f:\n for line in f:\n if '# added by sonar' in line:\n break\n else:\n f.write(f'source {...
<|body_start_0|> sonar.database.init() src_dir = os.path.join(os.path.dirname(__file__), 'files_to_copy/home') copy_tree(src_dir, str(Constants.SONAR_PATH)) with open(Path.home().joinpath('.bashrc'), 'r+') as f: for line in f: if '# added by sonar' in line: ...
The Init class defines functions to initialize sonar in various ways.
Init
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Init: """The Init class defines functions to initialize sonar in various ways.""" def one_time_setup(_args): """Performs initial setup for sonar. It creates the database, copies files over to the user sonar directory and adds the default boards to the database. Args: _args (object): ...
stack_v2_sparse_classes_36k_train_002421
16,914
permissive
[ { "docstring": "Performs initial setup for sonar. It creates the database, copies files over to the user sonar directory and adds the default boards to the database. Args: _args (object): Unused", "name": "one_time_setup", "signature": "def one_time_setup(_args)" }, { "docstring": "Helper functi...
2
stack_v2_sparse_classes_30k_train_006950
Implement the Python class `Init` described below. Class description: The Init class defines functions to initialize sonar in various ways. Method signatures and docstrings: - def one_time_setup(_args): Performs initial setup for sonar. It creates the database, copies files over to the user sonar directory and adds t...
Implement the Python class `Init` described below. Class description: The Init class defines functions to initialize sonar in various ways. Method signatures and docstrings: - def one_time_setup(_args): Performs initial setup for sonar. It creates the database, copies files over to the user sonar directory and adds t...
99de16dd16d0aa77734584e67263c78a37abef86
<|skeleton|> class Init: """The Init class defines functions to initialize sonar in various ways.""" def one_time_setup(_args): """Performs initial setup for sonar. It creates the database, copies files over to the user sonar directory and adds the default boards to the database. Args: _args (object): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Init: """The Init class defines functions to initialize sonar in various ways.""" def one_time_setup(_args): """Performs initial setup for sonar. It creates the database, copies files over to the user sonar directory and adds the default boards to the database. Args: _args (object): Unused""" ...
the_stack_v2_python_sparse
sonar/api.py
Zyk-Hyphen/sonar
train
0
dee0316cddc6c1c6e01691646718bf8364197fe4
[ "settings_dto = SettingsDTO()\nsettings_dto.mapper_level_advanced = current_app.config['MAPPER_LEVEL_ADVANCED']\nsettings_dto.mapper_level_intermediate = current_app.config['MAPPER_LEVEL_INTERMEDIATE']\nsettings_dto.supported_languages = SettingsService.get_supported_languages()\nreturn settings_dto", "app_langua...
<|body_start_0|> settings_dto = SettingsDTO() settings_dto.mapper_level_advanced = current_app.config['MAPPER_LEVEL_ADVANCED'] settings_dto.mapper_level_intermediate = current_app.config['MAPPER_LEVEL_INTERMEDIATE'] settings_dto.supported_languages = SettingsService.get_supported_languag...
SettingsService
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SettingsService: def get_settings(): """Gets all settings required by the client""" <|body_0|> def get_supported_languages(): """Gets all supported languages from the config""" <|body_1|> <|end_skeleton|> <|body_start_0|> settings_dto = SettingsDTO(...
stack_v2_sparse_classes_36k_train_002422
1,383
permissive
[ { "docstring": "Gets all settings required by the client", "name": "get_settings", "signature": "def get_settings()" }, { "docstring": "Gets all supported languages from the config", "name": "get_supported_languages", "signature": "def get_supported_languages()" } ]
2
stack_v2_sparse_classes_30k_train_001397
Implement the Python class `SettingsService` described below. Class description: Implement the SettingsService class. Method signatures and docstrings: - def get_settings(): Gets all settings required by the client - def get_supported_languages(): Gets all supported languages from the config
Implement the Python class `SettingsService` described below. Class description: Implement the SettingsService class. Method signatures and docstrings: - def get_settings(): Gets all settings required by the client - def get_supported_languages(): Gets all supported languages from the config <|skeleton|> class Setti...
45bf3937c74902226096aee5b49e7abea62df524
<|skeleton|> class SettingsService: def get_settings(): """Gets all settings required by the client""" <|body_0|> def get_supported_languages(): """Gets all supported languages from the config""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SettingsService: def get_settings(): """Gets all settings required by the client""" settings_dto = SettingsDTO() settings_dto.mapper_level_advanced = current_app.config['MAPPER_LEVEL_ADVANCED'] settings_dto.mapper_level_intermediate = current_app.config['MAPPER_LEVEL_INTERMEDIA...
the_stack_v2_python_sparse
backend/services/settings_service.py
hotosm/tasking-manager
train
526
c90fcecec2eff172d8b01235dddd8db5105b0e5b
[ "self.name = name\nself.price = price\nself.object_type = object_type\nself.flight_altitude = flight_altitude\nself.producing_country = producing_country\nself.owner_country = owner_country", "d_formater = {}\nd_formater['Имя'] = self.name\nd_formater['Цена'] = self.price\nd_formater['Тип объекта'] = self.object_...
<|body_start_0|> self.name = name self.price = price self.object_type = object_type self.flight_altitude = flight_altitude self.producing_country = producing_country self.owner_country = owner_country <|end_body_0|> <|body_start_1|> d_formater = {} d_form...
Класс летательный аппарат
AircraftClass
[ "WTFPL" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AircraftClass: """Класс летательный аппарат""" def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country): """Общие поля: название, цена, тип объекта, высота полета, страна производитель, страна владелец""" <|body_0|> def info(self): ...
stack_v2_sparse_classes_36k_train_002423
11,707
permissive
[ { "docstring": "Общие поля: название, цена, тип объекта, высота полета, страна производитель, страна владелец", "name": "__init__", "signature": "def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country)" }, { "docstring": "Метод для вывода информации об объ...
2
null
Implement the Python class `AircraftClass` described below. Class description: Класс летательный аппарат Method signatures and docstrings: - def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country): Общие поля: название, цена, тип объекта, высота полета, страна производитель, ст...
Implement the Python class `AircraftClass` described below. Class description: Класс летательный аппарат Method signatures and docstrings: - def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country): Общие поля: название, цена, тип объекта, высота полета, страна производитель, ст...
9575c43fa01c261ea1ed573df9b5686b5a6f4211
<|skeleton|> class AircraftClass: """Класс летательный аппарат""" def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country): """Общие поля: название, цена, тип объекта, высота полета, страна производитель, страна владелец""" <|body_0|> def info(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AircraftClass: """Класс летательный аппарат""" def __init__(self, name, price, object_type, flight_altitude, producing_country, owner_country): """Общие поля: название, цена, тип объекта, высота полета, страна производитель, страна владелец""" self.name = name self.price = price ...
the_stack_v2_python_sparse
Course_I/Алгоритмы Python/Part2/семинары/control1/airclass_module.py
GeorgiyDemo/FA
train
46
859a6a853023dee734f41a5663018a288f0de3cf
[ "tokens: List[str] = key.split('=')\nif len(tokens) != 2:\n raise Exception(f'Key {key} contains more than one occurrence of =.')\nif tokens[0] != key_type:\n raise Exception(f'Key {key} does not start from {key_type}=.')\nreturn tokens[1]", "second_part: str = cls.remove_prefix(key, key_type)\ntokens: List...
<|body_start_0|> tokens: List[str] = key.split('=') if len(tokens) != 2: raise Exception(f'Key {key} contains more than one occurrence of =.') if tokens[0] != key_type: raise Exception(f'Key {key} does not start from {key_type}=.') return tokens[1] <|end_body_0|> ...
Utilities for working with key strings.
KeyUtil
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeyUtil: """Utilities for working with key strings.""" def remove_prefix(cls, key: str, key_type: str) -> str: """Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that th...
stack_v2_sparse_classes_36k_train_002424
2,138
permissive
[ { "docstring": "Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that the second part does not contain =, but does not verify how many semicolon delimiters it has.", "name": "remove_prefix", ...
2
stack_v2_sparse_classes_30k_train_016152
Implement the Python class `KeyUtil` described below. Class description: Utilities for working with key strings. Method signatures and docstrings: - def remove_prefix(cls, key: str, key_type: str) -> str: Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and ret...
Implement the Python class `KeyUtil` described below. Class description: Utilities for working with key strings. Method signatures and docstrings: - def remove_prefix(cls, key: str, key_type: str) -> str: Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and ret...
40113ddfb68e62d98b880b3c7427db5cc9fbd8cd
<|skeleton|> class KeyUtil: """Utilities for working with key strings.""" def remove_prefix(cls, key: str, key_type: str) -> str: """Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeyUtil: """Utilities for working with key strings.""" def remove_prefix(cls, key: str, key_type: str) -> str: """Parse key string in KeyType=A;B;C format, verify that the first part (KeyType) matches key_type argument, and return the second part (A;B;C). This method verifies that the second part...
the_stack_v2_python_sparse
py/datacentric/storage/key_util.py
datacentricorg/datacentric-py
train
1
d1279ace29b0dafbae6d435c48f2f39d1f7ae30b
[ "self.function = function\nself.f_min = function(function.x)\nself.steps = []\nself.steps.append(self.function.x[:])\nself.dim = self.function.dim", "_s = 0\ncount_steps = 1\nwhile count_steps <= max_step:\n _check = self.update(abs_tol, rel_tol)\n count_steps += 1\n if _check < 1:\n _s += 1\n ...
<|body_start_0|> self.function = function self.f_min = function(function.x) self.steps = [] self.steps.append(self.function.x[:]) self.dim = self.function.dim <|end_body_0|> <|body_start_1|> _s = 0 count_steps = 1 while count_steps <= max_step: ...
GradientDescent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GradientDescent: def __init__(self, function): """function: instance of Function""" <|body_0|> def run(self, abs_tol=1e-05, rel_tol=0.001, step_break=100, max_step=5000): """abs_tol, rel_tol, step_break: stop when _check<1 (_check is what update should return) for st...
stack_v2_sparse_classes_36k_train_002425
1,892
permissive
[ { "docstring": "function: instance of Function", "name": "__init__", "signature": "def __init__(self, function)" }, { "docstring": "abs_tol, rel_tol, step_break: stop when _check<1 (_check is what update should return) for step_break consecutive steps max_step: maximum number of steps", "nam...
2
stack_v2_sparse_classes_30k_train_018248
Implement the Python class `GradientDescent` described below. Class description: Implement the GradientDescent class. Method signatures and docstrings: - def __init__(self, function): function: instance of Function - def run(self, abs_tol=1e-05, rel_tol=0.001, step_break=100, max_step=5000): abs_tol, rel_tol, step_br...
Implement the Python class `GradientDescent` described below. Class description: Implement the GradientDescent class. Method signatures and docstrings: - def __init__(self, function): function: instance of Function - def run(self, abs_tol=1e-05, rel_tol=0.001, step_break=100, max_step=5000): abs_tol, rel_tol, step_br...
e12ea464e7845793c88adfff6da4c8454099c03b
<|skeleton|> class GradientDescent: def __init__(self, function): """function: instance of Function""" <|body_0|> def run(self, abs_tol=1e-05, rel_tol=0.001, step_break=100, max_step=5000): """abs_tol, rel_tol, step_break: stop when _check<1 (_check is what update should return) for st...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GradientDescent: def __init__(self, function): """function: instance of Function""" self.function = function self.f_min = function(function.x) self.steps = [] self.steps.append(self.function.x[:]) self.dim = self.function.dim def run(self, abs_tol=1e-05, re...
the_stack_v2_python_sparse
Optimization/Minimization/Gradient-Descent/python/GD/GradientDescent.py
dkaramit/ASAP
train
2
d0e2934a12eacafa2f2a6bceb6124ec5e2def8be
[ "self.f = open(datafile, 'r')\nself.delimiter = delimiter\nfor i in range(skiprow):\n self.f.readline()\nself.current_line = self.f.readline()\nself.current_day = -1", "matlist = []\nif self.current_line == '':\n return None\nrowtext = np.array([float(k) for k in self.current_line.strip().split(self.delimit...
<|body_start_0|> self.f = open(datafile, 'r') self.delimiter = delimiter for i in range(skiprow): self.f.readline() self.current_line = self.f.readline() self.current_day = -1 <|end_body_0|> <|body_start_1|> matlist = [] if self.current_line == '': ...
Gives batches from a csv file on a per day basis. The first field is assumed to be the day field. Days are assumed to be sorted in ascending order (No out of order days in csv file). For batching data too large to fit into memory. Written for one pass on data!!!
DayBatcher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DayBatcher: """Gives batches from a csv file on a per day basis. The first field is assumed to be the day field. Days are assumed to be sorted in ascending order (No out of order days in csv file). For batching data too large to fit into memory. Written for one pass on data!!!""" def __init_...
stack_v2_sparse_classes_36k_train_002426
36,337
permissive
[ { "docstring": ":param datafile: (str) File to read lines from. :param skiprow: (int) How many lines to ignore at beginning of file (e.g. if file has a header) :param delimiter: (str) The delimiter for the csv file", "name": "__init__", "signature": "def __init__(self, datafile, skiprow=0, delimiter=','...
2
stack_v2_sparse_classes_30k_train_019453
Implement the Python class `DayBatcher` described below. Class description: Gives batches from a csv file on a per day basis. The first field is assumed to be the day field. Days are assumed to be sorted in ascending order (No out of order days in csv file). For batching data too large to fit into memory. Written for ...
Implement the Python class `DayBatcher` described below. Class description: Gives batches from a csv file on a per day basis. The first field is assumed to be the day field. Days are assumed to be sorted in ascending order (No out of order days in csv file). For batching data too large to fit into memory. Written for ...
92c004bc72f1480a4f9b26d304a900cbc8dea48d
<|skeleton|> class DayBatcher: """Gives batches from a csv file on a per day basis. The first field is assumed to be the day field. Days are assumed to be sorted in ascending order (No out of order days in csv file). For batching data too large to fit into memory. Written for one pass on data!!!""" def __init_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DayBatcher: """Gives batches from a csv file on a per day basis. The first field is assumed to be the day field. Days are assumed to be sorted in ascending order (No out of order days in csv file). For batching data too large to fit into memory. Written for one pass on data!!!""" def __init__(self, dataf...
the_stack_v2_python_sparse
safekit/batch.py
Tubbz-alt/safekit
train
0
f997e64a70c4998ef0dffad1d79ef7692936794d
[ "parameters = {}\nfor k, v in obj.parameters.items():\n if isinstance(v, DataArray):\n if len(v.coords) > 0:\n warnings.warn('Coordinates are dropped during serialization.', stacklevel=0)\n dims = v.dims\n v = v.data\n setattr(v, META_ATTR, dict(dims=dims))\n parameters[...
<|body_start_0|> parameters = {} for k, v in obj.parameters.items(): if isinstance(v, DataArray): if len(v.coords) > 0: warnings.warn('Coordinates are dropped during serialization.', stacklevel=0) dims = v.dims v = v.data ...
Serialization class for sympy style math expressions.
MathematicalExpressionConverter
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MathematicalExpressionConverter: """Serialization class for sympy style math expressions.""" def to_yaml_tree(self, obj: MathematicalExpression, tag: str, ctx) -> dict: """Convert to python dict.""" <|body_0|> def from_yaml_tree(self, node: dict, tag: str, ctx): ...
stack_v2_sparse_classes_36k_train_002427
1,609
permissive
[ { "docstring": "Convert to python dict.", "name": "to_yaml_tree", "signature": "def to_yaml_tree(self, obj: MathematicalExpression, tag: str, ctx) -> dict" }, { "docstring": "Construct from tree.", "name": "from_yaml_tree", "signature": "def from_yaml_tree(self, node: dict, tag: str, ctx...
2
null
Implement the Python class `MathematicalExpressionConverter` described below. Class description: Serialization class for sympy style math expressions. Method signatures and docstrings: - def to_yaml_tree(self, obj: MathematicalExpression, tag: str, ctx) -> dict: Convert to python dict. - def from_yaml_tree(self, node...
Implement the Python class `MathematicalExpressionConverter` described below. Class description: Serialization class for sympy style math expressions. Method signatures and docstrings: - def to_yaml_tree(self, obj: MathematicalExpression, tag: str, ctx) -> dict: Convert to python dict. - def from_yaml_tree(self, node...
7bc16a196ee669822f3663f3c7a08f6bbd0c76d5
<|skeleton|> class MathematicalExpressionConverter: """Serialization class for sympy style math expressions.""" def to_yaml_tree(self, obj: MathematicalExpression, tag: str, ctx) -> dict: """Convert to python dict.""" <|body_0|> def from_yaml_tree(self, node: dict, tag: str, ctx): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MathematicalExpressionConverter: """Serialization class for sympy style math expressions.""" def to_yaml_tree(self, obj: MathematicalExpression, tag: str, ctx) -> dict: """Convert to python dict.""" parameters = {} for k, v in obj.parameters.items(): if isinstance(v, D...
the_stack_v2_python_sparse
weldx/tags/core/mathematical_expression.py
BAMWelDX/weldx
train
20
af698f43b85cd87f2f13c10f3871ef86b32154de
[ "if model_format not in [XGBoostModelHandler.ModelFormats.PKL, XGBoostModelHandler.ModelFormats.JSON]:\n raise mlrun.errors.MLRunInvalidArgumentError(f\"Unrecognized model format: '{model_format}'. Please use one of the class members of 'TFKerasModelHandler.ModelFormats'\")\nif model_format == XGBoostModelHandle...
<|body_start_0|> if model_format not in [XGBoostModelHandler.ModelFormats.PKL, XGBoostModelHandler.ModelFormats.JSON]: raise mlrun.errors.MLRunInvalidArgumentError(f"Unrecognized model format: '{model_format}'. Please use one of the class members of 'TFKerasModelHandler.ModelFormats'") if mo...
Class for handling a XGBoost model, enabling loading and saving it during runs.
XGBoostModelHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XGBoostModelHandler: """Class for handling a XGBoost model, enabling loading and saving it during runs.""" def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union[Dict[str, Union[None, str, List[str]]], str]=None, custom_objects_m...
stack_v2_sparse_classes_36k_train_002428
11,617
permissive
[ { "docstring": "Initialize the handler. The model can be set here so it won't require loading. Note you must provide at least one of 'model' and 'model_path'. If a model is not given, the files in the model path will be collected automatically to be ready for loading. :param model: Model to handle or None in ca...
5
null
Implement the Python class `XGBoostModelHandler` described below. Class description: Class for handling a XGBoost model, enabling loading and saving it during runs. Method signatures and docstrings: - def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union...
Implement the Python class `XGBoostModelHandler` described below. Class description: Class for handling a XGBoost model, enabling loading and saving it during runs. Method signatures and docstrings: - def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union...
b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77
<|skeleton|> class XGBoostModelHandler: """Class for handling a XGBoost model, enabling loading and saving it during runs.""" def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union[Dict[str, Union[None, str, List[str]]], str]=None, custom_objects_m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XGBoostModelHandler: """Class for handling a XGBoost model, enabling loading and saving it during runs.""" def __init__(self, model: XGBoostTypes.ModelType=None, model_path: str=None, model_name: str=None, modules_map: Union[Dict[str, Union[None, str, List[str]]], str]=None, custom_objects_map: Union[Dic...
the_stack_v2_python_sparse
mlrun/frameworks/xgboost/model_handler.py
mlrun/mlrun
train
1,093
9195d92fbcaf14c4e970203f0d86e8062dc87da8
[ "super(CompoundForm, self).__init__(*args, **kwargs)\nself.compound = None\nself.chemSpider = ChemSpider(settings.CHEMSPIDER_TOKEN)\nself.fields['labGroup'].queryset = user.labgroup_set.all()\nif user.labgroup_set.all().exists():\n self.fields['labGroup'].empty_label = None", "searchResults = self.chemSpider.s...
<|body_start_0|> super(CompoundForm, self).__init__(*args, **kwargs) self.compound = None self.chemSpider = ChemSpider(settings.CHEMSPIDER_TOKEN) self.fields['labGroup'].queryset = user.labgroup_set.all() if user.labgroup_set.all().exists(): self.fields['labGroup'].em...
A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.
CompoundForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompoundForm: """A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.""" def __init__(self, user, *args, **kwargs): """Overridden version of the init method allo...
stack_v2_sparse_classes_36k_train_002429
9,303
no_license
[ { "docstring": "Overridden version of the init method allows us to place the user's lab groups as a restricted set.", "name": "__init__", "signature": "def __init__(self, user, *args, **kwargs)" }, { "docstring": "Check that the CSID is actually a valid id from chemspider.", "name": "clean_C...
4
stack_v2_sparse_classes_30k_train_016239
Implement the Python class `CompoundForm` described below. Class description: A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide. Method signatures and docstrings: - def __init__(self, user, *ar...
Implement the Python class `CompoundForm` described below. Class description: A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide. Method signatures and docstrings: - def __init__(self, user, *ar...
eae2009eadf87ffd2378233f3e153d385f4654d2
<|skeleton|> class CompoundForm: """A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.""" def __init__(self, user, *args, **kwargs): """Overridden version of the init method allo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompoundForm: """A form for users to add compounds to the compound guide. Forces a check against the chemspider database to ensure no spurious compounds make their way into the compound guide.""" def __init__(self, user, *args, **kwargs): """Overridden version of the init method allows us to plac...
the_stack_v2_python_sparse
DRP/forms/compound/modelforms.py
zhaojhao/DRP
train
0
d371e24d9b9ab89426acb2f2c42d96cbfa19a97a
[ "self._flat_layer_suffix = '_flat'\nself.old_layer = old_layer\nself.new_layer = new_layer\nself.diff_attribs = diff_attribs\nself.focus_attribs = focus_attribs\nself.morph_diff_tagger = DiffTagger(layer_a=old_layer + self._flat_layer_suffix, layer_b=new_layer + self._flat_layer_suffix, output_layer='morph_diff_lay...
<|body_start_0|> self._flat_layer_suffix = '_flat' self.old_layer = old_layer self.new_layer = new_layer self.diff_attribs = diff_attribs self.focus_attribs = focus_attribs self.morph_diff_tagger = DiffTagger(layer_a=old_layer + self._flat_layer_suffix, layer_b=new_layer ...
Finds all differences between two (Vabamorf's) morphological analysis layers, and groups differences in modified spans in a way that both matching and mismatching annotations are shown. Note: output grouped differences only cover modified spans; annotations on non-overlapping spans (missing and extra spans) will be lef...
MorphDiffFinder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MorphDiffFinder: """Finds all differences between two (Vabamorf's) morphological analysis layers, and groups differences in modified spans in a way that both matching and mismatching annotations are shown. Note: output grouped differences only cover modified spans; annotations on non-overlapping ...
stack_v2_sparse_classes_36k_train_002430
35,998
no_license
[ { "docstring": "Initializes MorphDiffFinder. A specification of comparable layers must be provided. :param old_layer: str Name of the old morph_analysis layer. :param new_layer: str Name of the new morph_analysis layer. :param diff_attribs: list List containing morph_analysis attributes which will be used for f...
2
stack_v2_sparse_classes_30k_train_016863
Implement the Python class `MorphDiffFinder` described below. Class description: Finds all differences between two (Vabamorf's) morphological analysis layers, and groups differences in modified spans in a way that both matching and mismatching annotations are shown. Note: output grouped differences only cover modified...
Implement the Python class `MorphDiffFinder` described below. Class description: Finds all differences between two (Vabamorf's) morphological analysis layers, and groups differences in modified spans in a way that both matching and mismatching annotations are shown. Note: output grouped differences only cover modified...
d0b498a08a938b204fc34c3ea5e3ee3eb57bb25d
<|skeleton|> class MorphDiffFinder: """Finds all differences between two (Vabamorf's) morphological analysis layers, and groups differences in modified spans in a way that both matching and mismatching annotations are shown. Note: output grouped differences only cover modified spans; annotations on non-overlapping ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MorphDiffFinder: """Finds all differences between two (Vabamorf's) morphological analysis layers, and groups differences in modified spans in a way that both matching and mismatching annotations are shown. Note: output grouped differences only cover modified spans; annotations on non-overlapping spans (missin...
the_stack_v2_python_sparse
diff_morph_analysis/morph_eval_utils.py
estnltk/estnltk-workflows
train
0
b24c2b30e3327ab3831f87abf15dd7b691b3a8b3
[ "APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant)\npaginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request))\ntry:\n\n def outputFunction(itemObj):\n return itemObj.getDict()\n\n def dbfn(storeConnection):\n return appObj.T...
<|body_start_0|> APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant) paginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request)) try: def outputFunction(itemObj): return itemObj.getDict() ...
Ticket Types
tickettypesInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class tickettypesInfo: """Ticket Types""" def get(self, tenant, tenantName): """Get list of ticket types""" <|body_0|> def post(self, tenant, tenantName): """Create Ticket Type""" <|body_1|> <|end_skeleton|> <|body_start_0|> APIAdminCommon.verifySecur...
stack_v2_sparse_classes_36k_train_002431
12,942
permissive
[ { "docstring": "Get list of ticket types", "name": "get", "signature": "def get(self, tenant, tenantName)" }, { "docstring": "Create Ticket Type", "name": "post", "signature": "def post(self, tenant, tenantName)" } ]
2
null
Implement the Python class `tickettypesInfo` described below. Class description: Ticket Types Method signatures and docstrings: - def get(self, tenant, tenantName): Get list of ticket types - def post(self, tenant, tenantName): Create Ticket Type
Implement the Python class `tickettypesInfo` described below. Class description: Ticket Types Method signatures and docstrings: - def get(self, tenant, tenantName): Get list of ticket types - def post(self, tenant, tenantName): Create Ticket Type <|skeleton|> class tickettypesInfo: """Ticket Types""" def ge...
d3908c46614fb1b638553282cd72ba3634277495
<|skeleton|> class tickettypesInfo: """Ticket Types""" def get(self, tenant, tenantName): """Get list of ticket types""" <|body_0|> def post(self, tenant, tenantName): """Create Ticket Type""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class tickettypesInfo: """Ticket Types""" def get(self, tenant, tenantName): """Get list of ticket types""" APIAdminCommon.verifySecurityOfAdminAPICall(appObj, request, tenant) paginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request))...
the_stack_v2_python_sparse
services/src/APIadmin_Tickets.py
rmetcalf9/saas_user_management_system
train
1
96c47e6eb04a7dde3aabd3f0291711bd4863275e
[ "assert self.normalized_payload is not None\nusername = self.normalized_payload['username']\nuser_id = user_services.get_user_id_from_username(username)\nif user_id is None:\n raise self.InvalidInputException('Invalid username: %s' % username)\nlanguage_code = self.normalized_payload.get('language_code', None)\n...
<|body_start_0|> assert self.normalized_payload is not None username = self.normalized_payload['username'] user_id = user_services.get_user_id_from_username(username) if user_id is None: raise self.InvalidInputException('Invalid username: %s' % username) language_code...
Handles contribution rights of a user on contributor dashboard page.
ContributionRightsHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContributionRightsHandler: """Handles contribution rights of a user on contributor dashboard page.""" def post(self, category: str) -> None: """Manages contributors' roles. Args: category: str. The role's category. Raises: Exception. The language_code cannot be None if the review cat...
stack_v2_sparse_classes_36k_train_002432
32,743
permissive
[ { "docstring": "Manages contributors' roles. Args: category: str. The role's category. Raises: Exception. The language_code cannot be None if the review category is translation. InvalidInputException. User already has rights to review translation. InvalidInputException. User already has rights to review questio...
2
null
Implement the Python class `ContributionRightsHandler` described below. Class description: Handles contribution rights of a user on contributor dashboard page. Method signatures and docstrings: - def post(self, category: str) -> None: Manages contributors' roles. Args: category: str. The role's category. Raises: Exce...
Implement the Python class `ContributionRightsHandler` described below. Class description: Handles contribution rights of a user on contributor dashboard page. Method signatures and docstrings: - def post(self, category: str) -> None: Manages contributors' roles. Args: category: str. The role's category. Raises: Exce...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class ContributionRightsHandler: """Handles contribution rights of a user on contributor dashboard page.""" def post(self, category: str) -> None: """Manages contributors' roles. Args: category: str. The role's category. Raises: Exception. The language_code cannot be None if the review cat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ContributionRightsHandler: """Handles contribution rights of a user on contributor dashboard page.""" def post(self, category: str) -> None: """Manages contributors' roles. Args: category: str. The role's category. Raises: Exception. The language_code cannot be None if the review category is tran...
the_stack_v2_python_sparse
core/controllers/contributor_dashboard_admin.py
oppia/oppia
train
6,172
01b6df14387be33a3b5d3799fe92f2424b671c44
[ "self.arrayOne = [10, 15, 8, 12, 94, 81, 5, 2, 11]\nself.arrayTwo = [10, 8, 5, 15, 2, 12, 11, 94, 81]\nself.output = True\nreturn (self.arrayOne, self.arrayTwo, self.output)", "arrayOne, arrayTwo, output = self.setUp()\noutput_method = sameBSTs(arrayOne, arrayTwo)\nself.assertEqual(output, output_method)" ]
<|body_start_0|> self.arrayOne = [10, 15, 8, 12, 94, 81, 5, 2, 11] self.arrayTwo = [10, 8, 5, 15, 2, 12, 11, 94, 81] self.output = True return (self.arrayOne, self.arrayTwo, self.output) <|end_body_0|> <|body_start_1|> arrayOne, arrayTwo, output = self.setUp() output_met...
Class with unittests for SameBSTs.py
test_SameBSTs
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class test_SameBSTs: """Class with unittests for SameBSTs.py""" def setUp(self): """Sets up input.""" <|body_0|> def test_user_input(self): """Checks if method works properly. Input cannot be empty string.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_002433
952
no_license
[ { "docstring": "Sets up input.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Checks if method works properly. Input cannot be empty string.", "name": "test_user_input", "signature": "def test_user_input(self)" } ]
2
null
Implement the Python class `test_SameBSTs` described below. Class description: Class with unittests for SameBSTs.py Method signatures and docstrings: - def setUp(self): Sets up input. - def test_user_input(self): Checks if method works properly. Input cannot be empty string.
Implement the Python class `test_SameBSTs` described below. Class description: Class with unittests for SameBSTs.py Method signatures and docstrings: - def setUp(self): Sets up input. - def test_user_input(self): Checks if method works properly. Input cannot be empty string. <|skeleton|> class test_SameBSTs: """...
3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f
<|skeleton|> class test_SameBSTs: """Class with unittests for SameBSTs.py""" def setUp(self): """Sets up input.""" <|body_0|> def test_user_input(self): """Checks if method works properly. Input cannot be empty string.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class test_SameBSTs: """Class with unittests for SameBSTs.py""" def setUp(self): """Sets up input.""" self.arrayOne = [10, 15, 8, 12, 94, 81, 5, 2, 11] self.arrayTwo = [10, 8, 5, 15, 2, 12, 11, 94, 81] self.output = True return (self.arrayOne, self.arrayTwo, self.output)...
the_stack_v2_python_sparse
AlgoExpert_algorithms/Hard/SameBSTs/test_SameBSTs.py
JakubKazimierski/PythonPortfolio
train
9
36af8e8c36192d5bed83b30257147efd749d217d
[ "self.session = session\nself._cache = {}\n\n@sqlalchemy.event.listens_for(session, 'after_commit')\n@sqlalchemy.event.listens_for(session, 'after_rollback')\ndef flush_cache(session):\n self._cache = {}", "if userid not in self._cache:\n self._cache[userid] = self.session.query(User).filter_by(userid=useri...
<|body_start_0|> self.session = session self._cache = {} @sqlalchemy.event.listens_for(session, 'after_commit') @sqlalchemy.event.listens_for(session, 'after_rollback') def flush_cache(session): self._cache = {} <|end_body_0|> <|body_start_1|> if userid not ...
A service for retrieving and performing common operations on users.
UserService
[ "MIT", "BSD-2-Clause", "BSD-3-Clause", "BSD-2-Clause-Views" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserService: """A service for retrieving and performing common operations on users.""" def __init__(self, session): """Create a new user service. :param session: the SQLAlchemy session object""" <|body_0|> def fetch(self, userid): """Fetch a user by userid, e.g. ...
stack_v2_sparse_classes_36k_train_002434
4,049
permissive
[ { "docstring": "Create a new user service. :param session: the SQLAlchemy session object", "name": "__init__", "signature": "def __init__(self, session)" }, { "docstring": "Fetch a user by userid, e.g. 'acct:foo@example.com' :returns: a user instance, if found :rtype: h.models.User or None", ...
2
stack_v2_sparse_classes_30k_train_008843
Implement the Python class `UserService` described below. Class description: A service for retrieving and performing common operations on users. Method signatures and docstrings: - def __init__(self, session): Create a new user service. :param session: the SQLAlchemy session object - def fetch(self, userid): Fetch a ...
Implement the Python class `UserService` described below. Class description: A service for retrieving and performing common operations on users. Method signatures and docstrings: - def __init__(self, session): Create a new user service. :param session: the SQLAlchemy session object - def fetch(self, userid): Fetch a ...
fd1decafdce981b681ef3bd59e001b1284498dae
<|skeleton|> class UserService: """A service for retrieving and performing common operations on users.""" def __init__(self, session): """Create a new user service. :param session: the SQLAlchemy session object""" <|body_0|> def fetch(self, userid): """Fetch a user by userid, e.g. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserService: """A service for retrieving and performing common operations on users.""" def __init__(self, session): """Create a new user service. :param session: the SQLAlchemy session object""" self.session = session self._cache = {} @sqlalchemy.event.listens_for(session...
the_stack_v2_python_sparse
h/accounts/services.py
project-star/h
train
1
d675ffb926b6f8f2fb131440c062b5fa10eee2f4
[ "super().__init__()\nself.H = H\nself.W = W\nself.factor = 2 ** len(channel_list)\nfc_size = int(channel_list[0] * H / self.factor * W / self.factor)\nmlp_dim = [z_dim] + hidden_dims + [fc_size]\nself.linear = MLP(mlp_dim)\nchannels = channel_list\nmodules = list()\nfor i in range(1, len(channels)):\n modules.ap...
<|body_start_0|> super().__init__() self.H = H self.W = W self.factor = 2 ** len(channel_list) fc_size = int(channel_list[0] * H / self.factor * W / self.factor) mlp_dim = [z_dim] + hidden_dims + [fc_size] self.linear = MLP(mlp_dim) channels = channel_list...
Convolutional decoder for images datasets. FC architecture followed by upscaling convolutions. Note that last layer uses a 1x1 kernel with no activations. See UpConvBlock and LastConv for details.
ConvDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvDecoder: """Convolutional decoder for images datasets. FC architecture followed by upscaling convolutions. Note that last layer uses a 1x1 kernel with no activations. See UpConvBlock and LastConv for details.""" def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim): ...
stack_v2_sparse_classes_36k_train_002435
10,936
no_license
[ { "docstring": "Init. Args: H(int): Height of the reconstructed data. W(int): Width of the reconstructed data input_channel(int): Number of channels in the reconstructed data. Typically 1 for grayscale and 3 for RGB. channel_list(List[int]): List of channels. Determines the number of UpConvBlock and associated ...
2
stack_v2_sparse_classes_30k_train_005838
Implement the Python class `ConvDecoder` described below. Class description: Convolutional decoder for images datasets. FC architecture followed by upscaling convolutions. Note that last layer uses a 1x1 kernel with no activations. See UpConvBlock and LastConv for details. Method signatures and docstrings: - def __in...
Implement the Python class `ConvDecoder` described below. Class description: Convolutional decoder for images datasets. FC architecture followed by upscaling convolutions. Note that last layer uses a 1x1 kernel with no activations. See UpConvBlock and LastConv for details. Method signatures and docstrings: - def __in...
9027b529eaa4cf0a38f25512141810f92db99639
<|skeleton|> class ConvDecoder: """Convolutional decoder for images datasets. FC architecture followed by upscaling convolutions. Note that last layer uses a 1x1 kernel with no activations. See UpConvBlock and LastConv for details.""" def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConvDecoder: """Convolutional decoder for images datasets. FC architecture followed by upscaling convolutions. Note that last layer uses a 1x1 kernel with no activations. See UpConvBlock and LastConv for details.""" def __init__(self, H, W, input_channel, channel_list, hidden_dims, z_dim): """Ini...
the_stack_v2_python_sparse
grae/models/torch_modules.py
jakerhodes/GRAE
train
0
3de740851487bad7f20045c6376c69e9b3072b0d
[ "try:\n return get_user_model().objects.create_user(**validated_data)\nexcept Exception as e:\n print(e)\n error = {'message': ','.join(e.args) if len(e.args) > 0 else 'Unknown Error'}\n raise serializers.ValidationError(error)", "instance.email = validated_data.get('email', instance.email)\ninstance....
<|body_start_0|> try: return get_user_model().objects.create_user(**validated_data) except Exception as e: print(e) error = {'message': ','.join(e.args) if len(e.args) > 0 else 'Unknown Error'} raise serializers.ValidationError(error) <|end_body_0|> <|bod...
FullUserSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FullUserSerializer: def create(self, validated_data): """Create and return a new user, given the validated data.""" <|body_0|> def update(self, instance, validated_data): """Update and return an existing user object, given the validated data.""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_002436
8,786
no_license
[ { "docstring": "Create and return a new user, given the validated data.", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Update and return an existing user object, given the validated data.", "name": "update", "signature": "def update(self, instance,...
2
stack_v2_sparse_classes_30k_train_008988
Implement the Python class `FullUserSerializer` described below. Class description: Implement the FullUserSerializer class. Method signatures and docstrings: - def create(self, validated_data): Create and return a new user, given the validated data. - def update(self, instance, validated_data): Update and return an e...
Implement the Python class `FullUserSerializer` described below. Class description: Implement the FullUserSerializer class. Method signatures and docstrings: - def create(self, validated_data): Create and return a new user, given the validated data. - def update(self, instance, validated_data): Update and return an e...
f1ae8fdb768710d3e0dea77628fd391a4549dd68
<|skeleton|> class FullUserSerializer: def create(self, validated_data): """Create and return a new user, given the validated data.""" <|body_0|> def update(self, instance, validated_data): """Update and return an existing user object, given the validated data.""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FullUserSerializer: def create(self, validated_data): """Create and return a new user, given the validated data.""" try: return get_user_model().objects.create_user(**validated_data) except Exception as e: print(e) error = {'message': ','.join(e.args...
the_stack_v2_python_sparse
backend/api/serializers.py
Evobolics/battlecode21
train
0
dffb0e7ae85bab72aaf38272a4d921d0686ccbeb
[ "if len(nums) == 1:\n return nums[0]\nans = float('-inf')\nfor i in range(len(nums)):\n for j in range(len(nums) + 1):\n if i >= j:\n continue\n ans = max(ans, sum(nums[i:j]))\nprint(ans)\nreturn ans", "\"\"\"\n Greedy method\n 1. Add element to sums\n 2. Compar...
<|body_start_0|> if len(nums) == 1: return nums[0] ans = float('-inf') for i in range(len(nums)): for j in range(len(nums) + 1): if i >= j: continue ans = max(ans, sum(nums[i:j])) print(ans) return ans <|...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSubArray_TLE(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def maxSubArray(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(nums) == 1: return num...
stack_v2_sparse_classes_36k_train_002437
1,889
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "maxSubArray_TLE", "signature": "def maxSubArray_TLE(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "maxSubArray", "signature": "def maxSubArray(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray_TLE(self, nums): :type nums: List[int] :rtype: int - def maxSubArray(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray_TLE(self, nums): :type nums: List[int] :rtype: int - def maxSubArray(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def maxSubA...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def maxSubArray_TLE(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def maxSubArray(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxSubArray_TLE(self, nums): """:type nums: List[int] :rtype: int""" if len(nums) == 1: return nums[0] ans = float('-inf') for i in range(len(nums)): for j in range(len(nums) + 1): if i >= j: continue ...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00053.Maximum Subarray.py
roger6blog/LeetCode
train
0
22ef2b0ef2fd54e04c079274f902d878a79fc345
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsDeviceStartupHistory()", "from .entity import Entity\nfrom .user_experience_analytics_operating_system_restart_category import UserExperienceAnalyticsOperatingSystemRestartCategory\nfrom .entity import Entity\nfr...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UserExperienceAnalyticsDeviceStartupHistory() <|end_body_0|> <|body_start_1|> from .entity import Entity from .user_experience_analytics_operating_system_restart_category import UserExpe...
The user experience analytics device startup history entity contains device boot performance history details.
UserExperienceAnalyticsDeviceStartupHistory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserExperienceAnalyticsDeviceStartupHistory: """The user experience analytics device startup history entity contains device boot performance history details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsDeviceStartupHistory: "...
stack_v2_sparse_classes_36k_train_002438
8,363
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsDeviceStartupHistory", "name": "create_from_discriminator_value", "signature": "def c...
3
stack_v2_sparse_classes_30k_train_014589
Implement the Python class `UserExperienceAnalyticsDeviceStartupHistory` described below. Class description: The user experience analytics device startup history entity contains device boot performance history details. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseN...
Implement the Python class `UserExperienceAnalyticsDeviceStartupHistory` described below. Class description: The user experience analytics device startup history entity contains device boot performance history details. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseN...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UserExperienceAnalyticsDeviceStartupHistory: """The user experience analytics device startup history entity contains device boot performance history details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsDeviceStartupHistory: "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserExperienceAnalyticsDeviceStartupHistory: """The user experience analytics device startup history entity contains device boot performance history details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsDeviceStartupHistory: """Creates a n...
the_stack_v2_python_sparse
msgraph/generated/models/user_experience_analytics_device_startup_history.py
microsoftgraph/msgraph-sdk-python
train
135
d06726a20cb5bea540755b31d49512dfcff6be58
[ "result = ''\ni = 0\nwhile i < len(number):\n count = 0\n last = number[i]\n while i < len(number) and number[i] == last:\n i += 1\n count += 1\n result += str(count) + last\nreturn result", "number = '1'\nfor i in range(n - 1):\n number = self.next(number)\nreturn number" ]
<|body_start_0|> result = '' i = 0 while i < len(number): count = 0 last = number[i] while i < len(number) and number[i] == last: i += 1 count += 1 result += str(count) + last return result <|end_body_0|> <|...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def next(self, number): """>>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'""" <|body_0|> def countAndSay(self, n): """:type n: int :rtype: str >>> s = Solution()...
stack_v2_sparse_classes_36k_train_002439
959
no_license
[ { "docstring": ">>> s = Solution() >>> s.next(\"1\") '11' >>> s.next(\"11\") '21' >>> s.next(\"21\") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'", "name": "next", "signature": "def next(self, number)" }, { "docstring": ":type n: int :rtype: str >>> s = Solution() >>> s.count...
2
stack_v2_sparse_classes_30k_test_000294
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def next(self, number): >>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211' - def coun...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def next(self, number): >>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211' - def coun...
3b13a02f9c8273f9794a57b948d2655792707f37
<|skeleton|> class Solution: def next(self, number): """>>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'""" <|body_0|> def countAndSay(self, n): """:type n: int :rtype: str >>> s = Solution()...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def next(self, number): """>>> s = Solution() >>> s.next("1") '11' >>> s.next("11") '21' >>> s.next("21") '1211' >>> s.next('1211') '111221' >>> s.next('111221') '312211'""" result = '' i = 0 while i < len(number): count = 0 last = number[i] ...
the_stack_v2_python_sparse
count_and_say.py
gsy/leetcode
train
1
98f3498b4190f094fde9bbae1169915961817cfb
[ "if not arg:\n self.push('501 Syntax: HELO hostname')\n return\nself.push('250-PyBitmessage %s' % softwareVersion)\nself.push('250 AUTH PLAIN')", "if not arg or arg[0:5] not in ['PLAIN']:\n self.push('501 Syntax: AUTH PLAIN')\n return\nauthstring = arg[6:]\ntry:\n decoded = base64.b64decode(authstr...
<|body_start_0|> if not arg: self.push('501 Syntax: HELO hostname') return self.push('250-PyBitmessage %s' % softwareVersion) self.push('250 AUTH PLAIN') <|end_body_0|> <|body_start_1|> if not arg or arg[0:5] not in ['PLAIN']: self.push('501 Syntax: A...
Asyncore channel for SMTP protocol (server)
smtpServerChannel
[ "HPND", "MIT", "BSD-2-Clause-Views", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class smtpServerChannel: """Asyncore channel for SMTP protocol (server)""" def smtp_EHLO(self, arg): """Process an EHLO""" <|body_0|> def smtp_AUTH(self, arg): """Process AUTH""" <|body_1|> def smtp_DATA(self, arg): """Process DATA""" <|bod...
stack_v2_sparse_classes_36k_train_002440
7,298
permissive
[ { "docstring": "Process an EHLO", "name": "smtp_EHLO", "signature": "def smtp_EHLO(self, arg)" }, { "docstring": "Process AUTH", "name": "smtp_AUTH", "signature": "def smtp_AUTH(self, arg)" }, { "docstring": "Process DATA", "name": "smtp_DATA", "signature": "def smtp_DATA...
3
stack_v2_sparse_classes_30k_test_001149
Implement the Python class `smtpServerChannel` described below. Class description: Asyncore channel for SMTP protocol (server) Method signatures and docstrings: - def smtp_EHLO(self, arg): Process an EHLO - def smtp_AUTH(self, arg): Process AUTH - def smtp_DATA(self, arg): Process DATA
Implement the Python class `smtpServerChannel` described below. Class description: Asyncore channel for SMTP protocol (server) Method signatures and docstrings: - def smtp_EHLO(self, arg): Process an EHLO - def smtp_AUTH(self, arg): Process AUTH - def smtp_DATA(self, arg): Process DATA <|skeleton|> class smtpServerC...
035fac1fc5e7900146230055627f62a23e7f0686
<|skeleton|> class smtpServerChannel: """Asyncore channel for SMTP protocol (server)""" def smtp_EHLO(self, arg): """Process an EHLO""" <|body_0|> def smtp_AUTH(self, arg): """Process AUTH""" <|body_1|> def smtp_DATA(self, arg): """Process DATA""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class smtpServerChannel: """Asyncore channel for SMTP protocol (server)""" def smtp_EHLO(self, arg): """Process an EHLO""" if not arg: self.push('501 Syntax: HELO hostname') return self.push('250-PyBitmessage %s' % softwareVersion) self.push('250 AUTH PLA...
the_stack_v2_python_sparse
src/class_smtpServer.py
PeterSurda/PyBitmessage
train
2
76cc24bd734fc2eb7c83d4145368cabbf06d324e
[ "queryset = Group.objects.filter(master=request.user)\nserializer = GroupSerializer(queryset, many=True)\nreturn Response(serializer.data)", "data = request.data\nnew_group = Group.objects.create(master=request.user, name=data['name'], img=data['img'])\nnew_group.save()\nfor member_id in data['members']:\n try...
<|body_start_0|> queryset = Group.objects.filter(master=request.user) serializer = GroupSerializer(queryset, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> data = request.data new_group = Group.objects.create(master=request.user, name=data['name'], i...
GroupViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupViewSet: def list(self, request): """## 그룹주가 만든 그룹 목록 확인하기 ### 토큰 받아서 그룹주 식별함""" <|body_0|> def create(self, request): """## 그룹 생성하기 ### 토큰 받아서 그룹 주인을 정하고, 친구 목록 중에서 그룹 멤버로 데려올 수 있음.""" <|body_1|> def retrieve(self, request, pk=None): """## ...
stack_v2_sparse_classes_36k_train_002441
8,398
no_license
[ { "docstring": "## 그룹주가 만든 그룹 목록 확인하기 ### 토큰 받아서 그룹주 식별함", "name": "list", "signature": "def list(self, request)" }, { "docstring": "## 그룹 생성하기 ### 토큰 받아서 그룹 주인을 정하고, 친구 목록 중에서 그룹 멤버로 데려올 수 있음.", "name": "create", "signature": "def create(self, request)" }, { "docstring": "## 그룹 ...
5
stack_v2_sparse_classes_30k_train_004963
Implement the Python class `GroupViewSet` described below. Class description: Implement the GroupViewSet class. Method signatures and docstrings: - def list(self, request): ## 그룹주가 만든 그룹 목록 확인하기 ### 토큰 받아서 그룹주 식별함 - def create(self, request): ## 그룹 생성하기 ### 토큰 받아서 그룹 주인을 정하고, 친구 목록 중에서 그룹 멤버로 데려올 수 있음. - def retrieve...
Implement the Python class `GroupViewSet` described below. Class description: Implement the GroupViewSet class. Method signatures and docstrings: - def list(self, request): ## 그룹주가 만든 그룹 목록 확인하기 ### 토큰 받아서 그룹주 식별함 - def create(self, request): ## 그룹 생성하기 ### 토큰 받아서 그룹 주인을 정하고, 친구 목록 중에서 그룹 멤버로 데려올 수 있음. - def retrieve...
41a1bb3a23fed99b8816519ebf529fa029362180
<|skeleton|> class GroupViewSet: def list(self, request): """## 그룹주가 만든 그룹 목록 확인하기 ### 토큰 받아서 그룹주 식별함""" <|body_0|> def create(self, request): """## 그룹 생성하기 ### 토큰 받아서 그룹 주인을 정하고, 친구 목록 중에서 그룹 멤버로 데려올 수 있음.""" <|body_1|> def retrieve(self, request, pk=None): """## ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupViewSet: def list(self, request): """## 그룹주가 만든 그룹 목록 확인하기 ### 토큰 받아서 그룹주 식별함""" queryset = Group.objects.filter(master=request.user) serializer = GroupSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): """## 그룹 생성하기 ##...
the_stack_v2_python_sparse
backend/group/views.py
applevalley/YOGOMOGO
train
0
2905a2635964abbc53d3bb28889666d187455915
[ "super().__init__()\nself.enc_img_attn = enc_img_attn\nif enc_img_attn == 'flat':\n self.multimodal_attn = FlatMMCrossAttentionSublayer(model_dim, n_heads, dropout, attn_dropout, pre_norm)\nelse:\n self.self_attn = SelfAttentionSublayer(model_dim, n_heads, dropout, attn_dropout, pre_norm)\nself.feed_forward =...
<|body_start_0|> super().__init__() self.enc_img_attn = enc_img_attn if enc_img_attn == 'flat': self.multimodal_attn = FlatMMCrossAttentionSublayer(model_dim, n_heads, dropout, attn_dropout, pre_norm) else: self.self_attn = SelfAttentionSublayer(model_dim, n_heads...
TFEncoderBlock
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TFEncoderBlock: def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): """Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model di...
stack_v2_sparse_classes_36k_train_002442
6,612
permissive
[ { "docstring": "Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model dimensions. :param ff_dim: The feed forward network dimensions. :param n_heads: The number of attention heads. :param ff_activ: The feed forward network activa...
2
null
Implement the Python class `TFEncoderBlock` described below. Class description: Implement the TFEncoderBlock class. Method signatures and docstrings: - def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): Creates a TFEncoderBlock, consisting...
Implement the Python class `TFEncoderBlock` described below. Class description: Implement the TFEncoderBlock class. Method signatures and docstrings: - def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): Creates a TFEncoderBlock, consisting...
6250b33dc518b3195da4fc9cc8d32ba7ada958c0
<|skeleton|> class TFEncoderBlock: def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): """Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model di...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TFEncoderBlock: def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): """Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model dimensions. :par...
the_stack_v2_python_sparse
pysimt/layers/encoders/transformers.py
welvin21/pysimt
train
0
c56ac94690fbec2ea84a0b954e0c54627a0dcb52
[ "tmp_spc = self._left_image.new_species(name='peak')\nif self._cineb_coords is not None:\n assert self._cineb_coords is not None and self._cineb_coords.e and (self._cineb_coords.g is not None)\n tmp_spc.coordinates = self._cineb_coords\n tmp_spc.energy = self._cineb_coords.e\n tmp_spc.gradient = self._c...
<|body_start_0|> tmp_spc = self._left_image.new_species(name='peak') if self._cineb_coords is not None: assert self._cineb_coords is not None and self._cineb_coords.e and (self._cineb_coords.g is not None) tmp_spc.coordinates = self._cineb_coords tmp_spc.energy = self...
Image-pair used for Dewar-Healy-Stewart (DHS) method to find transition states. In this method, only one side is modified in a step, so functions to work with only one side is present here
DHSImagePair
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DHSImagePair: """Image-pair used for Dewar-Healy-Stewart (DHS) method to find transition states. In this method, only one side is modified in a step, so functions to work with only one side is present here""" def ts_guess(self) -> Optional['Species']: """In DHS method, the images can...
stack_v2_sparse_classes_36k_train_002443
26,310
permissive
[ { "docstring": "In DHS method, the images can only rise in energy; therefore, the highest energy image is the ts_guess. If CI-NEB is run, then that result is returned instead", "name": "ts_guess", "signature": "def ts_guess(self) -> Optional['Species']" }, { "docstring": "For external usage, sup...
5
stack_v2_sparse_classes_30k_train_011523
Implement the Python class `DHSImagePair` described below. Class description: Image-pair used for Dewar-Healy-Stewart (DHS) method to find transition states. In this method, only one side is modified in a step, so functions to work with only one side is present here Method signatures and docstrings: - def ts_guess(se...
Implement the Python class `DHSImagePair` described below. Class description: Image-pair used for Dewar-Healy-Stewart (DHS) method to find transition states. In this method, only one side is modified in a step, so functions to work with only one side is present here Method signatures and docstrings: - def ts_guess(se...
4d6667592f083dfcf38de6b75c4222c0a0e7b60b
<|skeleton|> class DHSImagePair: """Image-pair used for Dewar-Healy-Stewart (DHS) method to find transition states. In this method, only one side is modified in a step, so functions to work with only one side is present here""" def ts_guess(self) -> Optional['Species']: """In DHS method, the images can...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DHSImagePair: """Image-pair used for Dewar-Healy-Stewart (DHS) method to find transition states. In this method, only one side is modified in a step, so functions to work with only one side is present here""" def ts_guess(self) -> Optional['Species']: """In DHS method, the images can only rise in...
the_stack_v2_python_sparse
autode/bracket/dhs.py
duartegroup/autodE
train
132
60392b959b52d3e8e49f8e465d1a3644d085de2c
[ "with open(path, 'r') as stream:\n lines = []\n for line in stream:\n if line.startswith(self.separator):\n yield self._parse(''.join(lines))\n lines = []\n else:\n lines.append(line)", "with open(path, 'r') as stream:\n for line in stream:\n yield se...
<|body_start_0|> with open(path, 'r') as stream: lines = [] for line in stream: if line.startswith(self.separator): yield self._parse(''.join(lines)) lines = [] else: lines.append(line) <|end_body...
Parser reads trace log files generated by the Fluidinfo API service.
TraceLogParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TraceLogParser: """Parser reads trace log files generated by the Fluidinfo API service.""" def parseOldFormat(self, path): """Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatib...
stack_v2_sparse_classes_36k_train_002444
10,436
permissive
[ { "docstring": "Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatibility. @param path: The path to a trace log file.", "name": "parseOldFormat", "signature": "def parseOldFormat(self, path)" }, ...
3
stack_v2_sparse_classes_30k_train_003970
Implement the Python class `TraceLogParser` described below. Class description: Parser reads trace log files generated by the Fluidinfo API service. Method signatures and docstrings: - def parseOldFormat(self, path): Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for eac...
Implement the Python class `TraceLogParser` described below. Class description: Parser reads trace log files generated by the Fluidinfo API service. Method signatures and docstrings: - def parseOldFormat(self, path): Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for eac...
b5a8c8349f3eaf3364cc4efba4736c3e33b30d96
<|skeleton|> class TraceLogParser: """Parser reads trace log files generated by the Fluidinfo API service.""" def parseOldFormat(self, path): """Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatib...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TraceLogParser: """Parser reads trace log files generated by the Fluidinfo API service.""" def parseOldFormat(self, path): """Generator that loads L{TraceLog} instances from an old log file. Old logs used multiple lines for each L{TraceLog}. This method is kept for backwards compatibility. @param...
the_stack_v2_python_sparse
fluiddb/scripts/logs.py
fluidinfo/fluiddb
train
3
9081a6e1813f9f7726cded26db81dd0d4067d2b6
[ "page = 'address'\nuser = request.user\naddress = Address.objects.get_default_address(user)\nreturn render(request, 'user_center_site.html', {'page': page, 'address': address})", "receiver = request.POST.get('receiver')\naddr = request.POST.get('addr')\nzipcode = request.POST.get('zipcode')\nphone = request.POST....
<|body_start_0|> page = 'address' user = request.user address = Address.objects.get_default_address(user) return render(request, 'user_center_site.html', {'page': page, 'address': address}) <|end_body_0|> <|body_start_1|> receiver = request.POST.get('receiver') addr = re...
UserAddressView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserAddressView: def get(self, request): """显示个人地址""" <|body_0|> def post(self, request): """地址的添加""" <|body_1|> <|end_skeleton|> <|body_start_0|> page = 'address' user = request.user address = Address.objects.get_default_address(use...
stack_v2_sparse_classes_36k_train_002445
8,760
no_license
[ { "docstring": "显示个人地址", "name": "get", "signature": "def get(self, request)" }, { "docstring": "地址的添加", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_009132
Implement the Python class `UserAddressView` described below. Class description: Implement the UserAddressView class. Method signatures and docstrings: - def get(self, request): 显示个人地址 - def post(self, request): 地址的添加
Implement the Python class `UserAddressView` described below. Class description: Implement the UserAddressView class. Method signatures and docstrings: - def get(self, request): 显示个人地址 - def post(self, request): 地址的添加 <|skeleton|> class UserAddressView: def get(self, request): """显示个人地址""" <|bod...
f1de495959e03f8b543fc1642b1332e370f1cf28
<|skeleton|> class UserAddressView: def get(self, request): """显示个人地址""" <|body_0|> def post(self, request): """地址的添加""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserAddressView: def get(self, request): """显示个人地址""" page = 'address' user = request.user address = Address.objects.get_default_address(user) return render(request, 'user_center_site.html', {'page': page, 'address': address}) def post(self, request): """地址...
the_stack_v2_python_sparse
apps/user/views.py
Icemelon99/test_project_dailyfresh
train
4
cf9a351466959671c79861fa5df16d55d565b568
[ "if model._meta.app_label == 'location' or model._meta.app_label == 'manual_override' or model._meta.app_label == 'notification' or (model._meta.app_label == 'report') or (model._meta.app_label == 'search') or (model._meta.app_label == 'stream') or (model._meta.app_label == 'users') or (model._meta.app_label == 'ya...
<|body_start_0|> if model._meta.app_label == 'location' or model._meta.app_label == 'manual_override' or model._meta.app_label == 'notification' or (model._meta.app_label == 'report') or (model._meta.app_label == 'search') or (model._meta.app_label == 'stream') or (model._meta.app_label == 'users') or (model._m...
Router for access to API DB
APIRouter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APIRouter: """Router for access to API DB""" def db_for_read(self, model, **hints): """API models to yte_1_cl_test_db_1""" <|body_0|> def db_for_write(self, model, **hints): """API models to api_db""" <|body_1|> def allow_relation(self, obj1, obj2, *...
stack_v2_sparse_classes_36k_train_002446
3,080
no_license
[ { "docstring": "API models to yte_1_cl_test_db_1", "name": "db_for_read", "signature": "def db_for_read(self, model, **hints)" }, { "docstring": "API models to api_db", "name": "db_for_write", "signature": "def db_for_write(self, model, **hints)" }, { "docstring": "Relation into ...
4
stack_v2_sparse_classes_30k_val_000070
Implement the Python class `APIRouter` described below. Class description: Router for access to API DB Method signatures and docstrings: - def db_for_read(self, model, **hints): API models to yte_1_cl_test_db_1 - def db_for_write(self, model, **hints): API models to api_db - def allow_relation(self, obj1, obj2, **hin...
Implement the Python class `APIRouter` described below. Class description: Router for access to API DB Method signatures and docstrings: - def db_for_read(self, model, **hints): API models to yte_1_cl_test_db_1 - def db_for_write(self, model, **hints): API models to api_db - def allow_relation(self, obj1, obj2, **hin...
840f31ff203457fa12ba2ac20f3e4ee07a3d3410
<|skeleton|> class APIRouter: """Router for access to API DB""" def db_for_read(self, model, **hints): """API models to yte_1_cl_test_db_1""" <|body_0|> def db_for_write(self, model, **hints): """API models to api_db""" <|body_1|> def allow_relation(self, obj1, obj2, *...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APIRouter: """Router for access to API DB""" def db_for_read(self, model, **hints): """API models to yte_1_cl_test_db_1""" if model._meta.app_label == 'location' or model._meta.app_label == 'manual_override' or model._meta.app_label == 'notification' or (model._meta.app_label == 'report')...
the_stack_v2_python_sparse
yap/router.py
gurkarangulati/CMSYapster
train
0
a2d690ee93c06ff051f58facaa6be11a8a9a0596
[ "self.logger = logger.SecureTeaLogger(__name__, debug=debug)\nself.rts_count = 0\nself.cts_count = 0\nself.rts_start_time = None\nself.cts_start_time = None\nself._THRESHOLD = 5", "if pkt.haslayer(scapy.Dot11):\n subtype = int(pkt[scapy.Dot11].subtype)\n if subtype == 11:\n self.rts_count = self.rts_...
<|body_start_0|> self.logger = logger.SecureTeaLogger(__name__, debug=debug) self.rts_count = 0 self.cts_count = 0 self.rts_start_time = None self.cts_start_time = None self._THRESHOLD = 5 <|end_body_0|> <|body_start_1|> if pkt.haslayer(scapy.Dot11): ...
HiddenNode Class.
HiddenNode
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HiddenNode: """HiddenNode Class.""" def __init__(self, debug=False): """Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None""" <|body_0|> def detect_hidden_node(self, pkt): """Count RTS & CTS packet threshold ratio t...
stack_v2_sparse_classes_36k_train_002447
3,487
permissive
[ { "docstring": "Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None", "name": "__init__", "signature": "def __init__(self, debug=False)" }, { "docstring": "Count RTS & CTS packet threshold ratio to detect hidden node attack. Generally, they should b...
3
null
Implement the Python class `HiddenNode` described below. Class description: HiddenNode Class. Method signatures and docstrings: - def __init__(self, debug=False): Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None - def detect_hidden_node(self, pkt): Count RTS & CTS pac...
Implement the Python class `HiddenNode` described below. Class description: HiddenNode Class. Method signatures and docstrings: - def __init__(self, debug=False): Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None - def detect_hidden_node(self, pkt): Count RTS & CTS pac...
43dec187e5848b9ced8a6b4957b6e9028d4d43cd
<|skeleton|> class HiddenNode: """HiddenNode Class.""" def __init__(self, debug=False): """Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None""" <|body_0|> def detect_hidden_node(self, pkt): """Count RTS & CTS packet threshold ratio t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HiddenNode: """HiddenNode Class.""" def __init__(self, debug=False): """Initialize HiddenNode class. Args: debug (bool): Log on terminal or not Raises: None Returns: None""" self.logger = logger.SecureTeaLogger(__name__, debug=debug) self.rts_count = 0 self.cts_count = 0 ...
the_stack_v2_python_sparse
securetea/lib/ids/r2l_rules/wireless/hidden_node.py
rejahrehim/SecureTea-Project
train
1
3d3319840b43424696654fb18535ad10811124cf
[ "self.lr = learning_rate\nself.momentum = momentum\nself.model_weight_specs = model_weight_specs\nself.noise_std = noise_std\nself.random_generator = tf.random.Generator.from_non_deterministic_state()", "def noise_tensor(spec):\n noise = self.random_generator.normal(spec.shape, stddev=self.noise_std)\n nois...
<|body_start_0|> self.lr = learning_rate self.momentum = momentum self.model_weight_specs = model_weight_specs self.noise_std = noise_std self.random_generator = tf.random.Generator.from_non_deterministic_state() <|end_body_0|> <|body_start_1|> def noise_tensor(spec): ...
Momentum DPSGD Optimizer.
DPSGDMServerOptimizer
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DPSGDMServerOptimizer: """Momentum DPSGD Optimizer.""" def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): """Initialize the momemtum DPSGD Optimizer.""" <|body_0|> def _noise_fn(self): """Re...
stack_v2_sparse_classes_36k_train_002448
9,237
permissive
[ { "docstring": "Initialize the momemtum DPSGD Optimizer.", "name": "__init__", "signature": "def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec])" }, { "docstring": "Returns random noise to be added for differential privacy.",...
4
stack_v2_sparse_classes_30k_train_020105
Implement the Python class `DPSGDMServerOptimizer` described below. Class description: Momentum DPSGD Optimizer. Method signatures and docstrings: - def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): Initialize the momemtum DPSGD Optimizer. - de...
Implement the Python class `DPSGDMServerOptimizer` described below. Class description: Momentum DPSGD Optimizer. Method signatures and docstrings: - def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): Initialize the momemtum DPSGD Optimizer. - de...
329e60fa56b87f691303638ceb9dfa1fc5083953
<|skeleton|> class DPSGDMServerOptimizer: """Momentum DPSGD Optimizer.""" def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): """Initialize the momemtum DPSGD Optimizer.""" <|body_0|> def _noise_fn(self): """Re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DPSGDMServerOptimizer: """Momentum DPSGD Optimizer.""" def __init__(self, learning_rate: float, momentum: float, noise_std: float, model_weight_specs: Collection[tf.TensorSpec]): """Initialize the momemtum DPSGD Optimizer.""" self.lr = learning_rate self.momentum = momentum ...
the_stack_v2_python_sparse
dp_ftrl/optimizer_utils.py
google-research/federated
train
595
209bf2f15a8d20730c0c4d69cb457e78dbd5a47a
[ "data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_dataStage02PhysiologySimulation(data.data)\ndata.clear_data()", "data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.update_dataStage02PhysiologySimulation(data.data)\ndata.clear_data()\ndata.clear_data()" ]
<|body_start_0|> data = base_importData() data.read_csv(filename) data.format_data() self.add_dataStage02PhysiologySimulation(data.data) data.clear_data() <|end_body_0|> <|body_start_1|> data = base_importData() data.read_csv(filename) data.format_data() ...
stage02_physiology_simulation_io
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class stage02_physiology_simulation_io: def import_dataStage02PhysiologySimulation_add(self, filename): """table adds""" <|body_0|> def import_dataStage02PhysiologySimulation_update(self, filename): """table adds""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_002449
1,114
permissive
[ { "docstring": "table adds", "name": "import_dataStage02PhysiologySimulation_add", "signature": "def import_dataStage02PhysiologySimulation_add(self, filename)" }, { "docstring": "table adds", "name": "import_dataStage02PhysiologySimulation_update", "signature": "def import_dataStage02Ph...
2
stack_v2_sparse_classes_30k_train_003929
Implement the Python class `stage02_physiology_simulation_io` described below. Class description: Implement the stage02_physiology_simulation_io class. Method signatures and docstrings: - def import_dataStage02PhysiologySimulation_add(self, filename): table adds - def import_dataStage02PhysiologySimulation_update(sel...
Implement the Python class `stage02_physiology_simulation_io` described below. Class description: Implement the stage02_physiology_simulation_io class. Method signatures and docstrings: - def import_dataStage02PhysiologySimulation_add(self, filename): table adds - def import_dataStage02PhysiologySimulation_update(sel...
65635495c4fb7cc98f5c6629e495850e908ea858
<|skeleton|> class stage02_physiology_simulation_io: def import_dataStage02PhysiologySimulation_add(self, filename): """table adds""" <|body_0|> def import_dataStage02PhysiologySimulation_update(self, filename): """table adds""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class stage02_physiology_simulation_io: def import_dataStage02PhysiologySimulation_add(self, filename): """table adds""" data = base_importData() data.read_csv(filename) data.format_data() self.add_dataStage02PhysiologySimulation(data.data) data.clear_data() def ...
the_stack_v2_python_sparse
SBaaS_COBRA/stage02_physiology_simulation_io.py
dmccloskey/SBaaS_COBRA
train
0
7a7cd4b303102855bc2248255533672412b410a9
[ "if K == 0:\n return 1.0\ndp = [0] * (N + 1)\ndp[0] = 1\nwsum = 1\nres = 0\nfor i in range(1, N + 1):\n dp[i] = wsum / W\n if i >= W:\n wsum -= dp[i - W]\n if i < K:\n wsum += dp[i]\n else:\n res += dp[i]\nreturn res", "if N >= K * W:\n return 1\ndp = [[0.0] * (K + W) for _ ...
<|body_start_0|> if K == 0: return 1.0 dp = [0] * (N + 1) dp[0] = 1 wsum = 1 res = 0 for i in range(1, N + 1): dp[i] = wsum / W if i >= W: wsum -= dp[i - W] if i < K: wsum += dp[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def new21Game(self, N, K, W): """:type N: int :type K: int :type W: int :rtype: float""" <|body_0|> def new21Game1(self, N, K, W): """:type N: int :type K: int :type W: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> if K...
stack_v2_sparse_classes_36k_train_002450
1,449
no_license
[ { "docstring": ":type N: int :type K: int :type W: int :rtype: float", "name": "new21Game", "signature": "def new21Game(self, N, K, W)" }, { "docstring": ":type N: int :type K: int :type W: int :rtype: float", "name": "new21Game1", "signature": "def new21Game1(self, N, K, W)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def new21Game(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float - def new21Game1(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def new21Game(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float - def new21Game1(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float <|skelet...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def new21Game(self, N, K, W): """:type N: int :type K: int :type W: int :rtype: float""" <|body_0|> def new21Game1(self, N, K, W): """:type N: int :type K: int :type W: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def new21Game(self, N, K, W): """:type N: int :type K: int :type W: int :rtype: float""" if K == 0: return 1.0 dp = [0] * (N + 1) dp[0] = 1 wsum = 1 res = 0 for i in range(1, N + 1): dp[i] = wsum / W if i >= ...
the_stack_v2_python_sparse
python/leetcode/837_New_21_Game.py
bobcaoge/my-code
train
0
52863f0e3a17dce398ab62a8519da6e457f840b8
[ "serialized = []\nif not root:\n return ''\nqueue, q_index, q_cnt = ([root], 0, 1)\nwhile q_cnt > 0:\n curr, q_index, q_cnt = (queue[q_index], q_index + 1, q_cnt - 1)\n if curr is None:\n serialized.append('NULL')\n continue\n serialized.append(str(curr.val))\n queue.append(curr.left)\n...
<|body_start_0|> serialized = [] if not root: return '' queue, q_index, q_cnt = ([root], 0, 1) while q_cnt > 0: curr, q_index, q_cnt = (queue[q_index], q_index + 1, q_cnt - 1) if curr is None: serialized.append('NULL') c...
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_002451
1,998
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_015275
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:...
49da8fca3e94cce01f2758b3f42f08b317db044d
<|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""" serialized = [] if not root: return '' queue, q_index, q_cnt = ([root], 0, 1) while q_cnt > 0: curr, q_index, q_cnt = (queue[q_index], q_i...
the_stack_v2_python_sparse
Solutions/297 Serialize and Deserialize Binar Tree/Solution2.py
raoqiyu/LeetCode
train
1
afb6e0cd52033335f21d6467d6b222aa46de4f38
[ "from queue import Queue\nN = len(board)\ndists = [N * N] * (N * N)\nq = Queue()\nq.put((1, 0))\nwhile not q.empty():\n square, move = q.get()\n if dists[square - 1] > move:\n dists[square - 1] = move\n for i in range(1, 7):\n next_square = square + i\n if next_square > N *...
<|body_start_0|> from queue import Queue N = len(board) dists = [N * N] * (N * N) q = Queue() q.put((1, 0)) while not q.empty(): square, move = q.get() if dists[square - 1] > move: dists[square - 1] = move for i in r...
Solution2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution2: def snakesAndLadders(self, board): """BFS, brute force :type board: List[List[int]] :rtype: int""" <|body_0|> def snakesAndLadders2(self, board): """BFS, improved with early termination :type board: List[List[int]] :rtype: int""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_002452
4,742
no_license
[ { "docstring": "BFS, brute force :type board: List[List[int]] :rtype: int", "name": "snakesAndLadders", "signature": "def snakesAndLadders(self, board)" }, { "docstring": "BFS, improved with early termination :type board: List[List[int]] :rtype: int", "name": "snakesAndLadders2", "signat...
2
stack_v2_sparse_classes_30k_train_007335
Implement the Python class `Solution2` described below. Class description: Implement the Solution2 class. Method signatures and docstrings: - def snakesAndLadders(self, board): BFS, brute force :type board: List[List[int]] :rtype: int - def snakesAndLadders2(self, board): BFS, improved with early termination :type bo...
Implement the Python class `Solution2` described below. Class description: Implement the Solution2 class. Method signatures and docstrings: - def snakesAndLadders(self, board): BFS, brute force :type board: List[List[int]] :rtype: int - def snakesAndLadders2(self, board): BFS, improved with early termination :type bo...
143aa25f92f3827aa379f29c67a9b7ec3757fef9
<|skeleton|> class Solution2: def snakesAndLadders(self, board): """BFS, brute force :type board: List[List[int]] :rtype: int""" <|body_0|> def snakesAndLadders2(self, board): """BFS, improved with early termination :type board: List[List[int]] :rtype: int""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution2: def snakesAndLadders(self, board): """BFS, brute force :type board: List[List[int]] :rtype: int""" from queue import Queue N = len(board) dists = [N * N] * (N * N) q = Queue() q.put((1, 0)) while not q.empty(): square, move = q.get...
the_stack_v2_python_sparse
py/leetcode_py/909.py
imsure/tech-interview-prep
train
0
92acae84b5e8b0ecd71a53af1456f8c04e82ae59
[ "self._agent_scope = agent_scope\nself.alive = False\nself._publisher = ZmqClient(host=host, port=port, timeout=2, serializer=U.serialize, deserializer=U.deserialize)", "info = {'agent_scope': self._agent_scope, 'time': time.time(), 'iteration': iteration, 'variable_list': list(var_dict.keys()), 'hash': U.pyobj_h...
<|body_start_0|> self._agent_scope = agent_scope self.alive = False self._publisher = ZmqClient(host=host, port=port, timeout=2, serializer=U.serialize, deserializer=U.deserialize) <|end_body_0|> <|body_start_1|> info = {'agent_scope': self._agent_scope, 'time': time.time(), 'iteration'...
Publishes parameters from the learner side Using ZmqPub socket
ParameterPublisher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParameterPublisher: """Publishes parameters from the learner side Using ZmqPub socket""" def __init__(self, host, port, agent_scope): """Args: host: IP of the ps port: the port connected to the pub socket""" <|body_0|> def publish(self, iteration, var_dict): """C...
stack_v2_sparse_classes_36k_train_002453
5,421
no_license
[ { "docstring": "Args: host: IP of the ps port: the port connected to the pub socket", "name": "__init__", "signature": "def __init__(self, host, port, agent_scope)" }, { "docstring": "Called by learner. Publishes model parameters with additional info Args: iteration: current learning iteration v...
4
null
Implement the Python class `ParameterPublisher` described below. Class description: Publishes parameters from the learner side Using ZmqPub socket Method signatures and docstrings: - def __init__(self, host, port, agent_scope): Args: host: IP of the ps port: the port connected to the pub socket - def publish(self, it...
Implement the Python class `ParameterPublisher` described below. Class description: Publishes parameters from the learner side Using ZmqPub socket Method signatures and docstrings: - def __init__(self, host, port, agent_scope): Args: host: IP of the ps port: the port connected to the pub socket - def publish(self, it...
21a497bd67d82aab27cb883386601db0a062c9d1
<|skeleton|> class ParameterPublisher: """Publishes parameters from the learner side Using ZmqPub socket""" def __init__(self, host, port, agent_scope): """Args: host: IP of the ps port: the port connected to the pub socket""" <|body_0|> def publish(self, iteration, var_dict): """C...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParameterPublisher: """Publishes parameters from the learner side Using ZmqPub socket""" def __init__(self, host, port, agent_scope): """Args: host: IP of the ps port: the port connected to the pub socket""" self._agent_scope = agent_scope self.alive = False self._publishe...
the_stack_v2_python_sparse
liaison/distributed/simple_parameter_server.py
aravic/liaison
train
0
77a05cc878f35fea2de464c9559a6e8a20ed3bff
[ "rota_tool = getToolByName(self, 'portal_rotatool')\nmembers = rota_tool.getAvailableReporters()\nreturn DisplayList([(m.UID(), m.Title()) for m in members])", "catalog = getToolByName(self, 'uid_catalog')\nteam_ids = [p.UID for p in catalog(portal_type='DebateRecordOffice')]\nreturn team_ids", "rota_tool = get...
<|body_start_0|> rota_tool = getToolByName(self, 'portal_rotatool') members = rota_tool.getAvailableReporters() return DisplayList([(m.UID(), m.Title()) for m in members]) <|end_body_0|> <|body_start_1|> catalog = getToolByName(self, 'uid_catalog') team_ids = [p.UID for p in cat...
DebateRecordFolder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DebateRecordFolder: def getReportersForSittingVocab(self): """Get the current parliament's team of reporters, and return the active memberships.""" <|body_0|> def getSpaceTeamsDefault(self): """Used from space_team_edit.pt""" <|body_1|> def getNotAddable...
stack_v2_sparse_classes_36k_train_002454
4,421
no_license
[ { "docstring": "Get the current parliament's team of reporters, and return the active memberships.", "name": "getReportersForSittingVocab", "signature": "def getReportersForSittingVocab(self)" }, { "docstring": "Used from space_team_edit.pt", "name": "getSpaceTeamsDefault", "signature": ...
4
stack_v2_sparse_classes_30k_val_000950
Implement the Python class `DebateRecordFolder` described below. Class description: Implement the DebateRecordFolder class. Method signatures and docstrings: - def getReportersForSittingVocab(self): Get the current parliament's team of reporters, and return the active memberships. - def getSpaceTeamsDefault(self): Us...
Implement the Python class `DebateRecordFolder` described below. Class description: Implement the DebateRecordFolder class. Method signatures and docstrings: - def getReportersForSittingVocab(self): Get the current parliament's team of reporters, and return the active memberships. - def getSpaceTeamsDefault(self): Us...
5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d
<|skeleton|> class DebateRecordFolder: def getReportersForSittingVocab(self): """Get the current parliament's team of reporters, and return the active memberships.""" <|body_0|> def getSpaceTeamsDefault(self): """Used from space_team_edit.pt""" <|body_1|> def getNotAddable...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DebateRecordFolder: def getReportersForSittingVocab(self): """Get the current parliament's team of reporters, and return the active memberships.""" rota_tool = getToolByName(self, 'portal_rotatool') members = rota_tool.getAvailableReporters() return DisplayList([(m.UID(), m.Tit...
the_stack_v2_python_sparse
archived/Bungeni/branches/plone3/debaterecord/DebateRecordFolder.py
malangalanga/bungeni-portal
train
0
7afb26e3e36c78a81fa66fe49253244b4f0bac3b
[ "config = ConfigParser.ConfigParser()\nconfig.read(cfg)\nfor section in config.sections():\n setattr(self, section, Dictionary())\n for name, raw_value in config.items(section):\n try:\n if config.get(section, name) in ['0', '1']:\n raise ValueError\n value = config...
<|body_start_0|> config = ConfigParser.ConfigParser() config.read(cfg) for section in config.sections(): setattr(self, section, Dictionary()) for name, raw_value in config.items(section): try: if config.get(section, name) in ['0', '1']:...
Config
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: def __init__(self, cfg='config.conf'): """@param file_name: file name without extension. @param cfg: configuration file path.""" <|body_0|> def get(self, section): """Get option. @param section: section to fetch. @return: option value.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_002455
1,928
permissive
[ { "docstring": "@param file_name: file name without extension. @param cfg: configuration file path.", "name": "__init__", "signature": "def __init__(self, cfg='config.conf')" }, { "docstring": "Get option. @param section: section to fetch. @return: option value.", "name": "get", "signatu...
2
stack_v2_sparse_classes_30k_train_006273
Implement the Python class `Config` described below. Class description: Implement the Config class. Method signatures and docstrings: - def __init__(self, cfg='config.conf'): @param file_name: file name without extension. @param cfg: configuration file path. - def get(self, section): Get option. @param section: secti...
Implement the Python class `Config` described below. Class description: Implement the Config class. Method signatures and docstrings: - def __init__(self, cfg='config.conf'): @param file_name: file name without extension. @param cfg: configuration file path. - def get(self, section): Get option. @param section: secti...
cec3f47692bc77fbdcb397ad7ec21c994328fc00
<|skeleton|> class Config: def __init__(self, cfg='config.conf'): """@param file_name: file name without extension. @param cfg: configuration file path.""" <|body_0|> def get(self, section): """Get option. @param section: section to fetch. @return: option value.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Config: def __init__(self, cfg='config.conf'): """@param file_name: file name without extension. @param cfg: configuration file path.""" config = ConfigParser.ConfigParser() config.read(cfg) for section in config.sections(): setattr(self, section, Dictionary()) ...
the_stack_v2_python_sparse
deeploader/dataset/config.py
cnzeki/DeepLoader
train
1
31a22d99baefc68a13279864e5804b3d3cb7b8ee
[ "session = Session()\ntry:\n organization = session.query(Organization).get(organization_code)\n if organization is None:\n raise falcon.HTTPNotFound()\n query = session.query(OrganizationDepartment).filter(OrganizationDepartment.organization_id == organization_code).order_by(OrganizationDepartment....
<|body_start_0|> session = Session() try: organization = session.query(Organization).get(organization_code) if organization is None: raise falcon.HTTPNotFound() query = session.query(OrganizationDepartment).filter(OrganizationDepartment.organization_id...
GET and POST departments of an organization.
Collection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Collection: """GET and POST departments of an organization.""" def on_get(self, req, resp, organization_code): """GETs a paged collection of departments of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organizati...
stack_v2_sparse_classes_36k_train_002456
5,562
no_license
[ { "docstring": "GETs a paged collection of departments of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The code of the organization.", "name": "on_get", "signature": "def on_get(self, req, resp, organization_code...
2
stack_v2_sparse_classes_30k_train_021268
Implement the Python class `Collection` described below. Class description: GET and POST departments of an organization. Method signatures and docstrings: - def on_get(self, req, resp, organization_code): GETs a paged collection of departments of an organization. :param req: See Falcon Request documentation. :param r...
Implement the Python class `Collection` described below. Class description: GET and POST departments of an organization. Method signatures and docstrings: - def on_get(self, req, resp, organization_code): GETs a paged collection of departments of an organization. :param req: See Falcon Request documentation. :param r...
62723133595829230e5b589431a32cda3b092460
<|skeleton|> class Collection: """GET and POST departments of an organization.""" def on_get(self, req, resp, organization_code): """GETs a paged collection of departments of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organizati...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Collection: """GET and POST departments of an organization.""" def on_get(self, req, resp, organization_code): """GETs a paged collection of departments of an organization. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param organization_code: The ...
the_stack_v2_python_sparse
knoweak/api/resources/organization_department.py
psvaiter/knoweak-api
train
0
9544ee5c679b775cc3ea532e4196c10044374d0e
[ "self.path = path\nself.filename = filename\ntry:\n self.dicom = pydicom.dcmread(os.path.join(self.path, self.filename))\n self.pixel_array = self.dicom.pixel_array\n self.is_series = len(self.pixel_array.shape) == 4\nexcept Exception as e:\n _logger.error(e)\n raise e", "if not os.path.exists('{}/...
<|body_start_0|> self.path = path self.filename = filename try: self.dicom = pydicom.dcmread(os.path.join(self.path, self.filename)) self.pixel_array = self.dicom.pixel_array self.is_series = len(self.pixel_array.shape) == 4 except Exception as e: ...
Compressor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Compressor: def __init__(self, path, filename): """Read dicom file to get fixel_array""" <|body_0|> def toJPEG(self): """compress dicom into jpeg images and return the path of folder contained them""" <|body_1|> <|end_skeleton|> <|body_start_0|> sel...
stack_v2_sparse_classes_36k_train_002457
1,329
no_license
[ { "docstring": "Read dicom file to get fixel_array", "name": "__init__", "signature": "def __init__(self, path, filename)" }, { "docstring": "compress dicom into jpeg images and return the path of folder contained them", "name": "toJPEG", "signature": "def toJPEG(self)" } ]
2
stack_v2_sparse_classes_30k_train_013990
Implement the Python class `Compressor` described below. Class description: Implement the Compressor class. Method signatures and docstrings: - def __init__(self, path, filename): Read dicom file to get fixel_array - def toJPEG(self): compress dicom into jpeg images and return the path of folder contained them
Implement the Python class `Compressor` described below. Class description: Implement the Compressor class. Method signatures and docstrings: - def __init__(self, path, filename): Read dicom file to get fixel_array - def toJPEG(self): compress dicom into jpeg images and return the path of folder contained them <|ske...
ba1f2100d444757a92eced52ca58a55c72ba3d9e
<|skeleton|> class Compressor: def __init__(self, path, filename): """Read dicom file to get fixel_array""" <|body_0|> def toJPEG(self): """compress dicom into jpeg images and return the path of folder contained them""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Compressor: def __init__(self, path, filename): """Read dicom file to get fixel_array""" self.path = path self.filename = filename try: self.dicom = pydicom.dcmread(os.path.join(self.path, self.filename)) self.pixel_array = self.dicom.pixel_array ...
the_stack_v2_python_sparse
services/dicom_service/compress.py
tungluu18/dicom-server
train
0
c32c09686ac1c33045eb45e481382250bc925336
[ "try:\n enc = binascii.b2a_base64(pickle.dumps(raw, -1))\n if settings.ENABLE_INTERNAL_ENCRYPTION:\n iv = binascii.b2a_hex(os.urandom(8))\n cipher = AES.new(key, AES.MODE_CBC, iv)\n enc = binascii.b2a_base64(cipher.encrypt(pad(enc)))\n return '%s/%s' % (iv.decode('utf-8'), enc.deco...
<|body_start_0|> try: enc = binascii.b2a_base64(pickle.dumps(raw, -1)) if settings.ENABLE_INTERNAL_ENCRYPTION: iv = binascii.b2a_hex(os.urandom(8)) cipher = AES.new(key, AES.MODE_CBC, iv) enc = binascii.b2a_base64(cipher.encrypt(pad(enc))) ...
AES encryption backend
AESEncryption
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AESEncryption: """AES encryption backend""" def encrypt_to_b64(raw): """encrypt and b64-encode data""" <|body_0|> def decrypt_from_b64(enc): """decrypt b64-encoded data""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: enc = binas...
stack_v2_sparse_classes_36k_train_002458
2,178
permissive
[ { "docstring": "encrypt and b64-encode data", "name": "encrypt_to_b64", "signature": "def encrypt_to_b64(raw)" }, { "docstring": "decrypt b64-encoded data", "name": "decrypt_from_b64", "signature": "def decrypt_from_b64(enc)" } ]
2
null
Implement the Python class `AESEncryption` described below. Class description: AES encryption backend Method signatures and docstrings: - def encrypt_to_b64(raw): encrypt and b64-encode data - def decrypt_from_b64(enc): decrypt b64-encoded data
Implement the Python class `AESEncryption` described below. Class description: AES encryption backend Method signatures and docstrings: - def encrypt_to_b64(raw): encrypt and b64-encode data - def decrypt_from_b64(enc): decrypt b64-encoded data <|skeleton|> class AESEncryption: """AES encryption backend""" ...
27a23ce47e3ec11b94f3355c2d2ee94c1958679c
<|skeleton|> class AESEncryption: """AES encryption backend""" def encrypt_to_b64(raw): """encrypt and b64-encode data""" <|body_0|> def decrypt_from_b64(enc): """decrypt b64-encoded data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AESEncryption: """AES encryption backend""" def encrypt_to_b64(raw): """encrypt and b64-encode data""" try: enc = binascii.b2a_base64(pickle.dumps(raw, -1)) if settings.ENABLE_INTERNAL_ENCRYPTION: iv = binascii.b2a_hex(os.urandom(8)) ...
the_stack_v2_python_sparse
will/backends/encryption/aes.py
skoczen/will
train
359
3be51894584c440b2b70367639511c9fc0fd5062
[ "self.vals = deque()\nself.size = size\nself.curr_size = 0\nself.sum = 0", "if self.size == 0:\n return None\nself.curr_size += 1\nself.sum += val\nself.vals.append(val)\nif self.curr_size > self.size:\n self.sum -= self.vals.popleft()\n self.curr_size -= 1\nreturn self.sum / self.curr_size" ]
<|body_start_0|> self.vals = deque() self.size = size self.curr_size = 0 self.sum = 0 <|end_body_0|> <|body_start_1|> if self.size == 0: return None self.curr_size += 1 self.sum += val self.vals.append(val) if self.curr_size > self.siz...
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.vals = deque() self.size...
stack_v2_sparse_classes_36k_train_002459
806
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
stack_v2_sparse_classes_30k_test_000795
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: ...
692bf0e5aab402d55463274e99ab4d0ed56ce64c
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" self.vals = deque() self.size = size self.curr_size = 0 self.sum = 0 def next(self, val): """:type val: int :rtype: float""" if self.size == 0: ...
the_stack_v2_python_sparse
346-moving_avg_from_data_stream.py
WweiL/LeetCode
train
0
957af9a64f24200768e1c28b5340ce3a1a8eaee9
[ "server = get_object_or_404(models.FederatedServer, id=server)\nusers = server.user_set\ndata = {'server': server, 'users': users, 'reports': models.Report.objects.filter(user__in=users.all()), 'followed_by_us': users.filter(followers__local=True), 'followed_by_them': users.filter(following__local=True), 'blocked_b...
<|body_start_0|> server = get_object_or_404(models.FederatedServer, id=server) users = server.user_set data = {'server': server, 'users': users, 'reports': models.Report.objects.filter(user__in=users.all()), 'followed_by_us': users.filter(followers__local=True), 'followed_by_them': users.filter(...
views for handling a specific federated server
FederatedServer
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FederatedServer: """views for handling a specific federated server""" def get(self, request, server): """load a server""" <|body_0|> def post(self, request, server): """update note""" <|body_1|> <|end_skeleton|> <|body_start_0|> server = get_obj...
stack_v2_sparse_classes_36k_train_002460
6,777
no_license
[ { "docstring": "load a server", "name": "get", "signature": "def get(self, request, server)" }, { "docstring": "update note", "name": "post", "signature": "def post(self, request, server)" } ]
2
null
Implement the Python class `FederatedServer` described below. Class description: views for handling a specific federated server Method signatures and docstrings: - def get(self, request, server): load a server - def post(self, request, server): update note
Implement the Python class `FederatedServer` described below. Class description: views for handling a specific federated server Method signatures and docstrings: - def get(self, request, server): load a server - def post(self, request, server): update note <|skeleton|> class FederatedServer: """views for handlin...
0f8da5b738047f3c34d60d93f59bdedd8f797224
<|skeleton|> class FederatedServer: """views for handling a specific federated server""" def get(self, request, server): """load a server""" <|body_0|> def post(self, request, server): """update note""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FederatedServer: """views for handling a specific federated server""" def get(self, request, server): """load a server""" server = get_object_or_404(models.FederatedServer, id=server) users = server.user_set data = {'server': server, 'users': users, 'reports': models.Repor...
the_stack_v2_python_sparse
bookwyrm/views/admin/federation.py
bookwyrm-social/bookwyrm
train
1,398
46bb0e75a2642b857c6fcf738230900d93dafce1
[ "super().__init__(interval=interval)\nself.atol = atol\nself.rtol = rtol", "if isinstance(field, FieldCollection):\n self._reference = np.array([f.magnitude for f in field])\nelse:\n self._reference = field.magnitude\nreturn super().initialize(field, info)", "if isinstance(field, FieldCollection):\n ma...
<|body_start_0|> super().__init__(interval=interval) self.atol = atol self.rtol = rtol <|end_body_0|> <|body_start_1|> if isinstance(field, FieldCollection): self._reference = np.array([f.magnitude for f in field]) else: self._reference = field.magnitude ...
Tracking interrupting the simulation when material conservation is broken
MaterialConservationTracker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaterialConservationTracker: """Tracking interrupting the simulation when material conservation is broken""" def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): """Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount dev...
stack_v2_sparse_classes_36k_train_002461
37,567
permissive
[ { "docstring": "Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount deviations rtol (float): Relative tolerance for amount deviations", "name": "__init__", "signature": "def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001)" }, { "doc...
3
stack_v2_sparse_classes_30k_train_008478
Implement the Python class `MaterialConservationTracker` described below. Class description: Tracking interrupting the simulation when material conservation is broken Method signatures and docstrings: - def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): Args: interval: {ARG_TRACKER_...
Implement the Python class `MaterialConservationTracker` described below. Class description: Tracking interrupting the simulation when material conservation is broken Method signatures and docstrings: - def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): Args: interval: {ARG_TRACKER_...
d9c931a8361eaf27bc3766daba26edc11756b5f5
<|skeleton|> class MaterialConservationTracker: """Tracking interrupting the simulation when material conservation is broken""" def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): """Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount dev...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaterialConservationTracker: """Tracking interrupting the simulation when material conservation is broken""" def __init__(self, interval: IntervalData=1, atol: float=0.0001, rtol: float=0.0001): """Args: interval: {ARG_TRACKER_INTERVAL} atol (float): Absolute tolerance for amount deviations rtol ...
the_stack_v2_python_sparse
pde/trackers/trackers.py
zwicker-group/py-pde
train
327
e87d483f88e92f6f1e4f4e17d35dfbc479a17fc0
[ "def binary_search(data, val):\n left = 0\n right = len(data) - 1\n while left < right:\n mid = left + right >> 1\n if val == data[mid]:\n return mid\n elif val < data[mid]:\n right = mid\n else:\n left = mid + 1\n return left\nif not nums:\n ...
<|body_start_0|> def binary_search(data, val): left = 0 right = len(data) - 1 while left < right: mid = left + right >> 1 if val == data[mid]: return mid elif val < data[mid]: right = mid ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS_dp(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def lengthOfLIS_dp(self, nums): """:type nums: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k_train_002462
3,797
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS", "signature": "def lengthOfLIS(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "lengthOfLIS_dp", "signature": "def lengthOfLIS_dp(self, nums)" }, { "docstring": ":type nums: List...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS_dp(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS_dp(self, nums): :type nums: L...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS_dp(self, nums): :type nums: List[int] :rtype: int - def lengthOfLIS_dp(self, nums): :type nums: L...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS_dp(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def lengthOfLIS_dp(self, nums): """:type nums: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lengthOfLIS(self, nums): """:type nums: List[int] :rtype: int""" def binary_search(data, val): left = 0 right = len(data) - 1 while left < right: mid = left + right >> 1 if val == data[mid]: r...
the_stack_v2_python_sparse
src/lt_300.py
oxhead/CodingYourWay
train
0
bee3d4f0aea87a8bf7d2551f4a0f57068b3b36dc
[ "fast, slow = (head, head)\nwhile fast and fast.next:\n fast, slow = (fast.next.next, slow.next)\n if fast is slow:\n fast = head\n while fast is not slow:\n fast, slow = (fast.next, slow.next)\n return fast\nreturn None", "if len(data) == 0 or data is None:\n return None\...
<|body_start_0|> fast, slow = (head, head) while fast and fast.next: fast, slow = (fast.next.next, slow.next) if fast is slow: fast = head while fast is not slow: fast, slow = (fast.next, slow.next) return fast ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def createList(self, data): """:param data: a list :return: a head node to a linked list""" <|body_1|> <|end_skeleton|> <|body_start_0|> fast, slow = (head...
stack_v2_sparse_classes_36k_train_002463
1,748
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "detectCycle", "signature": "def detectCycle(self, head)" }, { "docstring": ":param data: a list :return: a head node to a linked list", "name": "createList", "signature": "def createList(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_010929
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): :type head: ListNode :rtype: ListNode - def createList(self, data): :param data: a list :return: a head node to a linked list
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def detectCycle(self, head): :type head: ListNode :rtype: ListNode - def createList(self, data): :param data: a list :return: a head node to a linked list <|skeleton|> class Sol...
a5b02044ef39154b6a8d32eb57682f447e1632ba
<|skeleton|> class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def createList(self, data): """:param data: a list :return: a head node to a linked list""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def detectCycle(self, head): """:type head: ListNode :rtype: ListNode""" fast, slow = (head, head) while fast and fast.next: fast, slow = (fast.next.next, slow.next) if fast is slow: fast = head while fast is not slow: ...
the_stack_v2_python_sparse
algo/list/linked_list_cycle_II.py
xys234/coding-problems
train
0
a3dc338407be2b44db5de8aac0e0fb2446db016d
[ "self.num_class = -1\nself.num_bin = num_bin\nself.num_feature = -1\nself.prior = None\nself.miu = None\nself.sigma = None\nself.distribution = None\nself.mode = mode\nself.epsilon = 1e-09\nif 256 % self.num_bin != 0:\n print('error bin number!')\n exit()\nelse:\n self.dis_width = 256 / self.num_bin", "s...
<|body_start_0|> self.num_class = -1 self.num_bin = num_bin self.num_feature = -1 self.prior = None self.miu = None self.sigma = None self.distribution = None self.mode = mode self.epsilon = 1e-09 if 256 % self.num_bin != 0: pri...
NaiveBayseClassifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NaiveBayseClassifier: def __init__(self, mode=1, num_bin=32): """Constructor of Naive Bayes classifier The function would check if the number of bins is valid If it's invalid, error will raise and exit the program Arg: mode - The mode integer num_bin - The number of bins""" <|bod...
stack_v2_sparse_classes_36k_train_002464
3,971
no_license
[ { "docstring": "Constructor of Naive Bayes classifier The function would check if the number of bins is valid If it's invalid, error will raise and exit the program Arg: mode - The mode integer num_bin - The number of bins", "name": "__init__", "signature": "def __init__(self, mode=1, num_bin=32)" }, ...
3
stack_v2_sparse_classes_30k_train_007478
Implement the Python class `NaiveBayseClassifier` described below. Class description: Implement the NaiveBayseClassifier class. Method signatures and docstrings: - def __init__(self, mode=1, num_bin=32): Constructor of Naive Bayes classifier The function would check if the number of bins is valid If it's invalid, err...
Implement the Python class `NaiveBayseClassifier` described below. Class description: Implement the NaiveBayseClassifier class. Method signatures and docstrings: - def __init__(self, mode=1, num_bin=32): Constructor of Naive Bayes classifier The function would check if the number of bins is valid If it's invalid, err...
a99878bd85e69aebf4582efa7231ac2c3514fe8e
<|skeleton|> class NaiveBayseClassifier: def __init__(self, mode=1, num_bin=32): """Constructor of Naive Bayes classifier The function would check if the number of bins is valid If it's invalid, error will raise and exit the program Arg: mode - The mode integer num_bin - The number of bins""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NaiveBayseClassifier: def __init__(self, mode=1, num_bin=32): """Constructor of Naive Bayes classifier The function would check if the number of bins is valid If it's invalid, error will raise and exit the program Arg: mode - The mode integer num_bin - The number of bins""" self.num_class = -1...
the_stack_v2_python_sparse
hw2/1/classifier.py
SunnerLi/ml
train
0
782003429c9eed71dea3055aabf4fd7e1e34df8e
[ "user_id = self.cleaned_data['user']\ntry:\n user = User.objects.get(id=user_id)\nexcept User.DoesNotExist:\n raise forms.ValidationError(\"Cet utilisateur n'existe pas !\")\nreturn user", "group_id = self.cleaned_data['group']\ntry:\n group = Group.objects.get(id=group_id)\nexcept Group.DoesNotExist:\n ...
<|body_start_0|> user_id = self.cleaned_data['user'] try: user = User.objects.get(id=user_id) except User.DoesNotExist: raise forms.ValidationError("Cet utilisateur n'existe pas !") return user <|end_body_0|> <|body_start_1|> group_id = self.cleaned_data[...
Form to add GroupMembers objects, to user community inscription
GroupMemberInscriptionForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GroupMemberInscriptionForm: """Form to add GroupMembers objects, to user community inscription""" def clean_user(self): """Return the User object since the id input by user, if it exists""" <|body_0|> def clean_group(self): """Return the Group object since the id...
stack_v2_sparse_classes_36k_train_002465
4,015
no_license
[ { "docstring": "Return the User object since the id input by user, if it exists", "name": "clean_user", "signature": "def clean_user(self)" }, { "docstring": "Return the Group object since the id input by user, if it exists", "name": "clean_group", "signature": "def clean_group(self)" ...
4
stack_v2_sparse_classes_30k_train_014905
Implement the Python class `GroupMemberInscriptionForm` described below. Class description: Form to add GroupMembers objects, to user community inscription Method signatures and docstrings: - def clean_user(self): Return the User object since the id input by user, if it exists - def clean_group(self): Return the Grou...
Implement the Python class `GroupMemberInscriptionForm` described below. Class description: Form to add GroupMembers objects, to user community inscription Method signatures and docstrings: - def clean_user(self): Return the User object since the id input by user, if it exists - def clean_group(self): Return the Grou...
cf0b982a6df2b8b4318d12d344ef0827394eedfd
<|skeleton|> class GroupMemberInscriptionForm: """Form to add GroupMembers objects, to user community inscription""" def clean_user(self): """Return the User object since the id input by user, if it exists""" <|body_0|> def clean_group(self): """Return the Group object since the id...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GroupMemberInscriptionForm: """Form to add GroupMembers objects, to user community inscription""" def clean_user(self): """Return the User object since the id input by user, if it exists""" user_id = self.cleaned_data['user'] try: user = User.objects.get(id=user_id) ...
the_stack_v2_python_sparse
group_member/forms.py
cleliofavoccia/Share
train
0
171aff9e6483768a821a2bfa7a0eceafcb83882d
[ "if n <= 0:\n raise ValueError('n must be a positive value')\nif p < 0 or p > 1:\n raise ValueError('p must be greater than 0 and less than 1')\nself.n = int(n)\nself.p = float(p)\nif data is None:\n self.n = self.n\n self.p = self.p\nelse:\n if type(data) is not list:\n raise TypeError('data ...
<|body_start_0|> if n <= 0: raise ValueError('n must be a positive value') if p < 0 or p > 1: raise ValueError('p must be greater than 0 and less than 1') self.n = int(n) self.p = float(p) if data is None: self.n = self.n self.p = s...
represents a binomial distribution
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """represents a binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Binomial contructor""" <|body_0|> def pmf(self, k): """Calculates the value of the PMF for a given number""" <|body_1|> def cdf(self, k): """Calc...
stack_v2_sparse_classes_36k_train_002466
1,886
no_license
[ { "docstring": "Binomial contructor", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5)" }, { "docstring": "Calculates the value of the PMF for a given number", "name": "pmf", "signature": "def pmf(self, k)" }, { "docstring": "Calculates the value of the...
3
stack_v2_sparse_classes_30k_train_010588
Implement the Python class `Binomial` described below. Class description: represents a binomial distribution Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Binomial contructor - def pmf(self, k): Calculates the value of the PMF for a given number - def cdf(self, k): Calculates the valu...
Implement the Python class `Binomial` described below. Class description: represents a binomial distribution Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Binomial contructor - def pmf(self, k): Calculates the value of the PMF for a given number - def cdf(self, k): Calculates the valu...
4adb0b69ab12ebeec08b1cf603e5c738378f6806
<|skeleton|> class Binomial: """represents a binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Binomial contructor""" <|body_0|> def pmf(self, k): """Calculates the value of the PMF for a given number""" <|body_1|> def cdf(self, k): """Calc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Binomial: """represents a binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Binomial contructor""" if n <= 0: raise ValueError('n must be a positive value') if p < 0 or p > 1: raise ValueError('p must be greater than 0 and less than 1')...
the_stack_v2_python_sparse
math/0x03-probability/binomial.py
Jdavp/holbertonschool-machine_learning
train
0
1d0a52c75ac5ba7fd7f96acff93807ca8778aec5
[ "self.x = constant([[0.7, 0.9]])\nself.w1 = Variable(random_normal([2, 3], stddev=1, seed=1))\nself.w2 = Variable(random_normal([3, 1], stddev=1, seed=1))", "a = matmul(self.x, self.w1)\ny = matmul(a, self.w2)\nsess = Session()\nsess.run(self.w1.initializer)\nsess.run(self.w2.initializer)\nprint('第一种:', sess.run(...
<|body_start_0|> self.x = constant([[0.7, 0.9]]) self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1)) self.w2 = Variable(random_normal([3, 1], stddev=1, seed=1)) <|end_body_0|> <|body_start_1|> a = matmul(self.x, self.w1) y = matmul(a, self.w2) sess = Session() ...
神经网络
NeuralNetworks
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeuralNetworks: """神经网络""" def example_load_data(self): """加载数据""" <|body_0|> def example_compute(self): """简单的神经网络实现前向传播的算法 这里为什么能用矩阵乘法来计算呢?因为,通过求加权和发现 正好是矩阵的乘法运算结果。所以,这里充分的体现了数学的美""" <|body_1|> def example_2_load_data(self): """加载数据""" ...
stack_v2_sparse_classes_36k_train_002467
6,839
permissive
[ { "docstring": "加载数据", "name": "example_load_data", "signature": "def example_load_data(self)" }, { "docstring": "简单的神经网络实现前向传播的算法 这里为什么能用矩阵乘法来计算呢?因为,通过求加权和发现 正好是矩阵的乘法运算结果。所以,这里充分的体现了数学的美", "name": "example_compute", "signature": "def example_compute(self)" }, { "docstring": "加载数...
5
stack_v2_sparse_classes_30k_train_000360
Implement the Python class `NeuralNetworks` described below. Class description: 神经网络 Method signatures and docstrings: - def example_load_data(self): 加载数据 - def example_compute(self): 简单的神经网络实现前向传播的算法 这里为什么能用矩阵乘法来计算呢?因为,通过求加权和发现 正好是矩阵的乘法运算结果。所以,这里充分的体现了数学的美 - def example_2_load_data(self): 加载数据 - def example_2_comput...
Implement the Python class `NeuralNetworks` described below. Class description: 神经网络 Method signatures and docstrings: - def example_load_data(self): 加载数据 - def example_compute(self): 简单的神经网络实现前向传播的算法 这里为什么能用矩阵乘法来计算呢?因为,通过求加权和发现 正好是矩阵的乘法运算结果。所以,这里充分的体现了数学的美 - def example_2_load_data(self): 加载数据 - def example_2_comput...
c8da7128ea18ecaa5849f2066d321e70d6f97f70
<|skeleton|> class NeuralNetworks: """神经网络""" def example_load_data(self): """加载数据""" <|body_0|> def example_compute(self): """简单的神经网络实现前向传播的算法 这里为什么能用矩阵乘法来计算呢?因为,通过求加权和发现 正好是矩阵的乘法运算结果。所以,这里充分的体现了数学的美""" <|body_1|> def example_2_load_data(self): """加载数据""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NeuralNetworks: """神经网络""" def example_load_data(self): """加载数据""" self.x = constant([[0.7, 0.9]]) self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1)) self.w2 = Variable(random_normal([3, 1], stddev=1, seed=1)) def example_compute(self): """简单的神经网络实现前向...
the_stack_v2_python_sparse
PYSTUDY/ml/tensorflowlib.py
shi-cong/PYSTUDY
train
8
eab9e5ff4b18e6bde7916ea978ca4b746327435e
[ "if not email:\n raise ValueError('Users must have an Email address')\nif not first_name:\n raise ValueError('Users must have a First name')\nif not last_name:\n raise ValueError('Users must have a Last name')\nuser = self.model(email=self.normalize_email(email), first_name=first_name, last_name=last_name,...
<|body_start_0|> if not email: raise ValueError('Users must have an Email address') if not first_name: raise ValueError('Users must have a First name') if not last_name: raise ValueError('Users must have a Last name') user = self.model(email=self.norma...
AccountManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountManager: def create_user(self, email, first_name, last_name, password=None): """Creates and saves a User with the given email and password.""" <|body_0|> def create_superuser(self, email, first_name, last_name, password): """Creates and saves a superuser with ...
stack_v2_sparse_classes_36k_train_002468
4,129
no_license
[ { "docstring": "Creates and saves a User with the given email and password.", "name": "create_user", "signature": "def create_user(self, email, first_name, last_name, password=None)" }, { "docstring": "Creates and saves a superuser with the given email and password.", "name": "create_superus...
2
stack_v2_sparse_classes_30k_train_015890
Implement the Python class `AccountManager` described below. Class description: Implement the AccountManager class. Method signatures and docstrings: - def create_user(self, email, first_name, last_name, password=None): Creates and saves a User with the given email and password. - def create_superuser(self, email, fi...
Implement the Python class `AccountManager` described below. Class description: Implement the AccountManager class. Method signatures and docstrings: - def create_user(self, email, first_name, last_name, password=None): Creates and saves a User with the given email and password. - def create_superuser(self, email, fi...
72d2856e76998653e73c6aff17833446a019d1d8
<|skeleton|> class AccountManager: def create_user(self, email, first_name, last_name, password=None): """Creates and saves a User with the given email and password.""" <|body_0|> def create_superuser(self, email, first_name, last_name, password): """Creates and saves a superuser with ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountManager: def create_user(self, email, first_name, last_name, password=None): """Creates and saves a User with the given email and password.""" if not email: raise ValueError('Users must have an Email address') if not first_name: raise ValueError('Users mu...
the_stack_v2_python_sparse
accounts/models.py
w3kernel/sokalbikal
train
0
10a599f1047d645372cff39a354fdff3e6ccd0ba
[ "@lru_cache(None)\ndef dfs(remain: int) -> int:\n if remain < 0:\n return INF\n if remain == 0:\n return 0\n res = INF\n for select in nums:\n if remain - select < 0:\n break\n res = min(res, 1 + dfs(remain - select))\n return res\nnums = []\nfor v in range(k, n...
<|body_start_0|> @lru_cache(None) def dfs(remain: int) -> int: if remain < 0: return INF if remain == 0: return 0 res = INF for select in nums: if remain - select < 0: break ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumNumbers(self, num: int, k: int) -> int: """完全背包""" <|body_0|> def minimumNumbers2(self, num: int, k: int) -> int: """枚举+数学 若多重集里有 n 个整数,那么这些整数之和为 (10*∑ai + n*k) 只要 (num - nk) 能被 10 整除且大等于 0,就存在一个大小为 n 的集合。返回最小的符合要求的 n 即可""" <|body_1|> <|...
stack_v2_sparse_classes_36k_train_002469
1,774
no_license
[ { "docstring": "完全背包", "name": "minimumNumbers", "signature": "def minimumNumbers(self, num: int, k: int) -> int" }, { "docstring": "枚举+数学 若多重集里有 n 个整数,那么这些整数之和为 (10*∑ai + n*k) 只要 (num - nk) 能被 10 整除且大等于 0,就存在一个大小为 n 的集合。返回最小的符合要求的 n 即可", "name": "minimumNumbers2", "signature": "def mini...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumNumbers(self, num: int, k: int) -> int: 完全背包 - def minimumNumbers2(self, num: int, k: int) -> int: 枚举+数学 若多重集里有 n 个整数,那么这些整数之和为 (10*∑ai + n*k) 只要 (num - nk) 能被 10 整除且大...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumNumbers(self, num: int, k: int) -> int: 完全背包 - def minimumNumbers2(self, num: int, k: int) -> int: 枚举+数学 若多重集里有 n 个整数,那么这些整数之和为 (10*∑ai + n*k) 只要 (num - nk) 能被 10 整除且大...
7e79e26bb8f641868561b186e34c1127ed63c9e0
<|skeleton|> class Solution: def minimumNumbers(self, num: int, k: int) -> int: """完全背包""" <|body_0|> def minimumNumbers2(self, num: int, k: int) -> int: """枚举+数学 若多重集里有 n 个整数,那么这些整数之和为 (10*∑ai + n*k) 只要 (num - nk) 能被 10 整除且大等于 0,就存在一个大小为 n 的集合。返回最小的符合要求的 n 即可""" <|body_1|> <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minimumNumbers(self, num: int, k: int) -> int: """完全背包""" @lru_cache(None) def dfs(remain: int) -> int: if remain < 0: return INF if remain == 0: return 0 res = INF for select in nums: ...
the_stack_v2_python_sparse
11_动态规划/背包问题/完全背包/5218. 个位数字为 K 的整数之和.py
981377660LMT/algorithm-study
train
225
d55afd5e2d7f9b58223945d4a25bc1bf28fccc4c
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TermsAndConditionsAcceptanceStatus()", "from .entity import Entity\nfrom .terms_and_conditions import TermsAndConditions\nfrom .entity import Entity\nfrom .terms_and_conditions import TermsAndConditions\nfields: Dict[str, Callable[[Any...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return TermsAndConditionsAcceptanceStatus() <|end_body_0|> <|body_start_1|> from .entity import Entity from .terms_and_conditions import TermsAndConditions from .entity import Entity ...
A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain access to the Company Portal.
TermsAndConditionsAcceptanceStatus
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TermsAndConditionsAcceptanceStatus: """A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain access to the Company Portal.""" def...
stack_v2_sparse_classes_36k_train_002470
3,780
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TermsAndConditionsAcceptanceStatus", "name": "create_from_discriminator_value", "signature": "def create_fro...
3
null
Implement the Python class `TermsAndConditionsAcceptanceStatus` described below. Class description: A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain ac...
Implement the Python class `TermsAndConditionsAcceptanceStatus` described below. Class description: A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain ac...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class TermsAndConditionsAcceptanceStatus: """A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain access to the Company Portal.""" def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TermsAndConditionsAcceptanceStatus: """A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain access to the Company Portal.""" def create_from_...
the_stack_v2_python_sparse
msgraph/generated/models/terms_and_conditions_acceptance_status.py
microsoftgraph/msgraph-sdk-python
train
135
fbac0c2eb65b297e4ffce4d36fc3623561837483
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('henryhcy_wangyp', 'henryhcy_wangyp')\nurl = 'https://data.boston.gov/dataset/03693648-2c62-4a2c-a4ec-48de2ee14e18/resource/4582bec6-2b4f-4f9e-bc55-cbaa73117f4c/download/tmper3diw4s.csv'\nresponse = urlli...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('henryhcy_wangyp', 'henryhcy_wangyp') url = 'https://data.boston.gov/dataset/03693648-2c62-4a2c-a4ec-48de2ee14e18/resource/4582bec6-2b4f-4f9e-bc55-cbaa7311...
inspection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class inspection: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything ha...
stack_v2_sparse_classes_36k_train_002471
4,452
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
null
Implement the Python class `inspection` described below. Class description: Implement the inspection class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime...
Implement the Python class `inspection` described below. Class description: Implement the inspection class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class inspection: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything ha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class inspection: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('henryhcy_wangyp', 'henryhcy_wangyp') ...
the_stack_v2_python_sparse
henryhcy_wangyp/inspection.py
maximega/course-2019-spr-proj
train
2
f6d09ba5285026059a92d7c290ee8e0645324433
[ "self.canary = api\nupdate_interval = timedelta(seconds=30)\nsuper().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)", "locations_by_id: dict[str, Location] = {}\nreadings_by_device_id: dict[str, ValuesView[Reading]] = {}\nfor location in self.canary.get_locations():\n location_id = locat...
<|body_start_0|> self.canary = api update_interval = timedelta(seconds=30) super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval) <|end_body_0|> <|body_start_1|> locations_by_id: dict[str, Location] = {} readings_by_device_id: dict[str, ValuesView[Reading]...
Class to manage fetching Canary data.
CanaryDataUpdateCoordinator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CanaryDataUpdateCoordinator: """Class to manage fetching Canary data.""" def __init__(self, hass: HomeAssistant, *, api: Api) -> None: """Initialize global Canary data updater.""" <|body_0|> def _update_data(self) -> CanaryData: """Fetch data from Canary via sync...
stack_v2_sparse_classes_36k_train_002472
2,098
permissive
[ { "docstring": "Initialize global Canary data updater.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, *, api: Api) -> None" }, { "docstring": "Fetch data from Canary via sync functions.", "name": "_update_data", "signature": "def _update_data(self) -> CanaryD...
3
null
Implement the Python class `CanaryDataUpdateCoordinator` described below. Class description: Class to manage fetching Canary data. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, *, api: Api) -> None: Initialize global Canary data updater. - def _update_data(self) -> CanaryData: Fetch data...
Implement the Python class `CanaryDataUpdateCoordinator` described below. Class description: Class to manage fetching Canary data. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, *, api: Api) -> None: Initialize global Canary data updater. - def _update_data(self) -> CanaryData: Fetch data...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class CanaryDataUpdateCoordinator: """Class to manage fetching Canary data.""" def __init__(self, hass: HomeAssistant, *, api: Api) -> None: """Initialize global Canary data updater.""" <|body_0|> def _update_data(self) -> CanaryData: """Fetch data from Canary via sync...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CanaryDataUpdateCoordinator: """Class to manage fetching Canary data.""" def __init__(self, hass: HomeAssistant, *, api: Api) -> None: """Initialize global Canary data updater.""" self.canary = api update_interval = timedelta(seconds=30) super().__init__(hass, _LOGGER, nam...
the_stack_v2_python_sparse
homeassistant/components/canary/coordinator.py
home-assistant/core
train
35,501
4b0941ebbb30fd9786ab559bf9b5f9279b121635
[ "if not self._hasModule(**kwargs):\n return kwargs\nif self.ifOptions(**kwargs):\n try:\n kwargs['module'].run(**kwargs)\n except KeyError as e:\n kwargs['msg'] = '%s in %s' % (e, kwargs['module'].__module__)\n self.fail(**kwargs)\n except OSError as e:\n kwargs['msg'] = 'You...
<|body_start_0|> if not self._hasModule(**kwargs): return kwargs if self.ifOptions(**kwargs): try: kwargs['module'].run(**kwargs) except KeyError as e: kwargs['msg'] = '%s in %s' % (e, kwargs['module'].__module__) self.f...
Launch the selected module, scenario Usage into cli interface : run
ECommandRun
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ECommandRun: """Launch the selected module, scenario Usage into cli interface : run""" def execute(self, **kwargs): """Run the selected Module @param module: the module to launch @return: the main dictionary""" <|body_0|> def ifOptions(self, **kwargs): """Verify ...
stack_v2_sparse_classes_36k_train_002473
2,326
no_license
[ { "docstring": "Run the selected Module @param module: the module to launch @return: the main dictionary", "name": "execute", "signature": "def execute(self, **kwargs)" }, { "docstring": "Verify if all mandatory options are set @param module: the module to launch @return: True if all mandatory o...
2
stack_v2_sparse_classes_30k_test_000656
Implement the Python class `ECommandRun` described below. Class description: Launch the selected module, scenario Usage into cli interface : run Method signatures and docstrings: - def execute(self, **kwargs): Run the selected Module @param module: the module to launch @return: the main dictionary - def ifOptions(sel...
Implement the Python class `ECommandRun` described below. Class description: Launch the selected module, scenario Usage into cli interface : run Method signatures and docstrings: - def execute(self, **kwargs): Run the selected Module @param module: the module to launch @return: the main dictionary - def ifOptions(sel...
6d535410520acd27951b0af5711acbb6a30adcb4
<|skeleton|> class ECommandRun: """Launch the selected module, scenario Usage into cli interface : run""" def execute(self, **kwargs): """Run the selected Module @param module: the module to launch @return: the main dictionary""" <|body_0|> def ifOptions(self, **kwargs): """Verify ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ECommandRun: """Launch the selected module, scenario Usage into cli interface : run""" def execute(self, **kwargs): """Run the selected Module @param module: the module to launch @return: the main dictionary""" if not self._hasModule(**kwargs): return kwargs if self.if...
the_stack_v2_python_sparse
ease/ecommands/eecrun.py
thmsaurel/ease
train
4
a08ea37da9983e7a0f878a6033468aeb6e238d9e
[ "super().__init__(**kwargs)\ncs_dict = _get_driver_settings(self.CONFIG_NAME, self._ALT_CONFIG_NAMES, instance)\nself.cloud = cs_dict.pop('cloud', 'global')\nif 'cloud' in kwargs and kwargs['cloud']:\n self.cloud = kwargs['cloud']\napi_uri, oauth_uri, api_suffix = _select_api_uris(self.data_environment, self.clo...
<|body_start_0|> super().__init__(**kwargs) cs_dict = _get_driver_settings(self.CONFIG_NAME, self._ALT_CONFIG_NAMES, instance) self.cloud = cs_dict.pop('cloud', 'global') if 'cloud' in kwargs and kwargs['cloud']: self.cloud = kwargs['cloud'] api_uri, oauth_uri, api_su...
KqlDriver class to retreive date from MS Defender APIs.
MDATPDriver
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-3.0-only", "LGPL-2.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "EPL-1.0", "GPL-1.0-or-later", "LGPL-2.1-only", "MPL-2.0", "Python-2.0", "PSF-2.0", "LicenseRef-scancode-python-cwi", "GPL-2.0-or-later", "LGPL-2.1-or-later...
stack_v2_sparse_python_classes_v1
<|skeleton|> class MDATPDriver: """KqlDriver class to retreive date from MS Defender APIs.""" def __init__(self, connection_str: str=None, instance: str='Default', **kwargs): """Instantiate MSDefenderDriver and optionally connect. Parameters ---------- connection_str : str, optional Connection string i...
stack_v2_sparse_classes_36k_train_002474
4,334
permissive
[ { "docstring": "Instantiate MSDefenderDriver and optionally connect. Parameters ---------- connection_str : str, optional Connection string instance : str, optional The instance name from config to use", "name": "__init__", "signature": "def __init__(self, connection_str: str=None, instance: str='Defaul...
2
null
Implement the Python class `MDATPDriver` described below. Class description: KqlDriver class to retreive date from MS Defender APIs. Method signatures and docstrings: - def __init__(self, connection_str: str=None, instance: str='Default', **kwargs): Instantiate MSDefenderDriver and optionally connect. Parameters ----...
Implement the Python class `MDATPDriver` described below. Class description: KqlDriver class to retreive date from MS Defender APIs. Method signatures and docstrings: - def __init__(self, connection_str: str=None, instance: str='Default', **kwargs): Instantiate MSDefenderDriver and optionally connect. Parameters ----...
55c6c1aebb8505a220046705b7c74194f83d62f3
<|skeleton|> class MDATPDriver: """KqlDriver class to retreive date from MS Defender APIs.""" def __init__(self, connection_str: str=None, instance: str='Default', **kwargs): """Instantiate MSDefenderDriver and optionally connect. Parameters ---------- connection_str : str, optional Connection string i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MDATPDriver: """KqlDriver class to retreive date from MS Defender APIs.""" def __init__(self, connection_str: str=None, instance: str='Default', **kwargs): """Instantiate MSDefenderDriver and optionally connect. Parameters ---------- connection_str : str, optional Connection string instance : str...
the_stack_v2_python_sparse
msticpy/data/drivers/mdatp_driver.py
rhaug77/msticpy
train
0
e722a83e7cea1f59c51ee9abc5558f8cc4a40dc3
[ "condition = ['parameter_name_one', '*', '4.0', '+', 'parameter_name_two']\nexpected = ['parameter_name_one', 'parameter_name_two']\nresult = get_parameter_names(condition)\nself.assertEqual(result, expected)", "condition = [['parameter_name_one', '*', '4.0', '+', 'parameter_name_two'], ['parameter_name_three', '...
<|body_start_0|> condition = ['parameter_name_one', '*', '4.0', '+', 'parameter_name_two'] expected = ['parameter_name_one', 'parameter_name_two'] result = get_parameter_names(condition) self.assertEqual(result, expected) <|end_body_0|> <|body_start_1|> condition = [['parameter_...
Test the get_parameter_names method.
Test_get_parameter_names
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_get_parameter_names: """Test the get_parameter_names method.""" def test_basic(self): """Test that the get_parameter_names method does what it says.""" <|body_0|> def test_nested(self): """Test getting parameter names from nested lists.""" <|body_1|>...
stack_v2_sparse_classes_36k_train_002475
28,171
permissive
[ { "docstring": "Test that the get_parameter_names method does what it says.", "name": "test_basic", "signature": "def test_basic(self)" }, { "docstring": "Test getting parameter names from nested lists.", "name": "test_nested", "signature": "def test_nested(self)" } ]
2
stack_v2_sparse_classes_30k_test_000634
Implement the Python class `Test_get_parameter_names` described below. Class description: Test the get_parameter_names method. Method signatures and docstrings: - def test_basic(self): Test that the get_parameter_names method does what it says. - def test_nested(self): Test getting parameter names from nested lists.
Implement the Python class `Test_get_parameter_names` described below. Class description: Test the get_parameter_names method. Method signatures and docstrings: - def test_basic(self): Test that the get_parameter_names method does what it says. - def test_nested(self): Test getting parameter names from nested lists. ...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_get_parameter_names: """Test the get_parameter_names method.""" def test_basic(self): """Test that the get_parameter_names method does what it says.""" <|body_0|> def test_nested(self): """Test getting parameter names from nested lists.""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_get_parameter_names: """Test the get_parameter_names method.""" def test_basic(self): """Test that the get_parameter_names method does what it says.""" condition = ['parameter_name_one', '*', '4.0', '+', 'parameter_name_two'] expected = ['parameter_name_one', 'parameter_name_...
the_stack_v2_python_sparse
improver_tests/wxcode/wxcode/test_utilities.py
metoppv/improver
train
101
4328facf43ff7495b3105a47072a7a493f829876
[ "sum = nums[0]\nmax_sum = nums[0]\nfor i in range(1, len(nums)):\n if sum < 0:\n sum = 0\n sum += nums[i]\n max_sum = max(sum, max_sum)\nreturn max_sum", "for i in range(1, len(nums)):\n if nums[i - 1] > 0:\n nums[i] += nums[i - 1]\nreturn max(nums)" ]
<|body_start_0|> sum = nums[0] max_sum = nums[0] for i in range(1, len(nums)): if sum < 0: sum = 0 sum += nums[i] max_sum = max(sum, max_sum) return max_sum <|end_body_0|> <|body_start_1|> for i in range(1, len(nums)): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxSubArray(self, nums): """和最大的子列表 :type nums: List[int] :rtype: int""" <|body_0|> def maxSubArray2(self, nums): """和最大的子列表 :type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> sum = nums[0] max_su...
stack_v2_sparse_classes_36k_train_002476
1,389
no_license
[ { "docstring": "和最大的子列表 :type nums: List[int] :rtype: int", "name": "maxSubArray", "signature": "def maxSubArray(self, nums)" }, { "docstring": "和最大的子列表 :type nums: List[int] :rtype: int", "name": "maxSubArray2", "signature": "def maxSubArray2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_007671
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray(self, nums): 和最大的子列表 :type nums: List[int] :rtype: int - def maxSubArray2(self, nums): 和最大的子列表 :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxSubArray(self, nums): 和最大的子列表 :type nums: List[int] :rtype: int - def maxSubArray2(self, nums): 和最大的子列表 :type nums: List[int] :rtype: int <|skeleton|> class Solution: ...
04d87d76b762f6ea7cfb3a453382b2d7d4e154dc
<|skeleton|> class Solution: def maxSubArray(self, nums): """和最大的子列表 :type nums: List[int] :rtype: int""" <|body_0|> def maxSubArray2(self, nums): """和最大的子列表 :type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxSubArray(self, nums): """和最大的子列表 :type nums: List[int] :rtype: int""" sum = nums[0] max_sum = nums[0] for i in range(1, len(nums)): if sum < 0: sum = 0 sum += nums[i] max_sum = max(sum, max_sum) return...
the_stack_v2_python_sparse
leetcode/053 Maximum Subarray.py
mofei952/algorithm_exercise
train
1
788aad227949f75e1d69834b168e75e78bd7ab75
[ "address = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry'\nparam = {Request.AccessToken: accesstoken}\ndata = {Request.Template.IndustryFirst: firstid, Request.Template.IndustrySecond: secondid}\nrequest = web.JSONcreater(data)\nresponse, _ = web.post(address, param, request)\nresponse = web.JSONpars...
<|body_start_0|> address = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry' param = {Request.AccessToken: accesstoken} data = {Request.Template.IndustryFirst: firstid, Request.Template.IndustrySecond: secondid} request = web.JSONcreater(data) response, _ = web.post(a...
微信公众平台模板消息API实现: setindustry - 设置模板所属行业
TemplateMessage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplateMessage: """微信公众平台模板消息API实现: setindustry - 设置模板所属行业""" def setindustry(accesstoken: str, firstid: int, secondid: int) -> dict: """设置模板消息库所属行业: firstid: 第一个行业 id secondid: 第二个行业 id""" <|body_0|> def getindustry(accesstoken: str) -> dict: """获取当前设置的行业信息""" ...
stack_v2_sparse_classes_36k_train_002477
5,181
permissive
[ { "docstring": "设置模板消息库所属行业: firstid: 第一个行业 id secondid: 第二个行业 id", "name": "setindustry", "signature": "def setindustry(accesstoken: str, firstid: int, secondid: int) -> dict" }, { "docstring": "获取当前设置的行业信息", "name": "getindustry", "signature": "def getindustry(accesstoken: str) -> dict...
6
stack_v2_sparse_classes_30k_train_018841
Implement the Python class `TemplateMessage` described below. Class description: 微信公众平台模板消息API实现: setindustry - 设置模板所属行业 Method signatures and docstrings: - def setindustry(accesstoken: str, firstid: int, secondid: int) -> dict: 设置模板消息库所属行业: firstid: 第一个行业 id secondid: 第二个行业 id - def getindustry(accesstoken: str) -> ...
Implement the Python class `TemplateMessage` described below. Class description: 微信公众平台模板消息API实现: setindustry - 设置模板所属行业 Method signatures and docstrings: - def setindustry(accesstoken: str, firstid: int, secondid: int) -> dict: 设置模板消息库所属行业: firstid: 第一个行业 id secondid: 第二个行业 id - def getindustry(accesstoken: str) -> ...
79e34f4b8fba8c6fd208b5a3049103dca2064ab5
<|skeleton|> class TemplateMessage: """微信公众平台模板消息API实现: setindustry - 设置模板所属行业""" def setindustry(accesstoken: str, firstid: int, secondid: int) -> dict: """设置模板消息库所属行业: firstid: 第一个行业 id secondid: 第二个行业 id""" <|body_0|> def getindustry(accesstoken: str) -> dict: """获取当前设置的行业信息""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TemplateMessage: """微信公众平台模板消息API实现: setindustry - 设置模板所属行业""" def setindustry(accesstoken: str, firstid: int, secondid: int) -> dict: """设置模板消息库所属行业: firstid: 第一个行业 id secondid: 第二个行业 id""" address = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry' param = {Request.A...
the_stack_v2_python_sparse
leaf/weixin/apis/template.py
guiqiqi/leaf
train
122
1edee5c06a0173247e58575fdf79e2997c0915f0
[ "pos = 0\np = head\nps = {}\nidx = 0\nwhile p:\n if p in ps:\n pos = ps.get(p)\n print('pos = {}'.format(pos))\n return True\n else:\n ps.__setitem__(p, idx)\n p = p.next\n idx += 1\nreturn False", "slow = head\nif not head:\n return False\nfast = head.next\nwhile fast:\...
<|body_start_0|> pos = 0 p = head ps = {} idx = 0 while p: if p in ps: pos = ps.get(p) print('pos = {}'.format(pos)) return True else: ps.__setitem__(p, idx) p = p.next ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasCycle(self, head: ListNode) -> bool: """思路:如果是循环链表,以判空为结束条件的话会一直循环无法退出,而且又不知道链表长度。 我们希望,结束条件为相同节点,比如next的结点已经访问过了,说明有循环。此时需要将每个访问过的结点记录下来。 基于这个思路,空间复杂度是O(n),问题是还可以改进吗? 改进:见has_cycle()函数 :param head: :return:""" <|body_0|> def has_cycle(self, head: ListNode) ...
stack_v2_sparse_classes_36k_train_002478
2,430
no_license
[ { "docstring": "思路:如果是循环链表,以判空为结束条件的话会一直循环无法退出,而且又不知道链表长度。 我们希望,结束条件为相同节点,比如next的结点已经访问过了,说明有循环。此时需要将每个访问过的结点记录下来。 基于这个思路,空间复杂度是O(n),问题是还可以改进吗? 改进:见has_cycle()函数 :param head: :return:", "name": "hasCycle", "signature": "def hasCycle(self, head: ListNode) -> bool" }, { "docstring": "思路:在空间复杂度为O(1...
2
stack_v2_sparse_classes_30k_train_004600
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle(self, head: ListNode) -> bool: 思路:如果是循环链表,以判空为结束条件的话会一直循环无法退出,而且又不知道链表长度。 我们希望,结束条件为相同节点,比如next的结点已经访问过了,说明有循环。此时需要将每个访问过的结点记录下来。 基于这个思路,空间复杂度是O(n),问题是还可以改进吗? 改进:见ha...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle(self, head: ListNode) -> bool: 思路:如果是循环链表,以判空为结束条件的话会一直循环无法退出,而且又不知道链表长度。 我们希望,结束条件为相同节点,比如next的结点已经访问过了,说明有循环。此时需要将每个访问过的结点记录下来。 基于这个思路,空间复杂度是O(n),问题是还可以改进吗? 改进:见ha...
46cfe84921a9a3e865edd1f94e7807b320b53778
<|skeleton|> class Solution: def hasCycle(self, head: ListNode) -> bool: """思路:如果是循环链表,以判空为结束条件的话会一直循环无法退出,而且又不知道链表长度。 我们希望,结束条件为相同节点,比如next的结点已经访问过了,说明有循环。此时需要将每个访问过的结点记录下来。 基于这个思路,空间复杂度是O(n),问题是还可以改进吗? 改进:见has_cycle()函数 :param head: :return:""" <|body_0|> def has_cycle(self, head: ListNode) ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hasCycle(self, head: ListNode) -> bool: """思路:如果是循环链表,以判空为结束条件的话会一直循环无法退出,而且又不知道链表长度。 我们希望,结束条件为相同节点,比如next的结点已经访问过了,说明有循环。此时需要将每个访问过的结点记录下来。 基于这个思路,空间复杂度是O(n),问题是还可以改进吗? 改进:见has_cycle()函数 :param head: :return:""" pos = 0 p = head ps = {} idx = 0 w...
the_stack_v2_python_sparse
2020-07/Q141-has-cycle.py
EAGLE50/LearnLeetCode
train
0
e36fd2a8d85685271d97c4f5a6a2bcad5ea4c246
[ "self.capacity_value = capacity\nself.value_pq = []\nself.value_stack = []", "while self.value_pq and self.value_pq[0] < len(self.value_stack) and (len(self.value_stack[self.value_pq[0]]) == self.capacity_value):\n heapq.heappop(self.value_pq)\nif not self.value_pq:\n heapq.heappush(self.value_pq, len(self....
<|body_start_0|> self.capacity_value = capacity self.value_pq = [] self.value_stack = [] <|end_body_0|> <|body_start_1|> while self.value_pq and self.value_pq[0] < len(self.value_stack) and (len(self.value_stack[self.value_pq[0]]) == self.capacity_value): heapq.heappop(self....
DinnerPlates
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DinnerPlates: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def push(self, val): """:type val: int :rtype: None""" <|body_1|> def pop(self): """:rtype: int""" <|body_2|> def popAtStack(self, index): """:t...
stack_v2_sparse_classes_36k_train_002479
1,763
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type val: int :rtype: None", "name": "push", "signature": "def push(self, val)" }, { "docstring": ":rtype: int", "name": "pop", "signature": "def pop(...
4
null
Implement the Python class `DinnerPlates` described below. Class description: Implement the DinnerPlates class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def push(self, val): :type val: int :rtype: None - def pop(self): :rtype: int - def popAtStack(self, index): :type ind...
Implement the Python class `DinnerPlates` described below. Class description: Implement the DinnerPlates class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def push(self, val): :type val: int :rtype: None - def pop(self): :rtype: int - def popAtStack(self, index): :type ind...
dc45210cb2cc50bfefd8c21c865e6ee2163a022a
<|skeleton|> class DinnerPlates: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def push(self, val): """:type val: int :rtype: None""" <|body_1|> def pop(self): """:rtype: int""" <|body_2|> def popAtStack(self, index): """:t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DinnerPlates: def __init__(self, capacity): """:type capacity: int""" self.capacity_value = capacity self.value_pq = [] self.value_stack = [] def push(self, val): """:type val: int :rtype: None""" while self.value_pq and self.value_pq[0] < len(self.value_st...
the_stack_v2_python_sparse
practice/solution/1172_dinner_plate_stacks.py
kesarb/leetcode-summary-python
train
0
e6df46d3fb97b03a63d0d03440254b6cc4ff5edb
[ "self.pose_sub = rospy.Subscriber('pose_in', PoseStamped, self.pose_in_cb)\nself.pose_pub = rospy.Publisher('pose_out', PoseStamped)\nself.offset_x = translation[0]\nself.offset_y = translation[1]\nself.offset_z = translation[2]\nself.quat_offset = quaternion\nrospy.loginfo('[%s] Pose relay node started with:\\r\\n...
<|body_start_0|> self.pose_sub = rospy.Subscriber('pose_in', PoseStamped, self.pose_in_cb) self.pose_pub = rospy.Publisher('pose_out', PoseStamped) self.offset_x = translation[0] self.offset_y = translation[1] self.offset_z = translation[2] self.quat_offset = quaternion ...
ClickedPoseRelay
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClickedPoseRelay: def __init__(self, translation, quaternion): """Setup pub/subs and transform parameters""" <|body_0|> def pose_in_cb(self, ps_in): """Apply transform to received pose and republish""" <|body_1|> <|end_skeleton|> <|body_start_0|> se...
stack_v2_sparse_classes_36k_train_002480
3,093
no_license
[ { "docstring": "Setup pub/subs and transform parameters", "name": "__init__", "signature": "def __init__(self, translation, quaternion)" }, { "docstring": "Apply transform to received pose and republish", "name": "pose_in_cb", "signature": "def pose_in_cb(self, ps_in)" } ]
2
null
Implement the Python class `ClickedPoseRelay` described below. Class description: Implement the ClickedPoseRelay class. Method signatures and docstrings: - def __init__(self, translation, quaternion): Setup pub/subs and transform parameters - def pose_in_cb(self, ps_in): Apply transform to received pose and republish
Implement the Python class `ClickedPoseRelay` described below. Class description: Implement the ClickedPoseRelay class. Method signatures and docstrings: - def __init__(self, translation, quaternion): Setup pub/subs and transform parameters - def pose_in_cb(self, ps_in): Apply transform to received pose and republish...
86ae2c6e4e55acd424abb7fbb5bd63d9c29340ee
<|skeleton|> class ClickedPoseRelay: def __init__(self, translation, quaternion): """Setup pub/subs and transform parameters""" <|body_0|> def pose_in_cb(self, ps_in): """Apply transform to received pose and republish""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClickedPoseRelay: def __init__(self, translation, quaternion): """Setup pub/subs and transform parameters""" self.pose_sub = rospy.Subscriber('pose_in', PoseStamped, self.pose_in_cb) self.pose_pub = rospy.Publisher('pose_out', PoseStamped) self.offset_x = translation[0] ...
the_stack_v2_python_sparse
assistive_teleop/src/assistive_teleop/clicked_pose_relay.py
and/hrl-assistive
train
0
ee3c534ee682148d21573725a6d0d85d5f428acf
[ "res_set = set(A[0])\narr_size = len(A)\ncount_dict = {}\nres = []\nfor i in range(1, arr_size):\n res_set = set(A[i]) & res_set\n if len(res_set) != 0:\n i += 1\nfor char in res_set:\n count = A[0].count(char)\n for i in range(1, arr_size):\n count = min(A[i].count(char), count)\n ...
<|body_start_0|> res_set = set(A[0]) arr_size = len(A) count_dict = {} res = [] for i in range(1, arr_size): res_set = set(A[i]) & res_set if len(res_set) != 0: i += 1 for char in res_set: count = A[0].count(char) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def commonChars(self, A): """:type A: List[str] :rtype: List[str]""" <|body_0|> def commonChars2(self, words): """:type words: List[str] :rtype: List[str]""" <|body_1|> <|end_skeleton|> <|body_start_0|> res_set = set(A[0]) arr_size...
stack_v2_sparse_classes_36k_train_002481
2,410
no_license
[ { "docstring": ":type A: List[str] :rtype: List[str]", "name": "commonChars", "signature": "def commonChars(self, A)" }, { "docstring": ":type words: List[str] :rtype: List[str]", "name": "commonChars2", "signature": "def commonChars2(self, words)" } ]
2
stack_v2_sparse_classes_30k_train_002508
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def commonChars(self, A): :type A: List[str] :rtype: List[str] - def commonChars2(self, words): :type words: List[str] :rtype: List[str]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def commonChars(self, A): :type A: List[str] :rtype: List[str] - def commonChars2(self, words): :type words: List[str] :rtype: List[str] <|skeleton|> class Solution: def co...
813235789ce422a3bab198317aafc46fbc61625e
<|skeleton|> class Solution: def commonChars(self, A): """:type A: List[str] :rtype: List[str]""" <|body_0|> def commonChars2(self, words): """:type words: List[str] :rtype: List[str]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def commonChars(self, A): """:type A: List[str] :rtype: List[str]""" res_set = set(A[0]) arr_size = len(A) count_dict = {} res = [] for i in range(1, arr_size): res_set = set(A[i]) & res_set if len(res_set) != 0: ...
the_stack_v2_python_sparse
2.SET/e1002_Find Common Characters/solution.py
kimmyoo/python_leetcode
train
1
830a276688fba0bc102f1efac95f11725e197d13
[ "assert len(v) == len(u)\nif len(v) == 0 or len(u) == 0:\n return np.array([])\nelse:\n return v.dot(u)", "if isinstance(a, Ciphertext):\n product = [0 for _ in range(len(v))]\n for i in range(len(product)):\n product[i] = a * v[i]\n return product\nelse:\n raise TypeError('invalid scalar...
<|body_start_0|> assert len(v) == len(u) if len(v) == 0 or len(u) == 0: return np.array([]) else: return v.dot(u) <|end_body_0|> <|body_start_1|> if isinstance(a, Ciphertext): product = [0 for _ in range(len(v))] for i in range(len(product...
LinearAlgebra
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearAlgebra: def pdot(v, u): """Plaintext inner product :param v: numpy.ndarray :param u: numpy.ndarray :return:""" <|body_0|> def cmult(a, v): """Ciphertext scalar product a * v :param a: Ciphertext :param v: numpy.ndarray or list :return: list[Ciphertext]""" ...
stack_v2_sparse_classes_36k_train_002482
1,462
no_license
[ { "docstring": "Plaintext inner product :param v: numpy.ndarray :param u: numpy.ndarray :return:", "name": "pdot", "signature": "def pdot(v, u)" }, { "docstring": "Ciphertext scalar product a * v :param a: Ciphertext :param v: numpy.ndarray or list :return: list[Ciphertext]", "name": "cmult"...
4
null
Implement the Python class `LinearAlgebra` described below. Class description: Implement the LinearAlgebra class. Method signatures and docstrings: - def pdot(v, u): Plaintext inner product :param v: numpy.ndarray :param u: numpy.ndarray :return: - def cmult(a, v): Ciphertext scalar product a * v :param a: Ciphertext...
Implement the Python class `LinearAlgebra` described below. Class description: Implement the LinearAlgebra class. Method signatures and docstrings: - def pdot(v, u): Plaintext inner product :param v: numpy.ndarray :param u: numpy.ndarray :return: - def cmult(a, v): Ciphertext scalar product a * v :param a: Ciphertext...
db959eef96f95fcdd92185f0cb728d1d0b99857b
<|skeleton|> class LinearAlgebra: def pdot(v, u): """Plaintext inner product :param v: numpy.ndarray :param u: numpy.ndarray :return:""" <|body_0|> def cmult(a, v): """Ciphertext scalar product a * v :param a: Ciphertext :param v: numpy.ndarray or list :return: list[Ciphertext]""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearAlgebra: def pdot(v, u): """Plaintext inner product :param v: numpy.ndarray :param u: numpy.ndarray :return:""" assert len(v) == len(u) if len(v) == 0 or len(u) == 0: return np.array([]) else: return v.dot(u) def cmult(a, v): """Cipher...
the_stack_v2_python_sparse
privacy/math/linear_algebra.py
som-don/jeddak
train
0
3b14eb9047cc2e89f5dfab481511f1759f9347bd
[ "res = []\n\ndef pre_order(root: TreeNode):\n if root:\n res.append(str(root.val))\n pre_order(root.left)\n pre_order(root.right)\npre_order(root)\nreturn ' '.join(res)", "from collections import deque\nq = deque([int(d) for d in data.split()])\n\ndef build(minVal: int, maxVal: int) -> Tre...
<|body_start_0|> res = [] def pre_order(root: TreeNode): if root: res.append(str(root.val)) pre_order(root.left) pre_order(root.right) pre_order(root) return ' '.join(res) <|end_body_0|> <|body_start_1|> from collectio...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [] ...
stack_v2_sparse_classes_36k_train_002483
1,506
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
a390adeeb71e997b3c1a56c479825d4adda07ef9
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" res = [] def pre_order(root: TreeNode): if root: res.append(str(root.val)) pre_order(root.left) pre_order(root.right) pre_ord...
the_stack_v2_python_sparse
algorithms/python/serializeandDeserializeBST/serializeandDeserializeBST.py
MichelleZ/leetcode
train
3
120f5bedbd541f283a3887ba924cf866e3decf02
[ "self.list_index = [0] * 2\nself.next_list_index = 0\nself.lists = [v1, v2]", "result = self.lists[self.next_list_index][self.list_index[self.next_list_index]]\nself.list_index[self.next_list_index] += 1\nself.next_list_index = (self.next_list_index + 1) % 2\nreturn result", "index = self.list_index[self.next_l...
<|body_start_0|> self.list_index = [0] * 2 self.next_list_index = 0 self.lists = [v1, v2] <|end_body_0|> <|body_start_1|> result = self.lists[self.next_list_index][self.list_index[self.next_list_index]] self.list_index[self.next_list_index] += 1 self.next_list_index = (s...
ZigzagIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end...
stack_v2_sparse_classes_36k_train_002484
2,234
no_license
[ { "docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]", "name": "__init__", "signature": "def __init__(self, v1, v2)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": ":rtype: bool", "name"...
3
null
Implement the Python class `ZigzagIterator` described below. Class description: Implement the ZigzagIterator class. Method signatures and docstrings: - def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int] - def next(self): :rtype: int - def hasNext(self): :rtype: bo...
Implement the Python class `ZigzagIterator` described below. Class description: Implement the ZigzagIterator class. Method signatures and docstrings: - def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int] - def next(self): :rtype: int - def hasNext(self): :rtype: bo...
08c6d27498e35f636045fed05a6f94b760ab69ca
<|skeleton|> class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" self.list_index = [0] * 2 self.next_list_index = 0 self.lists = [v1, v2] def next(self): """:rtype: int""" result = self.lists[sel...
the_stack_v2_python_sparse
solutions/design/281.Zigzag.Iterator.py
ljia2/leetcode.py
train
0
8840aa3d67146a62f9c2733d84e461954c440811
[ "if isinstance(key, int):\n return Certificate(key)\nif key not in Certificate._member_map_:\n extend_enum(Certificate, key, default)\nreturn Certificate[key]", "if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 9 <= value <= 255...
<|body_start_0|> if isinstance(key, int): return Certificate(key) if key not in Certificate._member_map_: extend_enum(Certificate, key, default) return Certificate[key] <|end_body_0|> <|body_start_1|> if not (isinstance(value, int) and 0 <= value <= 255): ...
[Certificate] HIP Certificate Types
Certificate
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Certificate: """[Certificate] HIP Certificate Types""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_36k_train_002485
1,540
permissive
[ { "docstring": "Backport support for original codes.", "name": "get", "signature": "def get(key, default=-1)" }, { "docstring": "Lookup function used when value is not found.", "name": "_missing_", "signature": "def _missing_(cls, value)" } ]
2
stack_v2_sparse_classes_30k_train_008425
Implement the Python class `Certificate` described below. Class description: [Certificate] HIP Certificate Types Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found.
Implement the Python class `Certificate` described below. Class description: [Certificate] HIP Certificate Types Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found. <|skeleton|> class Certificate...
90cd07d67df28d5c5ab0585bc60f467a78d9db33
<|skeleton|> class Certificate: """[Certificate] HIP Certificate Types""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Certificate: """[Certificate] HIP Certificate Types""" def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Certificate(key) if key not in Certificate._member_map_: extend_enum(Certificate, key, default) ...
the_stack_v2_python_sparse
pcapkit/const/hip/certificate.py
stjordanis/PyPCAPKit
train
0
fcdd6beded96307d5f1f05081a3ca087f86cc77f
[ "self.sensor = Sensor('127.0.0.1', '8000')\nself.pump = Pump('127.0.0.1', '8001')\nself.decider = Decider(30, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.pump.set_state = MagicMock(return_value=True)", "for height in range(20, 40, 5):\n for state in self.controller.actions.v...
<|body_start_0|> self.sensor = Sensor('127.0.0.1', '8000') self.pump = Pump('127.0.0.1', '8001') self.decider = Decider(30, 0.05) self.controller = Controller(self.sensor, self.pump, self.decider) self.pump.set_state = MagicMock(return_value=True) <|end_body_0|> <|body_start_1|>...
Module tests for the water-regulation module
ModuleTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModuleTests: """Module tests for the water-regulation module""" def setUp(self): """setup to use in integration testing""" <|body_0|> def test_controller_decider(self): """test water-regulation module as a whole""" <|body_1|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_002486
1,205
no_license
[ { "docstring": "setup to use in integration testing", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "test water-regulation module as a whole", "name": "test_controller_decider", "signature": "def test_controller_decider(self)" } ]
2
null
Implement the Python class `ModuleTests` described below. Class description: Module tests for the water-regulation module Method signatures and docstrings: - def setUp(self): setup to use in integration testing - def test_controller_decider(self): test water-regulation module as a whole
Implement the Python class `ModuleTests` described below. Class description: Module tests for the water-regulation module Method signatures and docstrings: - def setUp(self): setup to use in integration testing - def test_controller_decider(self): test water-regulation module as a whole <|skeleton|> class ModuleTest...
b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1
<|skeleton|> class ModuleTests: """Module tests for the water-regulation module""" def setUp(self): """setup to use in integration testing""" <|body_0|> def test_controller_decider(self): """test water-regulation module as a whole""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModuleTests: """Module tests for the water-regulation module""" def setUp(self): """setup to use in integration testing""" self.sensor = Sensor('127.0.0.1', '8000') self.pump = Pump('127.0.0.1', '8001') self.decider = Decider(30, 0.05) self.controller = Controller(...
the_stack_v2_python_sparse
students/elnurad/lesson06/water-regulation/waterregulation/integrationtest.py
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
train
4
608451b887391fd19852682704602cd896258291
[ "filepath = os.path.dirname(os.path.abspath(__file__))\nname_path = filepath + '/data/' + file_name + '.csv'\nwrite_mode = 'r+' if os.path.exists(name_path) else 'w'\nwith open(name_path, write_mode) as csv_file:\n csv_file.seek(0)\n csv_file.write(SaveStaticFeatures.area_features_header_to_string() + '\\n')\...
<|body_start_0|> filepath = os.path.dirname(os.path.abspath(__file__)) name_path = filepath + '/data/' + file_name + '.csv' write_mode = 'r+' if os.path.exists(name_path) else 'w' with open(name_path, write_mode) as csv_file: csv_file.seek(0) csv_file.write(SaveSt...
SaveStaticFeatures
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SaveStaticFeatures: def array_to_csv(feature_array, file_name): """Saves the static features to a csv file :param feature_array: the list with the static features :param file_name: the desired filename :return:""" <|body_0|> def area_features_header_to_string(): """C...
stack_v2_sparse_classes_36k_train_002487
1,933
permissive
[ { "docstring": "Saves the static features to a csv file :param feature_array: the list with the static features :param file_name: the desired filename :return:", "name": "array_to_csv", "signature": "def array_to_csv(feature_array, file_name)" }, { "docstring": "Creates the header string for the...
2
stack_v2_sparse_classes_30k_train_018504
Implement the Python class `SaveStaticFeatures` described below. Class description: Implement the SaveStaticFeatures class. Method signatures and docstrings: - def array_to_csv(feature_array, file_name): Saves the static features to a csv file :param feature_array: the list with the static features :param file_name: ...
Implement the Python class `SaveStaticFeatures` described below. Class description: Implement the SaveStaticFeatures class. Method signatures and docstrings: - def array_to_csv(feature_array, file_name): Saves the static features to a csv file :param feature_array: the list with the static features :param file_name: ...
2708ca47d5b965ad531e5576d87fbe77e466c4e0
<|skeleton|> class SaveStaticFeatures: def array_to_csv(feature_array, file_name): """Saves the static features to a csv file :param feature_array: the list with the static features :param file_name: the desired filename :return:""" <|body_0|> def area_features_header_to_string(): """C...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SaveStaticFeatures: def array_to_csv(feature_array, file_name): """Saves the static features to a csv file :param feature_array: the list with the static features :param file_name: the desired filename :return:""" filepath = os.path.dirname(os.path.abspath(__file__)) name_path = filepa...
the_stack_v2_python_sparse
implementation/stofzuiger/feature_extraction/save_static_features.py
jellevanwezel/FinalThesisProject
train
0
ea437bed3ad149497a6351651834e5cc85e78755
[ "self.driver.find_element(WoDeLoator.TAB).click()\nself.driver.find_element(WoDeLoator.DENGLU).click()\nself.driver.find_element(WoDeLoator.PWDL).click()\nself.driver.find_element(WoDeLoator.UN).send_keys('17346500242')\nself.driver.find_element(WoDeLoator.PW).send_keys('00000000')\nself.driver.find_element(WoDeLoa...
<|body_start_0|> self.driver.find_element(WoDeLoator.TAB).click() self.driver.find_element(WoDeLoator.DENGLU).click() self.driver.find_element(WoDeLoator.PWDL).click() self.driver.find_element(WoDeLoator.UN).send_keys('17346500242') self.driver.find_element(WoDeLoator.PW).send_ke...
Login
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Login: def test_login(self): """用户名密码登录@author:kangjuan""" <|body_0|> def test_logout(self): """退出登录@author:kangjuan""" <|body_1|> def test_mycollect(self): """我收藏的@author:kangjuan""" <|body_2|> def test_mycontact(self): """我...
stack_v2_sparse_classes_36k_train_002488
3,505
no_license
[ { "docstring": "用户名密码登录@author:kangjuan", "name": "test_login", "signature": "def test_login(self)" }, { "docstring": "退出登录@author:kangjuan", "name": "test_logout", "signature": "def test_logout(self)" }, { "docstring": "我收藏的@author:kangjuan", "name": "test_mycollect", "s...
6
stack_v2_sparse_classes_30k_train_013393
Implement the Python class `Login` described below. Class description: Implement the Login class. Method signatures and docstrings: - def test_login(self): 用户名密码登录@author:kangjuan - def test_logout(self): 退出登录@author:kangjuan - def test_mycollect(self): 我收藏的@author:kangjuan - def test_mycontact(self): 我咨询的@author:kan...
Implement the Python class `Login` described below. Class description: Implement the Login class. Method signatures and docstrings: - def test_login(self): 用户名密码登录@author:kangjuan - def test_logout(self): 退出登录@author:kangjuan - def test_mycollect(self): 我收藏的@author:kangjuan - def test_mycontact(self): 我咨询的@author:kan...
a73e4ed1dc02f05e93f11788591efe68109fd277
<|skeleton|> class Login: def test_login(self): """用户名密码登录@author:kangjuan""" <|body_0|> def test_logout(self): """退出登录@author:kangjuan""" <|body_1|> def test_mycollect(self): """我收藏的@author:kangjuan""" <|body_2|> def test_mycontact(self): """我...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Login: def test_login(self): """用户名密码登录@author:kangjuan""" self.driver.find_element(WoDeLoator.TAB).click() self.driver.find_element(WoDeLoator.DENGLU).click() self.driver.find_element(WoDeLoator.PWDL).click() self.driver.find_element(WoDeLoator.UN).send_keys('173465002...
the_stack_v2_python_sparse
taocheApp/test_wode/test_login.py
zhangyanli616/TaoCheAuto
train
0
ec93a8a3fedc9309a307831ba07e4d7b530d0408
[ "QtGui.QLabel.__init__(self, parent)\nself.var_type = var_type\nself.setText(var_type)\nself.setAttribute(QtCore.Qt.WA_Hover)\nself.setCursor(CurrentTheme.OPEN_HAND_CURSOR)\nself.setToolTip('Drag to an input port')\nself.palette().setColor(QtGui.QPalette.WindowText, CurrentTheme.HOVER_DEFAULT_COLOR)", "if event.t...
<|body_start_0|> QtGui.QLabel.__init__(self, parent) self.var_type = var_type self.setText(var_type) self.setAttribute(QtCore.Qt.WA_Hover) self.setCursor(CurrentTheme.OPEN_HAND_CURSOR) self.setToolTip('Drag to an input port') self.palette().setColor(QtGui.QPalette...
QDragVariableLabel is a QLabel that can be dragged to connect to an input port
QDragVariableLabel
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QDragVariableLabel: """QDragVariableLabel is a QLabel that can be dragged to connect to an input port""" def __init__(self, var_type='', parent=None): """QDragVariableLabel(var_type:str, parent: QWidget) -> QDragVariableLabel Initialize the label with a variable type""" <|bod...
stack_v2_sparse_classes_36k_train_002489
22,077
permissive
[ { "docstring": "QDragVariableLabel(var_type:str, parent: QWidget) -> QDragVariableLabel Initialize the label with a variable type", "name": "__init__", "signature": "def __init__(self, var_type='', parent=None)" }, { "docstring": "event(event: QEvent) -> Event Result Override to handle hover ent...
3
null
Implement the Python class `QDragVariableLabel` described below. Class description: QDragVariableLabel is a QLabel that can be dragged to connect to an input port Method signatures and docstrings: - def __init__(self, var_type='', parent=None): QDragVariableLabel(var_type:str, parent: QWidget) -> QDragVariableLabel I...
Implement the Python class `QDragVariableLabel` described below. Class description: QDragVariableLabel is a QLabel that can be dragged to connect to an input port Method signatures and docstrings: - def __init__(self, var_type='', parent=None): QDragVariableLabel(var_type:str, parent: QWidget) -> QDragVariableLabel I...
23ef56ec24b85c82416e1437a08381635328abe5
<|skeleton|> class QDragVariableLabel: """QDragVariableLabel is a QLabel that can be dragged to connect to an input port""" def __init__(self, var_type='', parent=None): """QDragVariableLabel(var_type:str, parent: QWidget) -> QDragVariableLabel Initialize the label with a variable type""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QDragVariableLabel: """QDragVariableLabel is a QLabel that can be dragged to connect to an input port""" def __init__(self, var_type='', parent=None): """QDragVariableLabel(var_type:str, parent: QWidget) -> QDragVariableLabel Initialize the label with a variable type""" QtGui.QLabel.__ini...
the_stack_v2_python_sparse
vistrails_current/vistrails/gui/variable_dropbox.py
lumig242/VisTrailsRecommendation
train
3
38a66dee3a4e4909bad75891f1ba00c0cf5b096b
[ "if not isinstance(heuristic_function, HeuristicFunction):\n raise TypeError('Expected HeursiticFunction, got %s.' % type(heuristic_function))\nif not isinstance(layer_generator, LayerGenerator):\n raise TypeError('Expected LayerGenerator, got %s.' % type(layer_generator))\nif not is_real_number(success_thres...
<|body_start_0|> if not isinstance(heuristic_function, HeuristicFunction): raise TypeError('Expected HeursiticFunction, got %s.' % type(heuristic_function)) if not isinstance(layer_generator, LayerGenerator): raise TypeError('Expected LayerGenerator, got %s.' % type(layer_generat...
The QSearchSynthesisPass class. References: Davis, Marc G., et al. “Towards Optimal Topology Aware Quantum Circuit Synthesis.” 2020 IEEE International Conference on Quantum Computing and Engineering (QCE). IEEE, 2020.
QSearchSynthesisPass
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QSearchSynthesisPass: """The QSearchSynthesisPass class. References: Davis, Marc G., et al. “Towards Optimal Topology Aware Quantum Circuit Synthesis.” 2020 IEEE International Conference on Quantum Computing and Engineering (QCE). IEEE, 2020.""" def __init__(self, heuristic_function: Heurist...
stack_v2_sparse_classes_36k_train_002490
6,623
permissive
[ { "docstring": "Construct a search-based synthesis pass. Args: heuristic_function (HeuristicFunction): The heuristic to guide search. layer_generator (LayerGenerator): The successor function to guide node expansion. success_threshold (float): The distance threshold that determines successful termintation. Measu...
2
stack_v2_sparse_classes_30k_train_006521
Implement the Python class `QSearchSynthesisPass` described below. Class description: The QSearchSynthesisPass class. References: Davis, Marc G., et al. “Towards Optimal Topology Aware Quantum Circuit Synthesis.” 2020 IEEE International Conference on Quantum Computing and Engineering (QCE). IEEE, 2020. Method signatu...
Implement the Python class `QSearchSynthesisPass` described below. Class description: The QSearchSynthesisPass class. References: Davis, Marc G., et al. “Towards Optimal Topology Aware Quantum Circuit Synthesis.” 2020 IEEE International Conference on Quantum Computing and Engineering (QCE). IEEE, 2020. Method signatu...
3083218c2f4e3c3ce4ba027d12caa30c384d7665
<|skeleton|> class QSearchSynthesisPass: """The QSearchSynthesisPass class. References: Davis, Marc G., et al. “Towards Optimal Topology Aware Quantum Circuit Synthesis.” 2020 IEEE International Conference on Quantum Computing and Engineering (QCE). IEEE, 2020.""" def __init__(self, heuristic_function: Heurist...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QSearchSynthesisPass: """The QSearchSynthesisPass class. References: Davis, Marc G., et al. “Towards Optimal Topology Aware Quantum Circuit Synthesis.” 2020 IEEE International Conference on Quantum Computing and Engineering (QCE). IEEE, 2020.""" def __init__(self, heuristic_function: HeuristicFunction=AS...
the_stack_v2_python_sparse
bqskit/compiler/passes/synthesis/qsearch.py
mtreinish/bqskit
train
0
13fe935f5c7f0b7b3fde3dc1a7255e2ee92cb7d2
[ "if value is not None:\n if isinstance(value, str):\n value = value.encode('utf8')\n value = compress_string(value)\n value = value.encode('base64').decode('utf8')\nreturn value", "if isinstance(value, str):\n value = decompress_string(value)\nreturn value" ]
<|body_start_0|> if value is not None: if isinstance(value, str): value = value.encode('utf8') value = compress_string(value) value = value.encode('base64').decode('utf8') return value <|end_body_0|> <|body_start_1|> if isinstance(value, str):...
TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database.
CompressedTextField
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompressedTextField: """TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database.""" def get_prep_value(self, value): """Compress the text data.""" <|body_0|> def to_python(self, value): ...
stack_v2_sparse_classes_36k_train_002491
2,159
permissive
[ { "docstring": "Compress the text data.", "name": "get_prep_value", "signature": "def get_prep_value(self, value)" }, { "docstring": "Decompresses the value from the database.", "name": "to_python", "signature": "def to_python(self, value)" } ]
2
null
Implement the Python class `CompressedTextField` described below. Class description: TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database. Method signatures and docstrings: - def get_prep_value(self, value): Compress the text data. - ...
Implement the Python class `CompressedTextField` described below. Class description: TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database. Method signatures and docstrings: - def get_prep_value(self, value): Compress the text data. - ...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class CompressedTextField: """TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database.""" def get_prep_value(self, value): """Compress the text data.""" <|body_0|> def to_python(self, value): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompressedTextField: """TextField that transparently compresses data when saving to the database, and decompresses the data when retrieving it from the database.""" def get_prep_value(self, value): """Compress the text data.""" if value is not None: if isinstance(value, str): ...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/djangoapps/util/models.py
luque/better-ways-of-thinking-about-software
train
3
90b61c67022ddea582804ac8952d825dac68f539
[ "result = api.neutron.subnet_list(request, **request.GET)\nif request.GET.get('ensure_with_router', False):\n result = rest_utils.ensure_subnet_with_router(request, result)\nresult = rest_utils.ensure_network_detial_for_subnet(request, [n.to_dict() for n in result])\nreturn {'items': result}", "new_subnet = ap...
<|body_start_0|> result = api.neutron.subnet_list(request, **request.GET) if request.GET.get('ensure_with_router', False): result = rest_utils.ensure_subnet_with_router(request, result) result = rest_utils.ensure_network_detial_for_subnet(request, [n.to_dict() for n in result]) ...
API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets
Subnets
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subnets: """API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets""" def get(self, request): """Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet.""" <|body_0|> def post(se...
stack_v2_sparse_classes_36k_train_002492
30,067
permissive
[ { "docstring": "Get a list of subnets for a project The listing result is an object with property \"items\". Each item is a subnet.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a Subnet for a given Network :param name (optional): The subnet name. :param networ...
2
null
Implement the Python class `Subnets` described below. Class description: API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets Method signatures and docstrings: - def get(self, request): Get a list of subnets for a project The listing result is an object with property "items". Each...
Implement the Python class `Subnets` described below. Class description: API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets Method signatures and docstrings: - def get(self, request): Get a list of subnets for a project The listing result is an object with property "items". Each...
9524f1952461c83db485d5d1702c350b158d7ce0
<|skeleton|> class Subnets: """API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets""" def get(self, request): """Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet.""" <|body_0|> def post(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Subnets: """API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets""" def get(self, request): """Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet.""" result = api.neutron.subnet_list(request...
the_stack_v2_python_sparse
easystack_dashboard/api/rest/neutron.py
oksbsb/horizon-acc
train
0
3caf22232286cb18ae1219732c1206af67a9b262
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Proto file describing the keyword plan ad group service. Service to manage Keyword Plan ad groups.
KeywordPlanAdGroupServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeywordPlanAdGroupServiceServicer: """Proto file describing the keyword plan ad group service. Service to manage Keyword Plan ad groups.""" def GetKeywordPlanAdGroup(self, request, context): """Returns the requested Keyword Plan ad group in full detail.""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_002493
3,720
permissive
[ { "docstring": "Returns the requested Keyword Plan ad group in full detail.", "name": "GetKeywordPlanAdGroup", "signature": "def GetKeywordPlanAdGroup(self, request, context)" }, { "docstring": "Creates, updates, or removes Keyword Plan ad groups. Operation statuses are returned.", "name": "...
2
stack_v2_sparse_classes_30k_train_005146
Implement the Python class `KeywordPlanAdGroupServiceServicer` described below. Class description: Proto file describing the keyword plan ad group service. Service to manage Keyword Plan ad groups. Method signatures and docstrings: - def GetKeywordPlanAdGroup(self, request, context): Returns the requested Keyword Pla...
Implement the Python class `KeywordPlanAdGroupServiceServicer` described below. Class description: Proto file describing the keyword plan ad group service. Service to manage Keyword Plan ad groups. Method signatures and docstrings: - def GetKeywordPlanAdGroup(self, request, context): Returns the requested Keyword Pla...
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
<|skeleton|> class KeywordPlanAdGroupServiceServicer: """Proto file describing the keyword plan ad group service. Service to manage Keyword Plan ad groups.""" def GetKeywordPlanAdGroup(self, request, context): """Returns the requested Keyword Plan ad group in full detail.""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeywordPlanAdGroupServiceServicer: """Proto file describing the keyword plan ad group service. Service to manage Keyword Plan ad groups.""" def GetKeywordPlanAdGroup(self, request, context): """Returns the requested Keyword Plan ad group in full detail.""" context.set_code(grpc.StatusCode...
the_stack_v2_python_sparse
google/ads/google_ads/v3/proto/services/keyword_plan_ad_group_service_pb2_grpc.py
fiboknacky/google-ads-python
train
0
c228545508f8bd41e887a0aaacb2167d5bc5ea39
[ "super(Triangle, self).__init__(element_id, unit_length)\nassert size in range(3)\nself.size = size", "super(Triangle, self).init(points)\nif self.element_id in ['1', '2']:\n self.segments += [Segment(p1=self.points[i], p2=self.segments[(i + 1) % 3].midpoint) for i in range(3)]", "self.state = position // AN...
<|body_start_0|> super(Triangle, self).__init__(element_id, unit_length) assert size in range(3) self.size = size <|end_body_0|> <|body_start_1|> super(Triangle, self).init(points) if self.element_id in ['1', '2']: self.segments += [Segment(p1=self.points[i], p2=self...
Class for triangle. Note that point0 is right angle vertex.
Triangle
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Triangle: """Class for triangle. Note that point0 is right angle vertex.""" def __init__(self, element_id, size=0, unit_length=0.0): """Input: size: 0 means small, 1 means medium, 2 means large""" <|body_0|> def init(self, points): """For triangle, I think we sho...
stack_v2_sparse_classes_36k_train_002494
17,615
permissive
[ { "docstring": "Input: size: 0 means small, 1 means medium, 2 means large", "name": "__init__", "signature": "def __init__(self, element_id, size=0, unit_length=0.0)" }, { "docstring": "For triangle, I think we should add more segments.", "name": "init", "signature": "def init(self, poin...
6
stack_v2_sparse_classes_30k_test_000897
Implement the Python class `Triangle` described below. Class description: Class for triangle. Note that point0 is right angle vertex. Method signatures and docstrings: - def __init__(self, element_id, size=0, unit_length=0.0): Input: size: 0 means small, 1 means medium, 2 means large - def init(self, points): For tri...
Implement the Python class `Triangle` described below. Class description: Class for triangle. Note that point0 is right angle vertex. Method signatures and docstrings: - def __init__(self, element_id, size=0, unit_length=0.0): Input: size: 0 means small, 1 means medium, 2 means large - def init(self, points): For tri...
dcc26a99343e7d29199662ef3c9bf63f29513381
<|skeleton|> class Triangle: """Class for triangle. Note that point0 is right angle vertex.""" def __init__(self, element_id, size=0, unit_length=0.0): """Input: size: 0 means small, 1 means medium, 2 means large""" <|body_0|> def init(self, points): """For triangle, I think we sho...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Triangle: """Class for triangle. Note that point0 is right angle vertex.""" def __init__(self, element_id, size=0, unit_length=0.0): """Input: size: 0 means small, 1 means medium, 2 means large""" super(Triangle, self).__init__(element_id, unit_length) assert size in range(3) ...
the_stack_v2_python_sparse
normal_tangram/tangram_element.py
Wuziyi616/Artificial_Intelligence_Project1
train
12
b8f5fe6f883429ea655714b07357dd2885b2ff2b
[ "self.pool_size = pool_size\nif self.pool_size > 0:\n self.num_clips = 0\n self.clips = []", "if self.pool_size == 0:\n return clips\nreturn_clips = list()\nfor clip in clips:\n clip = torch.unsqueeze(clip.data, 0)\n if self.num_clips < self.pool_size:\n self.num_clips = self.num_clips + 1\n...
<|body_start_0|> self.pool_size = pool_size if self.pool_size > 0: self.num_clips = 0 self.clips = [] <|end_body_0|> <|body_start_1|> if self.pool_size == 0: return clips return_clips = list() for clip in clips: clip = torch.unsque...
This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators.
AudioPool
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AudioPool: """This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators.""" def __init__(self, pool_size): """Initialize the...
stack_v2_sparse_classes_36k_train_002495
2,211
permissive
[ { "docstring": "Initialize the ImagePool class Parameters: pool_size (int) -- the size of image buffer, if pool_size=0, no buffer will be created", "name": "__init__", "signature": "def __init__(self, pool_size)" }, { "docstring": "Return an image from the pool. Parameters: images: the latest ge...
2
null
Implement the Python class `AudioPool` described below. Class description: This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Method signatures and do...
Implement the Python class `AudioPool` described below. Class description: This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. Method signatures and do...
0aa9e8763597bf86ff0c13ae96dee75d165c4fc2
<|skeleton|> class AudioPool: """This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators.""" def __init__(self, pool_size): """Initialize the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AudioPool: """This class implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators.""" def __init__(self, pool_size): """Initialize the ImagePool cl...
the_stack_v2_python_sparse
styletransfer/util/audio_pool.py
jaeyeun97/MusicalStyleTransfer
train
1
4dbc70a9ca29603ffefacfff89f8bf0eb68e290b
[ "self.diff_args = diff_args\nself.cwd = cwd\nself.temp_dir = tempfile.mkdtemp()\nself.debug = debug\nself.vcs_helper = VCSHelper.get_helper(self.cwd, debug=self.debug)\nself.changed_files = self.vcs_helper.get_changed_files(self.diff_args)\nself.changed_hunks = []\nfor f in self.changed_files:\n self.changed_hun...
<|body_start_0|> self.diff_args = diff_args self.cwd = cwd self.temp_dir = tempfile.mkdtemp() self.debug = debug self.vcs_helper = VCSHelper.get_helper(self.cwd, debug=self.debug) self.changed_files = self.vcs_helper.get_changed_files(self.diff_args) self.changed_...
Class for handling understanding and parsing a specific diff. This class represents the entire diff.
DiffParser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiffParser: """Class for handling understanding and parsing a specific diff. This class represents the entire diff.""" def __init__(self, diff_args, cwd, debug=False, get_diff_headers=False): """Constructor. Args: diff_args: The arguments to be used for the Git diff. cwd: The working...
stack_v2_sparse_classes_36k_train_002496
2,727
permissive
[ { "docstring": "Constructor. Args: diff_args: The arguments to be used for the Git diff. cwd: The working directory. get_diff_headers: Whether we want per-file header hunks for this diff.", "name": "__init__", "signature": "def __init__(self, diff_args, cwd, debug=False, get_diff_headers=False)" }, ...
2
stack_v2_sparse_classes_30k_train_003290
Implement the Python class `DiffParser` described below. Class description: Class for handling understanding and parsing a specific diff. This class represents the entire diff. Method signatures and docstrings: - def __init__(self, diff_args, cwd, debug=False, get_diff_headers=False): Constructor. Args: diff_args: Th...
Implement the Python class `DiffParser` described below. Class description: Class for handling understanding and parsing a specific diff. This class represents the entire diff. Method signatures and docstrings: - def __init__(self, diff_args, cwd, debug=False, get_diff_headers=False): Constructor. Args: diff_args: Th...
17afe53e4a96c80f0a43093f5ea21d61c42a090b
<|skeleton|> class DiffParser: """Class for handling understanding and parsing a specific diff. This class represents the entire diff.""" def __init__(self, diff_args, cwd, debug=False, get_diff_headers=False): """Constructor. Args: diff_args: The arguments to be used for the Git diff. cwd: The working...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiffParser: """Class for handling understanding and parsing a specific diff. This class represents the entire diff.""" def __init__(self, diff_args, cwd, debug=False, get_diff_headers=False): """Constructor. Args: diff_args: The arguments to be used for the Git diff. cwd: The working directory. g...
the_stack_v2_python_sparse
parser/diff_parser.py
CJTozer/SublimeDiffView
train
23
d9cf2b4323bf234e810412b1ebd20ab94330dea4
[ "super().__init__(group=None, target=None, name='CheckpointWorker')\nself.notify = notify\nself.patterns = patterns", "while True:\n self.notify.wait(timeout=None)\n self.log.debug('got notification, starting work')\n matched_files = CheckpointWorker.get_matched_filenames(self.patterns)\n CheckpointWo...
<|body_start_0|> super().__init__(group=None, target=None, name='CheckpointWorker') self.notify = notify self.patterns = patterns <|end_body_0|> <|body_start_1|> while True: self.notify.wait(timeout=None) self.log.debug('got notification, starting work') ...
Thread to handle saving and staging out checkpoint files.
CheckpointWorker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CheckpointWorker: """Thread to handle saving and staging out checkpoint files.""" def __init__(self, notify: threading.Event, patterns: List[str]): """Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param...
stack_v2_sparse_classes_36k_train_002497
9,748
permissive
[ { "docstring": "Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param patterns: regex file patterns to match :type patterns: List[str]", "name": "__init__", "signature": "def __init__(self, notify: threading.Event, patterns:...
4
stack_v2_sparse_classes_30k_test_000518
Implement the Python class `CheckpointWorker` described below. Class description: Thread to handle saving and staging out checkpoint files. Method signatures and docstrings: - def __init__(self, notify: threading.Event, patterns: List[str]): Constructor :param notify: event to watch for, which will indicate that this...
Implement the Python class `CheckpointWorker` described below. Class description: Thread to handle saving and staging out checkpoint files. Method signatures and docstrings: - def __init__(self, notify: threading.Event, patterns: List[str]): Constructor :param notify: event to watch for, which will indicate that this...
6b7e41d7ebfacca23d853890937e593a248e6a6a
<|skeleton|> class CheckpointWorker: """Thread to handle saving and staging out checkpoint files.""" def __init__(self, notify: threading.Event, patterns: List[str]): """Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CheckpointWorker: """Thread to handle saving and staging out checkpoint files.""" def __init__(self, notify: threading.Event, patterns: List[str]): """Constructor :param notify: event to watch for, which will indicate that this thread needs to run :type notify: threading.Event :param patterns: re...
the_stack_v2_python_sparse
packages/pegasus-worker/src/Pegasus/cli/pegasus-checkpoint.py
pegasus-isi/pegasus
train
156
20371ad801e304ef0dbea40b3b182db9b276deb9
[ "self.pos = set([(0, 0)])\nself.snake = deque([(0, 0)])\nself.n = height\nself.m = width\nself.food = food\nself.dir = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}", "head = self.snake[0]\nnext_head = (head[0] + self.dir[direction][0], head[1] + self.dir[direction][1])\ntail = self.snake.pop()\nself.pos...
<|body_start_0|> self.pos = set([(0, 0)]) self.snake = deque([(0, 0)]) self.n = height self.m = width self.food = food self.dir = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)} <|end_body_0|> <|body_start_1|> head = self.snake[0] next_head = (head...
SnakeGame
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t...
stack_v2_sparse_classes_36k_train_002498
1,725
no_license
[ { "docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].", "name": "__init__", "signature": "def __init__(self, widt...
2
null
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
Implement the Python class `SnakeGame` described below. Class description: Implement the SnakeGame class. Method signatures and docstrings: - def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -...
355c0dbd32ad201800901f1bcc110550696bc96d
<|skeleton|> class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): """Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a...
the_stack_v2_python_sparse
LeetCode/codes/Games/353.py
adreena/MyStudyCorner
train
0
9e71414b936cdf0b023ceceb133694f1a426fddb
[ "m = {'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05', 'jun': '06', 'jul': '07', 'aug': '08', 'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'}\ns = month_name.strip()[:3].lower()\ntry:\n out = m[s]\n return out\nexcept Exception:\n raise ValueError('Not a month')", "m = {'SXF': 'BERL',...
<|body_start_0|> m = {'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05', 'jun': '06', 'jul': '07', 'aug': '08', 'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'} s = month_name.strip()[:3].lower() try: out = m[s] return out except Exception: ...
DataManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataManager: def month_string_to_number(cls, month_name): """:param month_name: shortcut of month's name :type month_name: str :return: the number of month :rtype: str""" <|body_0|> def transfer_airport_cod_names_to_all(cls, short_name): """:param short_name the code...
stack_v2_sparse_classes_36k_train_002499
2,818
no_license
[ { "docstring": ":param month_name: shortcut of month's name :type month_name: str :return: the number of month :rtype: str", "name": "month_string_to_number", "signature": "def month_string_to_number(cls, month_name)" }, { "docstring": ":param short_name the code name airport :type short_name st...
2
stack_v2_sparse_classes_30k_train_010725
Implement the Python class `DataManager` described below. Class description: Implement the DataManager class. Method signatures and docstrings: - def month_string_to_number(cls, month_name): :param month_name: shortcut of month's name :type month_name: str :return: the number of month :rtype: str - def transfer_airpo...
Implement the Python class `DataManager` described below. Class description: Implement the DataManager class. Method signatures and docstrings: - def month_string_to_number(cls, month_name): :param month_name: shortcut of month's name :type month_name: str :return: the number of month :rtype: str - def transfer_airpo...
d91de9c1f76b979ec16f5684f80336a09f429e99
<|skeleton|> class DataManager: def month_string_to_number(cls, month_name): """:param month_name: shortcut of month's name :type month_name: str :return: the number of month :rtype: str""" <|body_0|> def transfer_airport_cod_names_to_all(cls, short_name): """:param short_name the code...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataManager: def month_string_to_number(cls, month_name): """:param month_name: shortcut of month's name :type month_name: str :return: the number of month :rtype: str""" m = {'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05', 'jun': '06', 'jul': '07', 'aug': '08', 'sep': '09', '...
the_stack_v2_python_sparse
Data/DataManager.py
ziper02/TravelScanner
train
0