blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
c9be786a7bc279628ab12e1d941a4a802ac30cf5
[ "try:\n coconut_id = coconut.__class__.__name__ + '_' + str(coconut.weight)\n if isinstance(coconut, Coconut):\n if coconut_id in self.coconut_counts:\n self.coconut_counts[coconut_id] += number\n else:\n self.coconut_counts[coconut_id] = number\n else:\n raise At...
<|body_start_0|> try: coconut_id = coconut.__class__.__name__ + '_' + str(coconut.weight) if isinstance(coconut, Coconut): if coconut_id in self.coconut_counts: self.coconut_counts[coconut_id] += number else: self.co...
Inventory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Inventory: def add_coconut(self, coconut=None, number=0): """Add n coconuts to inventory""" <|body_0|> def remove_coconut(self, coconut=None, number=0): """Remove n coconuts from inventory""" <|body_1|> def display_inventory(self): """Display inv...
stack_v2_sparse_classes_75kplus_train_068100
3,825
no_license
[ { "docstring": "Add n coconuts to inventory", "name": "add_coconut", "signature": "def add_coconut(self, coconut=None, number=0)" }, { "docstring": "Remove n coconuts from inventory", "name": "remove_coconut", "signature": "def remove_coconut(self, coconut=None, number=0)" }, { "...
3
stack_v2_sparse_classes_30k_train_044433
Implement the Python class `Inventory` described below. Class description: Implement the Inventory class. Method signatures and docstrings: - def add_coconut(self, coconut=None, number=0): Add n coconuts to inventory - def remove_coconut(self, coconut=None, number=0): Remove n coconuts from inventory - def display_in...
Implement the Python class `Inventory` described below. Class description: Implement the Inventory class. Method signatures and docstrings: - def add_coconut(self, coconut=None, number=0): Add n coconuts to inventory - def remove_coconut(self, coconut=None, number=0): Remove n coconuts from inventory - def display_in...
f51c1d2d9557c95e869cbce5bff7158f5aa90192
<|skeleton|> class Inventory: def add_coconut(self, coconut=None, number=0): """Add n coconuts to inventory""" <|body_0|> def remove_coconut(self, coconut=None, number=0): """Remove n coconuts from inventory""" <|body_1|> def display_inventory(self): """Display inv...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Inventory: def add_coconut(self, coconut=None, number=0): """Add n coconuts to inventory""" try: coconut_id = coconut.__class__.__name__ + '_' + str(coconut.weight) if isinstance(coconut, Coconut): if coconut_id in self.coconut_counts: ...
the_stack_v2_python_sparse
Python 03: The Python Environment/Lesson 02: Converting Data into Structured Objects/coconuts.py
MTset/Python-Programming-Coursework
train
0
c7c0d475d7f359322f3080ceccd7a4f111d528d9
[ "temp = 0\ny = x\nif x < 0:\n return False\nelif x == 0:\n return True\nelif x > 0:\n while x:\n temp = temp * 10 + x % 10\n x = int(x / 10)\n if temp == y:\n return True\n else:\n return False", "new_x = x\nres = 0\nif x < 0:\n return False\nwhile new_x >= 1:\n a ...
<|body_start_0|> temp = 0 y = x if x < 0: return False elif x == 0: return True elif x > 0: while x: temp = temp * 10 + x % 10 x = int(x / 10) if temp == y: return True els...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, x: int) -> bool: """思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:""" <|body_0|> def isPalindrome2(self, x: int) -> ...
stack_v2_sparse_classes_75kplus_train_068101
1,619
no_license
[ { "docstring": "思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:", "name": "isPalindrome", "signature": "def isPalindrome(self, x: int) -> bool" }, { "docstring": "2020年6月1...
2
stack_v2_sparse_classes_30k_train_051825
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x: int) -> bool: 思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x: int) -> bool: 思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因...
578cacff5851c5c2522981693c34e3c318002d30
<|skeleton|> class Solution: def isPalindrome(self, x: int) -> bool: """思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:""" <|body_0|> def isPalindrome2(self, x: int) -> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isPalindrome(self, x: int) -> bool: """思路是设置一个为0的整数tmp,输入的数(x)取余拿到末尾数 tmp*10拿到首位数字加上末尾数得到新的tmp的第一个数 以此类推完整的倒序整个输入的x。 需要注意的有两点 1、每次过后x必须除以10再取整,保证每次都取到的是最后一位数字 2、必须要把x备份一下,否则过程中因为除以10了,x的结果会变成0 :param x: :return:""" temp = 0 y = x if x < 0: return False...
the_stack_v2_python_sparse
回文数.py
cjrzs/MyLeetCode
train
8
1d1c309cb307e861c7e6728ad8d18039797e7c89
[ "if not head or not head.next:\n return head\nfirstNode = head\nsecondNode = head.next\nfirstNode.next = self.swapPairs(secondNode.next)\nsecondNode.next = firstNode\nreturn secondNode", "dummyNode = ListNode(0)\ndummyNode.next = head\npreNode = dummyNode\nwhile head and head.next:\n firstNode = head\n s...
<|body_start_0|> if not head or not head.next: return head firstNode = head secondNode = head.next firstNode.next = self.swapPairs(secondNode.next) secondNode.next = firstNode return secondNode <|end_body_0|> <|body_start_1|> dummyNode = ListNode(0) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def swapPairs(self, head): """递归处理""" <|body_0|> def fun2(self, head): """迭代处理 1. 维护好待交换两节点的前驱和后继 2. 搞清楚待交换两节点的前驱和后继""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head or not head.next: return head firstNode = ...
stack_v2_sparse_classes_75kplus_train_068102
1,289
no_license
[ { "docstring": "递归处理", "name": "swapPairs", "signature": "def swapPairs(self, head)" }, { "docstring": "迭代处理 1. 维护好待交换两节点的前驱和后继 2. 搞清楚待交换两节点的前驱和后继", "name": "fun2", "signature": "def fun2(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_030516
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs(self, head): 递归处理 - def fun2(self, head): 迭代处理 1. 维护好待交换两节点的前驱和后继 2. 搞清楚待交换两节点的前驱和后继
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def swapPairs(self, head): 递归处理 - def fun2(self, head): 迭代处理 1. 维护好待交换两节点的前驱和后继 2. 搞清楚待交换两节点的前驱和后继 <|skeleton|> class Solution: def swapPairs(self, head): """递归处理""...
0b10f5731690da7998add288e4b0b87d5d71a97e
<|skeleton|> class Solution: def swapPairs(self, head): """递归处理""" <|body_0|> def fun2(self, head): """迭代处理 1. 维护好待交换两节点的前驱和后继 2. 搞清楚待交换两节点的前驱和后继""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def swapPairs(self, head): """递归处理""" if not head or not head.next: return head firstNode = head secondNode = head.next firstNode.next = self.swapPairs(secondNode.next) secondNode.next = firstNode return secondNode def fun2(sel...
the_stack_v2_python_sparse
leetcode/leetcode/24.两两交换链表中的节点.py
GGL12/myStudy
train
0
5efc1a278ac51ce79b8faa4b12fa1b9fb508245a
[ "self.__users_collection = users_collection\nself.__id_column = id_column\nself.__status_column = status_column\nself.__params_column = params_column\nself.__free_status = free_status\nself.__storage = storage\nself.__with_params = with_params", "columns = [self.__status_column]\nresponse = self.__storage.get_dat...
<|body_start_0|> self.__users_collection = users_collection self.__id_column = id_column self.__status_column = status_column self.__params_column = params_column self.__free_status = free_status self.__storage = storage self.__with_params = with_params <|end_body...
Class for managing users' state
StateManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StateManager: """Class for managing users' state""" def __init__(self, storage: Storage, users_collection: str='Users', id_column: str='_id', status_column: str='State', params_column: str='State_Params', free_status: str='free', with_params: bool=False): """Parameters ---------- sto...
stack_v2_sparse_classes_75kplus_train_068103
5,892
permissive
[ { "docstring": "Parameters ---------- storage : Storage pointer to the inherited class from Storage (i.e MongoDBStorage) users_collection : str, optional name of id column from users_collection, by default \"Users\" id_column : str, optional name of id column from users_collection, by default \"_id\" status_col...
6
stack_v2_sparse_classes_30k_train_050755
Implement the Python class `StateManager` described below. Class description: Class for managing users' state Method signatures and docstrings: - def __init__(self, storage: Storage, users_collection: str='Users', id_column: str='_id', status_column: str='State', params_column: str='State_Params', free_status: str='f...
Implement the Python class `StateManager` described below. Class description: Class for managing users' state Method signatures and docstrings: - def __init__(self, storage: Storage, users_collection: str='Users', id_column: str='_id', status_column: str='State', params_column: str='State_Params', free_status: str='f...
7bf107b448cdd0e5d7f1cf85726b06c677ed922d
<|skeleton|> class StateManager: """Class for managing users' state""" def __init__(self, storage: Storage, users_collection: str='Users', id_column: str='_id', status_column: str='State', params_column: str='State_Params', free_status: str='free', with_params: bool=False): """Parameters ---------- sto...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StateManager: """Class for managing users' state""" def __init__(self, storage: Storage, users_collection: str='Users', id_column: str='_id', status_column: str='State', params_column: str='State_Params', free_status: str='free', with_params: bool=False): """Parameters ---------- storage : Storag...
the_stack_v2_python_sparse
advancedbot/components/state_managing/statemanager.py
sdallaboratory/advanced-telegram-bot
train
6
555a63e5f144891b5bae20501841a74ac1937e8c
[ "self.name = name\nself.age = age\nself.favourite_food = food\nself.mood = 'Happy'", "if self.favourite_food == food:\n self.mood = 'ecstatic'\n print('Ah, this is my favourite!')" ]
<|body_start_0|> self.name = name self.age = age self.favourite_food = food self.mood = 'Happy' <|end_body_0|> <|body_start_1|> if self.favourite_food == food: self.mood = 'ecstatic' print('Ah, this is my favourite!') <|end_body_1|>
Person
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Person: def __init__(self, name, age, food): """(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.""" <|body_0|> def eat(self, food): """Person, string) -> NoneType Make this person eat the food. Change the ...
stack_v2_sparse_classes_75kplus_train_068104
678
permissive
[ { "docstring": "(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.", "name": "__init__", "signature": "def __init__(self, name, age, food)" }, { "docstring": "Person, string) -> NoneType Make this person eat the food. Change the mood of...
2
stack_v2_sparse_classes_30k_train_053690
Implement the Python class `Person` described below. Class description: Implement the Person class. Method signatures and docstrings: - def __init__(self, name, age, food): (Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood. - def eat(self, food): Person, str...
Implement the Python class `Person` described below. Class description: Implement the Person class. Method signatures and docstrings: - def __init__(self, name, age, food): (Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood. - def eat(self, food): Person, str...
37009dfdbef9a15c2851bcca2a4e029267e6a02d
<|skeleton|> class Person: def __init__(self, name, age, food): """(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.""" <|body_0|> def eat(self, food): """Person, string) -> NoneType Make this person eat the food. Change the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Person: def __init__(self, name, age, food): """(Person, string, int, string) -> NoneType Create new Person object with given, name, age, and favourite foood.""" self.name = name self.age = age self.favourite_food = food self.mood = 'Happy' def eat(self, food): ...
the_stack_v2_python_sparse
uoft/CSC148H1F Intro to Comp Sci/@week1_object_oriented/@@playground/class.py
Reginald-Lee/biji-ben
train
0
fef474436fa23697a0539df0fe47ed146f3b3b78
[ "self.__buckets = []\nfor num in range(size):\n self.__list = SortedList()\n self.__buckets.append(self.__list)", "table = ''\nfor num in range(len(self.__buckets)):\n table += '{%3i}%s\\n' % (self.__buckets[num].size(), str(self.__buckets[num]))\nreturn table", "code = int(hash_code(value))\npos = int...
<|body_start_0|> self.__buckets = [] for num in range(size): self.__list = SortedList() self.__buckets.append(self.__list) <|end_body_0|> <|body_start_1|> table = '' for num in range(len(self.__buckets)): table += '{%3i}%s\n' % (self.__buckets[num].si...
HashTable
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HashTable: def __init__(self, size): """H(size) creates a hash table with the desired size""" <|body_0|> def __str__(self): """H.__str__() or H --> str Returns the string representations of a hash table.""" <|body_1|> def insert(self, value): """...
stack_v2_sparse_classes_75kplus_train_068105
6,278
no_license
[ { "docstring": "H(size) creates a hash table with the desired size", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": "H.__str__() or H --> str Returns the string representations of a hash table.", "name": "__str__", "signature": "def __str__(self)" }, { ...
6
stack_v2_sparse_classes_30k_train_011706
Implement the Python class `HashTable` described below. Class description: Implement the HashTable class. Method signatures and docstrings: - def __init__(self, size): H(size) creates a hash table with the desired size - def __str__(self): H.__str__() or H --> str Returns the string representations of a hash table. -...
Implement the Python class `HashTable` described below. Class description: Implement the HashTable class. Method signatures and docstrings: - def __init__(self, size): H(size) creates a hash table with the desired size - def __str__(self): H.__str__() or H --> str Returns the string representations of a hash table. -...
ff38fb7cb7d0ee9abd02014d4c13e161d9647a17
<|skeleton|> class HashTable: def __init__(self, size): """H(size) creates a hash table with the desired size""" <|body_0|> def __str__(self): """H.__str__() or H --> str Returns the string representations of a hash table.""" <|body_1|> def insert(self, value): """...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HashTable: def __init__(self, size): """H(size) creates a hash table with the desired size""" self.__buckets = [] for num in range(size): self.__list = SortedList() self.__buckets.append(self.__list) def __str__(self): """H.__str__() or H --> str Re...
the_stack_v2_python_sparse
Task 2/hash_table.py
jsinoimeri/Gr12-Python
train
0
a64abaf0507f14698fb3a52090b09af888be8e4b
[ "youtify_user_model = get_current_youtify_user_model()\nif youtify_user_model == None:\n self.error(403)\n return\nplaylist_id = self.request.path.split('/')[-1]\nplaylist_model = Playlist.get_by_id(int(playlist_id))\njson = self.request.get('json', None)\ndevice = self.request.get('device')\nif json is None:...
<|body_start_0|> youtify_user_model = get_current_youtify_user_model() if youtify_user_model == None: self.error(403) return playlist_id = self.request.path.split('/')[-1] playlist_model = Playlist.get_by_id(int(playlist_id)) json = self.request.get('json'...
FavoriteHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FavoriteHandler: def post(self): """Add a track to the favorite list""" <|body_0|> def delete(self): """Remove a track from favorites""" <|body_1|> <|end_skeleton|> <|body_start_0|> youtify_user_model = get_current_youtify_user_model() if yo...
stack_v2_sparse_classes_75kplus_train_068106
2,421
permissive
[ { "docstring": "Add a track to the favorite list", "name": "post", "signature": "def post(self)" }, { "docstring": "Remove a track from favorites", "name": "delete", "signature": "def delete(self)" } ]
2
stack_v2_sparse_classes_30k_train_042626
Implement the Python class `FavoriteHandler` described below. Class description: Implement the FavoriteHandler class. Method signatures and docstrings: - def post(self): Add a track to the favorite list - def delete(self): Remove a track from favorites
Implement the Python class `FavoriteHandler` described below. Class description: Implement the FavoriteHandler class. Method signatures and docstrings: - def post(self): Add a track to the favorite list - def delete(self): Remove a track from favorites <|skeleton|> class FavoriteHandler: def post(self): ...
1855f242f15a9a66a8868ced849ddd77385426e7
<|skeleton|> class FavoriteHandler: def post(self): """Add a track to the favorite list""" <|body_0|> def delete(self): """Remove a track from favorites""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FavoriteHandler: def post(self): """Add a track to the favorite list""" youtify_user_model = get_current_youtify_user_model() if youtify_user_model == None: self.error(403) return playlist_id = self.request.path.split('/')[-1] playlist_model = Pl...
the_stack_v2_python_sparse
favorites.py
blen2r/youtify
train
0
ffebc5f1eb3aa791cc80d3e3f90a7077aafa4792
[ "assert 0.0 <= learning_rate <= 1, 'Invalid learning rate'\nself._num_elites = num_elites\nself._lr = learning_rate", "assert self._num_elites <= trajectories.discount.shape[0], 'num_elites needs to be smaller than population size'\nassert tf.equal(tf.reduce_all(trajectories.is_boundary()[:, :-1]), False), 'No tr...
<|body_start_0|> assert 0.0 <= learning_rate <= 1, 'Invalid learning rate' self._num_elites = num_elites self._lr = learning_rate <|end_body_0|> <|body_start_1|> assert self._num_elites <= trajectories.discount.shape[0], 'num_elites needs to be smaller than population size' asse...
This `PolicyStateUpdater` updates the policy state for the cross entropy method policy.
CrossEntropyMethodPolicyStateUpdater
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CrossEntropyMethodPolicyStateUpdater: """This `PolicyStateUpdater` updates the policy state for the cross entropy method policy.""" def __init__(self, num_elites: int, learning_rate: float): """:param num_elites: number of samples to use to update sampling distribution :param learnin...
stack_v2_sparse_classes_75kplus_train_068107
6,809
permissive
[ { "docstring": ":param num_elites: number of samples to use to update sampling distribution :param learning_rate: in [0,1] determines how quickly to update sampling distribution", "name": "__init__", "signature": "def __init__(self, num_elites: int, learning_rate: float)" }, { "docstring": "Upda...
2
stack_v2_sparse_classes_30k_train_019527
Implement the Python class `CrossEntropyMethodPolicyStateUpdater` described below. Class description: This `PolicyStateUpdater` updates the policy state for the cross entropy method policy. Method signatures and docstrings: - def __init__(self, num_elites: int, learning_rate: float): :param num_elites: number of samp...
Implement the Python class `CrossEntropyMethodPolicyStateUpdater` described below. Class description: This `PolicyStateUpdater` updates the policy state for the cross entropy method policy. Method signatures and docstrings: - def __init__(self, num_elites: int, learning_rate: float): :param num_elites: number of samp...
239a994cd7efc1054db5273a49befe2acc00c091
<|skeleton|> class CrossEntropyMethodPolicyStateUpdater: """This `PolicyStateUpdater` updates the policy state for the cross entropy method policy.""" def __init__(self, num_elites: int, learning_rate: float): """:param num_elites: number of samples to use to update sampling distribution :param learnin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CrossEntropyMethodPolicyStateUpdater: """This `PolicyStateUpdater` updates the policy state for the cross entropy method policy.""" def __init__(self, num_elites: int, learning_rate: float): """:param num_elites: number of samples to use to update sampling distribution :param learning_rate: in [0...
the_stack_v2_python_sparse
bellman/trajectory_optimisers/cross_entropy_method.py
Bellman-devs/bellman
train
49
ab8730795161ecb89426f9f0db37c162c2c1f894
[ "self.dic = {}\nfor word in set(dictionary):\n if word:\n if len(word) <= 2:\n if word not in self.dic:\n self.dic[word] = set()\n self.dic[word].add(word)\n else:\n abb = word[0] + str(len(word) - 2) + word[-1]\n if abb in self.dic:\n ...
<|body_start_0|> self.dic = {} for word in set(dictionary): if word: if len(word) <= 2: if word not in self.dic: self.dic[word] = set() self.dic[word].add(word) else: abb =...
ValidWordAbbr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """initialize your data structure here. :type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """check if a word is unique. :type word: str :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_75kplus_train_068108
1,496
no_license
[ { "docstring": "initialize your data structure here. :type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": "check if a word is unique. :type word: str :rtype: bool", "name": "isUnique", "signature": "def isUnique(self, word)" ...
2
stack_v2_sparse_classes_30k_test_001055
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str] - def isUnique(self, word): check if a word is unique. :type word: str ...
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str] - def isUnique(self, word): check if a word is unique. :type word: str ...
f1b85a2bfee024ef3afdf2ca0b223842c2d2d3f3
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """initialize your data structure here. :type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """check if a word is unique. :type word: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ValidWordAbbr: def __init__(self, dictionary): """initialize your data structure here. :type dictionary: List[str]""" self.dic = {} for word in set(dictionary): if word: if len(word) <= 2: if word not in self.dic: ...
the_stack_v2_python_sparse
288-Unique-Word-Abbreviation/solution.py
Xochitlxie/Leetcode
train
0
31ddae5b426974b91acf6cfbe555864b0391cae9
[ "super().__init__(structure, sort_structure=False, **kwargs)\nself.structure = structure\nself.num_perturb = num_perturb", "if self.num_perturb > 0 and self.num_perturb <= len(self.structure):\n syms = [site.specie.symbol for site in self.structure[self.num_perturb:]]\n syms = [a[0] for a in itertools.group...
<|body_start_0|> super().__init__(structure, sort_structure=False, **kwargs) self.structure = structure self.num_perturb = num_perturb <|end_body_0|> <|body_start_1|> if self.num_perturb > 0 and self.num_perturb <= len(self.structure): syms = [site.specie.symbol for site in ...
Derived Poscar class that allows the distinction of individual sites in the Structure
PoscarPerturb
[ "LicenseRef-scancode-hdf5", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PoscarPerturb: """Derived Poscar class that allows the distinction of individual sites in the Structure""" def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): """Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as "separate" sp...
stack_v2_sparse_classes_75kplus_train_068109
25,948
permissive
[ { "docstring": "Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as \"separate\" species **kwargs:", "name": "__init__", "signature": "def __init__(self, structure: Structure, num_perturb: int=1, **kwargs)" }, { "docstring": "Sequence of symbols associated wi...
3
stack_v2_sparse_classes_30k_test_001167
Implement the Python class `PoscarPerturb` described below. Class description: Derived Poscar class that allows the distinction of individual sites in the Structure Method signatures and docstrings: - def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): Args: structure: num_perturb: Number of sites...
Implement the Python class `PoscarPerturb` described below. Class description: Derived Poscar class that allows the distinction of individual sites in the Structure Method signatures and docstrings: - def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): Args: structure: num_perturb: Number of sites...
f4060e55ae3a22289fde9516ff0e8e4ac1d22190
<|skeleton|> class PoscarPerturb: """Derived Poscar class that allows the distinction of individual sites in the Structure""" def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): """Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as "separate" sp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PoscarPerturb: """Derived Poscar class that allows the distinction of individual sites in the Structure""" def __init__(self, structure: Structure, num_perturb: int=1, **kwargs): """Args: structure: num_perturb: Number of sites to perturb; First n sites are indicated as "separate" species **kwarg...
the_stack_v2_python_sparse
atomate/vasp/workflows/base/hubbard_hund_linresp.py
hackingmaterials/atomate
train
217
795453f10a85f9fe6bbec59c84e15847f13d9090
[ "self.id = id\nself.number = number\nself.name = name\nself.balance = balance\nself.mtype = mtype\nself.status = status\nself.customer_id = customer_id\nself.institution_id = institution_id\nself.balance_date = balance_date\nself.created_date = created_date\nself.currency = currency\nself.institution_login_id = ins...
<|body_start_0|> self.id = id self.number = number self.name = name self.balance = balance self.mtype = mtype self.status = status self.customer_id = customer_id self.institution_id = institution_id self.balance_date = balance_date self.cre...
Implementation of the 'Account1' model. TODO: type model description here. Attributes: id (string): TODO: type description here. number (string): TODO: type description here. name (string): TODO: type description here. balance (float): TODO: type description here. mtype (string): TODO: type description here. status (st...
Account1
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Account1: """Implementation of the 'Account1' model. TODO: type model description here. Attributes: id (string): TODO: type description here. number (string): TODO: type description here. name (string): TODO: type description here. balance (float): TODO: type description here. mtype (string): TOD...
stack_v2_sparse_classes_75kplus_train_068110
4,584
permissive
[ { "docstring": "Constructor for the Account1 class", "name": "__init__", "signature": "def __init__(self, id=None, number=None, name=None, balance=None, mtype=None, status=None, customer_id=None, institution_id=None, balance_date=None, created_date=None, currency=None, institution_login_id=None, display...
2
stack_v2_sparse_classes_30k_test_002609
Implement the Python class `Account1` described below. Class description: Implementation of the 'Account1' model. TODO: type model description here. Attributes: id (string): TODO: type description here. number (string): TODO: type description here. name (string): TODO: type description here. balance (float): TODO: typ...
Implement the Python class `Account1` described below. Class description: Implementation of the 'Account1' model. TODO: type model description here. Attributes: id (string): TODO: type description here. number (string): TODO: type description here. name (string): TODO: type description here. balance (float): TODO: typ...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class Account1: """Implementation of the 'Account1' model. TODO: type model description here. Attributes: id (string): TODO: type description here. number (string): TODO: type description here. name (string): TODO: type description here. balance (float): TODO: type description here. mtype (string): TOD...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Account1: """Implementation of the 'Account1' model. TODO: type model description here. Attributes: id (string): TODO: type description here. number (string): TODO: type description here. name (string): TODO: type description here. balance (float): TODO: type description here. mtype (string): TODO: type descr...
the_stack_v2_python_sparse
finicityapi/models/account_1.py
monarchmoney/finicity-python
train
0
3ae0ed4b3264bd97ca9c6a873fd87455121015fe
[ "if not grid:\n return 0\nm, n = (len(grid), len(grid[0]))\ndp = [[0] * n for i in xrange(m)]\nfor i in xrange(m):\n for j in xrange(n):\n if i == 0 and j == 0:\n dp[i][j] = grid[i][j]\n elif i == 0 and j != 0:\n dp[i][j] = dp[i][j - 1] + grid[i][j]\n elif i != 0 and...
<|body_start_0|> if not grid: return 0 m, n = (len(grid), len(grid[0])) dp = [[0] * n for i in xrange(m)] for i in xrange(m): for j in xrange(n): if i == 0 and j == 0: dp[i][j] = grid[i][j] elif i == 0 and j != 0...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minPathSum1(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def minPathSum2(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> def minPathSum(self, grid): """:type grid: List[List[int]] :rtyp...
stack_v2_sparse_classes_75kplus_train_068111
2,285
no_license
[ { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "minPathSum1", "signature": "def minPathSum1(self, grid)" }, { "docstring": ":type grid: List[List[int]] :rtype: int", "name": "minPathSum2", "signature": "def minPathSum2(self, grid)" }, { "docstring": ":type grid...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int - def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int - def minPathSum(self, grid): :type gr...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minPathSum1(self, grid): :type grid: List[List[int]] :rtype: int - def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int - def minPathSum(self, grid): :type gr...
9687f8e743a8b6396fff192f22b5256d1025f86b
<|skeleton|> class Solution: def minPathSum1(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_0|> def minPathSum2(self, grid): """:type grid: List[List[int]] :rtype: int""" <|body_1|> def minPathSum(self, grid): """:type grid: List[List[int]] :rtyp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minPathSum1(self, grid): """:type grid: List[List[int]] :rtype: int""" if not grid: return 0 m, n = (len(grid), len(grid[0])) dp = [[0] * n for i in xrange(m)] for i in xrange(m): for j in xrange(n): if i == 0 and j ...
the_stack_v2_python_sparse
2017/dp/Minimum_Path_Sum.py
buhuipao/LeetCode
train
5
487778158244c02cbb0cd58d140f553edd0dbea6
[ "super(CnnOnline_2DFlat, self).__init__()\nself.Conv1 = torch.nn.Conv1d(1, int(H), D_in, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros')\nself.lin1 = torch.nn.Linear(int(H), D_out, bias=False)\nself.relu = torch.nn.PReLU(num_parameters=int(H))", "Current_batchsize = int(x.shape[0])\nd...
<|body_start_0|> super(CnnOnline_2DFlat, self).__init__() self.Conv1 = torch.nn.Conv1d(1, int(H), D_in, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros') self.lin1 = torch.nn.Linear(int(H), D_out, bias=False) self.relu = torch.nn.PReLU(num_parameters=int(H)) <|...
CnnOnline_2DFlat
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CnnOnline_2DFlat: def __init__(self, D_in, H, D_out): """In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.""" <|body_0|> def forward(self, x): """In the forward function we accept a Tensor of input data and we must return a ...
stack_v2_sparse_classes_75kplus_train_068112
3,350
no_license
[ { "docstring": "In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.", "name": "__init__", "signature": "def __init__(self, D_in, H, D_out)" }, { "docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output d...
2
stack_v2_sparse_classes_30k_train_018156
Implement the Python class `CnnOnline_2DFlat` described below. Class description: Implement the CnnOnline_2DFlat class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Conv1d modules and assign them as member variables. - def forward(self, x): In the fo...
Implement the Python class `CnnOnline_2DFlat` described below. Class description: Implement the CnnOnline_2DFlat class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Conv1d modules and assign them as member variables. - def forward(self, x): In the fo...
2b8566b8b27d35174ec234ecd905c7f284e3af69
<|skeleton|> class CnnOnline_2DFlat: def __init__(self, D_in, H, D_out): """In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.""" <|body_0|> def forward(self, x): """In the forward function we accept a Tensor of input data and we must return a ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CnnOnline_2DFlat: def __init__(self, D_in, H, D_out): """In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.""" super(CnnOnline_2DFlat, self).__init__() self.Conv1 = torch.nn.Conv1d(1, int(H), D_in, stride=1, padding=0, dilation=1, groups=1, bia...
the_stack_v2_python_sparse
src_dir/DiscontinuedNets/cnn_collectionOnline2D_Flat.py
unravel11/GMRES-Learning
train
0
ee030a165e3dc8b9c3c6f40e5a5ffa043bc12e27
[ "url = longUrl[9:]\nlast = url.split('/')[-1]\nencode = last.encode('UTF-8', 'strict')\nreturn longUrl.replace(last, encode)", "url = shortUrl[9:]\nlast = url.split('/')[-1]\ndecode = last.decode('UTF-8', 'strict')\nreturn shortUrl.replace(last, decode)" ]
<|body_start_0|> url = longUrl[9:] last = url.split('/')[-1] encode = last.encode('UTF-8', 'strict') return longUrl.replace(last, encode) <|end_body_0|> <|body_start_1|> url = shortUrl[9:] last = url.split('/')[-1] decode = last.decode('UTF-8', 'strict') ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" <|body_0|> def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_75kplus_train_068113
734
no_license
[ { "docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str", "name": "encode", "signature": "def encode(self, longUrl)" }, { "docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str", "name": "decode", "signature": "def decode(self,...
2
stack_v2_sparse_classes_30k_train_017407
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str - def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str - def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s...
cbcebd132cdeb9daaf2f8257e677f9d588d77fa0
<|skeleton|> class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" <|body_0|> def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" url = longUrl[9:] last = url.split('/')[-1] encode = last.encode('UTF-8', 'strict') return longUrl.replace(last, encode) def decode(self, shortUrl): """...
the_stack_v2_python_sparse
Medium/Encode&DecodeTinyURL.py
rajgopav/Leetcode-python
train
0
c8585b74346b169df05e8e5b949c12260bf89f7e
[ "clen = len(prerequisites)\nif clen == 0:\n return [i for i in range(numCourses)]\ninverse_adj = [set() for _ in range(numCourses)]\nfor second, first in prerequisites:\n inverse_adj[second].add(first)\nvisited = [0 for _ in range(numCourses)]\nres = []\nfor i in range(numCourses):\n if self.__dfs(i, inver...
<|body_start_0|> clen = len(prerequisites) if clen == 0: return [i for i in range(numCourses)] inverse_adj = [set() for _ in range(numCourses)] for second, first in prerequisites: inverse_adj[second].add(first) visited = [0 for _ in range(numCourses)] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findOrder(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]""" <|body_0|> def __dfs(self, vertex, inverse_adj, visited, res): """注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inverse_adj...
stack_v2_sparse_classes_75kplus_train_068114
4,273
no_license
[ { "docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]", "name": "findOrder", "signature": "def findOrder(self, numCourses, prerequisites)" }, { "docstring": "注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inverse_adj: 逆邻接表,记录的是当前结点的前驱结点的集合 :param visited:...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int] - def __dfs(self, vertex, inverse_adj, visited, res):...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int] - def __dfs(self, vertex, inverse_adj, visited, res):...
b0f498ebe84e46b7e17e94759dd462891dcc8f85
<|skeleton|> class Solution: def findOrder(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]""" <|body_0|> def __dfs(self, vertex, inverse_adj, visited, res): """注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inverse_adj...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findOrder(self, numCourses, prerequisites): """:type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]""" clen = len(prerequisites) if clen == 0: return [i for i in range(numCourses)] inverse_adj = [set() for _ in range(numCourses)...
the_stack_v2_python_sparse
算法面试题汇总/graph-theory_4.py
wulinlw/leetcode_cn
train
0
64a05d95283cff7199d76904fb0385ab5412cd25
[ "most = 0\nfor idx, h in enumerate(height):\n for ridx, rh in enumerate(height[idx:]):\n most = max(ridx * min(h, rh), most)\nreturn most", "if not height[1:]:\n return 0\nleft = 0\nright = len(height) - 1\nmost = 0\nwhile left < right:\n most = max(most, min(height[left], height[right]) * (right ...
<|body_start_0|> most = 0 for idx, h in enumerate(height): for ridx, rh in enumerate(height[idx:]): most = max(ridx * min(h, rh), most) return most <|end_body_0|> <|body_start_1|> if not height[1:]: return 0 left = 0 right = len(he...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxArea2(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> most = 0 for idx, h in enumerate(hei...
stack_v2_sparse_classes_75kplus_train_068115
2,247
no_license
[ { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea2", "signature": "def maxArea2(self, height)" }, { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea", "signature": "def maxArea(self, height)" } ]
2
stack_v2_sparse_classes_30k_train_049454
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea2(self, height): :type height: List[int] :rtype: int - def maxArea(self, height): :type height: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea2(self, height): :type height: List[int] :rtype: int - def maxArea(self, height): :type height: List[int] :rtype: int <|skeleton|> class Solution: def maxArea2(s...
d2e8b2dca40fc955045eb62e576c776bad8ee5f1
<|skeleton|> class Solution: def maxArea2(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxArea2(self, height): """:type height: List[int] :rtype: int""" most = 0 for idx, h in enumerate(height): for ridx, rh in enumerate(height[idx:]): most = max(ridx * min(h, rh), most) return most def maxArea(self, height): ...
the_stack_v2_python_sparse
container-with-most-water/solution.py
childe/leetcode
train
2
f73e4bcf78273940cbba1f31c19d6d28be77824b
[ "for fld in ['LmChallengeResponseFields', 'NtChallengeResponseFields', 'DomainNameFields', 'UserNameFields', 'WorkstationFields', 'EncryptedRandomSessionKeyFields']:\n yield (fld, self[fld])\nreturn", "for _, item in self.enumerate():\n yield item\nreturn", "for item in self.iterate():\n yield item\nre...
<|body_start_0|> for fld in ['LmChallengeResponseFields', 'NtChallengeResponseFields', 'DomainNameFields', 'UserNameFields', 'WorkstationFields', 'EncryptedRandomSessionKeyFields']: yield (fld, self[fld]) return <|end_body_0|> <|body_start_1|> for _, item in self.enumerate(): ...
AUTHENTICATE_MESSAGE
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AUTHENTICATE_MESSAGE: def enumerate(self): """Yield the name and field that compose the message type payload.""" <|body_0|> def iterate(self): """Yield each field that composes the message type payload.""" <|body_1|> def Fields(self): """Yield al...
stack_v2_sparse_classes_75kplus_train_068116
31,838
permissive
[ { "docstring": "Yield the name and field that compose the message type payload.", "name": "enumerate", "signature": "def enumerate(self)" }, { "docstring": "Yield each field that composes the message type payload.", "name": "iterate", "signature": "def iterate(self)" }, { "docstr...
3
stack_v2_sparse_classes_30k_train_044279
Implement the Python class `AUTHENTICATE_MESSAGE` described below. Class description: Implement the AUTHENTICATE_MESSAGE class. Method signatures and docstrings: - def enumerate(self): Yield the name and field that compose the message type payload. - def iterate(self): Yield each field that composes the message type ...
Implement the Python class `AUTHENTICATE_MESSAGE` described below. Class description: Implement the AUTHENTICATE_MESSAGE class. Method signatures and docstrings: - def enumerate(self): Yield the name and field that compose the message type payload. - def iterate(self): Yield each field that composes the message type ...
e02b014dc764ed822288210248c9438a843af8a9
<|skeleton|> class AUTHENTICATE_MESSAGE: def enumerate(self): """Yield the name and field that compose the message type payload.""" <|body_0|> def iterate(self): """Yield each field that composes the message type payload.""" <|body_1|> def Fields(self): """Yield al...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AUTHENTICATE_MESSAGE: def enumerate(self): """Yield the name and field that compose the message type payload.""" for fld in ['LmChallengeResponseFields', 'NtChallengeResponseFields', 'DomainNameFields', 'UserNameFields', 'WorkstationFields', 'EncryptedRandomSessionKeyFields']: yiel...
the_stack_v2_python_sparse
template/protocol/nlmp.py
arizvisa/syringe
train
36
1832a3f147a28eae5e1ef741710d3ce4527cb0ed
[ "st = RouteFactory()\nurl = reverse('routes:v1_detail_route', kwargs={'pk': st.id})\nresponse = self.client.get(url)\nself.assertEquals(response.status_code, 200)\nself.assertEquals(response.data['id'], st.id)", "st = RouteFactory()\nurl = reverse('routes:v1_detail_route', kwargs={'pk': st.id})\nresponse = self.c...
<|body_start_0|> st = RouteFactory() url = reverse('routes:v1_detail_route', kwargs={'pk': st.id}) response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertEquals(response.data['id'], st.id) <|end_body_0|> <|body_start_1|> st = RouteFactory...
Test class for the detail methods for Route Model: Retrieve, update, destroy
RouteDetailTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RouteDetailTest: """Test class for the detail methods for Route Model: Retrieve, update, destroy""" def test_retrieve_successfully(self): """Retrieve test for Route Model API""" <|body_0|> def test_update_successfully(self): """Update unit test for Route Model AP...
stack_v2_sparse_classes_75kplus_train_068117
5,022
no_license
[ { "docstring": "Retrieve test for Route Model API", "name": "test_retrieve_successfully", "signature": "def test_retrieve_successfully(self)" }, { "docstring": "Update unit test for Route Model API", "name": "test_update_successfully", "signature": "def test_update_successfully(self)" ...
3
stack_v2_sparse_classes_30k_test_001487
Implement the Python class `RouteDetailTest` described below. Class description: Test class for the detail methods for Route Model: Retrieve, update, destroy Method signatures and docstrings: - def test_retrieve_successfully(self): Retrieve test for Route Model API - def test_update_successfully(self): Update unit te...
Implement the Python class `RouteDetailTest` described below. Class description: Test class for the detail methods for Route Model: Retrieve, update, destroy Method signatures and docstrings: - def test_retrieve_successfully(self): Retrieve test for Route Model API - def test_update_successfully(self): Update unit te...
8106a843c486cc89c648d50e5e377635527f4b72
<|skeleton|> class RouteDetailTest: """Test class for the detail methods for Route Model: Retrieve, update, destroy""" def test_retrieve_successfully(self): """Retrieve test for Route Model API""" <|body_0|> def test_update_successfully(self): """Update unit test for Route Model AP...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RouteDetailTest: """Test class for the detail methods for Route Model: Retrieve, update, destroy""" def test_retrieve_successfully(self): """Retrieve test for Route Model API""" st = RouteFactory() url = reverse('routes:v1_detail_route', kwargs={'pk': st.id}) response = se...
the_stack_v2_python_sparse
apps/lines/tests.py
vpes/django_tech_test
train
0
5651499124c41a07112ab3ae02d71076204266eb
[ "arr = list(s)\nself.reverse_string(arr, 0, len(arr) - 1)\nself.reverse_word(arr)\nword = self.trim_sides(arr)\nres = self.trim_space(word)\nreturn ''.join(res)", "while l < r:\n arr[l], arr[r] = (arr[r], arr[l])\n l += 1\n r -= 1\nreturn arr", "l, r = (0, 0)\nwhile r < len(arr):\n while r < len(arr...
<|body_start_0|> arr = list(s) self.reverse_string(arr, 0, len(arr) - 1) self.reverse_word(arr) word = self.trim_sides(arr) res = self.trim_space(word) return ''.join(res) <|end_body_0|> <|body_start_1|> while l < r: arr[l], arr[r] = (arr[r], arr[l]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseWords(self, s): """:type s: str :rtype: str""" <|body_0|> def reverse_string(self, arr, l, r): """reverse a given string""" <|body_1|> def reverse_word(self, arr): """reverse every words in a string""" <|body_2|> ...
stack_v2_sparse_classes_75kplus_train_068118
2,029
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "reverseWords", "signature": "def reverseWords(self, s)" }, { "docstring": "reverse a given string", "name": "reverse_string", "signature": "def reverse_string(self, arr, l, r)" }, { "docstring": "reverse every words in a string"...
5
stack_v2_sparse_classes_30k_train_040593
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseWords(self, s): :type s: str :rtype: str - def reverse_string(self, arr, l, r): reverse a given string - def reverse_word(self, arr): reverse every words in a string -...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseWords(self, s): :type s: str :rtype: str - def reverse_string(self, arr, l, r): reverse a given string - def reverse_word(self, arr): reverse every words in a string -...
db2cd34ee759721858a96d123e3cab4084e69129
<|skeleton|> class Solution: def reverseWords(self, s): """:type s: str :rtype: str""" <|body_0|> def reverse_string(self, arr, l, r): """reverse a given string""" <|body_1|> def reverse_word(self, arr): """reverse every words in a string""" <|body_2|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseWords(self, s): """:type s: str :rtype: str""" arr = list(s) self.reverse_string(arr, 0, len(arr) - 1) self.reverse_word(arr) word = self.trim_sides(arr) res = self.trim_space(word) return ''.join(res) def reverse_string(self, a...
the_stack_v2_python_sparse
Algorithm-Medium/151_Reverse_Words_in_a_String.py
yz5308/Python_Leetcode
train
0
6f74a0bd93e70d9867777fc630b9e97ee6d7c7e0
[ "if p == root or q == root:\n return root\nself.path_p = []\nself.path_q = []\n\ndef help(root, p, q, path):\n if root:\n if root == p:\n self.path_p = path + [root]\n if root == q:\n self.path_q = path + [root]\n if self.path_p and self.path_q:\n return\n...
<|body_start_0|> if p == root or q == root: return root self.path_p = [] self.path_q = [] def help(root, p, q, path): if root: if root == p: self.path_p = path + [root] if root == q: self.pat...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lowestCommonAncestor1(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" <|body_0|> def lowestCommonAncestor(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"...
stack_v2_sparse_classes_75kplus_train_068119
1,507
no_license
[ { "docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode", "name": "lowestCommonAncestor1", "signature": "def lowestCommonAncestor1(self, root, p, q)" }, { "docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode", "name": "lowe...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lowestCommonAncestor1(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode - def lowestCommonAncestor(self, root, p, q): :type root: T...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lowestCommonAncestor1(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode - def lowestCommonAncestor(self, root, p, q): :type root: T...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def lowestCommonAncestor1(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" <|body_0|> def lowestCommonAncestor(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def lowestCommonAncestor1(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" if p == root or q == root: return root self.path_p = [] self.path_q = [] def help(root, p, q, path): if root: ...
the_stack_v2_python_sparse
py/leetcode/236.py
wfeng1991/learnpy
train
0
8fa945357748d40d4b0f6fd00339ef2fa7ffec11
[ "queryset = Batch.objects.filter(id=pk)\nbatch = get_object_or_404(queryset)\ncsv_text = request.data.get('csv_text', None)\nif not csv_text:\n raise serializers.ValidationError({'csv_text': 'This field is required.'})\nBatchSerializer.validate_csv_fields(csv_text, batch.project)\ncsv_fh = io.StringIO(csv_text)\...
<|body_start_0|> queryset = Batch.objects.filter(id=pk) batch = get_object_or_404(queryset) csv_text = request.data.get('csv_text', None) if not csv_text: raise serializers.ValidationError({'csv_text': 'This field is required.'}) BatchSerializer.validate_csv_fields(cs...
list: Return a list of the existing batches. retrieve: Retrieve a batch as identified by id. create: Create a new batch and return it. partial_update: Update the name, active status or allotted assignment time for a batch.
BatchViewSet
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BatchViewSet: """list: Return a list of the existing batches. retrieve: Retrieve a batch as identified by id. create: Create a new batch and return it. partial_update: Update the name, active status or allotted assignment time for a batch.""" def add_tasks(self, request, pk): """Add ...
stack_v2_sparse_classes_75kplus_train_068120
11,044
permissive
[ { "docstring": "Add new tasks to an existing batch.", "name": "add_tasks", "signature": "def add_tasks(self, request, pk)" }, { "docstring": "Download the current answers for this batch as a csv file.", "name": "download_results", "signature": "def download_results(self, request, pk)" ...
4
null
Implement the Python class `BatchViewSet` described below. Class description: list: Return a list of the existing batches. retrieve: Retrieve a batch as identified by id. create: Create a new batch and return it. partial_update: Update the name, active status or allotted assignment time for a batch. Method signatures...
Implement the Python class `BatchViewSet` described below. Class description: list: Return a list of the existing batches. retrieve: Retrieve a batch as identified by id. create: Create a new batch and return it. partial_update: Update the name, active status or allotted assignment time for a batch. Method signatures...
935f63c94ec4d1e2fa507c8e187fa86e96fad82b
<|skeleton|> class BatchViewSet: """list: Return a list of the existing batches. retrieve: Retrieve a batch as identified by id. create: Create a new batch and return it. partial_update: Update the name, active status or allotted assignment time for a batch.""" def add_tasks(self, request, pk): """Add ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BatchViewSet: """list: Return a list of the existing batches. retrieve: Retrieve a batch as identified by id. create: Create a new batch and return it. partial_update: Update the name, active status or allotted assignment time for a batch.""" def add_tasks(self, request, pk): """Add new tasks to ...
the_stack_v2_python_sparse
turkle/api/views.py
hltcoe/turkle
train
142
46298e9755334032644770315bcfa6f96dbf4b5d
[ "self.app_name = app_name\nself.conf_type = conf_type\nself.log_level = log_level\nself.logger = logging.getLogger(self.app_name)\nself.logger.setLevel(logging.INFO)\nself.postgres = pg\nself.path_to_log = os.path.join(os.getcwd(), 'logs')\nself.log_file_name = None\nself.fh = None\nif not os.path.exists(self.path_...
<|body_start_0|> self.app_name = app_name self.conf_type = conf_type self.log_level = log_level self.logger = logging.getLogger(self.app_name) self.logger.setLevel(logging.INFO) self.postgres = pg self.path_to_log = os.path.join(os.getcwd(), 'logs') self.l...
Logger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Logger: def __init__(self, app_name, conf_type, log_level, pg): """Создает логгер. :param app_name: (str) Имя приложения :param conf_type: (str) Тип конфигураций (prod | dev) :param log_level: (str) Уровень логирования :param pg: Инстанс подключения к PostgreSql""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_068121
3,700
permissive
[ { "docstring": "Создает логгер. :param app_name: (str) Имя приложения :param conf_type: (str) Тип конфигураций (prod | dev) :param log_level: (str) Уровень логирования :param pg: Инстанс подключения к PostgreSql", "name": "__init__", "signature": "def __init__(self, app_name, conf_type, log_level, pg)" ...
4
null
Implement the Python class `Logger` described below. Class description: Implement the Logger class. Method signatures and docstrings: - def __init__(self, app_name, conf_type, log_level, pg): Создает логгер. :param app_name: (str) Имя приложения :param conf_type: (str) Тип конфигураций (prod | dev) :param log_level: ...
Implement the Python class `Logger` described below. Class description: Implement the Logger class. Method signatures and docstrings: - def __init__(self, app_name, conf_type, log_level, pg): Создает логгер. :param app_name: (str) Имя приложения :param conf_type: (str) Тип конфигураций (prod | dev) :param log_level: ...
47e5c67a2ccceb2f6a61531de31707d81af66a54
<|skeleton|> class Logger: def __init__(self, app_name, conf_type, log_level, pg): """Создает логгер. :param app_name: (str) Имя приложения :param conf_type: (str) Тип конфигураций (prod | dev) :param log_level: (str) Уровень логирования :param pg: Инстанс подключения к PostgreSql""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Logger: def __init__(self, app_name, conf_type, log_level, pg): """Создает логгер. :param app_name: (str) Имя приложения :param conf_type: (str) Тип конфигураций (prod | dev) :param log_level: (str) Уровень логирования :param pg: Инстанс подключения к PostgreSql""" self.app_name = app_name ...
the_stack_v2_python_sparse
Nika/logger.py
bekkazy-k/Nika
train
3
97903c44ec739602a4472cc4c6f6219a00073e89
[ "self.vcpus_total = compute['vcpus']\nself.vcpus_used = compute['vcpus_used']\nself.free_ram_mb = compute['free_ram_mb']\nself.total_usable_ram_mb = compute['memory_mb']\nself.free_disk_mb = compute['free_disk_gb'] * 1024\nstats = compute.get('stats', '{}')\nself.stats = jsonutils.loads(stats)", "self.free_ram_mb...
<|body_start_0|> self.vcpus_total = compute['vcpus'] self.vcpus_used = compute['vcpus_used'] self.free_ram_mb = compute['free_ram_mb'] self.total_usable_ram_mb = compute['memory_mb'] self.free_disk_mb = compute['free_disk_gb'] * 1024 stats = compute.get('stats', '{}') ...
Mutable and immutable information tracked for a host. This is an attempt to remove the ad-hoc data structures previously used and lock down access.
BaseBaremetalNodeState
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseBaremetalNodeState: """Mutable and immutable information tracked for a host. This is an attempt to remove the ad-hoc data structures previously used and lock down access.""" def update_from_compute_node(self, compute): """Update information about a host from its compute_node info...
stack_v2_sparse_classes_75kplus_train_068122
2,102
permissive
[ { "docstring": "Update information about a host from its compute_node info.", "name": "update_from_compute_node", "signature": "def update_from_compute_node(self, compute)" }, { "docstring": "Consume nodes entire resources regardless of instance request.", "name": "consume_from_instance", ...
2
null
Implement the Python class `BaseBaremetalNodeState` described below. Class description: Mutable and immutable information tracked for a host. This is an attempt to remove the ad-hoc data structures previously used and lock down access. Method signatures and docstrings: - def update_from_compute_node(self, compute): U...
Implement the Python class `BaseBaremetalNodeState` described below. Class description: Mutable and immutable information tracked for a host. This is an attempt to remove the ad-hoc data structures previously used and lock down access. Method signatures and docstrings: - def update_from_compute_node(self, compute): U...
3154f2cb0eb0d8c447c6d18ee0bab5e7dbeba60b
<|skeleton|> class BaseBaremetalNodeState: """Mutable and immutable information tracked for a host. This is an attempt to remove the ad-hoc data structures previously used and lock down access.""" def update_from_compute_node(self, compute): """Update information about a host from its compute_node info...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseBaremetalNodeState: """Mutable and immutable information tracked for a host. This is an attempt to remove the ad-hoc data structures previously used and lock down access.""" def update_from_compute_node(self, compute): """Update information about a host from its compute_node info.""" ...
the_stack_v2_python_sparse
nova/scheduler/base_baremetal_host_manager.py
virtualopensystems/nova
train
0
eb203bc93476b7b993df8e1b31c573a6242be77d
[ "sum_1 = 0\nstack = []\nfor i, h in enumerate(height):\n if not stack and h == 0:\n continue\n elif not stack or stack[-1][-1] > h:\n stack.append([i, h])\n else:\n lists = []\n while stack and stack[-1][-1] <= h:\n lists.append(stack.pop())\n if not stack:\n ...
<|body_start_0|> sum_1 = 0 stack = [] for i, h in enumerate(height): if not stack and h == 0: continue elif not stack or stack[-1][-1] > h: stack.append([i, h]) else: lists = [] while stack and st...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def trap(self, height): """:type height: List[int] :rtype: int 68ms""" <|body_0|> def trap_1(self, height): """:type height: List[int] :rtype: int 59ms""" <|body_1|> def trap_2(self, height): """:type height: List[int] :rtype: int 49ms"...
stack_v2_sparse_classes_75kplus_train_068123
2,988
no_license
[ { "docstring": ":type height: List[int] :rtype: int 68ms", "name": "trap", "signature": "def trap(self, height)" }, { "docstring": ":type height: List[int] :rtype: int 59ms", "name": "trap_1", "signature": "def trap_1(self, height)" }, { "docstring": ":type height: List[int] :rty...
3
stack_v2_sparse_classes_30k_train_045698
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def trap(self, height): :type height: List[int] :rtype: int 68ms - def trap_1(self, height): :type height: List[int] :rtype: int 59ms - def trap_2(self, height): :type height: Li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def trap(self, height): :type height: List[int] :rtype: int 68ms - def trap_1(self, height): :type height: List[int] :rtype: int 59ms - def trap_2(self, height): :type height: Li...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def trap(self, height): """:type height: List[int] :rtype: int 68ms""" <|body_0|> def trap_1(self, height): """:type height: List[int] :rtype: int 59ms""" <|body_1|> def trap_2(self, height): """:type height: List[int] :rtype: int 49ms"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def trap(self, height): """:type height: List[int] :rtype: int 68ms""" sum_1 = 0 stack = [] for i, h in enumerate(height): if not stack and h == 0: continue elif not stack or stack[-1][-1] > h: stack.append([i, h...
the_stack_v2_python_sparse
TrappingRainWater_HARD_42.py
953250587/leetcode-python
train
2
8d13bded0f33fd159d75be1b736785dce5691637
[ "hash_key = self.request.query_params.get('session')\nif hash_key is not None and hash_key:\n try:\n event = EventSession.objects.get(hash_key=hash_key)\n return Exam.objects.by_user_perms(self.request.user).filter(event=event).prefetch_related('comment_set').prefetch_related('usersession_set')\n ...
<|body_start_0|> hash_key = self.request.query_params.get('session') if hash_key is not None and hash_key: try: event = EventSession.objects.get(hash_key=hash_key) return Exam.objects.by_user_perms(self.request.user).filter(event=event).prefetch_related('comme...
This viewset register edx's exam on proctoring service and return generated code Required parameters: `examCode`, `organization`, `duration`, `reviewedExam`, `reviewerNotes`, `examPassword`, `examSponsor`, `examName`, `ssiProduct`, `orgExtra` orgExtra contain json like this: { "examStartDate": "2015-10-10 11:00", "exam...
ExamViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExamViewSet: """This viewset register edx's exam on proctoring service and return generated code Required parameters: `examCode`, `organization`, `duration`, `reviewedExam`, `reviewerNotes`, `examPassword`, `examSponsor`, `examName`, `ssiProduct`, `orgExtra` orgExtra contain json like this: { "ex...
stack_v2_sparse_classes_75kplus_train_068124
6,448
no_license
[ { "docstring": "This view should return a list of all the purchases for the user as determined by the username portion of the URL.", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Create new exam, on exam attempt. Find Event Session for this exam.", "name": ...
2
stack_v2_sparse_classes_30k_train_016033
Implement the Python class `ExamViewSet` described below. Class description: This viewset register edx's exam on proctoring service and return generated code Required parameters: `examCode`, `organization`, `duration`, `reviewedExam`, `reviewerNotes`, `examPassword`, `examSponsor`, `examName`, `ssiProduct`, `orgExtra`...
Implement the Python class `ExamViewSet` described below. Class description: This viewset register edx's exam on proctoring service and return generated code Required parameters: `examCode`, `organization`, `duration`, `reviewedExam`, `reviewerNotes`, `examPassword`, `examSponsor`, `examName`, `ssiProduct`, `orgExtra`...
b4f4564e70d6f78cadc999d10a78ad3e7f288671
<|skeleton|> class ExamViewSet: """This viewset register edx's exam on proctoring service and return generated code Required parameters: `examCode`, `organization`, `duration`, `reviewedExam`, `reviewerNotes`, `examPassword`, `examSponsor`, `examName`, `ssiProduct`, `orgExtra` orgExtra contain json like this: { "ex...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExamViewSet: """This viewset register edx's exam on proctoring service and return generated code Required parameters: `examCode`, `organization`, `duration`, `reviewedExam`, `reviewerNotes`, `examPassword`, `examSponsor`, `examName`, `ssiProduct`, `orgExtra` orgExtra contain json like this: { "examStartDate":...
the_stack_v2_python_sparse
proctoring/api_edx_views.py
miptliot/edx_proctor_webassistant
train
0
f42487cd68137f31655bb1896769dd2e504c68b7
[ "super().__init__(name)\nself._image = image\nself._command = command\nself._volumes = volumes\nself._devices = devices\nself._environment = environment\nself._network = network\nself._shm_size = shm_size\nself._triton_exec = None\nself._logging_thread = None\nself._log_file_path = pathlib.Path(log_file)", "devic...
<|body_start_0|> super().__init__(name) self._image = image self._command = command self._volumes = volumes self._devices = devices self._environment = environment self._network = network self._shm_size = shm_size self._triton_exec = None s...
TritonServerContainer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TritonServerContainer: def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'): """Initialize Triton Server Container Args: name: Container name comma...
stack_v2_sparse_classes_75kplus_train_068125
5,403
permissive
[ { "docstring": "Initialize Triton Server Container Args: name: Container name command: Triton Server command to exec on container start image: Docker Image volumes: Volumes to mount inside container devices: Devices which has to be visible in container environment: Environment variables log_file: Path where log...
5
stack_v2_sparse_classes_30k_train_000273
Implement the Python class `TritonServerContainer` described below. Class description: Implement the TritonServerContainer class. Method signatures and docstrings: - def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str],...
Implement the Python class `TritonServerContainer` described below. Class description: Implement the TritonServerContainer class. Method signatures and docstrings: - def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str],...
a5388a45f71a949639b35cc5b990bd130d2d8164
<|skeleton|> class TritonServerContainer: def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'): """Initialize Triton Server Container Args: name: Container name comma...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TritonServerContainer: def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'): """Initialize Triton Server Container Args: name: Container name command: Triton Ser...
the_stack_v2_python_sparse
PyTorch/LanguageModeling/BERT/triton/runner/maintainer/docker/containers/triton_server_container.py
NVIDIA/DeepLearningExamples
train
11,838
7295b7c3276c7a73717a23d73f71da6ee1d5b517
[ "vals = []\n\ndef pre_order(node):\n if node:\n vals.append(str(node.val))\n pre_order(node.left)\n pre_order(node.right)\n else:\n vals.append('null')\npre_order(root)\nreturn ' '.join(vals)", "vals = collections.deque(data.split())\n\ndef build_tree():\n val = vals.popleft()...
<|body_start_0|> vals = [] def pre_order(node): if node: vals.append(str(node.val)) pre_order(node.left) pre_order(node.right) else: vals.append('null') pre_order(root) return ' '.join(vals) <|end_bo...
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_75kplus_train_068126
1,426
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
07b8c34b12d05413466119a82247d7ee5cc34318
<|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_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" vals = [] def pre_order(node): if node: vals.append(str(node.val)) pre_order(node.left) pre_order(node.right) ...
the_stack_v2_python_sparse
297. Serialize and Deserialize Binary Tree.py
bryantbyr/LeetCode-solutions
train
1
6e49315508c1471995113a8770c6fc2b41301418
[ "if self.request.user.is_authenticated:\n user_profile = Profile.objects.get(user_id=request.user.id)\n profile_goods_cart_ids = list(Cart.objects.filter(profile=user_profile).order_by('-add_time').values_list('id', flat=True))\n profile_goods_cart = Cart.objects.select_related('goods').filter(profile=user...
<|body_start_0|> if self.request.user.is_authenticated: user_profile = Profile.objects.get(user_id=request.user.id) profile_goods_cart_ids = list(Cart.objects.filter(profile=user_profile).order_by('-add_time').values_list('id', flat=True)) profile_goods_cart = Cart.objects.se...
Представление для покупки товаров путем отправки POST запроса JSON файла — goods_buy: [{goods_1},{goods_2}]
BuyGoods
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuyGoods: """Представление для покупки товаров путем отправки POST запроса JSON файла — goods_buy: [{goods_1},{goods_2}]""" def post(self, request): """:param request: JSON goods_buy: [{goods_1},{goods_2}] Принимает JSON объект c товарами которые хочет купить пользователь""" ...
stack_v2_sparse_classes_75kplus_train_068127
8,672
no_license
[ { "docstring": ":param request: JSON goods_buy: [{goods_1},{goods_2}] Принимает JSON объект c товарами которые хочет купить пользователь", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Применение изменений в моделях при покупки товара пользователем", "name": "buy_...
3
stack_v2_sparse_classes_30k_train_023996
Implement the Python class `BuyGoods` described below. Class description: Представление для покупки товаров путем отправки POST запроса JSON файла — goods_buy: [{goods_1},{goods_2}] Method signatures and docstrings: - def post(self, request): :param request: JSON goods_buy: [{goods_1},{goods_2}] Принимает JSON объект...
Implement the Python class `BuyGoods` described below. Class description: Представление для покупки товаров путем отправки POST запроса JSON файла — goods_buy: [{goods_1},{goods_2}] Method signatures and docstrings: - def post(self, request): :param request: JSON goods_buy: [{goods_1},{goods_2}] Принимает JSON объект...
93fd0a54bde47e58314c1f13f54bb358f29524df
<|skeleton|> class BuyGoods: """Представление для покупки товаров путем отправки POST запроса JSON файла — goods_buy: [{goods_1},{goods_2}]""" def post(self, request): """:param request: JSON goods_buy: [{goods_1},{goods_2}] Принимает JSON объект c товарами которые хочет купить пользователь""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BuyGoods: """Представление для покупки товаров путем отправки POST запроса JSON файла — goods_buy: [{goods_1},{goods_2}]""" def post(self, request): """:param request: JSON goods_buy: [{goods_1},{goods_2}] Принимает JSON объект c товарами которые хочет купить пользователь""" if self.reque...
the_stack_v2_python_sparse
app_users/api/views.py
slimsevernake/Django-OnlineStore
train
0
92d933cda99076df618d0d3228e83d0cd21d9ebf
[ "super().__init__(**kwargs)\nself.garage = garage\nself.fenced = fenced\nself.num_stories = num_stories", "super().display()\nprint('HOUSE DETAILS')\nprint('# of stories: {}'.format(self.num_stories))\nprint('garage: {}'.format(self.garage))\nprint('fenced yard: {}'.format(self.fenced))", "parent_init = Propert...
<|body_start_0|> super().__init__(**kwargs) self.garage = garage self.fenced = fenced self.num_stories = num_stories <|end_body_0|> <|body_start_1|> super().display() print('HOUSE DETAILS') print('# of stories: {}'.format(self.num_stories)) print('garage:...
extends Property info about House
House
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class House: """extends Property info about House""" def __init__(self, num_stories='', garage='', fenced='', **kwargs): """contains info about garage and fenced :param num_stories: str (int) :param garage: str :param fenced: str :param kwargs: additional info""" <|body_0|> de...
stack_v2_sparse_classes_75kplus_train_068128
12,832
no_license
[ { "docstring": "contains info about garage and fenced :param num_stories: str (int) :param garage: str :param fenced: str :param kwargs: additional info", "name": "__init__", "signature": "def __init__(self, num_stories='', garage='', fenced='', **kwargs)" }, { "docstring": "output all info :ret...
3
stack_v2_sparse_classes_30k_train_028256
Implement the Python class `House` described below. Class description: extends Property info about House Method signatures and docstrings: - def __init__(self, num_stories='', garage='', fenced='', **kwargs): contains info about garage and fenced :param num_stories: str (int) :param garage: str :param fenced: str :pa...
Implement the Python class `House` described below. Class description: extends Property info about House Method signatures and docstrings: - def __init__(self, num_stories='', garage='', fenced='', **kwargs): contains info about garage and fenced :param num_stories: str (int) :param garage: str :param fenced: str :pa...
6c739a5d5445e9ff67fa468d9d9c86cd0be92ca5
<|skeleton|> class House: """extends Property info about House""" def __init__(self, num_stories='', garage='', fenced='', **kwargs): """contains info about garage and fenced :param num_stories: str (int) :param garage: str :param fenced: str :param kwargs: additional info""" <|body_0|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class House: """extends Property info about House""" def __init__(self, num_stories='', garage='', fenced='', **kwargs): """contains info about garage and fenced :param num_stories: str (int) :param garage: str :param fenced: str :param kwargs: additional info""" super().__init__(**kwargs) ...
the_stack_v2_python_sparse
lab_3_Zabulskyy.py
zabulskyy/ucu_projects
train
0
c66b5590ffee9b4125dfead0c11c3139b7de827c
[ "if final_values is None:\n final_values = {}\nself.final_values = final_values\nself.fade_factor = 0.5 ** (1 / semi_gen)\nself.verbose = verbose", "if self.verbose:\n print()\n print('--Exp Scheduler Values--')\nfor key in self.final_values:\n prev_value = getattr(conf.genome_config, key)\n if sel...
<|body_start_0|> if final_values is None: final_values = {} self.final_values = final_values self.fade_factor = 0.5 ** (1 / semi_gen) self.verbose = verbose <|end_body_0|> <|body_start_1|> if self.verbose: print() print('--Exp Scheduler Values...
Scheduler that allows parameter decay. The initial values are those put in the config file. The asymptotic values are those given in dictionnary 'final_values'. Only the parameters described in 'final_values' will be affectd by the sheduler. The decay factor is describe by 'semi_gen', the number of generations necessar...
ExponentialScheduler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExponentialScheduler: """Scheduler that allows parameter decay. The initial values are those put in the config file. The asymptotic values are those given in dictionnary 'final_values'. Only the parameters described in 'final_values' will be affectd by the sheduler. The decay factor is describe b...
stack_v2_sparse_classes_75kplus_train_068129
20,844
permissive
[ { "docstring": "semi_gen: number of generations required to be half way to th final value final_values: dictionnary of format {'parameter_name' (string): final value (float)} e.g. final_values = {\"node_add_prob\": 0.05, \"conn_add_prob\": 0.02} verbose: if 1, print the current values of the parameters", "n...
2
stack_v2_sparse_classes_30k_train_037156
Implement the Python class `ExponentialScheduler` described below. Class description: Scheduler that allows parameter decay. The initial values are those put in the config file. The asymptotic values are those given in dictionnary 'final_values'. Only the parameters described in 'final_values' will be affectd by the s...
Implement the Python class `ExponentialScheduler` described below. Class description: Scheduler that allows parameter decay. The initial values are those put in the config file. The asymptotic values are those given in dictionnary 'final_values'. Only the parameters described in 'final_values' will be affectd by the s...
6a8e167c59db343e4efa93e8d50a8807e64f607c
<|skeleton|> class ExponentialScheduler: """Scheduler that allows parameter decay. The initial values are those put in the config file. The asymptotic values are those given in dictionnary 'final_values'. Only the parameters described in 'final_values' will be affectd by the sheduler. The decay factor is describe b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ExponentialScheduler: """Scheduler that allows parameter decay. The initial values are those put in the config file. The asymptotic values are those given in dictionnary 'final_values'. Only the parameters described in 'final_values' will be affectd by the sheduler. The decay factor is describe by 'semi_gen',...
the_stack_v2_python_sparse
neat_local/scheduler.py
Maxwell1447/Neuro-evolution-in-speaker-recognition
train
2
9542499c30b6704dbfd78ff73e3da69bf61a9381
[ "if not user_name:\n raise ValueError('Users must have an usrer name address')\nuser = self.model(user_name=user_name, first_name=first_name, middel_name=middel_name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(user_name, first_name, middel_name, password=pas...
<|body_start_0|> if not user_name: raise ValueError('Users must have an usrer name address') user = self.model(user_name=user_name, first_name=first_name, middel_name=middel_name) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body...
MyUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyUserManager: def create_user(self, user_name, first_name, middel_name, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, user_name, first_name, middel_name, password): """Creates a...
stack_v2_sparse_classes_75kplus_train_068130
8,877
no_license
[ { "docstring": "Creates and saves a User with the given email, date of birth and password.", "name": "create_user", "signature": "def create_user(self, user_name, first_name, middel_name, password=None)" }, { "docstring": "Creates and saves a superuser with the given email, date of birth and pas...
2
stack_v2_sparse_classes_30k_train_039998
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, user_name, first_name, middel_name, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superu...
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, user_name, first_name, middel_name, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superu...
4f980f56661e6a2984302547e1964e36d0face99
<|skeleton|> class MyUserManager: def create_user(self, user_name, first_name, middel_name, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, user_name, first_name, middel_name, password): """Creates a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyUserManager: def create_user(self, user_name, first_name, middel_name, password=None): """Creates and saves a User with the given email, date of birth and password.""" if not user_name: raise ValueError('Users must have an usrer name address') user = self.model(user_name=...
the_stack_v2_python_sparse
authentication/models.py
risuicpc/HACKATHON
train
0
e36da7febc25d1808c02ff25647a226da476fa02
[ "result = local = -2147483647\nfor num in nums:\n local = local + num if local > 0 else num\n result = result if local < result else local\nreturn result", "maximum = nums[0]\nsummation = 0\nfor end in range(len(nums)):\n summation += nums[end]\n maximum = max(maximum, summation)\n if summation < 0...
<|body_start_0|> result = local = -2147483647 for num in nums: local = local + num if local > 0 else num result = result if local < result else local return result <|end_body_0|> <|body_start_1|> maximum = nums[0] summation = 0 for end in range(le...
Solution
[ "MIT" ]
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|> result = local = -2147483647 for num...
stack_v2_sparse_classes_75kplus_train_068131
688
permissive
[ { "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_006376
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: def maxSubArra...
c8bf33af30569177c5276ffcd72a8d93ba4c402a
<|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_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxSubArray(self, nums): """:type nums: List[int] :rtype: int""" result = local = -2147483647 for num in nums: local = local + num if local > 0 else num result = result if local < result else local return result def maxSubArray2(self, ...
the_stack_v2_python_sparse
1-100/51-60/53-maximumSubarray/maximumSubarray.py
xuychen/Leetcode
train
0
a52986be543427835a02850a35e69985f3b2ec27
[ "try:\n import puremagic\n return True\nexcept ModuleNotFoundError as ex:\n pass\nreturn False", "filename = file_check.check_file(filename)\nimport puremagic\ntry:\n rv = puremagic.magic_file(filename)\n if not rv:\n return None\n return clazz._find_mime_type(rv)\nexcept Exception as ex:...
<|body_start_0|> try: import puremagic return True except ModuleNotFoundError as ex: pass return False <|end_body_0|> <|body_start_1|> filename = file_check.check_file(filename) import puremagic try: rv = puremagic.magic_fi...
_file_mime_type_detector_puremagic
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _file_mime_type_detector_puremagic: def is_supported(clazz): """Return True if this class is supported on the current platform.""" <|body_0|> def detect_mime_type(clazz, filename): """Detect the mime type for file.""" <|body_1|> def _find_mime_type(clazz...
stack_v2_sparse_classes_75kplus_train_068132
1,234
permissive
[ { "docstring": "Return True if this class is supported on the current platform.", "name": "is_supported", "signature": "def is_supported(clazz)" }, { "docstring": "Detect the mime type for file.", "name": "detect_mime_type", "signature": "def detect_mime_type(clazz, filename)" }, { ...
3
stack_v2_sparse_classes_30k_val_000516
Implement the Python class `_file_mime_type_detector_puremagic` described below. Class description: Implement the _file_mime_type_detector_puremagic class. Method signatures and docstrings: - def is_supported(clazz): Return True if this class is supported on the current platform. - def detect_mime_type(clazz, filenam...
Implement the Python class `_file_mime_type_detector_puremagic` described below. Class description: Implement the _file_mime_type_detector_puremagic class. Method signatures and docstrings: - def is_supported(clazz): Return True if this class is supported on the current platform. - def detect_mime_type(clazz, filenam...
b9dd35b518848cea82e43d5016e425cc7dac32e5
<|skeleton|> class _file_mime_type_detector_puremagic: def is_supported(clazz): """Return True if this class is supported on the current platform.""" <|body_0|> def detect_mime_type(clazz, filename): """Detect the mime type for file.""" <|body_1|> def _find_mime_type(clazz...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _file_mime_type_detector_puremagic: def is_supported(clazz): """Return True if this class is supported on the current platform.""" try: import puremagic return True except ModuleNotFoundError as ex: pass return False def detect_mime_type...
the_stack_v2_python_sparse
lib/bes/fs/_detail/_file_mime_type_detector_puremagic.py
reconstruir/bes
train
0
94a888a1499bb625e2f178d3fc6de808917f70b2
[ "self.api = api\nself.data = None\nself.tasks = {}", "try:\n self.data = await self.api.user.get()\nexcept ClientResponseError as error:\n if error.status == HTTPStatus.TOO_MANY_REQUESTS:\n _LOGGER.warning('Sensor data update for %s has too many API requests; Skipping the update', DOMAIN)\n else:\...
<|body_start_0|> self.api = api self.data = None self.tasks = {} <|end_body_0|> <|body_start_1|> try: self.data = await self.api.user.get() except ClientResponseError as error: if error.status == HTTPStatus.TOO_MANY_REQUESTS: _LOGGER.warni...
Habitica API user data cache.
HabitipyData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HabitipyData: """Habitica API user data cache.""" def __init__(self, api): """Habitica API user data cache.""" <|body_0|> async def update(self): """Get a new fix from Habitica servers.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.api = ...
stack_v2_sparse_classes_75kplus_train_068133
8,016
permissive
[ { "docstring": "Habitica API user data cache.", "name": "__init__", "signature": "def __init__(self, api)" }, { "docstring": "Get a new fix from Habitica servers.", "name": "update", "signature": "async def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_018630
Implement the Python class `HabitipyData` described below. Class description: Habitica API user data cache. Method signatures and docstrings: - def __init__(self, api): Habitica API user data cache. - async def update(self): Get a new fix from Habitica servers.
Implement the Python class `HabitipyData` described below. Class description: Habitica API user data cache. Method signatures and docstrings: - def __init__(self, api): Habitica API user data cache. - async def update(self): Get a new fix from Habitica servers. <|skeleton|> class HabitipyData: """Habitica API us...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class HabitipyData: """Habitica API user data cache.""" def __init__(self, api): """Habitica API user data cache.""" <|body_0|> async def update(self): """Get a new fix from Habitica servers.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HabitipyData: """Habitica API user data cache.""" def __init__(self, api): """Habitica API user data cache.""" self.api = api self.data = None self.tasks = {} async def update(self): """Get a new fix from Habitica servers.""" try: self.data...
the_stack_v2_python_sparse
homeassistant/components/habitica/sensor.py
home-assistant/core
train
35,501
a28306e53c9456c5fa51fe4f80362c56f2b0c496
[ "actions_path = utils.get_kolla_actions_path()\ncmd = '%s config_reset' % actions_path\nerr_msg, output = utils.run_cmd(cmd, print_output=False)\nif err_msg:\n raise FailedOperation(u._('Configuration reset failed. {error} {message}').format(error=err_msg, message=output))", "check_arg(file_path, u._('File pat...
<|body_start_0|> actions_path = utils.get_kolla_actions_path() cmd = '%s config_reset' % actions_path err_msg, output = utils.run_cmd(cmd, print_output=False) if err_msg: raise FailedOperation(u._('Configuration reset failed. {error} {message}').format(error=err_msg, message=...
ConfigApi
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigApi: def config_reset(): """Config Reset. Resets the kolla-ansible configuration to its release defaults.""" <|body_0|> def config_import_inventory(self, file_path): """Config Import Inventory Import groups and child associations from the provided inventory fil...
stack_v2_sparse_classes_75kplus_train_068134
2,169
permissive
[ { "docstring": "Config Reset. Resets the kolla-ansible configuration to its release defaults.", "name": "config_reset", "signature": "def config_reset()" }, { "docstring": "Config Import Inventory Import groups and child associations from the provided inventory file. This currently does not impo...
2
null
Implement the Python class `ConfigApi` described below. Class description: Implement the ConfigApi class. Method signatures and docstrings: - def config_reset(): Config Reset. Resets the kolla-ansible configuration to its release defaults. - def config_import_inventory(self, file_path): Config Import Inventory Import...
Implement the Python class `ConfigApi` described below. Class description: Implement the ConfigApi class. Method signatures and docstrings: - def config_reset(): Config Reset. Resets the kolla-ansible configuration to its release defaults. - def config_import_inventory(self, file_path): Config Import Inventory Import...
dc38107ff2462f62124b5feab275fa369e223169
<|skeleton|> class ConfigApi: def config_reset(): """Config Reset. Resets the kolla-ansible configuration to its release defaults.""" <|body_0|> def config_import_inventory(self, file_path): """Config Import Inventory Import groups and child associations from the provided inventory fil...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConfigApi: def config_reset(): """Config Reset. Resets the kolla-ansible configuration to its release defaults.""" actions_path = utils.get_kolla_actions_path() cmd = '%s config_reset' % actions_path err_msg, output = utils.run_cmd(cmd, print_output=False) if err_msg: ...
the_stack_v2_python_sparse
kolla_cli/api/config.py
iputra/kolla-cli
train
0
533090537ef05fc6faa3738b6a8c8bfa6c2ca461
[ "buf = self.value[:]\nwhile True:\n if len(buf) <= 8:\n break\n next_entry_offset, flags, ea_name_length, ea_value_length = struct.unpack('<LBBH', buf[:8])\n if 9 + ea_name_length + ea_value_length > len(buf) or next_entry_offset > len(buf):\n break\n name = buf[8:8 + ea_name_length + 1]\n...
<|body_start_0|> buf = self.value[:] while True: if len(buf) <= 8: break next_entry_offset, flags, ea_name_length, ea_value_length = struct.unpack('<LBBH', buf[:8]) if 9 + ea_name_length + ea_value_length > len(buf) or next_entry_offset > len(buf): ...
$EA.
EA
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EA: """$EA.""" def data_parsed(self): """Attempt to parse the extended attribute and yield (name, flags, value) tuples.""" <|body_0|> def print_information(self): """Print all information in a human-readable form.""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_75kplus_train_068135
36,119
permissive
[ { "docstring": "Attempt to parse the extended attribute and yield (name, flags, value) tuples.", "name": "data_parsed", "signature": "def data_parsed(self)" }, { "docstring": "Print all information in a human-readable form.", "name": "print_information", "signature": "def print_informati...
2
stack_v2_sparse_classes_30k_train_003667
Implement the Python class `EA` described below. Class description: $EA. Method signatures and docstrings: - def data_parsed(self): Attempt to parse the extended attribute and yield (name, flags, value) tuples. - def print_information(self): Print all information in a human-readable form.
Implement the Python class `EA` described below. Class description: $EA. Method signatures and docstrings: - def data_parsed(self): Attempt to parse the extended attribute and yield (name, flags, value) tuples. - def print_information(self): Print all information in a human-readable form. <|skeleton|> class EA: ...
f9299b8ad0cb2a6bbbd5e65f01d2ba06406c70ac
<|skeleton|> class EA: """$EA.""" def data_parsed(self): """Attempt to parse the extended attribute and yield (name, flags, value) tuples.""" <|body_0|> def print_information(self): """Print all information in a human-readable form.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EA: """$EA.""" def data_parsed(self): """Attempt to parse the extended attribute and yield (name, flags, value) tuples.""" buf = self.value[:] while True: if len(buf) <= 8: break next_entry_offset, flags, ea_name_length, ea_value_length = st...
the_stack_v2_python_sparse
modules/NTFS/dfir_ntfs/Attributes.py
dfrc-korea/carpe
train
75
d50527a4a2c4782ab993436f24c364725ddf8dd7
[ "if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.TxWFParameters = TxWFParameters\nself.RcvParameters = RcvParameters\nsuper(TxRcvType, self).__init__(**kwargs)", "if self.TxWFParameters is None:\n return 0\nreturn le...
<|body_start_0|> if '_xml_ns' in kwargs: self._xml_ns = kwargs['_xml_ns'] if '_xml_ns_key' in kwargs: self._xml_ns_key = kwargs['_xml_ns_key'] self.TxWFParameters = TxWFParameters self.RcvParameters = RcvParameters super(TxRcvType, self).__init__(**kwargs)...
Parameters that describe the transmitted waveform(s) and receiver configurations used in the collection
TxRcvType
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TxRcvType: """Parameters that describe the transmitted waveform(s) and receiver configurations used in the collection""" def __init__(self, TxWFParameters=None, RcvParameters=None, **kwargs): """Parameters ---------- TxWFParameters : List[TxWFParametersType] RcvParameters : List[RcvP...
stack_v2_sparse_classes_75kplus_train_068136
8,516
permissive
[ { "docstring": "Parameters ---------- TxWFParameters : List[TxWFParametersType] RcvParameters : List[RcvParametersType] kwargs", "name": "__init__", "signature": "def __init__(self, TxWFParameters=None, RcvParameters=None, **kwargs)" }, { "docstring": "int: The number of transmit waveforms used....
3
null
Implement the Python class `TxRcvType` described below. Class description: Parameters that describe the transmitted waveform(s) and receiver configurations used in the collection Method signatures and docstrings: - def __init__(self, TxWFParameters=None, RcvParameters=None, **kwargs): Parameters ---------- TxWFParame...
Implement the Python class `TxRcvType` described below. Class description: Parameters that describe the transmitted waveform(s) and receiver configurations used in the collection Method signatures and docstrings: - def __init__(self, TxWFParameters=None, RcvParameters=None, **kwargs): Parameters ---------- TxWFParame...
de1b1886f161a83b6c89aadc7a2c7cfc4892ef81
<|skeleton|> class TxRcvType: """Parameters that describe the transmitted waveform(s) and receiver configurations used in the collection""" def __init__(self, TxWFParameters=None, RcvParameters=None, **kwargs): """Parameters ---------- TxWFParameters : List[TxWFParametersType] RcvParameters : List[RcvP...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TxRcvType: """Parameters that describe the transmitted waveform(s) and receiver configurations used in the collection""" def __init__(self, TxWFParameters=None, RcvParameters=None, **kwargs): """Parameters ---------- TxWFParameters : List[TxWFParametersType] RcvParameters : List[RcvParametersType...
the_stack_v2_python_sparse
sarpy/io/phase_history/cphd1_elements/TxRcv.py
ngageoint/sarpy
train
192
df4b3f6f33d1a0afa81b2aac8e36fcc0e572a0af
[ "LDC_Info.__init__(self)\nself.setTitle(self.name)\nself.status = compat_res[0]\nui = Ui_videoFrame()\nui.setupUi(self.frame)\nself.__fill_frame(ui, info_res, compat_res, diag_res)", "ui.productLineEdit.setText(QtGui.QApplication.translate('videoFrame', self._check_invalid_values(info_res.model[1]), None, QtGui.Q...
<|body_start_0|> LDC_Info.__init__(self) self.setTitle(self.name) self.status = compat_res[0] ui = Ui_videoFrame() ui.setupUi(self.frame) self.__fill_frame(ui, info_res, compat_res, diag_res) <|end_body_0|> <|body_start_1|> ui.productLineEdit.setText(QtGui.QAppli...
Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo.
GUIVideo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GUIVideo: """Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo.""" def __init__(self, info_res, compat_res, diag_res): """Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_r...
stack_v2_sparse_classes_75kplus_train_068137
4,657
no_license
[ { "docstring": "Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista com as tuples de resultados de compatibilidade [(True, msg)] diag_res -- Lista com os resultados do diagn�stico (lista de 'DaigResSound')", "name": "__init__", "signature"...
3
stack_v2_sparse_classes_30k_train_038532
Implement the Python class `GUIVideo` described below. Class description: Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo. Method signatures and docstrings: - def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os ...
Implement the Python class `GUIVideo` described below. Class description: Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo. Method signatures and docstrings: - def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os ...
bda0c2c8977dd1246339f1f0f4718d29e8795f21
<|skeleton|> class GUIVideo: """Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo.""" def __init__(self, info_res, compat_res, diag_res): """Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_r...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GUIVideo: """Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo.""" def __init__(self, info_res, compat_res, diag_res): """Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista c...
the_stack_v2_python_sparse
src/libs/video/gui_video.py
adrianomelo/ldc-desktop
train
1
0d69952302d41605b0c7d72515a278366e0f0593
[ "ret = [0]\nfor i in range(1, len(pattern)):\n j = ret[i - 1]\n while j > 0 and pattern[j] != pattern[i]:\n j = ret[j - 1]\n ret.append(j + 1 if pattern[j] == pattern[i] else j)\nreturn ret", "partial, ret, j = (self.partial(P), [], 0)\nfor i in range(len(T)):\n while j > 0 and T[i] != P[j]:\n ...
<|body_start_0|> ret = [0] for i in range(1, len(pattern)): j = ret[i - 1] while j > 0 and pattern[j] != pattern[i]: j = ret[j - 1] ret.append(j + 1 if pattern[j] == pattern[i] else j) return ret <|end_body_0|> <|body_start_1|> partial...
KMP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KMP: def partial(self, pattern): """Calculate partial match table: String -> [Int]""" <|body_0|> def search(self, T, P): """KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in S""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_75kplus_train_068138
2,065
no_license
[ { "docstring": "Calculate partial match table: String -> [Int]", "name": "partial", "signature": "def partial(self, pattern)" }, { "docstring": "KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in S", "name": "search", "signature":...
2
stack_v2_sparse_classes_30k_train_039748
Implement the Python class `KMP` described below. Class description: Implement the KMP class. Method signatures and docstrings: - def partial(self, pattern): Calculate partial match table: String -> [Int] - def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o...
Implement the Python class `KMP` described below. Class description: Implement the KMP class. Method signatures and docstrings: - def partial(self, pattern): Calculate partial match table: String -> [Int] - def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o...
112e9b0e2a44efc6c56d4b97976efb95b2d929b6
<|skeleton|> class KMP: def partial(self, pattern): """Calculate partial match table: String -> [Int]""" <|body_0|> def search(self, T, P): """KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in S""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KMP: def partial(self, pattern): """Calculate partial match table: String -> [Int]""" ret = [0] for i in range(1, len(pattern)): j = ret[i - 1] while j > 0 and pattern[j] != pattern[i]: j = ret[j - 1] ret.append(j + 1 if pattern[j] ==...
the_stack_v2_python_sparse
KMP.py
MasKong/Algorithms
train
0
a8bb393c49578613ff2432bd1dba8be6c76a1dc3
[ "self.face_detector = FaceDetector()\nself.cnn_input_size = 128\nself.marks = None\nself.model = keras.models.load_model(saved_model)", "left_x = box[0] + offset[0]\ntop_y = box[1] + offset[1]\nright_x = box[2] + offset[0]\nbottom_y = box[3] + offset[1]\nreturn [left_x, top_y, right_x, bottom_y]", "left_x = box...
<|body_start_0|> self.face_detector = FaceDetector() self.cnn_input_size = 128 self.marks = None self.model = keras.models.load_model(saved_model) <|end_body_0|> <|body_start_1|> left_x = box[0] + offset[0] top_y = box[1] + offset[1] right_x = box[2] + offset[0] ...
Facial landmark detector by Convolutional Neural Network
MarkDetector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarkDetector: """Facial landmark detector by Convolutional Neural Network""" def __init__(self, saved_model='models/pose_model'): """Initialization""" <|body_0|> def move_box(box, offset): """Move the box to direction specified by vector offset""" <|body_...
stack_v2_sparse_classes_75kplus_train_068139
8,266
no_license
[ { "docstring": "Initialization", "name": "__init__", "signature": "def __init__(self, saved_model='models/pose_model')" }, { "docstring": "Move the box to direction specified by vector offset", "name": "move_box", "signature": "def move_box(box, offset)" }, { "docstring": "Get a ...
6
null
Implement the Python class `MarkDetector` described below. Class description: Facial landmark detector by Convolutional Neural Network Method signatures and docstrings: - def __init__(self, saved_model='models/pose_model'): Initialization - def move_box(box, offset): Move the box to direction specified by vector offs...
Implement the Python class `MarkDetector` described below. Class description: Facial landmark detector by Convolutional Neural Network Method signatures and docstrings: - def __init__(self, saved_model='models/pose_model'): Initialization - def move_box(box, offset): Move the box to direction specified by vector offs...
aa13cfcb2e01b8b0db6086328f00e29a6b86021b
<|skeleton|> class MarkDetector: """Facial landmark detector by Convolutional Neural Network""" def __init__(self, saved_model='models/pose_model'): """Initialization""" <|body_0|> def move_box(box, offset): """Move the box to direction specified by vector offset""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MarkDetector: """Facial landmark detector by Convolutional Neural Network""" def __init__(self, saved_model='models/pose_model'): """Initialization""" self.face_detector = FaceDetector() self.cnn_input_size = 128 self.marks = None self.model = keras.models.load_mod...
the_stack_v2_python_sparse
vpt/processors/gaze_detector.py
IamMaxim/vigilant-palm-tree
train
0
180d571d24f7cf7c9ea4aa6f77dbb34e4374a38e
[ "super().__init__(*args, **kwargs)\nself.fields['details'].widget.attrs.update({'class': 'materialize-textarea'})\nself.fields['limit_date'].widget.attrs.update({'class': 'datepicker'})", "hours_input = self.cleaned_data['half_hour_count']\nif not hours_input[0].isdigit():\n raise ValidationError(\"Le nombre d...
<|body_start_0|> super().__init__(*args, **kwargs) self.fields['details'].widget.attrs.update({'class': 'materialize-textarea'}) self.fields['limit_date'].widget.attrs.update({'class': 'datepicker'}) <|end_body_0|> <|body_start_1|> hours_input = self.cleaned_data['half_hour_count'] ...
Define form for job offer publishing.
JobOfferForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobOfferForm: """Define form for job offer publishing.""" def __init__(self, *args, **kwargs): """Extend details field widget.""" <|body_0|> def clean_half_hour_count(self): """Convert form hours into half_hour number.""" <|body_1|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_75kplus_train_068140
1,324
no_license
[ { "docstring": "Extend details field widget.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Convert form hours into half_hour number.", "name": "clean_half_hour_count", "signature": "def clean_half_hour_count(self)" } ]
2
null
Implement the Python class `JobOfferForm` described below. Class description: Define form for job offer publishing. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Extend details field widget. - def clean_half_hour_count(self): Convert form hours into half_hour number.
Implement the Python class `JobOfferForm` described below. Class description: Define form for job offer publishing. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Extend details field widget. - def clean_half_hour_count(self): Convert form hours into half_hour number. <|skeleton|> class Job...
ae4f06e05b21bb208b5c5f7c59583110ad55b600
<|skeleton|> class JobOfferForm: """Define form for job offer publishing.""" def __init__(self, *args, **kwargs): """Extend details field widget.""" <|body_0|> def clean_half_hour_count(self): """Convert form hours into half_hour number.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JobOfferForm: """Define form for job offer publishing.""" def __init__(self, *args, **kwargs): """Extend details field widget.""" super().__init__(*args, **kwargs) self.fields['details'].widget.attrs.update({'class': 'materialize-textarea'}) self.fields['limit_date'].widge...
the_stack_v2_python_sparse
jobs/forms/job_offer.py
cmigazzi/P13_Final
train
0
1d41808229125aed317ccae89bf4798bd2229b2b
[ "result, n = (None, len(A))\nfor move in xrange(n):\n tmp = 0\n for i in xrange(n):\n tmp += A[i] * ((i + move) % n)\n result = max(tmp, result) if result else tmp\nreturn result if result else 0", "result, n = (None, len(A))\ntotal = sum(A)\nprevious = 0\nfor i in xrange(n):\n previous += i * ...
<|body_start_0|> result, n = (None, len(A)) for move in xrange(n): tmp = 0 for i in xrange(n): tmp += A[i] * ((i + move) % n) result = max(tmp, result) if result else tmp return result if result else 0 <|end_body_0|> <|body_start_1|> r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxRotateFunction(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def maxRotateFunction(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> result, n = (None, len(A)) for move i...
stack_v2_sparse_classes_75kplus_train_068141
1,058
no_license
[ { "docstring": ":type A: List[int] :rtype: int", "name": "maxRotateFunction", "signature": "def maxRotateFunction(self, A)" }, { "docstring": ":type A: List[int] :rtype: int", "name": "maxRotateFunction", "signature": "def maxRotateFunction(self, A)" } ]
2
stack_v2_sparse_classes_30k_train_048688
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxRotateFunction(self, A): :type A: List[int] :rtype: int - def maxRotateFunction(self, A): :type A: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxRotateFunction(self, A): :type A: List[int] :rtype: int - def maxRotateFunction(self, A): :type A: List[int] :rtype: int <|skeleton|> class Solution: def maxRotateFu...
ee79d3437cf47b26a4bca0ec798dc54d7b623453
<|skeleton|> class Solution: def maxRotateFunction(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def maxRotateFunction(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxRotateFunction(self, A): """:type A: List[int] :rtype: int""" result, n = (None, len(A)) for move in xrange(n): tmp = 0 for i in xrange(n): tmp += A[i] * ((i + move) % n) result = max(tmp, result) if result else tmp ...
the_stack_v2_python_sparse
Algorithm/Python/396. Rotate Function.py
WuLC/LeetCode
train
29
eb74eaf7bf59841c4786644a4840f9fd030aa8ad
[ "head = ListNode(-1)\np = head\nwhile l1 and l2:\n if l1.val < l2.val:\n p.next = l1\n l1 = l1.next\n else:\n p.next = l2\n l2 = l2.next\n p = p.next\nif l1:\n p.next = l1\nif l2:\n p.next = l2\nreturn head.next", "if l1 is None:\n return l2\nelif l2 is None:\n ret...
<|body_start_0|> head = ListNode(-1) p = head while l1 and l2: if l1.val < l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next if l1: p.next = l1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """双指针法""" <|body_0|> def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: """递归法""" <|body_1|> <|end_skeleton|> <|body_start_0|> head = ListNode(-1) p =...
stack_v2_sparse_classes_75kplus_train_068142
1,496
no_license
[ { "docstring": "双指针法", "name": "mergeTwoLists", "signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode" }, { "docstring": "递归法", "name": "mergeTwoLists2", "signature": "def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode" } ]
2
stack_v2_sparse_classes_30k_train_015432
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 双指针法 - def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归法
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 双指针法 - def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归法 <|skeleton|> class Solution: d...
13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08
<|skeleton|> class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """双指针法""" <|body_0|> def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: """递归法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """双指针法""" head = ListNode(-1) p = head while l1 and l2: if l1.val < l2.val: p.next = l1 l1 = l1.next else: p.next = l2 ...
the_stack_v2_python_sparse
Algorithms/21_Merge_Two_Sorted_Lists/Merge_Two_Sorted_Lists.py
lirui-ML/my_leetcode
train
1
a626a9a56a02f87d97b7dc242bbcc957c99f69ad
[ "DenseVectorPrf.__init__(self)\nself.alpha = alpha\nself.beta = beta\nself.gamma = gamma\nself.topk = topk\nself.bottomk = bottomk", "all_candidate_embs = [item.vectors for item in prf_candidates]\nweighted_query_embs = self.alpha * emb_qs\nweighted_mean_pos_doc_embs = self.beta * np.mean(all_candidate_embs[:self...
<|body_start_0|> DenseVectorPrf.__init__(self) self.alpha = alpha self.beta = beta self.gamma = gamma self.topk = topk self.bottomk = bottomk <|end_body_0|> <|body_start_1|> all_candidate_embs = [item.vectors for item in prf_candidates] weighted_query_emb...
DenseVectorRocchioPrf
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DenseVectorRocchioPrf: def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): """Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigne...
stack_v2_sparse_classes_75kplus_train_068143
7,539
permissive
[ { "docstring": "Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigned to the positive document embeddings. gamma : float Rocchio parameter, controls the weight assigned to the negative doc...
3
stack_v2_sparse_classes_30k_train_020093
Implement the Python class `DenseVectorRocchioPrf` described below. Class description: Implement the DenseVectorRocchioPrf class. Method signatures and docstrings: - def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): Parameters ---------- alpha : float Rocchio parameter, controls th...
Implement the Python class `DenseVectorRocchioPrf` described below. Class description: Implement the DenseVectorRocchioPrf class. Method signatures and docstrings: - def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): Parameters ---------- alpha : float Rocchio parameter, controls th...
42b354914b230880c91b2e4e70605b472441a9a1
<|skeleton|> class DenseVectorRocchioPrf: def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): """Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigne...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DenseVectorRocchioPrf: def __init__(self, alpha: float, beta: float, gamma: float, topk: int, bottomk: int): """Parameters ---------- alpha : float Rocchio parameter, controls the weight assigned to the original query embedding. beta : float Rocchio parameter, controls the weight assigned to the posit...
the_stack_v2_python_sparse
pyserini/search/faiss/_prf.py
castorini/pyserini
train
1,070
6dbbb0165a3e7b4a8f5c1900e13b0dda93327c4f
[ "super(RDB_Conv, self).__init__()\nCin = inChannels\nG = growRate\nself.shgroup = sh_groups\nself.congroup = conv_groups\nself.conv = Sequential(ops.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1, groups=self.congroup), ops.Relu())", "if self.data_format == 'channels_first':\n out = self.conv(channel...
<|body_start_0|> super(RDB_Conv, self).__init__() Cin = inChannels G = growRate self.shgroup = sh_groups self.congroup = conv_groups self.conv = Sequential(ops.Conv2d(Cin, G, kSize, padding=(kSize - 1) // 2, stride=1, groups=self.congroup), ops.Relu()) <|end_body_0|> <|b...
Convolution operation of efficient residual dense block with shuffle and group.
RDB_Conv
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RDB_Conv: """Convolution operation of efficient residual dense block with shuffle and group.""" def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): """Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rat...
stack_v2_sparse_classes_75kplus_train_068144
14,306
permissive
[ { "docstring": "Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rate of block :type growRate: int :param sh_groups: group number of shuffle operation :type sh_groups: int :param conv_groups: group number of convolution operation :type conv_groups: int :...
2
stack_v2_sparse_classes_30k_train_005279
Implement the Python class `RDB_Conv` described below. Class description: Convolution operation of efficient residual dense block with shuffle and group. Method signatures and docstrings: - def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): Initialize Block. :param inChannels: channel number o...
Implement the Python class `RDB_Conv` described below. Class description: Convolution operation of efficient residual dense block with shuffle and group. Method signatures and docstrings: - def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): Initialize Block. :param inChannels: channel number o...
e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04
<|skeleton|> class RDB_Conv: """Convolution operation of efficient residual dense block with shuffle and group.""" def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): """Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RDB_Conv: """Convolution operation of efficient residual dense block with shuffle and group.""" def __init__(self, inChannels, growRate, sh_groups, conv_groups, kSize=3): """Initialize Block. :param inChannels: channel number of input :type inChannels: int :param growRate: growth rate of block :t...
the_stack_v2_python_sparse
zeus/networks/erdb_esr.py
huawei-noah/xingtian
train
308
debcd35298539ba20ed8dc6b17ad58d32aed97f7
[ "task = Task.query.filter_by(id=task_id, job_id=job_id).first()\nif not task:\n return (jsonify(task_id=task_id, log=log_identifier, error='Specified task not found'), NOT_FOUND)\nlog = TaskLog.query.filter_by(identifier=log_identifier).first()\nif not log:\n return (jsonify(task_id=task_id, log=log_identifie...
<|body_start_0|> task = Task.query.filter_by(id=task_id, job_id=job_id).first() if not task: return (jsonify(task_id=task_id, log=log_identifier, error='Specified task not found'), NOT_FOUND) log = TaskLog.query.filter_by(identifier=log_identifier).first() if not log: ...
TaskLogfileAPI
[ "BSD-3-Clause", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskLogfileAPI: def get(self, job_id, task_id, attempt, log_identifier): """A ``GET`` to this endpoint will return the actual logfile or a redirect to it. .. http:get:: /api/v1/jobs/<job_id>/tasks/<task_id>/attempts/<attempt>/logs/<log_identifier>/logfile HTTP/1.1 **Request** .. sourceco...
stack_v2_sparse_classes_75kplus_train_068145
17,414
permissive
[ { "docstring": "A ``GET`` to this endpoint will return the actual logfile or a redirect to it. .. http:get:: /api/v1/jobs/<job_id>/tasks/<task_id>/attempts/<attempt>/logs/<log_identifier>/logfile HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/jobs/4/tasks/1300/attempts/5/logs/2014-09-03_10-58-59_4_4ee024...
2
null
Implement the Python class `TaskLogfileAPI` described below. Class description: Implement the TaskLogfileAPI class. Method signatures and docstrings: - def get(self, job_id, task_id, attempt, log_identifier): A ``GET`` to this endpoint will return the actual logfile or a redirect to it. .. http:get:: /api/v1/jobs/<jo...
Implement the Python class `TaskLogfileAPI` described below. Class description: Implement the TaskLogfileAPI class. Method signatures and docstrings: - def get(self, job_id, task_id, attempt, log_identifier): A ``GET`` to this endpoint will return the actual logfile or a redirect to it. .. http:get:: /api/v1/jobs/<jo...
ea04bbcb807eb669415c569417b4b1b68e75d29d
<|skeleton|> class TaskLogfileAPI: def get(self, job_id, task_id, attempt, log_identifier): """A ``GET`` to this endpoint will return the actual logfile or a redirect to it. .. http:get:: /api/v1/jobs/<job_id>/tasks/<task_id>/attempts/<attempt>/logs/<log_identifier>/logfile HTTP/1.1 **Request** .. sourceco...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TaskLogfileAPI: def get(self, job_id, task_id, attempt, log_identifier): """A ``GET`` to this endpoint will return the actual logfile or a redirect to it. .. http:get:: /api/v1/jobs/<job_id>/tasks/<task_id>/attempts/<attempt>/logs/<log_identifier>/logfile HTTP/1.1 **Request** .. sourcecode:: http GET ...
the_stack_v2_python_sparse
pyfarm/master/api/tasklogs.py
pyfarm/pyfarm-master
train
2
03867f1034b2e8e5b256466273b9181a834351d9
[ "if uuid is None:\n departments = DepartmentService.get_all()\n return ({'departments': self.department_schema.dump(departments, many=True)}, 200)\ndepartment = DepartmentService.get_by_uuid(uuid)\nif not department:\n return ({'message': 'object is not found '}, 404)\nreturn (self.department_schema.dump(d...
<|body_start_0|> if uuid is None: departments = DepartmentService.get_all() return ({'departments': self.department_schema.dump(departments, many=True)}, 200) department = DepartmentService.get_by_uuid(uuid) if not department: return ({'message': 'object is no...
Department REST resource.
DepartmentListApi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DepartmentListApi: """Department REST resource.""" def get(self, uuid=None): """Methog get""" <|body_0|> def post(self): """Methog post""" <|body_1|> def put(self, uuid): """Methog put""" <|body_2|> def delete(self, uuid): ...
stack_v2_sparse_classes_75kplus_train_068146
2,079
no_license
[ { "docstring": "Methog get", "name": "get", "signature": "def get(self, uuid=None)" }, { "docstring": "Methog post", "name": "post", "signature": "def post(self)" }, { "docstring": "Methog put", "name": "put", "signature": "def put(self, uuid)" }, { "docstring": "...
4
stack_v2_sparse_classes_30k_train_048442
Implement the Python class `DepartmentListApi` described below. Class description: Department REST resource. Method signatures and docstrings: - def get(self, uuid=None): Methog get - def post(self): Methog post - def put(self, uuid): Methog put - def delete(self, uuid): Methog delete
Implement the Python class `DepartmentListApi` described below. Class description: Department REST resource. Method signatures and docstrings: - def get(self, uuid=None): Methog get - def post(self): Methog post - def put(self, uuid): Methog put - def delete(self, uuid): Methog delete <|skeleton|> class DepartmentLi...
0a78ca5d8bca76c63ab2f1e5738e11096074403b
<|skeleton|> class DepartmentListApi: """Department REST resource.""" def get(self, uuid=None): """Methog get""" <|body_0|> def post(self): """Methog post""" <|body_1|> def put(self, uuid): """Methog put""" <|body_2|> def delete(self, uuid): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DepartmentListApi: """Department REST resource.""" def get(self, uuid=None): """Methog get""" if uuid is None: departments = DepartmentService.get_all() return ({'departments': self.department_schema.dump(departments, many=True)}, 200) department = Departme...
the_stack_v2_python_sparse
src/api/resources/departments.py
VladyslavPodrazhanskyi/departments_application
train
0
a17b83d526c2833d58a08949d753161de85d3523
[ "self.filename = filename\nself.pixel_size = pixel_size\nself.unit = unit\nif img_data is not None:\n self.img_data = img_data\n self.img_dims = self.img_data.shape\n self.img_bitdepth = self.img_data.dtype\nelse:\n self.get_image()\nself.tiles = {}", "if self.filename is not None:\n if os.path.spl...
<|body_start_0|> self.filename = filename self.pixel_size = pixel_size self.unit = unit if img_data is not None: self.img_data = img_data self.img_dims = self.img_data.shape self.img_bitdepth = self.img_data.dtype else: self.get_ima...
Class for a generic image
Image
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Image: """Class for a generic image""" def __init__(self, filename: Optional[str]=None, img_data: Optional[np.ndarray]=None, pixel_size: Optional[float]=None, unit: Optional[str]=None): """Class holding Image data + metadata Args: filename (Optional[str], optional): Filename for the ...
stack_v2_sparse_classes_75kplus_train_068147
4,444
permissive
[ { "docstring": "Class holding Image data + metadata Args: filename (Optional[str], optional): Filename for the image, in tiff or mrc. Defaults to None. img_data (Optional[np.ndarray], optional): Array holding image data. Defaults to None. pixel_size (Optional[float], optional): Pixel size. Defaults to None. uni...
3
stack_v2_sparse_classes_30k_train_015842
Implement the Python class `Image` described below. Class description: Class for a generic image Method signatures and docstrings: - def __init__(self, filename: Optional[str]=None, img_data: Optional[np.ndarray]=None, pixel_size: Optional[float]=None, unit: Optional[str]=None): Class holding Image data + metadata Ar...
Implement the Python class `Image` described below. Class description: Class for a generic image Method signatures and docstrings: - def __init__(self, filename: Optional[str]=None, img_data: Optional[np.ndarray]=None, pixel_size: Optional[float]=None, unit: Optional[str]=None): Class holding Image data + metadata Ar...
c5e0170031ffba0dce2c16414b91860988b566b2
<|skeleton|> class Image: """Class for a generic image""" def __init__(self, filename: Optional[str]=None, img_data: Optional[np.ndarray]=None, pixel_size: Optional[float]=None, unit: Optional[str]=None): """Class holding Image data + metadata Args: filename (Optional[str], optional): Filename for the ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Image: """Class for a generic image""" def __init__(self, filename: Optional[str]=None, img_data: Optional[np.ndarray]=None, pixel_size: Optional[float]=None, unit: Optional[str]=None): """Class holding Image data + metadata Args: filename (Optional[str], optional): Filename for the image, in tif...
the_stack_v2_python_sparse
src/quoll/io/reader.py
rosalindfranklininstitute/quoll
train
0
cfa77988b8017324c9384e4080bba104396d72f1
[ "super().__init__()\ninitialize(self, init_type)\nself.msd = HiFiGANMultiScaleDiscriminator(scales=scales, downsample_pooling=scale_downsample_pooling, downsample_pooling_params=scale_downsample_pooling_params, discriminator_params=scale_discriminator_params, follow_official_norm=follow_official_norm)\nself.mpd = H...
<|body_start_0|> super().__init__() initialize(self, init_type) self.msd = HiFiGANMultiScaleDiscriminator(scales=scales, downsample_pooling=scale_downsample_pooling, downsample_pooling_params=scale_downsample_pooling_params, discriminator_params=scale_discriminator_params, follow_official_norm=f...
HiFi-GAN multi-scale + multi-period discriminator module.
HiFiGANMultiScaleMultiPeriodDiscriminator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HiFiGANMultiScaleMultiPeriodDiscriminator: """HiFi-GAN multi-scale + multi-period discriminator module.""" def __init__(self, scales: int=3, scale_downsample_pooling: str='AvgPool1D', scale_downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2, 'padding': 2}, scale_discrim...
stack_v2_sparse_classes_75kplus_train_068148
30,988
permissive
[ { "docstring": "Initilize HiFiGAN multi-scale + multi-period discriminator module. Args: scales (int): Number of multi-scales. scale_downsample_pooling (str): Pooling module name for downsampling of the inputs. scale_downsample_pooling_params (dict): Parameters for the above pooling module. scale_discriminator_...
2
stack_v2_sparse_classes_30k_train_014461
Implement the Python class `HiFiGANMultiScaleMultiPeriodDiscriminator` described below. Class description: HiFi-GAN multi-scale + multi-period discriminator module. Method signatures and docstrings: - def __init__(self, scales: int=3, scale_downsample_pooling: str='AvgPool1D', scale_downsample_pooling_params: Dict[st...
Implement the Python class `HiFiGANMultiScaleMultiPeriodDiscriminator` described below. Class description: HiFi-GAN multi-scale + multi-period discriminator module. Method signatures and docstrings: - def __init__(self, scales: int=3, scale_downsample_pooling: str='AvgPool1D', scale_downsample_pooling_params: Dict[st...
17854a04d43c231eff66bfed9d6aa55e94a29e79
<|skeleton|> class HiFiGANMultiScaleMultiPeriodDiscriminator: """HiFi-GAN multi-scale + multi-period discriminator module.""" def __init__(self, scales: int=3, scale_downsample_pooling: str='AvgPool1D', scale_downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2, 'padding': 2}, scale_discrim...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HiFiGANMultiScaleMultiPeriodDiscriminator: """HiFi-GAN multi-scale + multi-period discriminator module.""" def __init__(self, scales: int=3, scale_downsample_pooling: str='AvgPool1D', scale_downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2, 'padding': 2}, scale_discriminator_params...
the_stack_v2_python_sparse
paddlespeech/t2s/models/hifigan/hifigan.py
anniyanvr/DeepSpeech-1
train
0
06dbc29738984f080d38ea0602d411d1c827b01e
[ "self.capacity = capacity\nself.d_cache = {}\nself.lru_cache = deque()", "if key not in self.d_cache:\n return -1\nelse:\n self.lru_cache.remove(key)\n self.lru_cache.appendleft(key)\n return self.d_cache[key]", "self.d_cache.update({key: value})\nif len(self.d_cache) > self.capacity:\n self.d_ca...
<|body_start_0|> self.capacity = capacity self.d_cache = {} self.lru_cache = deque() <|end_body_0|> <|body_start_1|> if key not in self.d_cache: return -1 else: self.lru_cache.remove(key) self.lru_cache.appendleft(key) return self....
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_068149
1,137
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
stack_v2_sparse_classes_30k_train_053558
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
638a1312a66805fefb2a1e1dd7b4968d2c957564
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.d_cache = {} self.lru_cache = deque() def get(self, key): """:type key: int :rtype: int""" if key not in self.d_cache: return -1 else: ...
the_stack_v2_python_sparse
lru_cache.py
wotann07/leetcode_py
train
0
022513e06de38bc45441ce79e5269fa1cb3ce05e
[ "await data.check(user)\nasync with aiosqlite.connect('data\\\\economy.db') as conn:\n async with conn.execute('SELECT * from ECONOMY') as cursor:\n async for row in cursor:\n if row[0] == user:\n return row[2]", "await data.check(user)\nasync with aiosqlite.connect('data\\\\ec...
<|body_start_0|> await data.check(user) async with aiosqlite.connect('data\\economy.db') as conn: async with conn.execute('SELECT * from ECONOMY') as cursor: async for row in cursor: if row[0] == user: return row[2] <|end_body_0|> ...
Bank
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bank: async def get(self, user): """Get someone's bank balance.""" <|body_0|> async def add(self, user, add): """Adds money to someone's bank.""" <|body_1|> async def remove(self, user, take): """Removes money from someone's bank.""" <|bo...
stack_v2_sparse_classes_75kplus_train_068150
5,807
no_license
[ { "docstring": "Get someone's bank balance.", "name": "get", "signature": "async def get(self, user)" }, { "docstring": "Adds money to someone's bank.", "name": "add", "signature": "async def add(self, user, add)" }, { "docstring": "Removes money from someone's bank.", "name"...
3
stack_v2_sparse_classes_30k_train_015566
Implement the Python class `Bank` described below. Class description: Implement the Bank class. Method signatures and docstrings: - async def get(self, user): Get someone's bank balance. - async def add(self, user, add): Adds money to someone's bank. - async def remove(self, user, take): Removes money from someone's ...
Implement the Python class `Bank` described below. Class description: Implement the Bank class. Method signatures and docstrings: - async def get(self, user): Get someone's bank balance. - async def add(self, user, add): Adds money to someone's bank. - async def remove(self, user, take): Removes money from someone's ...
3d075c516124d3a25feebd584fdc351c3abc6613
<|skeleton|> class Bank: async def get(self, user): """Get someone's bank balance.""" <|body_0|> async def add(self, user, add): """Adds money to someone's bank.""" <|body_1|> async def remove(self, user, take): """Removes money from someone's bank.""" <|bo...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Bank: async def get(self, user): """Get someone's bank balance.""" await data.check(user) async with aiosqlite.connect('data\\economy.db') as conn: async with conn.execute('SELECT * from ECONOMY') as cursor: async for row in cursor: if ro...
the_stack_v2_python_sparse
core/EcoCore.py
Smudge-Studios/smudge
train
0
94883229724aacbea61658f4593af4227778749c
[ "self.nesterov = nesterov\nself.learning_rate = learning_rate\nself.momentum = momentum\nself.accumulated = None", "worker_ids = list(dict_gradients.keys())\nif self.accumulated is None and self.momentum > 0:\n self.accumulated = []\n for index_layer in range(len(model.keras_model.get_weights())):\n ...
<|body_start_0|> self.nesterov = nesterov self.learning_rate = learning_rate self.momentum = momentum self.accumulated = None <|end_body_0|> <|body_start_1|> worker_ids = list(dict_gradients.keys()) if self.accumulated is None and self.momentum > 0: self.accu...
This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`.
SGD
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SGD: """This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`.""" def __init__(self, learning_rate, momentum=0, nesterov=False): """Create a :class:`SGD` instance. Parameters ---------- learning_rat...
stack_v2_sparse_classes_75kplus_train_068151
5,766
permissive
[ { "docstring": "Create a :class:`SGD` instance. Parameters ---------- learning_rate: float Learning rate for training. momentum: float Optimizer momentum. nesterov: boolean Flag indicating if the momentum optimizer is Nesterov or not.", "name": "__init__", "signature": "def __init__(self, learning_rate,...
2
stack_v2_sparse_classes_30k_train_048409
Implement the Python class `SGD` described below. Class description: This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`. Method signatures and docstrings: - def __init__(self, learning_rate, momentum=0, nesterov=False): Create a ...
Implement the Python class `SGD` described below. Class description: This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`. Method signatures and docstrings: - def __init__(self, learning_rate, momentum=0, nesterov=False): Create a ...
ccc0a7674a04ae0d00bedc38893b33184c5f68c6
<|skeleton|> class SGD: """This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`.""" def __init__(self, learning_rate, momentum=0, nesterov=False): """Create a :class:`SGD` instance. Parameters ---------- learning_rat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SGD: """This class implements the Stocastic Gradient Descent optimization approach, run at Master node. It inherits from :class:`GradientOptimizer`.""" def __init__(self, learning_rate, momentum=0, nesterov=False): """Create a :class:`SGD` instance. Parameters ---------- learning_rate: float Lear...
the_stack_v2_python_sparse
MMLL/aggregators/aggregator.py
Musketeer-H2020/MMLL-Robust
train
0
ea1446e829194f3f6abfca6a085dd1b9c67c1137
[ "super().__init__(**kwargs)\nself.login_page_selectors = kwargs.get('login_page_selectors', None)\nself.selectors = kwargs.get('selectors', None)\nself.login_button_selector = kwargs.get('login_button_selector', None)\nkwargs['selector'] = self.login_button_selector\nself.login_button_action = ScraperAction(**kwarg...
<|body_start_0|> super().__init__(**kwargs) self.login_page_selectors = kwargs.get('login_page_selectors', None) self.selectors = kwargs.get('selectors', None) self.login_button_selector = kwargs.get('login_button_selector', None) kwargs['selector'] = self.login_button_selector ...
Python class that will log into an interface
ScraperLogin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScraperLogin: """Python class that will log into an interface""" def __init__(self, **kwargs): """Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to op...
stack_v2_sparse_classes_75kplus_train_068152
4,501
no_license
[ { "docstring": "Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to open default None open_url: bool True to open upon startup and False it waits. command: str command this compone...
4
stack_v2_sparse_classes_30k_train_020557
Implement the Python class `ScraperLogin` described below. Class description: Python class that will log into an interface Method signatures and docstrings: - def __init__(self, **kwargs): Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_d...
Implement the Python class `ScraperLogin` described below. Class description: Python class that will log into an interface Method signatures and docstrings: - def __init__(self, **kwargs): Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_d...
c2577d8626e09a2f388b774fe0c78dda6a4464db
<|skeleton|> class ScraperLogin: """Python class that will log into an interface""" def __init__(self, **kwargs): """Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to op...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScraperLogin: """Python class that will log into an interface""" def __init__(self, **kwargs): """Constructor for all ScraperComponents :param **kwargs dict using the following data. driver: WebScraper driver default None web_driver: WebScraper default None scraper_url: str url to open default No...
the_stack_v2_python_sparse
events_hitparade_co/components/login.py
richardathitparade/hitparade_bots
train
0
0c537649fc89f3a6db7c05b8ef1c75265fe7524d
[ "if reflection_table.get_flags(reflection_table.flags.integrated_prf).count(True) == 0:\n raise NoProfilesException('WARNING: No profile-integrated reflections found')\nselection = reflection_table.get_flags(reflection_table.flags.integrated, all=False)\nreflection_table = reflection_table.select(selection)\nlog...
<|body_start_0|> if reflection_table.get_flags(reflection_table.flags.integrated_prf).count(True) == 0: raise NoProfilesException('WARNING: No profile-integrated reflections found') selection = reflection_table.get_flags(reflection_table.flags.integrated, all=False) reflection_table ...
Reduction methods for data with sum or profile intensities. Reflections with valid values for either intensity type are retained.
SumORPrfIntensityReducer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SumORPrfIntensityReducer: """Reduction methods for data with sum or profile intensities. Reflections with valid values for either intensity type are retained.""" def reduce_on_intensities(reflection_table): """Select reflections successfully integrated by sum and prf methods.""" ...
stack_v2_sparse_classes_75kplus_train_068153
38,270
permissive
[ { "docstring": "Select reflections successfully integrated by sum and prf methods.", "name": "reduce_on_intensities", "signature": "def reduce_on_intensities(reflection_table)" }, { "docstring": "Apply corrections to the intensities and variances (partiality, lp, qe).", "name": "apply_scalin...
2
stack_v2_sparse_classes_30k_train_004273
Implement the Python class `SumORPrfIntensityReducer` described below. Class description: Reduction methods for data with sum or profile intensities. Reflections with valid values for either intensity type are retained. Method signatures and docstrings: - def reduce_on_intensities(reflection_table): Select reflection...
Implement the Python class `SumORPrfIntensityReducer` described below. Class description: Reduction methods for data with sum or profile intensities. Reflections with valid values for either intensity type are retained. Method signatures and docstrings: - def reduce_on_intensities(reflection_table): Select reflection...
88bf7f7c5ac44defc046ebf0719cde748092cfff
<|skeleton|> class SumORPrfIntensityReducer: """Reduction methods for data with sum or profile intensities. Reflections with valid values for either intensity type are retained.""" def reduce_on_intensities(reflection_table): """Select reflections successfully integrated by sum and prf methods.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SumORPrfIntensityReducer: """Reduction methods for data with sum or profile intensities. Reflections with valid values for either intensity type are retained.""" def reduce_on_intensities(reflection_table): """Select reflections successfully integrated by sum and prf methods.""" if reflec...
the_stack_v2_python_sparse
src/dials/util/filter_reflections.py
dials/dials
train
71
b421b5feeca6ba51be0159db4ec5e674e2335ac6
[ "get_request = request.query_params\nfile_name = get_request.get('file_name')\nif not file_name:\n raise InvalidParameterException('Missing one or more required query parameters: file_name')\nreturn self.get_download_status_response(file_name=file_name)", "download_job = get_download_job(file_name)\nfile_path ...
<|body_start_0|> get_request = request.query_params file_name = get_request.get('file_name') if not file_name: raise InvalidParameterException('Missing one or more required query parameters: file_name') return self.get_download_status_response(file_name=file_name) <|end_body_...
This route gets the current status of a download job that that has been requested with the `v2/download/awards/` or `v2/download/transaction/` endpoint that same day. Accessed by both `v2/download/status/?file_name=""` and `v2/bulk_download/status/?file_name=""`.
DownloadStatusViewSet
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DownloadStatusViewSet: """This route gets the current status of a download job that that has been requested with the `v2/download/awards/` or `v2/download/transaction/` endpoint that same day. Accessed by both `v2/download/status/?file_name=""` and `v2/bulk_download/status/?file_name=""`.""" ...
stack_v2_sparse_classes_75kplus_train_068154
2,016
permissive
[ { "docstring": "Obtain status for the download job matching the file name provided", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Generate download status response which encompasses various elements to provide accurate status for state of a download job", "name": "...
2
null
Implement the Python class `DownloadStatusViewSet` described below. Class description: This route gets the current status of a download job that that has been requested with the `v2/download/awards/` or `v2/download/transaction/` endpoint that same day. Accessed by both `v2/download/status/?file_name=""` and `v2/bulk_...
Implement the Python class `DownloadStatusViewSet` described below. Class description: This route gets the current status of a download job that that has been requested with the `v2/download/awards/` or `v2/download/transaction/` endpoint that same day. Accessed by both `v2/download/status/?file_name=""` and `v2/bulk_...
38f920438697930ae3ac57bbcaae9034877d8fb7
<|skeleton|> class DownloadStatusViewSet: """This route gets the current status of a download job that that has been requested with the `v2/download/awards/` or `v2/download/transaction/` endpoint that same day. Accessed by both `v2/download/status/?file_name=""` and `v2/bulk_download/status/?file_name=""`.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DownloadStatusViewSet: """This route gets the current status of a download job that that has been requested with the `v2/download/awards/` or `v2/download/transaction/` endpoint that same day. Accessed by both `v2/download/status/?file_name=""` and `v2/bulk_download/status/?file_name=""`.""" def get(self...
the_stack_v2_python_sparse
usaspending_api/download/v2/download_status.py
fedspendingtransparency/usaspending-api
train
276
9251b2fe1bd84f36119cadde501ff41ed6d9f7c7
[ "if not strs:\n return chr(258)\nreturn chr(257).join(strs)", "if s == chr(258):\n return []\nreturn s.split(chr(257))" ]
<|body_start_0|> if not strs: return chr(258) return chr(257).join(strs) <|end_body_0|> <|body_start_1|> if s == chr(258): return [] return s.split(chr(257)) <|end_body_1|>
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" <|body_0|> def decode(self, s: str) -> [str]: """Decodes a single string to a list of strings.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not st...
stack_v2_sparse_classes_75kplus_train_068155
2,535
no_license
[ { "docstring": "Encodes a list of strings to a single string.", "name": "encode", "signature": "def encode(self, strs: [str]) -> str" }, { "docstring": "Decodes a single string to a list of strings.", "name": "decode", "signature": "def decode(self, s: str) -> [str]" } ]
2
stack_v2_sparse_classes_30k_test_001888
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string. - def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string. - def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. <|skeleton|> cla...
44765a7d89423b7ec2c159f70b1a6f6e446523c2
<|skeleton|> class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" <|body_0|> def decode(self, s: str) -> [str]: """Decodes a single string to a list of strings.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" if not strs: return chr(258) return chr(257).join(strs) def decode(self, s: str) -> [str]: """Decodes a single string to a list of strings.""" if s == chr(2...
the_stack_v2_python_sparse
python/_0001_0500/0271_encode-and-decode-strings.py
Wang-Yann/LeetCodeMe
train
0
9ed5a2425042d0e129ebe8034ec9ba2124835648
[ "self.logger = policy.logger\nself.yaml = policy.main_policy['port_sets']['port_set_list'][idx]\nself.name = self.yaml['name']\nvalidate(self.logger, self.yaml, PORT_SET_SCHEMA, 'port_set')\nport_list = self.yaml['port_list']\nfor ports in port_list:\n ports['ports_xform'] = transform_ports(ports['ports'])", "...
<|body_start_0|> self.logger = policy.logger self.yaml = policy.main_policy['port_sets']['port_set_list'][idx] self.name = self.yaml['name'] validate(self.logger, self.yaml, PORT_SET_SCHEMA, 'port_set') port_list = self.yaml['port_list'] for ports in port_list: ...
An object that represents a single port set
PortSet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PortSet: """An object that represents a single port set""" def __init__(self, policy, idx): """Initialise the PortSet Class""" <|body_0|> def is_member(self, dpid, port, vlan_id=0): """Check to see supplied dpid/port/vlan_id is member of this port set. Returns a ...
stack_v2_sparse_classes_75kplus_train_068156
38,856
permissive
[ { "docstring": "Initialise the PortSet Class", "name": "__init__", "signature": "def __init__(self, policy, idx)" }, { "docstring": "Check to see supplied dpid/port/vlan_id is member of this port set. Returns a Boolean", "name": "is_member", "signature": "def is_member(self, dpid, port, ...
2
stack_v2_sparse_classes_30k_train_027871
Implement the Python class `PortSet` described below. Class description: An object that represents a single port set Method signatures and docstrings: - def __init__(self, policy, idx): Initialise the PortSet Class - def is_member(self, dpid, port, vlan_id=0): Check to see supplied dpid/port/vlan_id is member of this...
Implement the Python class `PortSet` described below. Class description: An object that represents a single port set Method signatures and docstrings: - def __init__(self, policy, idx): Initialise the PortSet Class - def is_member(self, dpid, port, vlan_id=0): Check to see supplied dpid/port/vlan_id is member of this...
55cc27e81defc42775ff563bfbef31800e089b14
<|skeleton|> class PortSet: """An object that represents a single port set""" def __init__(self, policy, idx): """Initialise the PortSet Class""" <|body_0|> def is_member(self, dpid, port, vlan_id=0): """Check to see supplied dpid/port/vlan_id is member of this port set. Returns a ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PortSet: """An object that represents a single port set""" def __init__(self, policy, idx): """Initialise the PortSet Class""" self.logger = policy.logger self.yaml = policy.main_policy['port_sets']['port_set_list'][idx] self.name = self.yaml['name'] validate(self....
the_stack_v2_python_sparse
nmeta/policy.py
awesome-nfv/nmeta
train
0
6e677ce3ce567f282a5dacb9fe94563dbaaf4f2b
[ "if len(digits) == 0:\n return []\nd = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\nans = ['']\nfor digit in digits:\n temp = []\n for s in ans:\n for c in d[int(digit)]:\n temp.append(s + c)\n ans = temp\nreturn ans", "if len(digits) == 0:\n return []\nd = ...
<|body_start_0|> if len(digits) == 0: return [] d = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] ans = [''] for digit in digits: temp = [] for s in ans: for c in d[int(digit)]: temp.append(s + c...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str] BFS: time: O(4^n), space: O(4^n * 2) since we have a temp on 18, its asymptotic length is also O(4^n) in the final round reference: https://www.youtube.com/watch?v=fLy8t33M1qQ""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_068157
2,300
no_license
[ { "docstring": ":type digits: str :rtype: List[str] BFS: time: O(4^n), space: O(4^n * 2) since we have a temp on 18, its asymptotic length is also O(4^n) in the final round reference: https://www.youtube.com/watch?v=fLy8t33M1qQ", "name": "letterCombinations", "signature": "def letterCombinations(self, d...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def letterCombinations(self, digits): :type digits: str :rtype: List[str] BFS: time: O(4^n), space: O(4^n * 2) since we have a temp on 18, its asymptotic length is also O(4^n) in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def letterCombinations(self, digits): :type digits: str :rtype: List[str] BFS: time: O(4^n), space: O(4^n * 2) since we have a temp on 18, its asymptotic length is also O(4^n) in...
9746205998338fb4d7fd51300a21149c4181fc8f
<|skeleton|> class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str] BFS: time: O(4^n), space: O(4^n * 2) since we have a temp on 18, its asymptotic length is also O(4^n) in the final round reference: https://www.youtube.com/watch?v=fLy8t33M1qQ""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def letterCombinations(self, digits): """:type digits: str :rtype: List[str] BFS: time: O(4^n), space: O(4^n * 2) since we have a temp on 18, its asymptotic length is also O(4^n) in the final round reference: https://www.youtube.com/watch?v=fLy8t33M1qQ""" if len(digits) == 0: ...
the_stack_v2_python_sparse
leetcode/search/1_letter_combination_phone_number.py
RuizhenMai/academic-blog
train
0
464ebe7a98f4f90c7f2111d2f6a6d123f7a0eba4
[ "super().__init__()\nself.num_fields = num_fields\nself.transforms = transforms\nself.length = 1", "if inputs.dim() == 2:\n inputs = inputs.unsqueeze(dim=-1)\nif self.transforms:\n inputs = self.transforms(inputs)\ninputs.names = ('B', 'N', 'E')\nreturn inputs" ]
<|body_start_0|> super().__init__() self.num_fields = num_fields self.transforms = transforms self.length = 1 <|end_body_0|> <|body_start_1|> if inputs.dim() == 2: inputs = inputs.unsqueeze(dim=-1) if self.transforms: inputs = self.transforms(inpu...
Base Input class for value to be passed directly.
ValueInput
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValueInput: """Base Input class for value to be passed directly.""" def __init__(self, num_fields: int, transforms: Optional[Callable]=None): """Initialize ValueInput Args: num_fields (int): Number of inputs' fields.""" <|body_0|> def forward(self, inputs: torch.Tensor) ...
stack_v2_sparse_classes_75kplus_train_068158
1,059
permissive
[ { "docstring": "Initialize ValueInput Args: num_fields (int): Number of inputs' fields.", "name": "__init__", "signature": "def __init__(self, num_fields: int, transforms: Optional[Callable]=None)" }, { "docstring": "Forward calculation of ValueInput. Args: inputs (T), shape = (B, N): Tensor of ...
2
null
Implement the Python class `ValueInput` described below. Class description: Base Input class for value to be passed directly. Method signatures and docstrings: - def __init__(self, num_fields: int, transforms: Optional[Callable]=None): Initialize ValueInput Args: num_fields (int): Number of inputs' fields. - def forw...
Implement the Python class `ValueInput` described below. Class description: Base Input class for value to be passed directly. Method signatures and docstrings: - def __init__(self, num_fields: int, transforms: Optional[Callable]=None): Initialize ValueInput Args: num_fields (int): Number of inputs' fields. - def forw...
751a43b9cd35e951d81c0d9cf46507b1777bb7ff
<|skeleton|> class ValueInput: """Base Input class for value to be passed directly.""" def __init__(self, num_fields: int, transforms: Optional[Callable]=None): """Initialize ValueInput Args: num_fields (int): Number of inputs' fields.""" <|body_0|> def forward(self, inputs: torch.Tensor) ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ValueInput: """Base Input class for value to be passed directly.""" def __init__(self, num_fields: int, transforms: Optional[Callable]=None): """Initialize ValueInput Args: num_fields (int): Number of inputs' fields.""" super().__init__() self.num_fields = num_fields self....
the_stack_v2_python_sparse
torecsys/inputs/base/value_inp.py
p768lwy3/torecsys
train
98
82a930f739e72f6da303b4cfa3f015d7718d3ce3
[ "assert features.is_contiguous()\nassert indices.is_contiguous()\nassert weight.is_contiguous()\nB, c, m = features.size()\nn = indices.size(1)\nctx.three_interpolate_for_backward = (indices, weight, m)\noutput = features.new_empty(B, c, n)\next_module.three_interpolate_forward(features, indices, weight, output, b=...
<|body_start_0|> assert features.is_contiguous() assert indices.is_contiguous() assert weight.is_contiguous() B, c, m = features.size() n = indices.size(1) ctx.three_interpolate_for_backward = (indices, weight, m) output = features.new_empty(B, c, n) ext_m...
Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.
ThreeInterpolate
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThreeInterpolate: """Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.""" def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """Arg...
stack_v2_sparse_classes_75kplus_train_068159
2,240
permissive
[ { "docstring": "Args: features (torch.Tensor): (B, C, M) Features descriptors to be interpolated. indices (torch.Tensor): (B, n, 3) indices of three nearest neighbor features for the target features. weight (torch.Tensor): (B, n, 3) weights of three nearest neighbor features for the target features. Returns: to...
2
stack_v2_sparse_classes_30k_train_016958
Implement the Python class `ThreeInterpolate` described below. Class description: Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details. Method signatures and docstrings: - def forward(ctx: Any, features: torch.Tensor, indices:...
Implement the Python class `ThreeInterpolate` described below. Class description: Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details. Method signatures and docstrings: - def forward(ctx: Any, features: torch.Tensor, indices:...
6e9ee26718b22961d5c34caca4108413b1b7b3af
<|skeleton|> class ThreeInterpolate: """Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.""" def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """Arg...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ThreeInterpolate: """Performs weighted linear interpolation on 3 features. Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ for more details.""" def forward(ctx: Any, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """Args: features (...
the_stack_v2_python_sparse
mmcv/ops/three_interpolate.py
open-mmlab/mmcv
train
5,319
c3a38c921925b5fe392567fc06a3419bdc8ee4d0
[ "try:\n obj_kwargs = kwargs.copy()\n obj_kwargs[self.uri_object_key] = object_id\n review_request = resources.review_request.get_object(request, *args, **obj_kwargs)\n user = resources.user.get_object(request, *args, **kwargs)\nexcept (ReviewRequest.DoesNotExist, User.DoesNotExist):\n return DOES_NOT...
<|body_start_0|> try: obj_kwargs = kwargs.copy() obj_kwargs[self.uri_object_key] = object_id review_request = resources.review_request.get_object(request, *args, **obj_kwargs) user = resources.user.get_object(request, *args, **kwargs) except (ReviewRequest...
A base resource for objects archived or muted by a user.
BaseArchivedObjectResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseArchivedObjectResource: """A base resource for objects archived or muted by a user.""" def create(self, request, object_id, *args, **kwargs): """Handle HTTP POST operations.""" <|body_0|> def delete(self, request, review_request_id, *args, **kwargs): """Handl...
stack_v2_sparse_classes_75kplus_train_068160
3,181
permissive
[ { "docstring": "Handle HTTP POST operations.", "name": "create", "signature": "def create(self, request, object_id, *args, **kwargs)" }, { "docstring": "Handle HTTP DELETE operations.", "name": "delete", "signature": "def delete(self, request, review_request_id, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_test_002187
Implement the Python class `BaseArchivedObjectResource` described below. Class description: A base resource for objects archived or muted by a user. Method signatures and docstrings: - def create(self, request, object_id, *args, **kwargs): Handle HTTP POST operations. - def delete(self, request, review_request_id, *a...
Implement the Python class `BaseArchivedObjectResource` described below. Class description: A base resource for objects archived or muted by a user. Method signatures and docstrings: - def create(self, request, object_id, *args, **kwargs): Handle HTTP POST operations. - def delete(self, request, review_request_id, *a...
c3a991f1e9d7682239a1ab0e8661cee6da01d537
<|skeleton|> class BaseArchivedObjectResource: """A base resource for objects archived or muted by a user.""" def create(self, request, object_id, *args, **kwargs): """Handle HTTP POST operations.""" <|body_0|> def delete(self, request, review_request_id, *args, **kwargs): """Handl...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BaseArchivedObjectResource: """A base resource for objects archived or muted by a user.""" def create(self, request, object_id, *args, **kwargs): """Handle HTTP POST operations.""" try: obj_kwargs = kwargs.copy() obj_kwargs[self.uri_object_key] = object_id ...
the_stack_v2_python_sparse
reviewboard/webapi/resources/base_archived_object.py
reviewboard/reviewboard
train
1,141
c6880af19233a48abb697f13caf1fbedc4ae6fb5
[ "if not request.user.id:\n return BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_NOT_LOGIN_ERR).to_response()\nvarieties_id = request.GET.get('varieties_id', None)\nformulas = Formula.objects.filter(Q(user_id=None) | Q(user_id=request.user.id))\nif varieties_id:\n formulas = formulas.filter(id...
<|body_start_0|> if not request.user.id: return BackstageHTTPResponse(code=BackstageHTTPResponse.API_HTTP_CODE_NOT_LOGIN_ERR).to_response() varieties_id = request.GET.get('varieties_id', None) formulas = Formula.objects.filter(Q(user_id=None) | Q(user_id=request.user.id)) if ...
UserSubscriptionFormulaListAPI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserSubscriptionFormulaListAPI: def get(self, request, *args, **kwargs): """用户的公式订阅情况 --- parameters: - name: varieties_id description: 品类 id type: integer paramType: query required: false - name: index description: 页数 type: integer paramType: query required: false - name: number descrip...
stack_v2_sparse_classes_75kplus_train_068161
18,230
no_license
[ { "docstring": "用户的公式订阅情况 --- parameters: - name: varieties_id description: 品类 id type: integer paramType: query required: false - name: index description: 页数 type: integer paramType: query required: false - name: number description: 每页条数 type: integer paramType: query required: false", "name": "get", "...
2
null
Implement the Python class `UserSubscriptionFormulaListAPI` described below. Class description: Implement the UserSubscriptionFormulaListAPI class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 用户的公式订阅情况 --- parameters: - name: varieties_id description: 品类 id type: integer paramType: qu...
Implement the Python class `UserSubscriptionFormulaListAPI` described below. Class description: Implement the UserSubscriptionFormulaListAPI class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): 用户的公式订阅情况 --- parameters: - name: varieties_id description: 品类 id type: integer paramType: qu...
c50def8cde58fd4663032b860eb058302cbac6da
<|skeleton|> class UserSubscriptionFormulaListAPI: def get(self, request, *args, **kwargs): """用户的公式订阅情况 --- parameters: - name: varieties_id description: 品类 id type: integer paramType: query required: false - name: index description: 页数 type: integer paramType: query required: false - name: number descrip...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserSubscriptionFormulaListAPI: def get(self, request, *args, **kwargs): """用户的公式订阅情况 --- parameters: - name: varieties_id description: 品类 id type: integer paramType: query required: false - name: index description: 页数 type: integer paramType: query required: false - name: number description: 每页条数 typ...
the_stack_v2_python_sparse
src/api/user/views.py
fan1018wen/Alpha
train
0
3a84a7d819f55a709b6ae15f23d6dc7cf4851a43
[ "user = request.user\ntry:\n profile_serializer = ProfileSerializer(user.profile)\n return Response(profile_serializer.data)\nexcept:\n return Response({'message': 'Nothing here.'})", "try:\n profile = Profile.objects.get(user=request.user)\nexcept:\n profile = Profile.objects.create(user=request.u...
<|body_start_0|> user = request.user try: profile_serializer = ProfileSerializer(user.profile) return Response(profile_serializer.data) except: return Response({'message': 'Nothing here.'}) <|end_body_0|> <|body_start_1|> try: profile = Pr...
An extension of the User model for custom logic about the user.
ProfileDetail
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileDetail: """An extension of the User model for custom logic about the user.""" def get(self, request, *args, **kwargs): """Get the User profile information, if it exists.""" <|body_0|> def post(self, request, format=None): """Get or create a user Profile an...
stack_v2_sparse_classes_75kplus_train_068162
1,903
no_license
[ { "docstring": "Get the User profile information, if it exists.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Get or create a user Profile and modify it.", "name": "post", "signature": "def post(self, request, format=None)" } ]
2
stack_v2_sparse_classes_30k_train_016662
Implement the Python class `ProfileDetail` described below. Class description: An extension of the User model for custom logic about the user. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Get the User profile information, if it exists. - def post(self, request, format=None): Get or cre...
Implement the Python class `ProfileDetail` described below. Class description: An extension of the User model for custom logic about the user. Method signatures and docstrings: - def get(self, request, *args, **kwargs): Get the User profile information, if it exists. - def post(self, request, format=None): Get or cre...
d04b8d9826c74454e28cdf7282bdcba693e52b67
<|skeleton|> class ProfileDetail: """An extension of the User model for custom logic about the user.""" def get(self, request, *args, **kwargs): """Get the User profile information, if it exists.""" <|body_0|> def post(self, request, format=None): """Get or create a user Profile an...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileDetail: """An extension of the User model for custom logic about the user.""" def get(self, request, *args, **kwargs): """Get the User profile information, if it exists.""" user = request.user try: profile_serializer = ProfileSerializer(user.profile) ...
the_stack_v2_python_sparse
api/users/views.py
johnckealy/flora
train
0
148654ee9d4cb62d3c338266442bed1546e41d41
[ "if not matrix:\n return 0\nheights = [0] * len(matrix[0])\nresult = 0\nfor row in matrix:\n for i, v in enumerate(row):\n if v == '0':\n heights[i] = 0\n if v == '1':\n heights[i] += 1\n result = max(result, self.largestRectangleArea(heights))\nreturn result", "stack ...
<|body_start_0|> if not matrix: return 0 heights = [0] * len(matrix[0]) result = 0 for row in matrix: for i, v in enumerate(row): if v == '0': heights[i] = 0 if v == '1': heights[i] += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maximalRectangle(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_0|> def largestRectangleArea(self, heights): """:type heights: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not matrix: ...
stack_v2_sparse_classes_75kplus_train_068163
1,488
no_license
[ { "docstring": ":type matrix: List[List[str]] :rtype: int", "name": "maximalRectangle", "signature": "def maximalRectangle(self, matrix)" }, { "docstring": ":type heights: List[int] :rtype: int", "name": "largestRectangleArea", "signature": "def largestRectangleArea(self, heights)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int - def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int - def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int <|skeleton|> class ...
bfd16678f179bbfc7564bfc079d2fa4b3e554be6
<|skeleton|> class Solution: def maximalRectangle(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_0|> def largestRectangleArea(self, heights): """:type heights: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maximalRectangle(self, matrix): """:type matrix: List[List[str]] :rtype: int""" if not matrix: return 0 heights = [0] * len(matrix[0]) result = 0 for row in matrix: for i, v in enumerate(row): if v == '0': ...
the_stack_v2_python_sparse
Stack/maximum-rectangle.py
HeliWang/upstream
train
0
368888fb1e64c4db439ab918cff26e087df5c3cc
[ "logging.debug('Page Parse started on:{}'.format(response.url))\ntitles = response.xpath('//a[contains(@href,\"/s/\")]')\nfor title in titles:\n item = items.MonkPageItem()\n title_text = title.xpath('text()').extract()[0]\n title_url = response.urljoin(title.xpath('@href').extract()[0])\n item['url'] =...
<|body_start_0|> logging.debug('Page Parse started on:{}'.format(response.url)) titles = response.xpath('//a[contains(@href,"/s/")]') for title in titles: item = items.MonkPageItem() title_text = title.xpath('text()').extract()[0] title_url = response.urljoin(...
FanfictionSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FanfictionSpider: def parse_page(self, response): """:rtype: object :param response:""" <|body_0|> def parse_story_page(self, response): """:param response: :rtype: MonkStoryItem""" <|body_1|> <|end_skeleton|> <|body_start_0|> logging.debug('Page Pa...
stack_v2_sparse_classes_75kplus_train_068164
2,963
no_license
[ { "docstring": ":rtype: object :param response:", "name": "parse_page", "signature": "def parse_page(self, response)" }, { "docstring": ":param response: :rtype: MonkStoryItem", "name": "parse_story_page", "signature": "def parse_story_page(self, response)" } ]
2
stack_v2_sparse_classes_30k_train_018919
Implement the Python class `FanfictionSpider` described below. Class description: Implement the FanfictionSpider class. Method signatures and docstrings: - def parse_page(self, response): :rtype: object :param response: - def parse_story_page(self, response): :param response: :rtype: MonkStoryItem
Implement the Python class `FanfictionSpider` described below. Class description: Implement the FanfictionSpider class. Method signatures and docstrings: - def parse_page(self, response): :rtype: object :param response: - def parse_story_page(self, response): :param response: :rtype: MonkStoryItem <|skeleton|> class...
54ca3becfc3ddd1002f2e0fed51061e4f5872dc3
<|skeleton|> class FanfictionSpider: def parse_page(self, response): """:rtype: object :param response:""" <|body_0|> def parse_story_page(self, response): """:param response: :rtype: MonkStoryItem""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FanfictionSpider: def parse_page(self, response): """:rtype: object :param response:""" logging.debug('Page Parse started on:{}'.format(response.url)) titles = response.xpath('//a[contains(@href,"/s/")]') for title in titles: item = items.MonkPageItem() ...
the_stack_v2_python_sparse
lib/Monk/Monk/spiders/fan_spider.py
geekman2/GutenTag
train
3
fef62df2b73ea735ce349933973ceeeb86e52ccc
[ "super(self.__class__, self).__init__(source=source)\nself.provides = dict(source.provides)\nself.time_source = time_source", "gen = iter(self.source)\n\ndef _append(zult, simple_frame):\n for key in self.provides.keys():\n zult[key].append(simple_frame[key])\nframe = next(gen)\nfor timeframe in self.ti...
<|body_start_0|> super(self.__class__, self).__init__(source=source) self.provides = dict(source.provides) self.time_source = time_source <|end_body_0|> <|body_start_1|> gen = iter(self.source) def _append(zult, simple_frame): for key in self.provides.keys(): ...
Accumulate simple frames to follow a timestream being provided
AccumlateSimpleFramesFilter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccumlateSimpleFramesFilter: """Accumulate simple frames to follow a timestream being provided""" def __init__(self, time_source, source, **kwargs): """:param time_source: time-frame source :param source: data-frame source holding only simple (single-timestep) frames :param kwargs:""...
stack_v2_sparse_classes_75kplus_train_068165
11,464
no_license
[ { "docstring": ":param time_source: time-frame source :param source: data-frame source holding only simple (single-timestep) frames :param kwargs:", "name": "__init__", "signature": "def __init__(self, time_source, source, **kwargs)" }, { "docstring": "Iterate through time_source For each data f...
2
null
Implement the Python class `AccumlateSimpleFramesFilter` described below. Class description: Accumulate simple frames to follow a timestream being provided Method signatures and docstrings: - def __init__(self, time_source, source, **kwargs): :param time_source: time-frame source :param source: data-frame source hold...
Implement the Python class `AccumlateSimpleFramesFilter` described below. Class description: Accumulate simple frames to follow a timestream being provided Method signatures and docstrings: - def __init__(self, time_source, source, **kwargs): :param time_source: time-frame source :param source: data-frame source hold...
32741e8fe1313ff8785029165bef31347cc2a3c3
<|skeleton|> class AccumlateSimpleFramesFilter: """Accumulate simple frames to follow a timestream being provided""" def __init__(self, time_source, source, **kwargs): """:param time_source: time-frame source :param source: data-frame source holding only simple (single-timestep) frames :param kwargs:""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AccumlateSimpleFramesFilter: """Accumulate simple frames to follow a timestream being provided""" def __init__(self, time_source, source, **kwargs): """:param time_source: time-frame source :param source: data-frame source holding only simple (single-timestep) frames :param kwargs:""" sup...
the_stack_v2_python_sparse
DplKit/python/dplkit/simple/filter.py
rayg-ssec/DplTools
train
0
2b127c3da67e6a7e5061ae90c5e4ac381b1b4a87
[ "@suppress_warnings\ndef func():\n warn('this is a warning!')\nwith catch_warnings(record=True) as warning_list:\n func()\nself.assertEqual(warning_list, [])", "@suppress_warnings\ndef func_with_name():\n \"\"\"and docstring\"\"\"\nself.assertEqual(func_with_name.__name__, 'func_with_name')\nself.assertE...
<|body_start_0|> @suppress_warnings def func(): warn('this is a warning!') with catch_warnings(record=True) as warning_list: func() self.assertEqual(warning_list, []) <|end_body_0|> <|body_start_1|> @suppress_warnings def func_with_name(): ...
SuppressWarningTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuppressWarningTests: def test_suppress_warnings_works(self): """suppress_warnings() hides all warnings""" <|body_0|> def test_suppress_warnings_is_a_good_decorator(self): """suppress_warnings() does not clobber function name and docstring""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus_train_068166
2,724
no_license
[ { "docstring": "suppress_warnings() hides all warnings", "name": "test_suppress_warnings_works", "signature": "def test_suppress_warnings_works(self)" }, { "docstring": "suppress_warnings() does not clobber function name and docstring", "name": "test_suppress_warnings_is_a_good_decorator", ...
2
stack_v2_sparse_classes_30k_train_054646
Implement the Python class `SuppressWarningTests` described below. Class description: Implement the SuppressWarningTests class. Method signatures and docstrings: - def test_suppress_warnings_works(self): suppress_warnings() hides all warnings - def test_suppress_warnings_is_a_good_decorator(self): suppress_warnings()...
Implement the Python class `SuppressWarningTests` described below. Class description: Implement the SuppressWarningTests class. Method signatures and docstrings: - def test_suppress_warnings_works(self): suppress_warnings() hides all warnings - def test_suppress_warnings_is_a_good_decorator(self): suppress_warnings()...
78aa82cdb35808988214329b3b1aabcc2d1a5e01
<|skeleton|> class SuppressWarningTests: def test_suppress_warnings_works(self): """suppress_warnings() hides all warnings""" <|body_0|> def test_suppress_warnings_is_a_good_decorator(self): """suppress_warnings() does not clobber function name and docstring""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SuppressWarningTests: def test_suppress_warnings_works(self): """suppress_warnings() hides all warnings""" @suppress_warnings def func(): warn('this is a warning!') with catch_warnings(record=True) as warning_list: func() self.assertEqual(warning...
the_stack_v2_python_sparse
venv/lib/python3.6/site-packages/plainbox/impl/test_testing_utils.py
utkarshyadavin/CloudMarks
train
0
943389a3e3862396f4192eebec9b3491ad2ccb19
[ "length = len(s)\nf = [False for i in range(length + 1)]\nf[0] = True\nfor i in range(length):\n for j in range(i + 1, length + 1):\n if f[i] and s[i:j] in word_dict:\n f[j] = True\nreturn f[length]", "length = len(s)\nf = [False for i in range(length + 1)]\nf[0] = True\nfor i in range(1, len...
<|body_start_0|> length = len(s) f = [False for i in range(length + 1)] f[0] = True for i in range(length): for j in range(i + 1, length + 1): if f[i] and s[i:j] in word_dict: f[j] = True return f[length] <|end_body_0|> <|body_star...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def word_break(self, s: str, word_dict: List[str]) -> bool: """判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值""" <|body_0|> def word_break2(self, s: str, word_dict: List[str]) -> bool: """判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值"""...
stack_v2_sparse_classes_75kplus_train_068167
2,675
permissive
[ { "docstring": "判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值", "name": "word_break", "signature": "def word_break(self, s: str, word_dict: List[str]) -> bool" }, { "docstring": "判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值", "name": "word_break2", "signature": "de...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def word_break(self, s: str, word_dict: List[str]) -> bool: 判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值 - def word_break2(self, s: str, word_dict: List[str]) -> bool...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def word_break(self, s: str, word_dict: List[str]) -> bool: 判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值 - def word_break2(self, s: str, word_dict: List[str]) -> bool...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def word_break(self, s: str, word_dict: List[str]) -> bool: """判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值""" <|body_0|> def word_break2(self, s: str, word_dict: List[str]) -> bool: """判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def word_break(self, s: str, word_dict: List[str]) -> bool: """判断一个单词是不是分成这个数组 Args: s: 字符串 word_dict: 字符表 Returns: 布尔值""" length = len(s) f = [False for i in range(length + 1)] f[0] = True for i in range(length): for j in range(i + 1, length + 1):...
the_stack_v2_python_sparse
src/leetcodepython/string/word_break_139.py
zhangyu345293721/leetcode
train
101
6ebffe4efca66e88ff842b505da6aa9e4ae2cd56
[ "if SINGLE_DB_NAME:\n return SINGLE_DB_NAME\nif cls.database_name is None:\n raise AttributeError(f'Define `database_name` as class variable for {cls.__qualname__}.')\nreturn cls.database_name", "if cls.collection_name is None:\n raise AttributeError(f'Define `collection_name` as class variable for {cls....
<|body_start_0|> if SINGLE_DB_NAME: return SINGLE_DB_NAME if cls.database_name is None: raise AttributeError(f'Define `database_name` as class variable for {cls.__qualname__}.') return cls.database_name <|end_body_0|> <|body_start_1|> if cls.collection_name is No...
Mixin to force the user specify the collection properties.
CollectionPropertiesMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CollectionPropertiesMixin: """Mixin to force the user specify the collection properties.""" def get_db_name(cls): """Get the database name (defined as class variable ``database_name``) of the collection. If single-db is in effect, return the name of the single-db instead. :return: da...
stack_v2_sparse_classes_75kplus_train_068168
2,411
permissive
[ { "docstring": "Get the database name (defined as class variable ``database_name``) of the collection. If single-db is in effect, return the name of the single-db instead. :return: database name of the collection :raises AttributeError: if `database_name` is undefined or `None`", "name": "get_db_name", ...
3
stack_v2_sparse_classes_30k_val_002918
Implement the Python class `CollectionPropertiesMixin` described below. Class description: Mixin to force the user specify the collection properties. Method signatures and docstrings: - def get_db_name(cls): Get the database name (defined as class variable ``database_name``) of the collection. If single-db is in effe...
Implement the Python class `CollectionPropertiesMixin` described below. Class description: Mixin to force the user specify the collection properties. Method signatures and docstrings: - def get_db_name(cls): Get the database name (defined as class variable ``database_name``) of the collection. If single-db is in effe...
c7da1e91783dce3a2b71b955b3a22b68db9056cf
<|skeleton|> class CollectionPropertiesMixin: """Mixin to force the user specify the collection properties.""" def get_db_name(cls): """Get the database name (defined as class variable ``database_name``) of the collection. If single-db is in effect, return the name of the single-db instead. :return: da...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CollectionPropertiesMixin: """Mixin to force the user specify the collection properties.""" def get_db_name(cls): """Get the database name (defined as class variable ``database_name``) of the collection. If single-db is in effect, return the name of the single-db instead. :return: database name o...
the_stack_v2_python_sparse
mongodb/factory/mixin/prop.py
RxJellyBot/Jelly-Bot
train
5
a0b4907783fdf36bd373af68cc3e1ba41536293a
[ "assert video_stream is not None, 'Video Streaming must be provided'\nassert issubclass(type(video_stream), BaseVideoStream), 'Video streamer must be subclass of BaseVideoStream'\nassert object_estimator is not None, 'Object estimator must be provided'\nassert issubclass(type(object_estimator), BaseObjectEstimator)...
<|body_start_0|> assert video_stream is not None, 'Video Streaming must be provided' assert issubclass(type(video_stream), BaseVideoStream), 'Video streamer must be subclass of BaseVideoStream' assert object_estimator is not None, 'Object estimator must be provided' assert issubclass(typ...
App
CameraApp
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CameraApp: """App""" def __init__(self, video_stream, object_estimator, app_logger=None, app_timer_logger=None, window_size_secs=5, pubsub_publisher=None, pubsub_topic=None): """Constructor Args: ``video_stream`` (object): ``object_estimator`` (object): ``app_logger`` (:class:`~utils...
stack_v2_sparse_classes_75kplus_train_068169
5,482
permissive
[ { "docstring": "Constructor Args: ``video_stream`` (object): ``object_estimator`` (object): ``app_logger`` (:class:`~utils.BigQueryConn`): BigQuery Connector ``window_size_secs``: Time window to make estimation", "name": "__init__", "signature": "def __init__(self, video_stream, object_estimator, app_lo...
3
stack_v2_sparse_classes_30k_val_000734
Implement the Python class `CameraApp` described below. Class description: App Method signatures and docstrings: - def __init__(self, video_stream, object_estimator, app_logger=None, app_timer_logger=None, window_size_secs=5, pubsub_publisher=None, pubsub_topic=None): Constructor Args: ``video_stream`` (object): ``ob...
Implement the Python class `CameraApp` described below. Class description: App Method signatures and docstrings: - def __init__(self, video_stream, object_estimator, app_logger=None, app_timer_logger=None, window_size_secs=5, pubsub_publisher=None, pubsub_topic=None): Constructor Args: ``video_stream`` (object): ``ob...
3f537ea40ceefdcf5f3044b6931bfa3951c351f7
<|skeleton|> class CameraApp: """App""" def __init__(self, video_stream, object_estimator, app_logger=None, app_timer_logger=None, window_size_secs=5, pubsub_publisher=None, pubsub_topic=None): """Constructor Args: ``video_stream`` (object): ``object_estimator`` (object): ``app_logger`` (:class:`~utils...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CameraApp: """App""" def __init__(self, video_stream, object_estimator, app_logger=None, app_timer_logger=None, window_size_secs=5, pubsub_publisher=None, pubsub_topic=None): """Constructor Args: ``video_stream`` (object): ``object_estimator`` (object): ``app_logger`` (:class:`~utils.BigQueryConn...
the_stack_v2_python_sparse
tracking2/apps/tracker_counter.py
brungcm/health-hack-2019
train
0
8096c7179022f8197dcd55b2e77397c06d6f9574
[ "self.directory = tempfile.mkdtemp(TestRecipyBase.__name__)\nself.original_script = os.path.join(os.path.dirname(__file__), TestRecipyBase.SCRIPT_NAME)\nself.script = os.path.join(self.directory, TestRecipyBase.SCRIPT_NAME)\nshutil.copy(self.original_script, self.script)\nself.input_file = os.path.join(self.directo...
<|body_start_0|> self.directory = tempfile.mkdtemp(TestRecipyBase.__name__) self.original_script = os.path.join(os.path.dirname(__file__), TestRecipyBase.SCRIPT_NAME) self.script = os.path.join(self.directory, TestRecipyBase.SCRIPT_NAME) shutil.copy(self.original_script, self.script) ...
Base class for recipy tests.
TestRecipyBase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRecipyBase: """Base class for recipy tests.""" def setup_method(self, method): """py.test setup function, creates test directory in $TEMP, initialises it as a Git repository, copies SCRIPT_NAME to it, creates input file, and commits SCRIPT_NAME. Note: this function defines member...
stack_v2_sparse_classes_75kplus_train_068170
3,367
permissive
[ { "docstring": "py.test setup function, creates test directory in $TEMP, initialises it as a Git repository, copies SCRIPT_NAME to it, creates input file, and commits SCRIPT_NAME. Note: this function defines member variables self.directory, self.script, self.original_script, self.input_file and self.output_file...
2
null
Implement the Python class `TestRecipyBase` described below. Class description: Base class for recipy tests. Method signatures and docstrings: - def setup_method(self, method): py.test setup function, creates test directory in $TEMP, initialises it as a Git repository, copies SCRIPT_NAME to it, creates input file, an...
Implement the Python class `TestRecipyBase` described below. Class description: Base class for recipy tests. Method signatures and docstrings: - def setup_method(self, method): py.test setup function, creates test directory in $TEMP, initialises it as a Git repository, copies SCRIPT_NAME to it, creates input file, an...
d8f8fe8ace3659f1d700bb454e68a8db453e84f4
<|skeleton|> class TestRecipyBase: """Base class for recipy tests.""" def setup_method(self, method): """py.test setup function, creates test directory in $TEMP, initialises it as a Git repository, copies SCRIPT_NAME to it, creates input file, and commits SCRIPT_NAME. Note: this function defines member...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestRecipyBase: """Base class for recipy tests.""" def setup_method(self, method): """py.test setup function, creates test directory in $TEMP, initialises it as a Git repository, copies SCRIPT_NAME to it, creates input file, and commits SCRIPT_NAME. Note: this function defines member variables se...
the_stack_v2_python_sparse
integration_test/test_recipy_base.py
fakegit/recipy
train
0
da9302d0f79550134f36f63fe32f9f12f72d4ce6
[ "for name in self.success_urls:\n if name in form.data:\n self.success_url = self.success_urls[name]\n break\nreturn HttpResponseRedirect(self.get_success_url())", "if self.success_url:\n url = force_text(self.success_url)\nelse:\n raise ImproperlyConfigured(_('No URL to redirect to. Provid...
<|body_start_0|> for name in self.success_urls: if name in form.data: self.success_url = self.success_urls[name] break return HttpResponseRedirect(self.get_success_url()) <|end_body_0|> <|body_start_1|> if self.success_url: url = force_tex...
A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete" value="Delete"/> View: MyMultiSubmitView(Mult...
MultiRedirectMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiRedirectMixin: """A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete"...
stack_v2_sparse_classes_75kplus_train_068171
1,344
no_license
[ { "docstring": "Form is valid: Pick the url and redirect.", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "Returns the supplied success URL.", "name": "get_success_url", "signature": "def get_success_url(self)" } ]
2
stack_v2_sparse_classes_30k_train_034562
Implement the Python class `MultiRedirectMixin` described below. Class description: A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Creat...
Implement the Python class `MultiRedirectMixin` described below. Class description: A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Creat...
df662e8f1110fd0ae3a90549bd6f54d2ee6b04be
<|skeleton|> class MultiRedirectMixin: """A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiRedirectMixin: """A mixin that supports submit-specific success redirection. Either specify one success_url, or provide dict with names of submit actions given in template as keys Example: In template: <input type="submit" name="create_new" value="Create"/> <input type="submit" name="delete" value="Delet...
the_stack_v2_python_sparse
catalogue/mixins.py
csdbrass/CSDLibrary
train
0
f88b3a9fa2d468104ababa88ab717b6405bf783d
[ "def rserialize(root: TreeNode, string: str):\n if not root:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string += rserialize(root.left, string)\n string += rserialize(root.right, string)\n return string\nreturn rserialize(root, '')", "def rdeserialize(tree: ...
<|body_start_0|> def rserialize(root: TreeNode, string: str): if not root: string += 'None,' else: string += str(root.val) + ',' string += rserialize(root.left, string) string += rserialize(root.right, string) re...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. Time Complexity: O(N) Space Complexity: O(N) :param root: :return:""" <|body_0|> def deserialize(self, data: str): """Decodes encoded data to tree. Time Complexity: O(N) Space Co...
stack_v2_sparse_classes_75kplus_train_068172
1,331
no_license
[ { "docstring": "Encodes a tree to a single string. Time Complexity: O(N) Space Complexity: O(N) :param root: :return:", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes encoded data to tree. Time Complexity: O(N) Space Complexity: O(N) :pa...
2
stack_v2_sparse_classes_30k_train_051744
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. Time Complexity: O(N) Space Complexity: O(N) :param root: :return: - def deserialize(self, data: str): De...
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. Time Complexity: O(N) Space Complexity: O(N) :param root: :return: - def deserialize(self, data: str): De...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. Time Complexity: O(N) Space Complexity: O(N) :param root: :return:""" <|body_0|> def deserialize(self, data: str): """Decodes encoded data to tree. Time Complexity: O(N) Space Co...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. Time Complexity: O(N) Space Complexity: O(N) :param root: :return:""" def rserialize(root: TreeNode, string: str): if not root: string += 'None,' else: ...
the_stack_v2_python_sparse
expedia/serialize_and_deserialize_tree.py
Shiv2157k/leet_code
train
1
35c238d6b9488886acdf278f72735651157db5fe
[ "self.data_train, self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split=['train', 'validation'], as_supervised=True)\nself.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(self.data_train)\nself.data_train = self.data_train.map(self.tf_encode).cache()\nself.data_valid = self.data_valid.map(self.tf...
<|body_start_0|> self.data_train, self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split=['train', 'validation'], as_supervised=True) self.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(self.data_train) self.data_train = self.data_train.map(self.tf_encode).cache() self...
Load and prep a dataset for machine translation
Dataset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """Load and prep a dataset for machine translation""" def __init__(self): """initialization""" <|body_0|> def tokenize_dataset(self, data): """Create sub-word tokenizers for our dataset""" <|body_1|> def encode(self, pt, en): """Enco...
stack_v2_sparse_classes_75kplus_train_068173
1,759
no_license
[ { "docstring": "initialization", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Create sub-word tokenizers for our dataset", "name": "tokenize_dataset", "signature": "def tokenize_dataset(self, data)" }, { "docstring": "Encode a translation into tokens",...
4
null
Implement the Python class `Dataset` described below. Class description: Load and prep a dataset for machine translation Method signatures and docstrings: - def __init__(self): initialization - def tokenize_dataset(self, data): Create sub-word tokenizers for our dataset - def encode(self, pt, en): Encode a translatio...
Implement the Python class `Dataset` described below. Class description: Load and prep a dataset for machine translation Method signatures and docstrings: - def __init__(self): initialization - def tokenize_dataset(self, data): Create sub-word tokenizers for our dataset - def encode(self, pt, en): Encode a translatio...
16dc37d1c6dc00a271053b60724c51763914029a
<|skeleton|> class Dataset: """Load and prep a dataset for machine translation""" def __init__(self): """initialization""" <|body_0|> def tokenize_dataset(self, data): """Create sub-word tokenizers for our dataset""" <|body_1|> def encode(self, pt, en): """Enco...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Dataset: """Load and prep a dataset for machine translation""" def __init__(self): """initialization""" self.data_train, self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split=['train', 'validation'], as_supervised=True) self.tokenizer_pt, self.tokenizer_en = self.tokeni...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/2-dataset.py
jaycer95/holbertonschool-machine_learning
train
0
83f48c6325f84d5f3ee91a6ce30059010c9c5402
[ "if count_tag in self.tagnames and self.length:\n return float(self.get(count_tag)) / (self.length - unit_length + 1)\nelse:\n return None", "c = self.coverage(count_tag=count_tag, unit_length=unit_length)\nif c is None:\n self.try_get_length()\n raise gfapy.NotFoundError('Tag {} undefined for segment...
<|body_start_0|> if count_tag in self.tagnames and self.length: return float(self.get(count_tag)) / (self.length - unit_length + 1) else: return None <|end_body_0|> <|body_start_1|> c = self.coverage(count_tag=count_tag, unit_length=unit_length) if c is None: ...
Coverage
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Coverage: def coverage(self, count_tag='RC', unit_length=1): """Compute the coverage from the value a count_tag (RC, KC or FC). If unit_length is provided then: count/(length-unit_length+1), otherwise: count/length. The latter is a good approximation if length >>> unit_length. Parameters...
stack_v2_sparse_classes_75kplus_train_068174
1,226
permissive
[ { "docstring": "Compute the coverage from the value a count_tag (RC, KC or FC). If unit_length is provided then: count/(length-unit_length+1), otherwise: count/length. The latter is a good approximation if length >>> unit_length. Parameters: count_tag (str): integer tag from which the count shall be taken (defa...
2
stack_v2_sparse_classes_30k_train_052789
Implement the Python class `Coverage` described below. Class description: Implement the Coverage class. Method signatures and docstrings: - def coverage(self, count_tag='RC', unit_length=1): Compute the coverage from the value a count_tag (RC, KC or FC). If unit_length is provided then: count/(length-unit_length+1), ...
Implement the Python class `Coverage` described below. Class description: Implement the Coverage class. Method signatures and docstrings: - def coverage(self, count_tag='RC', unit_length=1): Compute the coverage from the value a count_tag (RC, KC or FC). If unit_length is provided then: count/(length-unit_length+1), ...
12b31daac26ab137b6ee4a29b4f14554ba962dcb
<|skeleton|> class Coverage: def coverage(self, count_tag='RC', unit_length=1): """Compute the coverage from the value a count_tag (RC, KC or FC). If unit_length is provided then: count/(length-unit_length+1), otherwise: count/length. The latter is a good approximation if length >>> unit_length. Parameters...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Coverage: def coverage(self, count_tag='RC', unit_length=1): """Compute the coverage from the value a count_tag (RC, KC or FC). If unit_length is provided then: count/(length-unit_length+1), otherwise: count/length. The latter is a good approximation if length >>> unit_length. Parameters: count_tag (s...
the_stack_v2_python_sparse
gfapy/line/segment/coverage.py
ggonnella/gfapy
train
63
1bf286a85ed20389d3d206d5fe932e7afae862ce
[ "from scipy.optimize import minimize\n\ndef f1_opt(x):\n return -f1_score(true_y, pred_y >= x)\nresult = minimize(f1_opt, x0=np.array([0.5]), method='Nelder-Mead')\nbest_threshold = result['x'].item()\nreturn best_threshold", "df_pred = pd.read_csv(f'{pred_dir}/train_probas.tsv', sep=',')\ntrain_y = train_df['...
<|body_start_0|> from scipy.optimize import minimize def f1_opt(x): return -f1_score(true_y, pred_y >= x) result = minimize(f1_opt, x0=np.array([0.5]), method='Nelder-Mead') best_threshold = result['x'].item() return best_threshold <|end_body_0|> <|body_start_1|> ...
Submit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Submit: def nelder_mead_th(true_y, pred_y): """ネルダーミードでf1スコアから2値分類のbestな閾値見つける""" <|body_0|> def pred_nelder_mead(pred_dir, out_dir): """nelder_meadで決めた閾値でcvの平均値を2値化する""" <|body_1|> <|end_skeleton|> <|body_start_0|> from scipy.optimize import minimi...
stack_v2_sparse_classes_75kplus_train_068175
6,514
no_license
[ { "docstring": "ネルダーミードでf1スコアから2値分類のbestな閾値見つける", "name": "nelder_mead_th", "signature": "def nelder_mead_th(true_y, pred_y)" }, { "docstring": "nelder_meadで決めた閾値でcvの平均値を2値化する", "name": "pred_nelder_mead", "signature": "def pred_nelder_mead(pred_dir, out_dir)" } ]
2
stack_v2_sparse_classes_30k_train_048404
Implement the Python class `Submit` described below. Class description: Implement the Submit class. Method signatures and docstrings: - def nelder_mead_th(true_y, pred_y): ネルダーミードでf1スコアから2値分類のbestな閾値見つける - def pred_nelder_mead(pred_dir, out_dir): nelder_meadで決めた閾値でcvの平均値を2値化する
Implement the Python class `Submit` described below. Class description: Implement the Submit class. Method signatures and docstrings: - def nelder_mead_th(true_y, pred_y): ネルダーミードでf1スコアから2値分類のbestな閾値見つける - def pred_nelder_mead(pred_dir, out_dir): nelder_meadで決めた閾値でcvの平均値を2値化する <|skeleton|> class Submit: def nel...
44cd6fafb503665df8a2d5030f427f11b10025e5
<|skeleton|> class Submit: def nelder_mead_th(true_y, pred_y): """ネルダーミードでf1スコアから2値分類のbestな閾値見つける""" <|body_0|> def pred_nelder_mead(pred_dir, out_dir): """nelder_meadで決めた閾値でcvの平均値を2値化する""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Submit: def nelder_mead_th(true_y, pred_y): """ネルダーミードでf1スコアから2値分類のbestな閾値見つける""" from scipy.optimize import minimize def f1_opt(x): return -f1_score(true_y, pred_y >= x) result = minimize(f1_opt, x0=np.array([0.5]), method='Nelder-Mead') best_threshold = r...
the_stack_v2_python_sparse
notebook/tmp.py
riron1206/Probspace_geme_compe
train
0
5ee18fa9af9efb894d2f8996ef864f1a2ec12e80
[ "self.power_spectrum = power_spectrum\nself.delta_f = delta_f\nself.zero_padding = zero_padding\nif any(self.power_spectrum < self.eps):\n if not suppress_small_elements_warning:\n logging.warning('Some elements of power spectrum are too small, setting to zero')\n self.power_spectrum[self.power_spectru...
<|body_start_0|> self.power_spectrum = power_spectrum self.delta_f = delta_f self.zero_padding = zero_padding if any(self.power_spectrum < self.eps): if not suppress_small_elements_warning: logging.warning('Some elements of power spectrum are too small, settin...
SpectralFactorization
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpectralFactorization: def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): """Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with ...
stack_v2_sparse_classes_75kplus_train_068176
3,853
permissive
[ { "docstring": "Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with transfer function h(f), reconstruct the phase of h(f) so that h(t) = 0 for t < 0. The answer is only unique up to an all-pass component; the...
2
stack_v2_sparse_classes_30k_train_010233
Implement the Python class `SpectralFactorization` described below. Class description: Implement the SpectralFactorization class. Method signatures and docstrings: - def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): Calculate the minimum-phase causal wavelet of ...
Implement the Python class `SpectralFactorization` described below. Class description: Implement the SpectralFactorization class. Method signatures and docstrings: - def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): Calculate the minimum-phase causal wavelet of ...
4fc56396ad603bbe61e6d548f66b818d51a3301b
<|skeleton|> class SpectralFactorization: def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): """Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SpectralFactorization: def __init__(self, power_spectrum, delta_f, zero_padding=0, suppress_small_elements_warning: bool=False): """Calculate the minimum-phase causal wavelet of a given power spectrum. In other words: Given the power transmission spectrum S(f) = |h(f)|² of a system with transfer funct...
the_stack_v2_python_sparse
pycqed/analysis/tools/spectralfac.py
DiCarloLab-Delft/PycQED_py3
train
72
e469cf92dda1dbb9382197bb20d6c35ec88bc1bb
[ "self.n_input = n_input\nself.n_hidden = n_hidden\nself.n_output = n_output\nself.learning_rate = learning_rate\nself.reg_lambda = reg_lambda\nself.initialize_weights()", "np.random.seed(0)\nself.W1 = np.random.randn(self.n_input, self.n_hidden)\nself.b1 = np.random.randn(self.n_hidden)\nself.W2 = np.random.randn...
<|body_start_0|> self.n_input = n_input self.n_hidden = n_hidden self.n_output = n_output self.learning_rate = learning_rate self.reg_lambda = reg_lambda self.initialize_weights() <|end_body_0|> <|body_start_1|> np.random.seed(0) self.W1 = np.random.randn...
A class representing a single layer neural network for classification.
NN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NN: """A class representing a single layer neural network for classification.""" def __init__(self, n_input, n_hidden, n_output, learning_rate=0.01, reg_lambda=0.01): """Initializes the neural network. Arguments: n_input(int): The number of units in the input layer. n_hidden(int): Th...
stack_v2_sparse_classes_75kplus_train_068177
3,871
no_license
[ { "docstring": "Initializes the neural network. Arguments: n_input(int): The number of units in the input layer. n_hidden(int): The number of units in the hidden layer. n_output(int): The number of units in the output layer. learning_rate(float): The learning rate to use when performing gradient descent. reg_la...
6
stack_v2_sparse_classes_30k_test_000673
Implement the Python class `NN` described below. Class description: A class representing a single layer neural network for classification. Method signatures and docstrings: - def __init__(self, n_input, n_hidden, n_output, learning_rate=0.01, reg_lambda=0.01): Initializes the neural network. Arguments: n_input(int): ...
Implement the Python class `NN` described below. Class description: A class representing a single layer neural network for classification. Method signatures and docstrings: - def __init__(self, n_input, n_hidden, n_output, learning_rate=0.01, reg_lambda=0.01): Initializes the neural network. Arguments: n_input(int): ...
15c7b77142c51c44dc9ee9a18654c124a3300dd1
<|skeleton|> class NN: """A class representing a single layer neural network for classification.""" def __init__(self, n_input, n_hidden, n_output, learning_rate=0.01, reg_lambda=0.01): """Initializes the neural network. Arguments: n_input(int): The number of units in the input layer. n_hidden(int): Th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NN: """A class representing a single layer neural network for classification.""" def __init__(self, n_input, n_hidden, n_output, learning_rate=0.01, reg_lambda=0.01): """Initializes the neural network. Arguments: n_input(int): The number of units in the input layer. n_hidden(int): The number of u...
the_stack_v2_python_sparse
Labs/Lab7Solutions/lab7.py
swansonk14/IntroML
train
31
ac76cea8c052c4ef57ca082b50d812c1532ec02b
[ "self.current_state = states.PLNOverallState(annotated_interactions, active_gene_threshold, transition_ratio, selected_links, alpha, beta, link_prior, parameters_state_class)\nself.state_recorder = state_recorder_class(self.current_state.links_state.process_links, self.current_state.parameters_state.get_parameter_d...
<|body_start_0|> self.current_state = states.PLNOverallState(annotated_interactions, active_gene_threshold, transition_ratio, selected_links, alpha, beta, link_prior, parameters_state_class) self.state_recorder = state_recorder_class(self.current_state.links_state.process_links, self.current_state.param...
A class representing Simulated Annealing for process linkage networks.
PLNSimulatedAnnealing
[ "MIT", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PLNSimulatedAnnealing: """A class representing Simulated Annealing for process linkage networks.""" def __init__(self, annotated_interactions, active_gene_threshold, transition_ratio, num_steps=NUM_STEPS, temperature=TEMPERATURE, end_temperature=END_TEMPERATURE, selected_links=None, alpha=No...
stack_v2_sparse_classes_75kplus_train_068178
9,668
permissive
[ { "docstring": "Create a new instance. :Parameters: - `annotated_interactions`: an `AnnotatedInteractionsGraph` instance - `active_gene_threshold`: the threshold at or above which a gene is considered \"active\" - `transition_ratio`: a `float` indicating the ratio of link transitions to parameter transitions - ...
3
stack_v2_sparse_classes_30k_train_028152
Implement the Python class `PLNSimulatedAnnealing` described below. Class description: A class representing Simulated Annealing for process linkage networks. Method signatures and docstrings: - def __init__(self, annotated_interactions, active_gene_threshold, transition_ratio, num_steps=NUM_STEPS, temperature=TEMPERA...
Implement the Python class `PLNSimulatedAnnealing` described below. Class description: A class representing Simulated Annealing for process linkage networks. Method signatures and docstrings: - def __init__(self, annotated_interactions, active_gene_threshold, transition_ratio, num_steps=NUM_STEPS, temperature=TEMPERA...
f3cf02c41e26b0318674cb20703bd6f4442a688e
<|skeleton|> class PLNSimulatedAnnealing: """A class representing Simulated Annealing for process linkage networks.""" def __init__(self, annotated_interactions, active_gene_threshold, transition_ratio, num_steps=NUM_STEPS, temperature=TEMPERATURE, end_temperature=END_TEMPERATURE, selected_links=None, alpha=No...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PLNSimulatedAnnealing: """A class representing Simulated Annealing for process linkage networks.""" def __init__(self, annotated_interactions, active_gene_threshold, transition_ratio, num_steps=NUM_STEPS, temperature=TEMPERATURE, end_temperature=END_TEMPERATURE, selected_links=None, alpha=None, beta=None...
the_stack_v2_python_sparse
bpn/mcmc/simulatedannealing.py
Python3pkg/BiologicalProcessNetworks
train
0
1bd14d16d3028fdc344985f6dbbac2c84cb6fd99
[ "timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)", "query_hash = hash(query)\naction = self._GetRowValue(query_hash, row, 'action')\nif action.startswith('/safari/'):\n event_data = MacOSKnowledgeCSa...
<|body_start_0|> timestamp = self._GetRowValue(query_hash, row, value_name) if timestamp is None: return None return dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp) <|end_body_0|> <|body_start_1|> query_hash = hash(query) action = self._GetRowValue(query_hash, r...
SQLite parser plugin for MacOS Duet/KnowledgeC database files.
MacOSKnowledgeCPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MacOSKnowledgeCPlugin: """SQLite parser plugin for MacOS Duet/KnowledgeC database files.""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that...
stack_v2_sparse_classes_75kplus_train_068179
31,607
permissive
[ { "docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.CocoaTime: date and time value or None if not available.", "name...
2
null
Implement the Python class `MacOSKnowledgeCPlugin` described below. Class description: SQLite parser plugin for MacOS Duet/KnowledgeC database files. Method signatures and docstrings: - def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): h...
Implement the Python class `MacOSKnowledgeCPlugin` described below. Class description: SQLite parser plugin for MacOS Duet/KnowledgeC database files. Method signatures and docstrings: - def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): h...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class MacOSKnowledgeCPlugin: """SQLite parser plugin for MacOS Duet/KnowledgeC database files.""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MacOSKnowledgeCPlugin: """SQLite parser plugin for MacOS Duet/KnowledgeC database files.""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the...
the_stack_v2_python_sparse
plaso/parsers/sqlite_plugins/macos_knowledgec.py
log2timeline/plaso
train
1,506
383d97923b42a58f6a89e7816db99de837ae939f
[ "self.curve = generator.curve()\nself.generator = generator\nself.point = point\nn = generator.order()\nif not n:\n raise RuntimeError('Generator point must have order.')\nif not n * point == ellipticcurve.INFINITY:\n raise RuntimeError('Generator point order is bad.')\nif point.x() < 0 or n <= point.x() or p...
<|body_start_0|> self.curve = generator.curve() self.generator = generator self.point = point n = generator.order() if not n: raise RuntimeError('Generator point must have order.') if not n * point == ellipticcurve.INFINITY: raise RuntimeError('Gen...
Public key for ECDSA.
Public_key
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Public_key: """Public key for ECDSA.""" def __init__(self, generator, point): """generator is the Point that generates the group, point is the Point that defines the public key.""" <|body_0|> def verifies(self, hash, signature): """Verify that signature is a vali...
stack_v2_sparse_classes_75kplus_train_068180
9,224
no_license
[ { "docstring": "generator is the Point that generates the group, point is the Point that defines the public key.", "name": "__init__", "signature": "def __init__(self, generator, point)" }, { "docstring": "Verify that signature is a valid signature of hash. Return True if the signature is valid....
2
stack_v2_sparse_classes_30k_train_017047
Implement the Python class `Public_key` described below. Class description: Public key for ECDSA. Method signatures and docstrings: - def __init__(self, generator, point): generator is the Point that generates the group, point is the Point that defines the public key. - def verifies(self, hash, signature): Verify tha...
Implement the Python class `Public_key` described below. Class description: Public key for ECDSA. Method signatures and docstrings: - def __init__(self, generator, point): generator is the Point that generates the group, point is the Point that defines the public key. - def verifies(self, hash, signature): Verify tha...
a473d0d389612e53a2ad6fe8a18d984474c44623
<|skeleton|> class Public_key: """Public key for ECDSA.""" def __init__(self, generator, point): """generator is the Point that generates the group, point is the Point that defines the public key.""" <|body_0|> def verifies(self, hash, signature): """Verify that signature is a vali...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Public_key: """Public key for ECDSA.""" def __init__(self, generator, point): """generator is the Point that generates the group, point is the Point that defines the public key.""" self.curve = generator.curve() self.generator = generator self.point = point n = gen...
the_stack_v2_python_sparse
p/dist-packages/ecdsa/ecdsa.py
joshg111/craigslist_kbb
train
7
5ca99a8b67a790edca346773a1e378784166f571
[ "ObjectManager.__init__(self)\nself.setters.update({'name': 'set_general', 'resource_types': 'set_many', 'session_resource_type_requirements': 'set_many'})\nself.getters.update({'name': 'get_general', 'resource_types': 'get_many_to_many', 'session_resource_type_requirements': 'get_many_to_one'})\nself.my_django_mod...
<|body_start_0|> ObjectManager.__init__(self) self.setters.update({'name': 'set_general', 'resource_types': 'set_many', 'session_resource_type_requirements': 'set_many'}) self.getters.update({'name': 'get_general', 'resource_types': 'get_many_to_many', 'session_resource_type_requirements': 'get_...
Manage Resources in the Power Reg system
ResourceManager
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceManager: """Manage Resources in the Power Reg system""" def __init__(self): """constructor""" <|body_0|> def create(self, auth_token, name): """Create a new Resource @param name name of the Resource @return instance of Resource""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus_train_068181
1,339
permissive
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Create a new Resource @param name name of the Resource @return instance of Resource", "name": "create", "signature": "def create(self, auth_token, name)" } ]
2
stack_v2_sparse_classes_30k_val_000926
Implement the Python class `ResourceManager` described below. Class description: Manage Resources in the Power Reg system Method signatures and docstrings: - def __init__(self): constructor - def create(self, auth_token, name): Create a new Resource @param name name of the Resource @return instance of Resource
Implement the Python class `ResourceManager` described below. Class description: Manage Resources in the Power Reg system Method signatures and docstrings: - def __init__(self): constructor - def create(self, auth_token, name): Create a new Resource @param name name of the Resource @return instance of Resource <|ske...
a59457bc37f0501aea1f54d006a6de94ff80511c
<|skeleton|> class ResourceManager: """Manage Resources in the Power Reg system""" def __init__(self): """constructor""" <|body_0|> def create(self, auth_token, name): """Create a new Resource @param name name of the Resource @return instance of Resource""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResourceManager: """Manage Resources in the Power Reg system""" def __init__(self): """constructor""" ObjectManager.__init__(self) self.setters.update({'name': 'set_general', 'resource_types': 'set_many', 'session_resource_type_requirements': 'set_many'}) self.getters.upda...
the_stack_v2_python_sparse
pr_services/resource_system/resource_manager.py
ninemoreminutes/openassign-server
train
0
1b799d29e872380c076af43a5963a172f23c5d76
[ "self.objective = objective\nself.seed = seed\nself.column_text = column_text\nself.class_weight = class_weight\nself.is_NN = False\nself.info_scores = {}", "if self.is_NN:\n self.gridsearch = GridSearch_NN(self, self.hyper_params(size_params))\n self.gridsearch.train(x, y, nfolds, scoring, verbose, time_li...
<|body_start_0|> self.objective = objective self.seed = seed self.column_text = column_text self.class_weight = class_weight self.is_NN = False self.info_scores = {} <|end_body_0|> <|body_start_1|> if self.is_NN: self.gridsearch = GridSearch_NN(self, ...
Parent class of models
Model
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Model: """Parent class of models""" def __init__(self, objective, seed, column_text, class_weight): """Args: objective (str) : 'binary' or 'binary_proba' or 'text_binary' or 'text_binary_proba' seed (int) column_text (str) : name of the column with texts class_weight (None or 'balanc...
stack_v2_sparse_classes_75kplus_train_068182
5,480
no_license
[ { "docstring": "Args: objective (str) : 'binary' or 'binary_proba' or 'text_binary' or 'text_binary_proba' seed (int) column_text (str) : name of the column with texts class_weight (None or 'balanced') : apply a weight for each class", "name": "__init__", "signature": "def __init__(self, objective, seed...
5
stack_v2_sparse_classes_30k_train_008151
Implement the Python class `Model` described below. Class description: Parent class of models Method signatures and docstrings: - def __init__(self, objective, seed, column_text, class_weight): Args: objective (str) : 'binary' or 'binary_proba' or 'text_binary' or 'text_binary_proba' seed (int) column_text (str) : na...
Implement the Python class `Model` described below. Class description: Parent class of models Method signatures and docstrings: - def __init__(self, objective, seed, column_text, class_weight): Args: objective (str) : 'binary' or 'binary_proba' or 'text_binary' or 'text_binary_proba' seed (int) column_text (str) : na...
315494b1fe22d349d337fc43dc87d4085581e07e
<|skeleton|> class Model: """Parent class of models""" def __init__(self, objective, seed, column_text, class_weight): """Args: objective (str) : 'binary' or 'binary_proba' or 'text_binary' or 'text_binary_proba' seed (int) column_text (str) : name of the column with texts class_weight (None or 'balanc...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Model: """Parent class of models""" def __init__(self, objective, seed, column_text, class_weight): """Args: objective (str) : 'binary' or 'binary_proba' or 'text_binary' or 'text_binary_proba' seed (int) column_text (str) : name of the column with texts class_weight (None or 'balanced') : apply ...
the_stack_v2_python_sparse
class_models.py
Tarandro/BinaryML_churn
train
0
7fcb046d01ceabc3bc776ca83e81eab44e490c5f
[ "post_body = json.dumps({'application_credential': kwargs})\nresp, body = self.post('users/%s/application_credentials' % user_id, post_body)\nself.expected_success(201, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)", "resp, body = self.get('users/%s/application_credentials/%s'...
<|body_start_0|> post_body = json.dumps({'application_credential': kwargs}) resp, body = self.post('users/%s/application_credentials' % user_id, post_body) self.expected_success(201, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body) <|end_body_0|> ...
ApplicationCredentialsClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApplicationCredentialsClient: def create_application_credential(self, user_id, **kwargs): """Creates an application credential. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3/index.html#create-applicatio...
stack_v2_sparse_classes_75kplus_train_068183
3,449
permissive
[ { "docstring": "Creates an application credential. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3/index.html#create-application-credential", "name": "create_application_credential", "signature": "def create_application_...
4
stack_v2_sparse_classes_30k_train_012091
Implement the Python class `ApplicationCredentialsClient` described below. Class description: Implement the ApplicationCredentialsClient class. Method signatures and docstrings: - def create_application_credential(self, user_id, **kwargs): Creates an application credential. For a full list of available parameters, pl...
Implement the Python class `ApplicationCredentialsClient` described below. Class description: Implement the ApplicationCredentialsClient class. Method signatures and docstrings: - def create_application_credential(self, user_id, **kwargs): Creates an application credential. For a full list of available parameters, pl...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class ApplicationCredentialsClient: def create_application_credential(self, user_id, **kwargs): """Creates an application credential. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3/index.html#create-applicatio...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ApplicationCredentialsClient: def create_application_credential(self, user_id, **kwargs): """Creates an application credential. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3/index.html#create-application-credential""...
the_stack_v2_python_sparse
tempest/lib/services/identity/v3/application_credentials_client.py
openstack/tempest
train
270
e8645b24f89a25162c401501d9a79fc8da214a54
[ "self._cache = cache\nself._package = package\nself._service_manager = service_manager", "self._service_manager.RecordServices()\ntry:\n self._package.mark_install(True, True, False)\n logging.info('Installing...')\n self._cache.commit()\nexcept (apt.cache.FetchFailedException, SystemError) as e:\n lo...
<|body_start_0|> self._cache = cache self._package = package self._service_manager = service_manager <|end_body_0|> <|body_start_1|> self._service_manager.RecordServices() try: self._package.mark_install(True, True, False) logging.info('Installing...') ...
A Debian "install" trigger.
DebInstall
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DebInstall: """A Debian "install" trigger.""" def __init__(self, cache, package, service_manager): """Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.""" <|body_0|> def RunTrigger(self): ...
stack_v2_sparse_classes_75kplus_train_068184
10,965
no_license
[ { "docstring": "Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.", "name": "__init__", "signature": "def __init__(self, cache, package, service_manager)" }, { "docstring": "Run a Debian \"install\" trigger. This t...
2
stack_v2_sparse_classes_30k_train_010740
Implement the Python class `DebInstall` described below. Class description: A Debian "install" trigger. Method signatures and docstrings: - def __init__(self, cache, package, service_manager): Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the applic...
Implement the Python class `DebInstall` described below. Class description: A Debian "install" trigger. Method signatures and docstrings: - def __init__(self, cache, package, service_manager): Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the applic...
3fa5a9d67eb4eea87d3a54b1af5946cec8b67cca
<|skeleton|> class DebInstall: """A Debian "install" trigger.""" def __init__(self, cache, package, service_manager): """Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.""" <|body_0|> def RunTrigger(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DebInstall: """A Debian "install" trigger.""" def __init__(self, cache, package, service_manager): """Constructor. Args: cache: An apt cache. package: A package to be installed. service_manager: A service manager for the application.""" self._cache = cache self._package = package ...
the_stack_v2_python_sparse
guest/deb_triggers.py
tojo2000/wheelbarrow
train
0
37770a84501ea37bdeecbf2c0011fde6972d7616
[ "self.player_1 = {'type': 'computer', 'name': 'T3M4', 'phrase': opponent_list[4]['phrase'], 'record': {'win': 0, 'loss': 0}, 'gs': 0, 'rs': 0, 'deck': [], 'hand': [-3, -1, 1, 2], 'state': None, 'main': True, 'paradigm': 'new'}\nself.player_2 = {'type': 'computer', 'name': opponent_list[4]['name'], 'phrase': opponen...
<|body_start_0|> self.player_1 = {'type': 'computer', 'name': 'T3M4', 'phrase': opponent_list[4]['phrase'], 'record': {'win': 0, 'loss': 0}, 'gs': 0, 'rs': 0, 'deck': [], 'hand': [-3, -1, 1, 2], 'state': None, 'main': True, 'paradigm': 'new'} self.player_2 = {'type': 'computer', 'name': opponent_list[4]...
Pazaak
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pazaak: def __init__(self): """Initializes the player, computer, data, and options for the game The key/ value pairs in the player_1 / 2 dictionaries are referred to as attributes throughout the program.""" <|body_0|> def play(self): """Runs the game by calling a fun...
stack_v2_sparse_classes_75kplus_train_068185
4,099
no_license
[ { "docstring": "Initializes the player, computer, data, and options for the game The key/ value pairs in the player_1 / 2 dictionaries are referred to as attributes throughout the program.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Runs the game by calling a funct...
2
null
Implement the Python class `Pazaak` described below. Class description: Implement the Pazaak class. Method signatures and docstrings: - def __init__(self): Initializes the player, computer, data, and options for the game The key/ value pairs in the player_1 / 2 dictionaries are referred to as attributes throughout th...
Implement the Python class `Pazaak` described below. Class description: Implement the Pazaak class. Method signatures and docstrings: - def __init__(self): Initializes the player, computer, data, and options for the game The key/ value pairs in the player_1 / 2 dictionaries are referred to as attributes throughout th...
916347e9e49276ee4a4d9677deaaac8084c42e55
<|skeleton|> class Pazaak: def __init__(self): """Initializes the player, computer, data, and options for the game The key/ value pairs in the player_1 / 2 dictionaries are referred to as attributes throughout the program.""" <|body_0|> def play(self): """Runs the game by calling a fun...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Pazaak: def __init__(self): """Initializes the player, computer, data, and options for the game The key/ value pairs in the player_1 / 2 dictionaries are referred to as attributes throughout the program.""" self.player_1 = {'type': 'computer', 'name': 'T3M4', 'phrase': opponent_list[4]['phrase...
the_stack_v2_python_sparse
modules/primary/pazaak.py
Richd4y/Pazaak-Card-Game
train
0
3fa06a6e7073b0305e42b8027d830166a475e009
[ "n = len(nums)\n\n@lru_cache(None)\ndef dfs(index: int) -> bool:\n if index >= n:\n return index == n\n res = False\n if index + 1 < n and nums[index] == nums[index + 1]:\n res |= dfs(index + 2)\n if index + 2 < n and (nums[index] == nums[index + 1] == nums[index + 2] or nums[index] == num...
<|body_start_0|> n = len(nums) @lru_cache(None) def dfs(index: int) -> bool: if index >= n: return index == n res = False if index + 1 < n and nums[index] == nums[index + 1]: res |= dfs(index + 2) if index + 2 < n a...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def validPartition(self, nums: List[int]) -> bool: """dp分割子数组""" <|body_0|> def validPartition2(self, nums: List[int]) -> bool: """dp分割子数组""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) @lru_cache(None) def ...
stack_v2_sparse_classes_75kplus_train_068186
2,222
no_license
[ { "docstring": "dp分割子数组", "name": "validPartition", "signature": "def validPartition(self, nums: List[int]) -> bool" }, { "docstring": "dp分割子数组", "name": "validPartition2", "signature": "def validPartition2(self, nums: List[int]) -> bool" } ]
2
stack_v2_sparse_classes_30k_val_001032
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validPartition(self, nums: List[int]) -> bool: dp分割子数组 - def validPartition2(self, nums: List[int]) -> bool: dp分割子数组
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validPartition(self, nums: List[int]) -> bool: dp分割子数组 - def validPartition2(self, nums: List[int]) -> bool: dp分割子数组 <|skeleton|> class Solution: def validPartition(sel...
7e79e26bb8f641868561b186e34c1127ed63c9e0
<|skeleton|> class Solution: def validPartition(self, nums: List[int]) -> bool: """dp分割子数组""" <|body_0|> def validPartition2(self, nums: List[int]) -> bool: """dp分割子数组""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def validPartition(self, nums: List[int]) -> bool: """dp分割子数组""" n = len(nums) @lru_cache(None) def dfs(index: int) -> bool: if index >= n: return index == n res = False if index + 1 < n and nums[index] == nums[inde...
the_stack_v2_python_sparse
11_动态规划/子数组/6137. 检查数组是否存在有效划分-分割子数组.py
981377660LMT/algorithm-study
train
225
68d14797317058f2429f2b20b9db60a89cf7cb5d
[ "super(BahdanauAttention, self).__init__()\nself.normalize = normalize\nself.batch_first = batch_first\nself.num_units = num_units\nself.linear_q = nn.Linear(query_size, num_units, bias=False)\nself.linear_k = nn.Linear(key_size, num_units, bias=False)\nnn.init.uniform_(self.linear_q.weight.data, -init_weight, init...
<|body_start_0|> super(BahdanauAttention, self).__init__() self.normalize = normalize self.batch_first = batch_first self.num_units = num_units self.linear_q = nn.Linear(query_size, num_units, bias=False) self.linear_k = nn.Linear(key_size, num_units, bias=False) ...
Bahdanau Attention (https://arxiv.org/abs/1409.0473) Implementation is very similar to tf.contrib.seq2seq.BahdanauAttention
BahdanauAttention
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BahdanauAttention: """Bahdanau Attention (https://arxiv.org/abs/1409.0473) Implementation is very similar to tf.contrib.seq2seq.BahdanauAttention""" def __init__(self, query_size, key_size, num_units, normalize=False, batch_first=False, init_weight=0.1): """Constructor for the Bahdan...
stack_v2_sparse_classes_75kplus_train_068187
6,755
permissive
[ { "docstring": "Constructor for the BahdanauAttention. :param query_size: feature dimension for query :param key_size: feature dimension for keys :param num_units: internal feature dimension :param normalize: whether to normalize energy term :param batch_first: if True batch size is the 1st dimension, if False ...
5
stack_v2_sparse_classes_30k_train_019209
Implement the Python class `BahdanauAttention` described below. Class description: Bahdanau Attention (https://arxiv.org/abs/1409.0473) Implementation is very similar to tf.contrib.seq2seq.BahdanauAttention Method signatures and docstrings: - def __init__(self, query_size, key_size, num_units, normalize=False, batch_...
Implement the Python class `BahdanauAttention` described below. Class description: Bahdanau Attention (https://arxiv.org/abs/1409.0473) Implementation is very similar to tf.contrib.seq2seq.BahdanauAttention Method signatures and docstrings: - def __init__(self, query_size, key_size, num_units, normalize=False, batch_...
a5388a45f71a949639b35cc5b990bd130d2d8164
<|skeleton|> class BahdanauAttention: """Bahdanau Attention (https://arxiv.org/abs/1409.0473) Implementation is very similar to tf.contrib.seq2seq.BahdanauAttention""" def __init__(self, query_size, key_size, num_units, normalize=False, batch_first=False, init_weight=0.1): """Constructor for the Bahdan...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BahdanauAttention: """Bahdanau Attention (https://arxiv.org/abs/1409.0473) Implementation is very similar to tf.contrib.seq2seq.BahdanauAttention""" def __init__(self, query_size, key_size, num_units, normalize=False, batch_first=False, init_weight=0.1): """Constructor for the BahdanauAttention. ...
the_stack_v2_python_sparse
PyTorch/Translation/GNMT/seq2seq/models/attention.py
NVIDIA/DeepLearningExamples
train
11,838
cf9e6bef68f464922d94f22edb15f3ddd4077905
[ "try:\n return super().make_context(info_name, args, parent, **extra)\nexcept Exception as e:\n telemetry_client = parent.obj['TELEMETRY_CLIENT']\n if isinstance(e, click.exceptions.Exit) and e.exit_code == 0:\n telemetry_client.send_command_telemetry(parent, extra_info_name=info_name, is_help=True)...
<|body_start_0|> try: return super().make_context(info_name, args, parent, **extra) except Exception as e: telemetry_client = parent.obj['TELEMETRY_CLIENT'] if isinstance(e, click.exceptions.Exit) and e.exit_code == 0: telemetry_client.send_command_tel...
OctaviaCommand
[ "MIT", "Apache-2.0", "BSD-3-Clause", "Elastic-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OctaviaCommand: def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: """Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this...
stack_v2_sparse_classes_75kplus_train_068188
2,019
permissive
[ { "docstring": "Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this invocation. args (t.List[str]): The arguments to parse as list of strings. parent (t.Optional[click.Context], optional): The parent context if available.. Defaults to Non...
2
stack_v2_sparse_classes_30k_train_012843
Implement the Python class `OctaviaCommand` described below. Class description: Implement the OctaviaCommand class. Method signatures and docstrings: - def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: Wrap parent make conte...
Implement the Python class `OctaviaCommand` described below. Class description: Implement the OctaviaCommand class. Method signatures and docstrings: - def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: Wrap parent make conte...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class OctaviaCommand: def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: """Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OctaviaCommand: def make_context(self, info_name: t.Optional[str], args: t.List[str], parent: t.Optional[click.Context]=None, **extra: t.Any) -> click.Context: """Wrap parent make context with telemetry sending in case of failure. Args: info_name (t.Optional[str]): The info name for this invocation. a...
the_stack_v2_python_sparse
dts/airbyte/octavia-cli/octavia_cli/base_commands.py
alldatacenter/alldata
train
774
bdbd12e1449c843427c3a42c44a4aa2d372f4ae1
[ "self.hints = {}\nself.arrays = {}\nself.compilers = {}\nself.specializers = {}\nself.object_store = ObjectStore(config['object_store'])\nif config['open_ahead']:\n self.object_store.open_ahead()\nfor compiler in config['compilers']:\n self.compilers[compiler] = Compiler(config['compilers'][compiler])\nfor sl...
<|body_start_0|> self.hints = {} self.arrays = {} self.compilers = {} self.specializers = {} self.object_store = ObjectStore(config['object_store']) if config['open_ahead']: self.object_store.open_ahead() for compiler in config['compilers']: ...
Encapsulation of runtime activities, compilation, loading, etc.
Runtime
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Runtime: """Encapsulation of runtime activities, compilation, loading, etc.""" def __init__(self, config): """:param config pych.Config: pyChapel configuration""" <|body_0|> def hint(self, extern): """Hint the runtime that we might be interested in this extern at...
stack_v2_sparse_classes_75kplus_train_068189
6,809
permissive
[ { "docstring": ":param config pych.Config: pyChapel configuration", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "Hint the runtime that we might be interested in this extern at some point in the future.", "name": "hint", "signature": "def hint(self, ext...
4
stack_v2_sparse_classes_30k_test_001741
Implement the Python class `Runtime` described below. Class description: Encapsulation of runtime activities, compilation, loading, etc. Method signatures and docstrings: - def __init__(self, config): :param config pych.Config: pyChapel configuration - def hint(self, extern): Hint the runtime that we might be interes...
Implement the Python class `Runtime` described below. Class description: Encapsulation of runtime activities, compilation, loading, etc. Method signatures and docstrings: - def __init__(self, config): :param config pych.Config: pyChapel configuration - def hint(self, extern): Hint the runtime that we might be interes...
76243e750833213b8dbc1ae55b29c24c9cdf7322
<|skeleton|> class Runtime: """Encapsulation of runtime activities, compilation, loading, etc.""" def __init__(self, config): """:param config pych.Config: pyChapel configuration""" <|body_0|> def hint(self, extern): """Hint the runtime that we might be interested in this extern at...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Runtime: """Encapsulation of runtime activities, compilation, loading, etc.""" def __init__(self, config): """:param config pych.Config: pyChapel configuration""" self.hints = {} self.arrays = {} self.compilers = {} self.specializers = {} self.object_store ...
the_stack_v2_python_sparse
module/pych/runtime.py
safl/pychapel
train
2
8cb5ee0e7fa87bca8beeb005f6cc9b75065fc694
[ "mile_rule = self.env.ref('metro_park_base_data_10.repair_rule_l')\nfor record in self:\n if record.rule and record.rule.id == mile_rule.id:\n record.is_mile = True", "if len(self) == 0:\n return\nfor record in self:\n if not record.plan_id or not record.dev:\n continue\n pre_date_train_...
<|body_start_0|> mile_rule = self.env.ref('metro_park_base_data_10.repair_rule_l') for record in self: if record.rule and record.rule.id == mile_rule.id: record.is_mile = True <|end_body_0|> <|body_start_1|> if len(self) == 0: return for record in...
日计划设备检修信息,包含计划内容和日常维护及运行内容
RuleInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RuleInfo: """日计划设备检修信息,包含计划内容和日常维护及运行内容""" def _compute_is_mile(self): """计算是否为公里数 :return:""" <|body_0|> def _compute_last_repair_info(self): """计算上次里程修信息 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> mile_rule = self.env.ref('metro_...
stack_v2_sparse_classes_75kplus_train_068190
1,559
no_license
[ { "docstring": "计算是否为公里数 :return:", "name": "_compute_is_mile", "signature": "def _compute_is_mile(self)" }, { "docstring": "计算上次里程修信息 :return:", "name": "_compute_last_repair_info", "signature": "def _compute_last_repair_info(self)" } ]
2
stack_v2_sparse_classes_30k_train_047352
Implement the Python class `RuleInfo` described below. Class description: 日计划设备检修信息,包含计划内容和日常维护及运行内容 Method signatures and docstrings: - def _compute_is_mile(self): 计算是否为公里数 :return: - def _compute_last_repair_info(self): 计算上次里程修信息 :return:
Implement the Python class `RuleInfo` described below. Class description: 日计划设备检修信息,包含计划内容和日常维护及运行内容 Method signatures and docstrings: - def _compute_is_mile(self): 计算是否为公里数 :return: - def _compute_last_repair_info(self): 计算上次里程修信息 :return: <|skeleton|> class RuleInfo: """日计划设备检修信息,包含计划内容和日常维护及运行内容""" def _...
13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9
<|skeleton|> class RuleInfo: """日计划设备检修信息,包含计划内容和日常维护及运行内容""" def _compute_is_mile(self): """计算是否为公里数 :return:""" <|body_0|> def _compute_last_repair_info(self): """计算上次里程修信息 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RuleInfo: """日计划设备检修信息,包含计划内容和日常维护及运行内容""" def _compute_is_mile(self): """计算是否为公里数 :return:""" mile_rule = self.env.ref('metro_park_base_data_10.repair_rule_l') for record in self: if record.rule and record.rule.id == mile_rule.id: record.is_mile = True...
the_stack_v2_python_sparse
mdias_addons/metro_park_base_data_10/models/plan_date_rule_info.py
rezaghanimi/main_mdias
train
0
3c2ae1718db51e2625f9bb18367957de2df00787
[ "super(ReparametrisedGaussianEncoder, self).__init__(data_dim=data_dim, noise_dim=noise_dim, latent_dim=latent_dim, network_architecture=network_architecture, name=name or 'Reparametrised Gaussian Encoder')\nlatent_mean, latent_log_var = get_network_by_name['reparametrised_encoder'][network_architecture](self.data_...
<|body_start_0|> super(ReparametrisedGaussianEncoder, self).__init__(data_dim=data_dim, noise_dim=noise_dim, latent_dim=latent_dim, network_architecture=network_architecture, name=name or 'Reparametrised Gaussian Encoder') latent_mean, latent_log_var = get_network_by_name['reparametrised_encoder'][netwo...
A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space
ReparametrisedGaussianEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReparametrisedGaussianEncoder: """A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space""" def __init__(self, data_dim, noise_dim, latent_dim, netw...
stack_v2_sparse_classes_75kplus_train_068191
23,104
permissive
[ { "docstring": "Args: data_dim: int, flattened data space dimensionality noise_dim: int, flattened noise space dimensionality latent_dim: int, flattened latent space dimensionality network_architecture: str, the architecture name for the body of the reparametrised Gaussian Encoder model name: str, optional iden...
2
stack_v2_sparse_classes_30k_train_025238
Implement the Python class `ReparametrisedGaussianEncoder` described below. Class description: A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space Method signatures and do...
Implement the Python class `ReparametrisedGaussianEncoder` described below. Class description: A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space Method signatures and do...
545e4993c90622f05b5b7ba0183bc07d5972371e
<|skeleton|> class ReparametrisedGaussianEncoder: """A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space""" def __init__(self, data_dim, noise_dim, latent_dim, netw...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReparametrisedGaussianEncoder: """A ReparametrisedGaussianEncoder model is trained to parametrise a Gaussian latent variables: Data | ----------- | Encoder | ----------- | mu + sigma * Noise <--- Reparametrised Gaussian latent space""" def __init__(self, data_dim, noise_dim, latent_dim, network_architect...
the_stack_v2_python_sparse
playground/models/networks/encoder.py
gdikov/vae-playground
train
1
a7f1895d39686f6be4c38fc530889c9c16c1edb3
[ "if model._meta.app_label in ['goibibo']:\n db_name = 'goibibo_slave'\nelse:\n db_name = 'default'\nreturn db_name", "if model._meta.app_label == 'goibibo':\n if model._meta.model_name in NO_WRITE_MODELS:\n raise Exception('write not allowed here')\n db_name = 'goibibo_master'\nelse:\n db_na...
<|body_start_0|> if model._meta.app_label in ['goibibo']: db_name = 'goibibo_slave' else: db_name = 'default' return db_name <|end_body_0|> <|body_start_1|> if model._meta.app_label == 'goibibo': if model._meta.model_name in NO_WRITE_MODELS: ...
Goibibo Database Router. A router to control all database operations on models in the Goibibo Application.
GoibiboApplicationRouter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoibiboApplicationRouter: """Goibibo Database Router. A router to control all database operations on models in the Goibibo Application.""" def db_for_read(model, **hints): """Return db for read.""" <|body_0|> def db_for_write(model, **hints): """Return db for wri...
stack_v2_sparse_classes_75kplus_train_068192
2,912
no_license
[ { "docstring": "Return db for read.", "name": "db_for_read", "signature": "def db_for_read(model, **hints)" }, { "docstring": "Return db for write.", "name": "db_for_write", "signature": "def db_for_write(model, **hints)" }, { "docstring": "Return flag to allow migrations.", ...
4
null
Implement the Python class `GoibiboApplicationRouter` described below. Class description: Goibibo Database Router. A router to control all database operations on models in the Goibibo Application. Method signatures and docstrings: - def db_for_read(model, **hints): Return db for read. - def db_for_write(model, **hint...
Implement the Python class `GoibiboApplicationRouter` described below. Class description: Goibibo Database Router. A router to control all database operations on models in the Goibibo Application. Method signatures and docstrings: - def db_for_read(model, **hints): Return db for read. - def db_for_write(model, **hint...
26ca47c726f2c38211247a41d294e38a67cecb7f
<|skeleton|> class GoibiboApplicationRouter: """Goibibo Database Router. A router to control all database operations on models in the Goibibo Application.""" def db_for_read(model, **hints): """Return db for read.""" <|body_0|> def db_for_write(model, **hints): """Return db for wri...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GoibiboApplicationRouter: """Goibibo Database Router. A router to control all database operations on models in the Goibibo Application.""" def db_for_read(model, **hints): """Return db for read.""" if model._meta.app_label in ['goibibo']: db_name = 'goibibo_slave' else...
the_stack_v2_python_sparse
depot/depot_proj/db_router.py
rsenwar/depot
train
0
adeadef0a9995f28fbac2dc8a8e3efa9a3075c97
[ "state = self.device.states.get(self.entity_description.key)\nif not state or not state.value:\n return None\nif self.entity_description.native_value:\n return self.entity_description.native_value(state.value)\nif isinstance(state.value, (dict, list)):\n return None\nreturn state.value", "if not (default...
<|body_start_0|> state = self.device.states.get(self.entity_description.key) if not state or not state.value: return None if self.entity_description.native_value: return self.entity_description.native_value(state.value) if isinstance(state.value, (dict, list)): ...
Representation of an Overkiz Sensor.
OverkizStateSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OverkizStateSensor: """Representation of an Overkiz Sensor.""" def native_value(self) -> StateType: """Return the value of the sensor.""" <|body_0|> def native_unit_of_measurement(self) -> str | None: """Return the unit of measurement.""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus_train_068193
20,039
permissive
[ { "docstring": "Return the value of the sensor.", "name": "native_value", "signature": "def native_value(self) -> StateType" }, { "docstring": "Return the unit of measurement.", "name": "native_unit_of_measurement", "signature": "def native_unit_of_measurement(self) -> str | None" } ]
2
stack_v2_sparse_classes_30k_train_042971
Implement the Python class `OverkizStateSensor` described below. Class description: Representation of an Overkiz Sensor. Method signatures and docstrings: - def native_value(self) -> StateType: Return the value of the sensor. - def native_unit_of_measurement(self) -> str | None: Return the unit of measurement.
Implement the Python class `OverkizStateSensor` described below. Class description: Representation of an Overkiz Sensor. Method signatures and docstrings: - def native_value(self) -> StateType: Return the value of the sensor. - def native_unit_of_measurement(self) -> str | None: Return the unit of measurement. <|ske...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class OverkizStateSensor: """Representation of an Overkiz Sensor.""" def native_value(self) -> StateType: """Return the value of the sensor.""" <|body_0|> def native_unit_of_measurement(self) -> str | None: """Return the unit of measurement.""" <|body_1|> <|en...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OverkizStateSensor: """Representation of an Overkiz Sensor.""" def native_value(self) -> StateType: """Return the value of the sensor.""" state = self.device.states.get(self.entity_description.key) if not state or not state.value: return None if self.entity_des...
the_stack_v2_python_sparse
homeassistant/components/overkiz/sensor.py
home-assistant/core
train
35,501
db78845e26e90421164181e7742dcb33ccad6673
[ "def transform(node):\n if node:\n vals.append(str(node.val))\n transform(node.left)\n transform(node.right)\nvals = []\ntransform(root)\nreturn ' '.join(vals)", "def helper(lower=float('-inf'), upper=float('inf')):\n if not queue or queue[0] < lower or queue[0] > upper:\n return...
<|body_start_0|> def transform(node): if node: vals.append(str(node.val)) transform(node.left) transform(node.right) vals = [] transform(root) return ' '.join(vals) <|end_body_0|> <|body_start_1|> def helper(lower=float...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize1(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|> def serialize(self, root: TreeNode) -> str: ...
stack_v2_sparse_classes_75kplus_train_068194
3,487
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize1", "signature": "def serialize1(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" }, { "d...
5
stack_v2_sparse_classes_30k_train_013792
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize1(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. - def serialize(self,...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize1(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. - def serialize(self,...
502e121cc25fcd81afe3d029145aeee56db794f0
<|skeleton|> class Codec: def serialize1(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|> def serialize(self, root: TreeNode) -> str: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize1(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" def transform(node): if node: vals.append(str(node.val)) transform(node.left) transform(node.right) vals = [] transform(root)...
the_stack_v2_python_sparse
449serialize.py
qinzhouhit/leetcode
train
0
7f014722a979fc59a01016b085b9ed3765c49804
[ "super(NoopResetEnv, self).__init__(env)\nself.noop_max = noop_max\nassert env.unwrapped.get_action_meanings()[0] == 'NOOP'", "self.env.reset()\nnoops = np.random.randint(1, self.noop_max + 1)\nfor _ in range(noops):\n obs, _, _, _ = self.env.step(0)\nreturn obs" ]
<|body_start_0|> super(NoopResetEnv, self).__init__(env) self.noop_max = noop_max assert env.unwrapped.get_action_meanings()[0] == 'NOOP' <|end_body_0|> <|body_start_1|> self.env.reset() noops = np.random.randint(1, self.noop_max + 1) for _ in range(noops): o...
NoopResetEnv
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NoopResetEnv: def __init__(self, env=None, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.""" <|body_0|> def _reset(self): """Do no-op action for a number of steps in [1, noop_max].""" <|body...
stack_v2_sparse_classes_75kplus_train_068195
7,958
no_license
[ { "docstring": "Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.", "name": "__init__", "signature": "def __init__(self, env=None, noop_max=30)" }, { "docstring": "Do no-op action for a number of steps in [1, noop_max].", "name": "_reset", ...
2
stack_v2_sparse_classes_30k_train_032457
Implement the Python class `NoopResetEnv` described below. Class description: Implement the NoopResetEnv class. Method signatures and docstrings: - def __init__(self, env=None, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. - def _reset(self): Do no-op...
Implement the Python class `NoopResetEnv` described below. Class description: Implement the NoopResetEnv class. Method signatures and docstrings: - def __init__(self, env=None, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. - def _reset(self): Do no-op...
44fa78bf9c0e03be39d431d2b6d01f11198ab610
<|skeleton|> class NoopResetEnv: def __init__(self, env=None, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.""" <|body_0|> def _reset(self): """Do no-op action for a number of steps in [1, noop_max].""" <|body...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NoopResetEnv: def __init__(self, env=None, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.""" super(NoopResetEnv, self).__init__(env) self.noop_max = noop_max assert env.unwrapped.get_action_meanings()[0] == 'N...
the_stack_v2_python_sparse
utils/DQNCore.py
pierresdr/belief_rpz_dmdp_ijcnn_2021
train
2
18c133242c9ecee522b4a64558781d156c0cca95
[ "self.name = kwargs.get('name')\nself.description = kwargs.get('description')\nself.project_name = kwargs.get('project_name')\nself.rule_settings = list()\nrule_settings = kwargs.get('rules')\nif not rule_settings:\n rule_settings = kwargs.get('rule_settings')\nif rule_settings:\n for rule_setting in rule_set...
<|body_start_0|> self.name = kwargs.get('name') self.description = kwargs.get('description') self.project_name = kwargs.get('project_name') self.rule_settings = list() rule_settings = kwargs.get('rules') if not rule_settings: rule_settings = kwargs.get('rule_s...
Class representing a keypair configuration
SecurityGroupConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecurityGroupConfig: """Class representing a keypair configuration""" def __init__(self, **kwargs): """Constructor :param name: The security group's name (required) :param description: The security group's description (optional) :param project_name: The name of the project under whic...
stack_v2_sparse_classes_75kplus_train_068196
14,004
permissive
[ { "docstring": "Constructor :param name: The security group's name (required) :param description: The security group's description (optional) :param project_name: The name of the project under which the security group will be created :param rule_settings: a list of SecurityGroupRuleConfig objects :return:", ...
2
null
Implement the Python class `SecurityGroupConfig` described below. Class description: Class representing a keypair configuration Method signatures and docstrings: - def __init__(self, **kwargs): Constructor :param name: The security group's name (required) :param description: The security group's description (optional...
Implement the Python class `SecurityGroupConfig` described below. Class description: Class representing a keypair configuration Method signatures and docstrings: - def __init__(self, **kwargs): Constructor :param name: The security group's name (required) :param description: The security group's description (optional...
567cdf25e1319fbc8a1a874dd18d21f88948e67e
<|skeleton|> class SecurityGroupConfig: """Class representing a keypair configuration""" def __init__(self, **kwargs): """Constructor :param name: The security group's name (required) :param description: The security group's description (optional) :param project_name: The name of the project under whic...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SecurityGroupConfig: """Class representing a keypair configuration""" def __init__(self, **kwargs): """Constructor :param name: The security group's name (required) :param description: The security group's description (optional) :param project_name: The name of the project under which the securit...
the_stack_v2_python_sparse
snaps/config/security_group.py
opnfv/snaps
train
2
a6fe4fceaeacd915c9e40ab1af13fc6f0518e332
[ "super(LineCtrl, self).__init__(parent, id_, u'', size=size, style=wx.TE_PROCESS_ENTER, validator=util.IntValidator(0, 65535))\nself._last = 0\nself.GetDoc = get_doc", "val = self.GetValue()\nif not val.isdigit():\n return\nval = int(val) - 1\ndoc = self.GetDoc()\nlines = doc.GetLineCount()\nif val > lines:\n ...
<|body_start_0|> super(LineCtrl, self).__init__(parent, id_, u'', size=size, style=wx.TE_PROCESS_ENTER, validator=util.IntValidator(0, 65535)) self._last = 0 self.GetDoc = get_doc <|end_body_0|> <|body_start_1|> val = self.GetValue() if not val.isdigit(): return ...
A custom int control for providing a go To line control for the Command Bar.
LineCtrl
[ "BSD-3-Clause", "LicenseRef-scancode-python-cwi", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-free-unknown", "Python-2.0", "LGPL-2.0-or-later", "WxWindows-exception-3.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LineCtrl: """A custom int control for providing a go To line control for the Command Bar.""" def __init__(self, parent, id_, get_doc, size=wx.DefaultSize): """Initializes the LineCtrl control and its attributes. @param parent: Parent Window @param id_: Control ID @param get_doc: call...
stack_v2_sparse_classes_75kplus_train_068197
44,291
permissive
[ { "docstring": "Initializes the LineCtrl control and its attributes. @param parent: Parent Window @param id_: Control ID @param get_doc: callback method for retrieving a reference to the current document. @keyword size: Control Size (tuple)", "name": "__init__", "signature": "def __init__(self, parent, ...
3
stack_v2_sparse_classes_30k_train_049501
Implement the Python class `LineCtrl` described below. Class description: A custom int control for providing a go To line control for the Command Bar. Method signatures and docstrings: - def __init__(self, parent, id_, get_doc, size=wx.DefaultSize): Initializes the LineCtrl control and its attributes. @param parent: ...
Implement the Python class `LineCtrl` described below. Class description: A custom int control for providing a go To line control for the Command Bar. Method signatures and docstrings: - def __init__(self, parent, id_, get_doc, size=wx.DefaultSize): Initializes the LineCtrl control and its attributes. @param parent: ...
77d66c719b5746f37af51ad593e2941ed6fbba17
<|skeleton|> class LineCtrl: """A custom int control for providing a go To line control for the Command Bar.""" def __init__(self, parent, id_, get_doc, size=wx.DefaultSize): """Initializes the LineCtrl control and its attributes. @param parent: Parent Window @param id_: Control ID @param get_doc: call...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LineCtrl: """A custom int control for providing a go To line control for the Command Bar.""" def __init__(self, parent, id_, get_doc, size=wx.DefaultSize): """Initializes the LineCtrl control and its attributes. @param parent: Parent Window @param id_: Control ID @param get_doc: callback method f...
the_stack_v2_python_sparse
base/lib/python2.7/site-packages/wx-3.0-gtk2/wx/tools/Editra/src/ed_cmdbar.py
jorgediazjr/dials-dev20191018
train
0
96df271790b98bf100fda916dd4956e0f08797ad
[ "sensor = BME680Sensor(self.mudpi, config)\nif sensor:\n self.add_component(sensor)\nreturn True", "if not isinstance(config, list):\n config = [config]\nfor conf in config:\n if not conf.get('key'):\n raise ConfigError('Missing `key` in i2c display config.')\n if not conf.get('address'):\n ...
<|body_start_0|> sensor = BME680Sensor(self.mudpi, config) if sensor: self.add_component(sensor) return True <|end_body_0|> <|body_start_1|> if not isinstance(config, list): config = [config] for conf in config: if not conf.get('key'): ...
Interface
[ "BSD-4-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interface: def load(self, config): """Load BME680 sensor component from configs""" <|body_0|> def validate(self, config): """Validate the bme680 config""" <|body_1|> <|end_skeleton|> <|body_start_0|> sensor = BME680Sensor(self.mudpi, config) ...
stack_v2_sparse_classes_75kplus_train_068198
3,300
permissive
[ { "docstring": "Load BME680 sensor component from configs", "name": "load", "signature": "def load(self, config)" }, { "docstring": "Validate the bme680 config", "name": "validate", "signature": "def validate(self, config)" } ]
2
stack_v2_sparse_classes_30k_train_018346
Implement the Python class `Interface` described below. Class description: Implement the Interface class. Method signatures and docstrings: - def load(self, config): Load BME680 sensor component from configs - def validate(self, config): Validate the bme680 config
Implement the Python class `Interface` described below. Class description: Implement the Interface class. Method signatures and docstrings: - def load(self, config): Load BME680 sensor component from configs - def validate(self, config): Validate the bme680 config <|skeleton|> class Interface: def load(self, co...
fb206b1136f529c7197f1e6b29629ed05630d377
<|skeleton|> class Interface: def load(self, config): """Load BME680 sensor component from configs""" <|body_0|> def validate(self, config): """Validate the bme680 config""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Interface: def load(self, config): """Load BME680 sensor component from configs""" sensor = BME680Sensor(self.mudpi, config) if sensor: self.add_component(sensor) return True def validate(self, config): """Validate the bme680 config""" if not is...
the_stack_v2_python_sparse
mudpi/extensions/bme680/sensor.py
mistasp0ck/mudpi-core
train
0
942714f4b8023e452e056b7ea12d72b2d5563c29
[ "super(PlacementShiftNet, self).__init__()\nself.num_out_dims = num_out_dims\nself.drop_prob = drop_prob\nself.layer1 = nn.Sequential(nn.Conv2d(in_channels, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), nn.Conv2d(32, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2, dil...
<|body_start_0|> super(PlacementShiftNet, self).__init__() self.num_out_dims = num_out_dims self.drop_prob = drop_prob self.layer1 = nn.Sequential(nn.Conv2d(in_channels, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), nn.Conv2d(32, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), ...
PlacementShiftNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlacementShiftNet: def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): """Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations...
stack_v2_sparse_classes_75kplus_train_068199
13,489
no_license
[ { "docstring": "Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations can be applied outside of this class's forward", "name": "__init__", "signature": "def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1...
2
stack_v2_sparse_classes_30k_train_037294
Implement the Python class `PlacementShiftNet` described below. Class description: Implement the PlacementShiftNet class. Method signatures and docstrings: - def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): Same as PlacementShiftDistNet,...
Implement the Python class `PlacementShiftNet` described below. Class description: Implement the PlacementShiftNet class. Method signatures and docstrings: - def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): Same as PlacementShiftDistNet,...
ad713e4eb15a2d9573622bace528fc86e19a6545
<|skeleton|> class PlacementShiftNet: def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): """Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PlacementShiftNet: def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): """Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations can be applie...
the_stack_v2_python_sparse
manipulation/plating/RNNs/rnns/networks.py
HARPLab/gastronomy
train
6