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
467
8.64k
id
stringlengths
40
40
length_bytes
int64
515
49.7k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
160
3.93k
prompted_full_text
stringlengths
681
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.09k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
331
8.3k
source
stringclasses
1 value
source_path
stringlengths
5
177
source_repo
stringlengths
6
88
split
stringclasses
1 value
star_events_count
int64
0
209k
64fe7e624a47662c42b5c6cd7c74b4a4671cf300
[ "d_collected_int = math.floor(days_collected)\nend_time = end_time or datetime.utcnow()\nearliest = end_time - timedelta(days=days_collected)\nself.avg_calculatable: bool = d_collected_int > HourlyResult.DAYS_NONE\nself.denom: List[float] = []\nif self.avg_calculatable:\n add_one_end = end_time.hour\n if earl...
<|body_start_0|> d_collected_int = math.floor(days_collected) end_time = end_time or datetime.utcnow() earliest = end_time - timedelta(days=days_collected) self.avg_calculatable: bool = d_collected_int > HourlyResult.DAYS_NONE self.denom: List[float] = [] if self.avg_calc...
Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``.
HourlyResult
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HourlyResult: """Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``.""" def __init__(self, days_collected:...
stack_v2_sparse_classes_10k_train_008300
6,459
permissive
[ { "docstring": "Initalizing method of :class:`HourlyResult`. :param days_collected: \"claimed\" days collected of the data :param end_time: end time of the data. current time in UTC if not given", "name": "__init__", "signature": "def __init__(self, days_collected: float, *, end_time: Optional[datetime]...
2
stack_v2_sparse_classes_30k_train_001415
Implement the Python class `HourlyResult` described below. Class description: Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``. Me...
Implement the Python class `HourlyResult` described below. Class description: Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``. Me...
c7da1e91783dce3a2b71b955b3a22b68db9056cf
<|skeleton|> class HourlyResult: """Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``.""" def __init__(self, days_collected:...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class HourlyResult: """Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``.""" def __init__(self, days_collected: float, *, en...
the_stack_v2_python_sparse
models/stats/base.py
RxJellyBot/Jelly-Bot
train
5
a24fd9e3332d60a70c72263725aa8fc42f9bb77c
[ "queue = deque()\nif root:\n queue.append(root)\ns = []\nwhile len(queue) > 0:\n node = queue.popleft()\n if node is None:\n s.append('null')\n else:\n s.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\nreturn ','.join(s)", "ss = data.split(',')\n...
<|body_start_0|> queue = deque() if root: queue.append(root) s = [] while len(queue) > 0: node = queue.popleft() if node is None: s.append('null') else: s.append(str(node.val)) queue.append(no...
Codec_BFS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec_BFS: 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|> <|b...
stack_v2_sparse_classes_10k_train_008301
5,078
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_BFS` described below. Class description: Implement the Codec_BFS 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...
Implement the Python class `Codec_BFS` described below. Class description: Implement the Codec_BFS 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...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Codec_BFS: 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_10k
data/stack_v2_sparse_classes_30k
class Codec_BFS: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" queue = deque() if root: queue.append(root) s = [] while len(queue) > 0: node = queue.popleft() if node is None: ...
the_stack_v2_python_sparse
code297SerializeAndDeserializeBinaryTree.py
cybelewang/leetcode-python
train
0
02e059cf0d98f794d181458bfc60acc71721c38a
[ "assert isinstance(entityCount, int)\nassert entityCount >= 2\nself.entityCount = entityCount\nassert acceptedEntityTypes is None or isinstance(acceptedEntityTypes, list)\nif acceptedEntityTypes is None:\n self.acceptedEntityTypes = None\nelse:\n for acceptedEntityType in acceptedEntityTypes:\n assert ...
<|body_start_0|> assert isinstance(entityCount, int) assert entityCount >= 2 self.entityCount = entityCount assert acceptedEntityTypes is None or isinstance(acceptedEntityTypes, list) if acceptedEntityTypes is None: self.acceptedEntityTypes = None else: ...
Generates set of all possible relations in corpus. :ivar entityCount: Number of entities in each relation (default=2) :ivar acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same length as entityCount. None will match all candidate relations.
CandidateBuilder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CandidateBuilder: """Generates set of all possible relations in corpus. :ivar entityCount: Number of entities in each relation (default=2) :ivar acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same length as entityCount. None will match all c...
stack_v2_sparse_classes_10k_train_008302
2,967
permissive
[ { "docstring": "Constructor :param entityCount: Number of entities in each relation (default=2) :param acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same length as entityCount. None will match all candidate relations. :type entityCount: int :type accepted...
2
stack_v2_sparse_classes_30k_train_005090
Implement the Python class `CandidateBuilder` described below. Class description: Generates set of all possible relations in corpus. :ivar entityCount: Number of entities in each relation (default=2) :ivar acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same lengt...
Implement the Python class `CandidateBuilder` described below. Class description: Generates set of all possible relations in corpus. :ivar entityCount: Number of entities in each relation (default=2) :ivar acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same lengt...
b6eac60fa40086b4c44e98e0baa34b760310d284
<|skeleton|> class CandidateBuilder: """Generates set of all possible relations in corpus. :ivar entityCount: Number of entities in each relation (default=2) :ivar acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same length as entityCount. None will match all c...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CandidateBuilder: """Generates set of all possible relations in corpus. :ivar entityCount: Number of entities in each relation (default=2) :ivar acceptedEntityTypes: Tuples of entities that candidate relations must match. Each entity should be the same length as entityCount. None will match all candidate rela...
the_stack_v2_python_sparse
kindred/CandidateBuilder.py
jakelever/kindred
train
158
2b3d9dee1a08c017f17e621e995a8ecd1e8aed43
[ "mol = Chem.MolFromSmiles(smiles)\nengine = ScaffoldGenerator(include_chirality=include_chirality)\nscaffold = engine.get_scaffold(mol)\nreturn scaffold", "np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)\nscaffolds = {}\nlog('About to generate scaffolds', self.verbose)\ndata_len = len(dat...
<|body_start_0|> mol = Chem.MolFromSmiles(smiles) engine = ScaffoldGenerator(include_chirality=include_chirality) scaffold = engine.get_scaffold(mol) return scaffold <|end_body_0|> <|body_start_1|> np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0) ...
Class for doing data splits based on the scaffold of small molecules.
ScaffoldSplitter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScaffoldSplitter: """Class for doing data splits based on the scaffold of small molecules.""" def generate_scaffold(self, smiles, include_chirality=False): """Compute the Bemis-Murcko scaffold for a SMILES string.""" <|body_0|> def split(self, dataset, frac_train=0.5, fr...
stack_v2_sparse_classes_10k_train_008303
3,303
no_license
[ { "docstring": "Compute the Bemis-Murcko scaffold for a SMILES string.", "name": "generate_scaffold", "signature": "def generate_scaffold(self, smiles, include_chirality=False)" }, { "docstring": "Splits internal compounds into train/validation/test by scaffold.", "name": "split", "signa...
2
stack_v2_sparse_classes_30k_train_004625
Implement the Python class `ScaffoldSplitter` described below. Class description: Class for doing data splits based on the scaffold of small molecules. Method signatures and docstrings: - def generate_scaffold(self, smiles, include_chirality=False): Compute the Bemis-Murcko scaffold for a SMILES string. - def split(s...
Implement the Python class `ScaffoldSplitter` described below. Class description: Class for doing data splits based on the scaffold of small molecules. Method signatures and docstrings: - def generate_scaffold(self, smiles, include_chirality=False): Compute the Bemis-Murcko scaffold for a SMILES string. - def split(s...
57e40d04181059ca39890d22361606edfadcc930
<|skeleton|> class ScaffoldSplitter: """Class for doing data splits based on the scaffold of small molecules.""" def generate_scaffold(self, smiles, include_chirality=False): """Compute the Bemis-Murcko scaffold for a SMILES string.""" <|body_0|> def split(self, dataset, frac_train=0.5, fr...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ScaffoldSplitter: """Class for doing data splits based on the scaffold of small molecules.""" def generate_scaffold(self, smiles, include_chirality=False): """Compute the Bemis-Murcko scaffold for a SMILES string.""" mol = Chem.MolFromSmiles(smiles) engine = ScaffoldGenerator(incl...
the_stack_v2_python_sparse
utils/splitter/scaffoldsplitter.py
moguizhizi/Adaptive-Graph-Convolutional-Network
train
0
7c3f55e49c21ef73190fc2778eb1d36ff10ffde9
[ "def dfs(i, remains: List[int]):\n if i == n + 1:\n return 1\n cnt = 0\n for j in range(1, n + 1):\n if remains[j] is None and (i % j == 0 or j % i == 0):\n remains[j] = i\n cnt += dfs(i + 1, remains)\n remains[j] = None\n return cnt\nreturn dfs(1, [None] *...
<|body_start_0|> def dfs(i, remains: List[int]): if i == n + 1: return 1 cnt = 0 for j in range(1, n + 1): if remains[j] is None and (i % j == 0 or j % i == 0): remains[j] = i cnt += dfs(i + 1, remains) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countArrangement(self, n: int) -> int: """DFS using a list""" <|body_0|> def countArrangement(self, n: int) -> int: """DFS using a binary number to make argument hashable for caching""" <|body_1|> def countArrangement(self, n: int) -> int: ...
stack_v2_sparse_classes_10k_train_008304
2,867
no_license
[ { "docstring": "DFS using a list", "name": "countArrangement", "signature": "def countArrangement(self, n: int) -> int" }, { "docstring": "DFS using a binary number to make argument hashable for caching", "name": "countArrangement", "signature": "def countArrangement(self, n: int) -> int...
3
stack_v2_sparse_classes_30k_val_000246
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countArrangement(self, n: int) -> int: DFS using a list - def countArrangement(self, n: int) -> int: DFS using a binary number to make argument hashable for caching - def cou...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countArrangement(self, n: int) -> int: DFS using a list - def countArrangement(self, n: int) -> int: DFS using a binary number to make argument hashable for caching - def cou...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def countArrangement(self, n: int) -> int: """DFS using a list""" <|body_0|> def countArrangement(self, n: int) -> int: """DFS using a binary number to make argument hashable for caching""" <|body_1|> def countArrangement(self, n: int) -> int: ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def countArrangement(self, n: int) -> int: """DFS using a list""" def dfs(i, remains: List[int]): if i == n + 1: return 1 cnt = 0 for j in range(1, n + 1): if remains[j] is None and (i % j == 0 or j % i == 0): ...
the_stack_v2_python_sparse
leetcode/solved/526_Beautiful_Arrangement/solution.py
sungminoh/algorithms
train
0
ba9c3d93f21944a4b7f6dbf60a31d7663516af06
[ "email_account_map = collections.defaultdict(list)\nfor i, account in enumerate(accounts):\n for email in account[1:]:\n email_account_map[email].append(i)\n\ndef dfs(i, emails, visited):\n if visited[i]:\n return\n visited[i] = True\n for email in accounts[i][1:]:\n emails.add(emai...
<|body_start_0|> email_account_map = collections.defaultdict(list) for i, account in enumerate(accounts): for email in account[1:]: email_account_map[email].append(i) def dfs(i, emails, visited): if visited[i]: return visited[i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: """graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))""" <|body_0|> def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: """union-find""" ...
stack_v2_sparse_classes_10k_train_008305
4,358
no_license
[ { "docstring": "graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))", "name": "accountsMerge1", "signature": "def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]" }, { "docstring": "union-find", "name": "accountsMerge1", "signature": "def accou...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i)) - def accountsMerge1(self, ac...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i)) - def accountsMerge1(self, ac...
6ff1941ff213a843013100ac7033e2d4f90fbd6a
<|skeleton|> class Solution: def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: """graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))""" <|body_0|> def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: """union-find""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def accountsMerge1(self, accounts: List[List[str]]) -> List[List[str]]: """graph + dfs: account -> email time: O(Sum((N_i)log(N_i))) space: O(Sum(N_i))""" email_account_map = collections.defaultdict(list) for i, account in enumerate(accounts): for email in account...
the_stack_v2_python_sparse
Leetcode 0721. Accounts Merge.py
Chaoran-sjsu/leetcode
train
0
8f4e820e2ef8e7ea9487dcfe55779e6de9fd418d
[ "testcase = TestCaseTable(**request.json)\ndb.session.add(testcase)\ndb.session.commit()\nreturn 'OK'\nabort(404)", "if 'name' in request.json:\n testcase = TestCaseTable.query.filter_by(name=request.json.get('name')).first()\n testcase.content = request.json.get('content')\n testcase.description = reque...
<|body_start_0|> testcase = TestCaseTable(**request.json) db.session.add(testcase) db.session.commit() return 'OK' abort(404) <|end_body_0|> <|body_start_1|> if 'name' in request.json: testcase = TestCaseTable.query.filter_by(name=request.json.get('name')).fi...
TestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCase: def post(self): """存储用例 :return:""" <|body_0|> def put(self): """更新用例 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> testcase = TestCaseTable(**request.json) db.session.add(testcase) db.session.commit() re...
stack_v2_sparse_classes_10k_train_008306
6,802
no_license
[ { "docstring": "存储用例 :return:", "name": "post", "signature": "def post(self)" }, { "docstring": "更新用例 :return:", "name": "put", "signature": "def put(self)" } ]
2
stack_v2_sparse_classes_30k_train_006568
Implement the Python class `TestCase` described below. Class description: Implement the TestCase class. Method signatures and docstrings: - def post(self): 存储用例 :return: - def put(self): 更新用例 :return:
Implement the Python class `TestCase` described below. Class description: Implement the TestCase class. Method signatures and docstrings: - def post(self): 存储用例 :return: - def put(self): 更新用例 :return: <|skeleton|> class TestCase: def post(self): """存储用例 :return:""" <|body_0|> def put(self):...
5ff767243f7d7f698997633f39ecd4c4ebcc998a
<|skeleton|> class TestCase: def post(self): """存储用例 :return:""" <|body_0|> def put(self): """更新用例 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestCase: def post(self): """存储用例 :return:""" testcase = TestCaseTable(**request.json) db.session.add(testcase) db.session.commit() return 'OK' abort(404) def put(self): """更新用例 :return:""" if 'name' in request.json: testcase = T...
the_stack_v2_python_sparse
backend/server.py
ceshiren/HogwartsSDET16
train
16
703232a621d6c94a7c084dfac8099e2a409e4695
[ "osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)\nself.deploy._CheckDeployType()\nself.assertTrue(self.getCopyPath('envoy_shell'))\nself.assertFalse(self.getCopyPath('app_shell'))\nself.assertFalse(self.getCopyPath('chrome'))", "osutils.Touch(os.path.join(self.deploy.optio...
<|body_start_0|> osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True) self.deploy._CheckDeployType() self.assertTrue(self.getCopyPath('envoy_shell')) self.assertFalse(self.getCopyPath('app_shell')) self.assertFalse(self.getCopyPath('chrome')) <...
Test detection of deployment type using build dir.
TestDeploymentType
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDeploymentType: """Test detection of deployment type using build dir.""" def testEnvoyDetection(self): """Check for an envoy deployment""" <|body_0|> def testAppShellDetection(self): """Check for an app_shell deployment""" <|body_1|> def testChro...
stack_v2_sparse_classes_10k_train_008307
13,041
permissive
[ { "docstring": "Check for an envoy deployment", "name": "testEnvoyDetection", "signature": "def testEnvoyDetection(self)" }, { "docstring": "Check for an app_shell deployment", "name": "testAppShellDetection", "signature": "def testAppShellDetection(self)" }, { "docstring": "Chec...
4
null
Implement the Python class `TestDeploymentType` described below. Class description: Test detection of deployment type using build dir. Method signatures and docstrings: - def testEnvoyDetection(self): Check for an envoy deployment - def testAppShellDetection(self): Check for an app_shell deployment - def testChromeAn...
Implement the Python class `TestDeploymentType` described below. Class description: Test detection of deployment type using build dir. Method signatures and docstrings: - def testEnvoyDetection(self): Check for an envoy deployment - def testAppShellDetection(self): Check for an app_shell deployment - def testChromeAn...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class TestDeploymentType: """Test detection of deployment type using build dir.""" def testEnvoyDetection(self): """Check for an envoy deployment""" <|body_0|> def testAppShellDetection(self): """Check for an app_shell deployment""" <|body_1|> def testChro...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestDeploymentType: """Test detection of deployment type using build dir.""" def testEnvoyDetection(self): """Check for an envoy deployment""" osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True) self.deploy._CheckDeployType() self.asser...
the_stack_v2_python_sparse
third_party/chromite/scripts/deploy_chrome_unittest.py
metux/chromium-suckless
train
5
1f2011aa16b4793522f6d81e1fd09a5007f0b3c4
[ "if not root:\n return ''\nqueue = deque()\nqueue.append(root)\nresult = ''\nwhile queue:\n node = queue.popleft()\n if node:\n result += str(node.val) + ','\n queue.append(node.left)\n queue.append(node.right)\n else:\n result += '#,'\nresult = result[:-1]\nreturn result", ...
<|body_start_0|> if not root: return '' queue = deque() queue.append(root) result = '' while queue: node = queue.popleft() if node: result += str(node.val) + ',' queue.append(node.left) queue.appe...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_10k_train_008308
2,640
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_003656
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:...
b62862b90886f85c33271b881ac1365871731dcc
<|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_10k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' queue = deque() queue.append(root) result = '' while queue: node = queue.popleft() if node: ...
the_stack_v2_python_sparse
serialize_tree.py
ashutosh-narkar/LeetCode
train
0
2dba7ede63cbf51a867ad6f5923b6dcce4c5c905
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RelatedContact()", "from .contact_relationship import ContactRelationship\nfrom .contact_relationship import ContactRelationship\nfields: Dict[str, Callable[[Any], None]] = {'accessConsent': lambda n: setattr(self, 'access_consent', n....
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return RelatedContact() <|end_body_0|> <|body_start_1|> from .contact_relationship import ContactRelationship from .contact_relationship import ContactRelationship fields: Dict[str, Cal...
RelatedContact
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelatedContact: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur...
stack_v2_sparse_classes_10k_train_008309
3,694
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: RelatedContact", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_valu...
3
null
Implement the Python class `RelatedContact` described below. Class description: Implement the RelatedContact class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: Creates a new instance of the appropriate class based on discriminator va...
Implement the Python class `RelatedContact` described below. Class description: Implement the RelatedContact class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: Creates a new instance of the appropriate class based on discriminator va...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class RelatedContact: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RelatedContact: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RelatedContact: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: RelatedCon...
the_stack_v2_python_sparse
msgraph/generated/models/related_contact.py
microsoftgraph/msgraph-sdk-python
train
135
987960badf80458cb3cde7066c2171e61b49b579
[ "b_values = self._encoding(max_log_scale, embedding_size, num_inputs)\na_values = torch.ones(b_values.shape[1])\nsuper().__init__(num_inputs, num_outputs, a_values, b_values, [num_channels] * num_layers)", "embedding_size = embedding_size // num_inputs\nfrequencies_matrix = 2.0 ** torch.linspace(0, max_log_scale,...
<|body_start_0|> b_values = self._encoding(max_log_scale, embedding_size, num_inputs) a_values = torch.ones(b_values.shape[1]) super().__init__(num_inputs, num_outputs, a_values, b_values, [num_channels] * num_layers) <|end_body_0|> <|body_start_1|> embedding_size = embedding_size // nu...
Version of FFN with positional encoding.
PositionalFMLP
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PositionalFMLP: """Version of FFN with positional encoding.""" def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): """Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int):...
stack_v2_sparse_classes_10k_train_008310
8,060
permissive
[ { "docstring": "Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of dimensions in the output max_log_scale (float): Maximum log scale for embedding num_layers (int, optional): Number of layers in the MLP. Defaults to 4. num_channels (int, optional): Number of chan...
2
stack_v2_sparse_classes_30k_train_000862
Implement the Python class `PositionalFMLP` described below. Class description: Version of FFN with positional encoding. Method signatures and docstrings: - def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): Constructor. Args: num_inputs (i...
Implement the Python class `PositionalFMLP` described below. Class description: Version of FFN with positional encoding. Method signatures and docstrings: - def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): Constructor. Args: num_inputs (i...
94a402cab47a2bd6241608308371490079af4d53
<|skeleton|> class PositionalFMLP: """Version of FFN with positional encoding.""" def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): """Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int):...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PositionalFMLP: """Version of FFN with positional encoding.""" def __init__(self, num_inputs: int, num_outputs: int, max_log_scale: float, num_layers=3, num_channels=256, embedding_size=256): """Constructor. Args: num_inputs (int): Number of dimensions in the input num_outputs (int): Number of di...
the_stack_v2_python_sparse
draugr/torch_utilities/architectures/mlp_variants/fourier.py
cnheider/draugr
train
4
5983b54aba73962c78575d99b22dca29054791bf
[ "super(LabelSmoothingLoss, self).__init__()\nself.criterion = nn.KLDivLoss(reduction='none')\nself.padding_idx = padding_idx\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.size = size\nself.normalize_length = normalize_length", "assert x.size(2) == self.size\nbatch_size = x.size(0)\nx = x.vi...
<|body_start_0|> super(LabelSmoothingLoss, self).__init__() self.criterion = nn.KLDivLoss(reduction='none') self.padding_idx = padding_idx self.confidence = 1.0 - smoothing self.smoothing = smoothing self.size = size self.normalize_length = normalize_length <|end_...
Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothing=0.1 [0,1,2] -> [ [0.9, 0.05, 0....
LabelSmoothingLoss
[ "GPL-1.0-or-later", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ...
stack_v2_sparse_classes_10k_train_008311
3,459
permissive
[ { "docstring": "Construct an LabelSmoothingLoss object.", "name": "__init__", "signature": "def __init__(self, size: int, padding_idx: int, smoothing: float, normalize_length: bool=False)" }, { "docstring": "Compute loss between x and target. The model outputs and data labels tensors are flatten...
2
null
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1....
Implement the Python class `LabelSmoothingLoss` described below. Class description: Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1....
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class LabelSmoothingLoss: """Label-smoothing loss. In a standard CE loss, the label's data distribution is: [0,1,2] -> [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ] In the smoothing version CE Loss,some probabilities are taken from the true label prob (1.0) and are divided among other labels. e.g. smoothin...
the_stack_v2_python_sparse
PyTorch/built-in/audio/Wenet_Conformer_for_Pytorch/wenet/transformer/label_smoothing_loss.py
Ascend/ModelZoo-PyTorch
train
23
f4024a3136f0a56071238bd8822c94c61a10c346
[ "if output_md is None:\n output_md = metadata_info.ClassificationTensorMd(name=_OUTPUT_NAME, description=_OUTPUT_DESCRIPTION)\nreturn cls.create_from_metadata_info_for_multihead(model_buffer, general_md, input_md, [output_md])", "if general_md is None:\n general_md = metadata_info.GeneralMd(name=_MODEL_NAME...
<|body_start_0|> if output_md is None: output_md = metadata_info.ClassificationTensorMd(name=_OUTPUT_NAME, description=_OUTPUT_DESCRIPTION) return cls.create_from_metadata_info_for_multihead(model_buffer, general_md, input_md, [output_md]) <|end_body_0|> <|body_start_1|> if general_...
Writes metadata into an audio classifier.
MetadataWriter
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "GPL-1.0-or-later", "MIT", "LGPL-2.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetadataWriter: """Writes metadata into an audio classifier.""" def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]...
stack_v2_sparse_classes_10k_train_008312
7,060
permissive
[ { "docstring": "Creates MetadataWriter based on general/input/output information. Args: model_buffer: valid buffer of the model file. general_md: general information about the model. If not specified, default general metadata will be generated. input_md: input audio tensor informaton. If not specified, default ...
3
null
Implement the Python class `MetadataWriter` described below. Class description: Writes metadata into an audio classifier. Method signatures and docstrings: - def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTenso...
Implement the Python class `MetadataWriter` described below. Class description: Writes metadata into an audio classifier. Method signatures and docstrings: - def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTenso...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class MetadataWriter: """Writes metadata into an audio classifier.""" def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MetadataWriter: """Writes metadata into an audio classifier.""" def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=None): ...
the_stack_v2_python_sparse
third_party/tflite_support/src/tensorflow_lite_support/metadata/python/metadata_writers/audio_classifier.py
chromium/chromium
train
17,408
fd5afd07ad8325ff4df2f0d9a54f82b5bb11a342
[ "if len(nums) == 0:\n return 0\nnums = [0] + nums\nf = [0 for _ in range(len(nums))]\nf[1] = nums[1]\nfor i in range(2, len(nums)):\n f[i] = max(nums[i] + f[i - 2], f[i - 1])\nreturn f[-1]", "if len(nums) == 0:\n return 0\nif len(nums) == 1:\n return nums[0]\nreturn max(self.rob_origin(nums[1:]), self...
<|body_start_0|> if len(nums) == 0: return 0 nums = [0] + nums f = [0 for _ in range(len(nums))] f[1] = nums[1] for i in range(2, len(nums)): f[i] = max(nums[i] + f[i - 2], f[i - 1]) return f[-1] <|end_body_0|> <|body_start_1|> if len(nums...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob_origin(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(nums) == 0: return 0 nums =...
stack_v2_sparse_classes_10k_train_008313
743
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "rob_origin", "signature": "def rob_origin(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "rob", "signature": "def rob(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob_origin(self, nums): :type nums: List[int] :rtype: int - def rob(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 rob_origin(self, nums): :type nums: List[int] :rtype: int - def rob(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def rob_origin(self, num...
c2b01374942dcba7fbbe7865d13d7599bbc083f3
<|skeleton|> class Solution: def rob_origin(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def rob(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def rob_origin(self, nums): """:type nums: List[int] :rtype: int""" if len(nums) == 0: return 0 nums = [0] + nums f = [0 for _ in range(len(nums))] f[1] = nums[1] for i in range(2, len(nums)): f[i] = max(nums[i] + f[i - 2], f[i ...
the_stack_v2_python_sparse
P0213.py
chenjiahui1991/LeetCode
train
0
2c12afdc1e69d238023ae3865f7eee477a864361
[ "if file_path is None:\n return False\ntry:\n if os.path.exists(file_path):\n os.remove(file_path)\nexcept Exception as ex:\n if ignore_errors:\n return False\n raise ex\nreturn True", "if directory_path is None:\n return False\ntry:\n if os.path.exists(directory_path):\n sh...
<|body_start_0|> if file_path is None: return False try: if os.path.exists(file_path): os.remove(file_path) except Exception as ex: if ignore_errors: return False raise ex return True <|end_body_0|> <|body_s...
Utilities for reading/writing to and from files.
CommonIOUtils
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommonIOUtils: """Utilities for reading/writing to and from files.""" def delete_file(file_path: str, ignore_errors: bool=False) -> bool: """delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If ...
stack_v2_sparse_classes_10k_train_008314
4,270
permissive
[ { "docstring": "delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If True, any exceptions thrown will be ignored (Useful in preventing infinite loops) :type ignore_errors: bool, optional :return: True if successful. False ...
4
null
Implement the Python class `CommonIOUtils` described below. Class description: Utilities for reading/writing to and from files. Method signatures and docstrings: - def delete_file(file_path: str, ignore_errors: bool=False) -> bool: delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file ...
Implement the Python class `CommonIOUtils` described below. Class description: Utilities for reading/writing to and from files. Method signatures and docstrings: - def delete_file(file_path: str, ignore_errors: bool=False) -> bool: delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file ...
b59ea7e5f4bd01d3b3bd7603843d525a9c179867
<|skeleton|> class CommonIOUtils: """Utilities for reading/writing to and from files.""" def delete_file(file_path: str, ignore_errors: bool=False) -> bool: """delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CommonIOUtils: """Utilities for reading/writing to and from files.""" def delete_file(file_path: str, ignore_errors: bool=False) -> bool: """delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If True, any exc...
the_stack_v2_python_sparse
src/sims4communitylib/utils/common_io_utils.py
velocist/TS4CheatsInfo
train
1
7f3ea4aeceac9362b57fa35cad570abe55c4032e
[ "assert isinstance(msg, str), 'Invalid message %s' % msg\nself.data = data\nself.messageByType = {}\nself.messages = []\nself.update(msg, *items)\nsuper().__init__()", "for item in items:\n if isinstance(item, str):\n self.messages.append(item)\n else:\n typ = typeFor(item)\n assert isi...
<|body_start_0|> assert isinstance(msg, str), 'Invalid message %s' % msg self.data = data self.messageByType = {} self.messages = [] self.update(msg, *items) super().__init__() <|end_body_0|> <|body_start_1|> for item in items: if isinstance(item, str...
Exception to be raised when the input is invalid.
InputError
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InputError: """Exception to be raised when the input is invalid.""" def __init__(self, msg, *items, **data): """Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any t...
stack_v2_sparse_classes_10k_train_008315
5,632
no_license
[ { "docstring": "Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any type. raise InputError('Something wrong with the id', Entity.Id) # The message is associated with the entity id. raise InputE...
3
stack_v2_sparse_classes_30k_train_004444
Implement the Python class `InputError` described below. Class description: Exception to be raised when the input is invalid. Method signatures and docstrings: - def __init__(self, msg, *items, **data): Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='b...
Implement the Python class `InputError` described below. Class description: Exception to be raised when the input is invalid. Method signatures and docstrings: - def __init__(self, msg, *items, **data): Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='b...
e0b3466b34d31548996d57be4a9dac134d904380
<|skeleton|> class InputError: """Exception to be raised when the input is invalid.""" def __init__(self, msg, *items, **data): """Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any t...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class InputError: """Exception to be raised when the input is invalid.""" def __init__(self, msg, *items, **data): """Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any type. raise In...
the_stack_v2_python_sparse
components/ally-api/ally/api/error.py
cristidomsa/Ally-Py
train
0
f46874aae652fa3eb63244fb046e91dd42da42aa
[ "self.chap_file_name = chap_file_name\nself.epub = epub\nself.nlp: dict[str, Language] = self.epub.nlp\nself.pipe: dict[str, TranslationPipelineCache] = self.epub.pipe\nself.lang_orig: str = self.epub.lang_orig\nself.lang_dest: str = self.epub.lang_dest\nself.soup = BeautifulSoup(chap_content, features='html.parser...
<|body_start_0|> self.chap_file_name = chap_file_name self.epub = epub self.nlp: dict[str, Language] = self.epub.nlp self.pipe: dict[str, TranslationPipelineCache] = self.epub.pipe self.lang_orig: str = self.epub.lang_orig self.lang_dest: str = self.epub.lang_dest ...
Chapter class. Parse the chapter content to find the Paragraphs in <p> tags.
Chapter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Chapter: """Chapter class. Parse the chapter content to find the Paragraphs in <p> tags.""" def __init__(self, chap_content: bytes, chap_file_name: str, epub: 'EPub') -> None: """Initialize a chapter. TODO: Pass lang tags?""" <|body_0|> def build_index(self): """...
stack_v2_sparse_classes_10k_train_008316
10,849
no_license
[ { "docstring": "Initialize a chapter. TODO: Pass lang tags?", "name": "__init__", "signature": "def __init__(self, chap_content: bytes, chap_file_name: str, epub: 'EPub') -> None" }, { "docstring": "Build maps to go from ``sent_in_chap_id`` to ``(par_id, sent_in_par_id)`` and vice-versa.", "...
6
stack_v2_sparse_classes_30k_train_005241
Implement the Python class `Chapter` described below. Class description: Chapter class. Parse the chapter content to find the Paragraphs in <p> tags. Method signatures and docstrings: - def __init__(self, chap_content: bytes, chap_file_name: str, epub: 'EPub') -> None: Initialize a chapter. TODO: Pass lang tags? - de...
Implement the Python class `Chapter` described below. Class description: Chapter class. Parse the chapter content to find the Paragraphs in <p> tags. Method signatures and docstrings: - def __init__(self, chap_content: bytes, chap_file_name: str, epub: 'EPub') -> None: Initialize a chapter. TODO: Pass lang tags? - de...
1d7e5657014b00612cde87b78d5506a9e8b6adfc
<|skeleton|> class Chapter: """Chapter class. Parse the chapter content to find the Paragraphs in <p> tags.""" def __init__(self, chap_content: bytes, chap_file_name: str, epub: 'EPub') -> None: """Initialize a chapter. TODO: Pass lang tags?""" <|body_0|> def build_index(self): """...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Chapter: """Chapter class. Parse the chapter content to find the Paragraphs in <p> tags.""" def __init__(self, chap_content: bytes, chap_file_name: str, epub: 'EPub') -> None: """Initialize a chapter. TODO: Pass lang tags?""" self.chap_file_name = chap_file_name self.epub = epub ...
the_stack_v2_python_sparse
python/streamlit-sample/align-epub/epub.py
Pitrified/snippet
train
2
afcf4094b8bc6cc883ff27e95c3d60484828c11a
[ "if self.game_id[0:2] == NBA_GAME_ID_PREFIX:\n return NBA_STRING\nelif self.game_id[0:2] == G_LEAGUE_GAME_ID_PREFIX:\n return D_LEAGUE_STRING\nelif self.game_id[0:2] == WNBA_GAME_ID_PREFIX:\n return WNBA_STRING", "if self.game_id[3] == '9':\n return '19' + self.game_id[3] + self.game_id[4]\nelse:\n ...
<|body_start_0|> if self.game_id[0:2] == NBA_GAME_ID_PREFIX: return NBA_STRING elif self.game_id[0:2] == G_LEAGUE_GAME_ID_PREFIX: return D_LEAGUE_STRING elif self.game_id[0:2] == WNBA_GAME_ID_PREFIX: return WNBA_STRING <|end_body_0|> <|body_start_1|> ...
Base Class for all data.nba.com data loaders This class should not be instantiated directly
DataNbaLoaderBase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataNbaLoaderBase: """Base Class for all data.nba.com data loaders This class should not be instantiated directly""" def league(self): """Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league""" <|body_0|> def season(s...
stack_v2_sparse_classes_10k_train_008317
1,242
permissive
[ { "docstring": "Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league", "name": "league", "signature": "def league(self)" }, { "docstring": "Returns year in which season starts for game id 4th and 5th characters in game id represent season yea...
2
stack_v2_sparse_classes_30k_train_006819
Implement the Python class `DataNbaLoaderBase` described below. Class description: Base Class for all data.nba.com data loaders This class should not be instantiated directly Method signatures and docstrings: - def league(self): Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba...
Implement the Python class `DataNbaLoaderBase` described below. Class description: Base Class for all data.nba.com data loaders This class should not be instantiated directly Method signatures and docstrings: - def league(self): Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba...
38d5d75be50a478dbe718700c880e48020ffa123
<|skeleton|> class DataNbaLoaderBase: """Base Class for all data.nba.com data loaders This class should not be instantiated directly""" def league(self): """Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league""" <|body_0|> def season(s...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DataNbaLoaderBase: """Base Class for all data.nba.com data loaders This class should not be instantiated directly""" def league(self): """Returns League for game id. First 2 in game id represent league - 00 for nba, 10 for wnba, 20 for g-league""" if self.game_id[0:2] == NBA_GAME_ID_PREFI...
the_stack_v2_python_sparse
pbpstats/data_loader/data_nba/base.py
dblackrun/pbpstats
train
73
74b1fa3e9a976311979e1c49b3659036856f89ab
[ "database.drop_tables([Customer])\ndatabase.create_tables([Customer])\nLOGGER.info('test setup complete')", "pass\nadd_customer(self.customer_111[0], self.customer_111[1], self.customer_111[2], self.customer_111[3], self.customer_111[4], self.customer_111[5], self.customer_111[6], self.customer_111[7])\ncustomer ...
<|body_start_0|> database.drop_tables([Customer]) database.create_tables([Customer]) LOGGER.info('test setup complete') <|end_body_0|> <|body_start_1|> pass add_customer(self.customer_111[0], self.customer_111[1], self.customer_111[2], self.customer_111[3], self.customer_111[4],...
testing basic operation
SuiteOfTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SuiteOfTests: """testing basic operation""" def setUp(self): """sets up the database""" <|body_0|> def test_add_customer(self): """test add customer""" <|body_1|> def test_search_customer(self): """test search customer""" <|body_2|> ...
stack_v2_sparse_classes_10k_train_008318
5,744
no_license
[ { "docstring": "sets up the database", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "test add customer", "name": "test_add_customer", "signature": "def test_add_customer(self)" }, { "docstring": "test search customer", "name": "test_search_customer", ...
6
null
Implement the Python class `SuiteOfTests` described below. Class description: testing basic operation Method signatures and docstrings: - def setUp(self): sets up the database - def test_add_customer(self): test add customer - def test_search_customer(self): test search customer - def test_delete_customer(self): test...
Implement the Python class `SuiteOfTests` described below. Class description: testing basic operation Method signatures and docstrings: - def setUp(self): sets up the database - def test_add_customer(self): test add customer - def test_search_customer(self): test search customer - def test_delete_customer(self): test...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class SuiteOfTests: """testing basic operation""" def setUp(self): """sets up the database""" <|body_0|> def test_add_customer(self): """test add customer""" <|body_1|> def test_search_customer(self): """test search customer""" <|body_2|> ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SuiteOfTests: """testing basic operation""" def setUp(self): """sets up the database""" database.drop_tables([Customer]) database.create_tables([Customer]) LOGGER.info('test setup complete') def test_add_customer(self): """test add customer""" pass ...
the_stack_v2_python_sparse
students/mmancini/lesson03/test_basic_operations.py
JavaRod/SP_Python220B_2019
train
1
6d0946232c0bbb3988daacfd5ddc13314dba2110
[ "self.scipy = scipy\nself.data = data\nself.mu = mu\nself.sigma = sigma\nself.log = log\nself.info = info\nself.epsilon = epsilon", "if self.data is None:\n output = gaussian(x, scipy=self.scipy, data=self.data, mu=self.mu[idx], sigma=self.sigma[idx], log=self.log, info=self.info, epsilon=self.epsilon)\nelse:\...
<|body_start_0|> self.scipy = scipy self.data = data self.mu = mu self.sigma = sigma self.log = log self.info = info self.epsilon = epsilon <|end_body_0|> <|body_start_1|> if self.data is None: output = gaussian(x, scipy=self.scipy, data=self....
GaussianDistribution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaussianDistribution: def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): """Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs ...
stack_v2_sparse_classes_10k_train_008319
47,457
no_license
[ { "docstring": "Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs inside forward *Unimodal and univariate* Inputs: scipy (bool): if True use scipy's pdf functions, use custom is False see: https://docs....
2
null
Implement the Python class `GaussianDistribution` described below. Class description: Implement the GaussianDistribution class. Method signatures and docstrings: - def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): Class for passing values through a Gaussian distrib...
Implement the Python class `GaussianDistribution` described below. Class description: Implement the GaussianDistribution class. Method signatures and docstrings: - def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): Class for passing values through a Gaussian distrib...
ad713e4eb15a2d9573622bace528fc86e19a6545
<|skeleton|> class GaussianDistribution: def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): """Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GaussianDistribution: def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): """Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs inside forward...
the_stack_v2_python_sparse
manipulation/plating/GMM-Placing/gmm_placing/gaussian.py
HARPLab/gastronomy
train
6
a6a99ba75e9744fd4886bb06b052b77bea153e13
[ "res = self.sumNumbers_(root)\nres = [int(i) for i in res]\nreturn sum(res)", "if root is None:\n return []\nif root.left is None and root.right is None:\n return [str(root.val)]\nleft_sum: List[str] = self.sumNumbers_(root.left)\nres = []\nfor i in left_sum:\n res.append(str(root.val) + str(i))\nprint(r...
<|body_start_0|> res = self.sumNumbers_(root) res = [int(i) for i in res] return sum(res) <|end_body_0|> <|body_start_1|> if root is None: return [] if root.left is None and root.right is None: return [str(root.val)] left_sum: List[str] = self.sum...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sumNumbers(self, root: TreeNode) -> int: """从根节点到叶子节点的数字之和""" <|body_0|> def sumNumbers_(self, root: TreeNode) -> List[str]: """创建这个函数的原因是 # 输入:root = [4,9,0,5,1] 左边有两个路径495,491 那么左边应该返回是一个List [95,91], 然后再去加上根节点, 用List[str]的原因是中间有00的情况,转化为int会丢掉 :rtype...
stack_v2_sparse_classes_10k_train_008320
2,100
no_license
[ { "docstring": "从根节点到叶子节点的数字之和", "name": "sumNumbers", "signature": "def sumNumbers(self, root: TreeNode) -> int" }, { "docstring": "创建这个函数的原因是 # 输入:root = [4,9,0,5,1] 左边有两个路径495,491 那么左边应该返回是一个List [95,91], 然后再去加上根节点, 用List[str]的原因是中间有00的情况,转化为int会丢掉 :rtype: object", "name": "sumNumbers_", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sumNumbers(self, root: TreeNode) -> int: 从根节点到叶子节点的数字之和 - def sumNumbers_(self, root: TreeNode) -> List[str]: 创建这个函数的原因是 # 输入:root = [4,9,0,5,1] 左边有两个路径495,491 那么左边应该返回是一个Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sumNumbers(self, root: TreeNode) -> int: 从根节点到叶子节点的数字之和 - def sumNumbers_(self, root: TreeNode) -> List[str]: 创建这个函数的原因是 # 输入:root = [4,9,0,5,1] 左边有两个路径495,491 那么左边应该返回是一个Lis...
cd46cf08a580c418cc40a68bf9b32371fc69a803
<|skeleton|> class Solution: def sumNumbers(self, root: TreeNode) -> int: """从根节点到叶子节点的数字之和""" <|body_0|> def sumNumbers_(self, root: TreeNode) -> List[str]: """创建这个函数的原因是 # 输入:root = [4,9,0,5,1] 左边有两个路径495,491 那么左边应该返回是一个List [95,91], 然后再去加上根节点, 用List[str]的原因是中间有00的情况,转化为int会丢掉 :rtype...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def sumNumbers(self, root: TreeNode) -> int: """从根节点到叶子节点的数字之和""" res = self.sumNumbers_(root) res = [int(i) for i in res] return sum(res) def sumNumbers_(self, root: TreeNode) -> List[str]: """创建这个函数的原因是 # 输入:root = [4,9,0,5,1] 左边有两个路径495,491 那么左边应该返回是一个...
the_stack_v2_python_sparse
tree/129 sumNumbers.py
pangyouzhen/data-structure
train
0
160446a2f3e1d695680252c4458d31cf4d6f8173
[ "dp = [0] * (amount + 1)\ndp[0] = 1\nfor coin in coins:\n for i in range(coin, amount + 1):\n dp[i] += dp[i - coin]\nreturn dp[amount]", "dp = [0] * (amount + 1)\ndp[0] = 1\ncoins.sort()\nfor i in range(1, amount + 1):\n for coin in coins:\n if i - coin > -1:\n dp[i] += dp[i - coin]...
<|body_start_0|> dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for i in range(coin, amount + 1): dp[i] += dp[i - coin] return dp[amount] <|end_body_0|> <|body_start_1|> dp = [0] * (amount + 1) dp[0] = 1 coins.sort() for ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def change(self, amount, coins): """:type amount: int :type coins: List[int] :rtype: int""" <|body_0|> def change_Wrong(self, amount, coins): """:type amount: int :type coins: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_008321
2,543
no_license
[ { "docstring": ":type amount: int :type coins: List[int] :rtype: int", "name": "change", "signature": "def change(self, amount, coins)" }, { "docstring": ":type amount: int :type coins: List[int] :rtype: int", "name": "change_Wrong", "signature": "def change_Wrong(self, amount, coins)" ...
2
stack_v2_sparse_classes_30k_train_006870
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int - def change_Wrong(self, amount, coins): :type amount: int :type coins: List[int] :rtype: in...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int - def change_Wrong(self, amount, coins): :type amount: int :type coins: List[int] :rtype: in...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def change(self, amount, coins): """:type amount: int :type coins: List[int] :rtype: int""" <|body_0|> def change_Wrong(self, amount, coins): """:type amount: int :type coins: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def change(self, amount, coins): """:type amount: int :type coins: List[int] :rtype: int""" dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for i in range(coin, amount + 1): dp[i] += dp[i - coin] return dp[amount] def chan...
the_stack_v2_python_sparse
code518CoinChange2.py
cybelewang/leetcode-python
train
0
3024ef2c5cf655e8cdec3c7599e7fc864aa608fb
[ "self.set = set()\nself.table = collections.defaultdict(int)\nself.total = 0", "self.set.add(timestamp)\nself.table[timestamp] += 1\nself.total += 1\ntmp = min(self.set)\nwhile timestamp - tmp >= 300:\n self.total -= self.table[tmp]\n self.table[tmp] = 0\n self.set.remove(tmp)\n tmp = min(self.set)", ...
<|body_start_0|> self.set = set() self.table = collections.defaultdict(int) self.total = 0 <|end_body_0|> <|body_start_1|> self.set.add(timestamp) self.table[timestamp] += 1 self.total += 1 tmp = min(self.set) while timestamp - tmp >= 300: sel...
HitCounter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HitCounter: def __init__(self): """Initialize your data structure here.""" <|body_0|> def hit(self, timestamp: int) -> None: """Record a hit. @param timestamp - The current timestamp (in seconds granularity).""" <|body_1|> def getHits(self, timestamp: in...
stack_v2_sparse_classes_10k_train_008322
1,412
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).", "name": "hit", "signature": "def hit(self, timestamp: int) -> None" }, { ...
3
stack_v2_sparse_classes_30k_train_000579
Implement the Python class `HitCounter` described below. Class description: Implement the HitCounter class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari...
Implement the Python class `HitCounter` described below. Class description: Implement the HitCounter class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari...
54d0b3c237e0ffed8782915d6b75b7c6a0fe0de7
<|skeleton|> class HitCounter: def __init__(self): """Initialize your data structure here.""" <|body_0|> def hit(self, timestamp: int) -> None: """Record a hit. @param timestamp - The current timestamp (in seconds granularity).""" <|body_1|> def getHits(self, timestamp: in...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class HitCounter: def __init__(self): """Initialize your data structure here.""" self.set = set() self.table = collections.defaultdict(int) self.total = 0 def hit(self, timestamp: int) -> None: """Record a hit. @param timestamp - The current timestamp (in seconds granula...
the_stack_v2_python_sparse
0362_Design_Hit_Counter/try_2.py
novayo/LeetCode
train
8
f1b537b3865b0aa315b8685656e6862a20b14e85
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
The JobController provides methods to manage jobs.
JobControllerServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobControllerServicer: """The JobController provides methods to manage jobs.""" def SubmitJob(self, request, context): """Submits a job to a cluster.""" <|body_0|> def GetJob(self, request, context): """Gets the resource representation for a job in a project.""" ...
stack_v2_sparse_classes_10k_train_008323
6,938
permissive
[ { "docstring": "Submits a job to a cluster.", "name": "SubmitJob", "signature": "def SubmitJob(self, request, context)" }, { "docstring": "Gets the resource representation for a job in a project.", "name": "GetJob", "signature": "def GetJob(self, request, context)" }, { "docstrin...
6
stack_v2_sparse_classes_30k_train_002932
Implement the Python class `JobControllerServicer` described below. Class description: The JobController provides methods to manage jobs. Method signatures and docstrings: - def SubmitJob(self, request, context): Submits a job to a cluster. - def GetJob(self, request, context): Gets the resource representation for a ...
Implement the Python class `JobControllerServicer` described below. Class description: The JobController provides methods to manage jobs. Method signatures and docstrings: - def SubmitJob(self, request, context): Submits a job to a cluster. - def GetJob(self, request, context): Gets the resource representation for a ...
d897d56bce03d1fda98b79afb08264e51d46c421
<|skeleton|> class JobControllerServicer: """The JobController provides methods to manage jobs.""" def SubmitJob(self, request, context): """Submits a job to a cluster.""" <|body_0|> def GetJob(self, request, context): """Gets the resource representation for a job in a project.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class JobControllerServicer: """The JobController provides methods to manage jobs.""" def SubmitJob(self, request, context): """Submits a job to a cluster.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError...
the_stack_v2_python_sparse
dataproc/google/cloud/dataproc_v1/proto/jobs_pb2_grpc.py
tswast/google-cloud-python
train
1
936171128a03de9b1c3fb1b3ceefea5cd224a70e
[ "super(FastGradientMethod, self).__init__(model, sess, dtypestr, **kwargs)\nself.feedable_kwargs = ('eps', 'y', 'y_target', 'clip_min', 'clip_max')\nself.structural_kwargs = ['ord', 'sanity_checks']", "assert self.parse_params(**kwargs)\nlabels, _nb_classes = self.get_or_guess_labels(x, kwargs)\nreturn fgm(x, sel...
<|body_start_0|> super(FastGradientMethod, self).__init__(model, sess, dtypestr, **kwargs) self.feedable_kwargs = ('eps', 'y', 'y_target', 'clip_min', 'clip_max') self.structural_kwargs = ['ord', 'sanity_checks'] <|end_body_0|> <|body_start_1|> assert self.parse_params(**kwargs) ...
This attack was originally implemented by Goodfellow et al. (2014) with the infinity norm (and is known as the "Fast Gradient Sign Method"). This implementation extends the attack to other norms, and is therefore called the Fast Gradient Method. Paper link: https://arxiv.org/abs/1412.6572 :param model: cleverhans.model...
FastGradientMethod
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FastGradientMethod: """This attack was originally implemented by Goodfellow et al. (2014) with the infinity norm (and is known as the "Fast Gradient Sign Method"). This implementation extends the attack to other norms, and is therefore called the Fast Gradient Method. Paper link: https://arxiv.or...
stack_v2_sparse_classes_10k_train_008324
8,992
permissive
[ { "docstring": "Create a FastGradientMethod instance. Note: the model parameter should be an instance of the cleverhans.model.Model abstraction provided by CleverHans.", "name": "__init__", "signature": "def __init__(self, model, sess=None, dtypestr='float32', **kwargs)" }, { "docstring": "Retur...
3
stack_v2_sparse_classes_30k_train_002458
Implement the Python class `FastGradientMethod` described below. Class description: This attack was originally implemented by Goodfellow et al. (2014) with the infinity norm (and is known as the "Fast Gradient Sign Method"). This implementation extends the attack to other norms, and is therefore called the Fast Gradie...
Implement the Python class `FastGradientMethod` described below. Class description: This attack was originally implemented by Goodfellow et al. (2014) with the infinity norm (and is known as the "Fast Gradient Sign Method"). This implementation extends the attack to other norms, and is therefore called the Fast Gradie...
bbe96757fa7daded0090b1d9a26b9c90d7d87c61
<|skeleton|> class FastGradientMethod: """This attack was originally implemented by Goodfellow et al. (2014) with the infinity norm (and is known as the "Fast Gradient Sign Method"). This implementation extends the attack to other norms, and is therefore called the Fast Gradient Method. Paper link: https://arxiv.or...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FastGradientMethod: """This attack was originally implemented by Goodfellow et al. (2014) with the infinity norm (and is known as the "Fast Gradient Sign Method"). This implementation extends the attack to other norms, and is therefore called the Fast Gradient Method. Paper link: https://arxiv.org/abs/1412.65...
the_stack_v2_python_sparse
cleverhans/attacks/fast_gradient_method.py
yogeshbalaji/InvGAN
train
17
0ca6fc1f8c555fdb1a279957f42bc8a9306011c9
[ "for r in range(len(A)):\n for c in range(len(A[0])):\n A[r][c] ^= 1\nfor r in range(len(A)):\n A[r].reverse()\nreturn A", "reverse = []\nfor i in A:\n temp = []\n for j in reversed(i):\n if j == 0:\n temp.append(1)\n else:\n temp.append(0)\n reverse.appen...
<|body_start_0|> for r in range(len(A)): for c in range(len(A[0])): A[r][c] ^= 1 for r in range(len(A)): A[r].reverse() return A <|end_body_0|> <|body_start_1|> reverse = [] for i in A: temp = [] for j in reversed(i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def flipAndInvertImage(self, A): """:type A: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def flipAndInvertImage(self, A): """:type A: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> for r i...
stack_v2_sparse_classes_10k_train_008325
875
no_license
[ { "docstring": ":type A: List[List[int]] :rtype: List[List[int]]", "name": "flipAndInvertImage", "signature": "def flipAndInvertImage(self, A)" }, { "docstring": ":type A: List[List[int]] :rtype: List[List[int]]", "name": "flipAndInvertImage", "signature": "def flipAndInvertImage(self, A...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flipAndInvertImage(self, A): :type A: List[List[int]] :rtype: List[List[int]] - def flipAndInvertImage(self, A): :type A: List[List[int]] :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flipAndInvertImage(self, A): :type A: List[List[int]] :rtype: List[List[int]] - def flipAndInvertImage(self, A): :type A: List[List[int]] :rtype: List[List[int]] <|skeleton|...
c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0
<|skeleton|> class Solution: def flipAndInvertImage(self, A): """:type A: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def flipAndInvertImage(self, A): """:type A: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def flipAndInvertImage(self, A): """:type A: List[List[int]] :rtype: List[List[int]]""" for r in range(len(A)): for c in range(len(A[0])): A[r][c] ^= 1 for r in range(len(A)): A[r].reverse() return A def flipAndInvertImage(...
the_stack_v2_python_sparse
code/832#Flipping an Image.py
EachenKuang/LeetCode
train
28
4fc7a32c0888f1e407ae4a4706eaaf40051e0623
[ "super(Transpose1dLayer, self).__init__()\nself.upsample = upsample\nreflection_pad = nn.ConstantPad1d(kernel_size // 2, value=0)\nconv1d = nn.Conv1d(in_channels, out_channels, kernel_size, stride)\nconv1d.weight.data.normal_(0.0, 0.02)\nConv1dTrans = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, strid...
<|body_start_0|> super(Transpose1dLayer, self).__init__() self.upsample = upsample reflection_pad = nn.ConstantPad1d(kernel_size // 2, value=0) conv1d = nn.Conv1d(in_channels, out_channels, kernel_size, stride) conv1d.weight.data.normal_(0.0, 0.02) Conv1dTrans = nn.ConvTr...
Package of all 1d Convolution Transpose Layer
Transpose1dLayer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Transpose1dLayer: """Package of all 1d Convolution Transpose Layer""" def __init__(self, in_channels, out_channels, kernel_size, stride, padding=11, upsample=None, output_padding=1, use_batch_norm=False) -> NoReturn: """Initialize 1d Convolution Transpose Layer package -*-*-*Convolut...
stack_v2_sparse_classes_10k_train_008326
5,819
permissive
[ { "docstring": "Initialize 1d Convolution Transpose Layer package -*-*-*Convolution Transpose summary*-*-*- There isn't a direct back-process to convolution like deconvolution but there is a technique to retrieve most of the information back called \"Convolution Transpose\". Apply convolution with bigger kernel...
2
stack_v2_sparse_classes_30k_train_005963
Implement the Python class `Transpose1dLayer` described below. Class description: Package of all 1d Convolution Transpose Layer Method signatures and docstrings: - def __init__(self, in_channels, out_channels, kernel_size, stride, padding=11, upsample=None, output_padding=1, use_batch_norm=False) -> NoReturn: Initial...
Implement the Python class `Transpose1dLayer` described below. Class description: Package of all 1d Convolution Transpose Layer Method signatures and docstrings: - def __init__(self, in_channels, out_channels, kernel_size, stride, padding=11, upsample=None, output_padding=1, use_batch_norm=False) -> NoReturn: Initial...
4eea5339c8ad0aae2861b8f7cc8ea88bdd0852ed
<|skeleton|> class Transpose1dLayer: """Package of all 1d Convolution Transpose Layer""" def __init__(self, in_channels, out_channels, kernel_size, stride, padding=11, upsample=None, output_padding=1, use_batch_norm=False) -> NoReturn: """Initialize 1d Convolution Transpose Layer package -*-*-*Convolut...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Transpose1dLayer: """Package of all 1d Convolution Transpose Layer""" def __init__(self, in_channels, out_channels, kernel_size, stride, padding=11, upsample=None, output_padding=1, use_batch_norm=False) -> NoReturn: """Initialize 1d Convolution Transpose Layer package -*-*-*Convolution Transpose...
the_stack_v2_python_sparse
not_functional/models/architectures/layers/BaseLayers.py
develooper1994/MasterThesis
train
6
73dc5a7d0ef009b7289a3b07bea55fc9b7055afd
[ "super(Embedding, self).__init__()\nself.dropout = dropout\nwith self.init_scope():\n self.embed = L.EmbedID(num_classes, embedding_dim, ignore_label=ignore_index)\n if use_cuda:\n self.embed.to_gpu()", "y = self.embed(y)\nif self.dropout > 0:\n y = F.dropout(y, ratio=self.dropout)\nreturn y" ]
<|body_start_0|> super(Embedding, self).__init__() self.dropout = dropout with self.init_scope(): self.embed = L.EmbedID(num_classes, embedding_dim, ignore_label=ignore_index) if use_cuda: self.embed.to_gpu() <|end_body_0|> <|body_start_1|> y = se...
Embedding
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Embedding: def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): """Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target space...
stack_v2_sparse_classes_10k_train_008327
5,435
no_license
[ { "docstring": "Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (float, optional): the probability to drop nodes of the embedding ignore_index (int, optional): use_cuda...
2
stack_v2_sparse_classes_30k_val_000355
Implement the Python class `Embedding` described below. Class description: Implement the Embedding class. Method signatures and docstrings: - def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (incl...
Implement the Python class `Embedding` described below. Class description: Implement the Embedding class. Method signatures and docstrings: - def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (incl...
b6b60a338d65bb369d0034f423feb09db10db8b7
<|skeleton|> class Embedding: def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): """Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target space...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Embedding: def __init__(self, num_classes, embedding_dim, dropout=0, ignore_index=-1, use_cuda=False): """Embedding layer. Args: num_classes (int): the number of nodes in softmax layer (including <SOS> and <EOS> classes) embedding_dim (int): the dimension of the embedding in target spaces dropout (flo...
the_stack_v2_python_sparse
models/chainer/linear.py
carolinebear/pytorch_end2end_speech_recognition
train
0
e586d4fa8b815942078d576ab2fc68423d8082c3
[ "if safe:\n endpoint = SAFE_BOORU_ENDPOINT\n provider = SAFE_BOORU_PROVIDER\n banned_tags = SAFE_TAGS_BANNED\nelse:\n endpoint = NSFW_BOORU_ENDPOINT\n provider = NSFW_BOORU_PROVIDER\n banned_tags = NSFW_TAGS_BANNED\nhandler = ImageHandlerBooru(provider, endpoint, None, banned_tags, requested_tags,...
<|body_start_0|> if safe: endpoint = SAFE_BOORU_ENDPOINT provider = SAFE_BOORU_PROVIDER banned_tags = SAFE_TAGS_BANNED else: endpoint = NSFW_BOORU_ENDPOINT provider = NSFW_BOORU_PROVIDER banned_tags = NSFW_TAGS_BANNED handle...
Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.
ImageCache
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageCache: """Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.""" def __new_...
stack_v2_sparse_classes_10k_train_008328
9,784
no_license
[ { "docstring": "Creates a new image cache for booru commands. Parameters ---------- requested_tags : `set` of `str` The requested tags. safe : `bool` Whether we want safe images.", "name": "__new__", "signature": "def __new__(cls, requested_tags, safe)" }, { "docstring": "Invokes the booru cache...
4
null
Implement the Python class `ImageCache` described below. Class description: Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the ...
Implement the Python class `ImageCache` described below. Class description: Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the ...
74f92b598e86606ea3a269311316cddd84a5215f
<|skeleton|> class ImageCache: """Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.""" def __new_...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ImageCache: """Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.""" def __new__(cls, reques...
the_stack_v2_python_sparse
koishi/plugins/image_handling_commands/booru/booru.py
HuyaneMatsu/Koishi
train
17
a97d04663c98faf08f6ac2c7cf5c7e7db5b5f4a0
[ "smach.State.__init__(self, outcomes=['succeeded', 'failed'])\nself._robot = robot\nself._srv = rospy.ServiceProxy(robot.robot_name + '/ed/fit_entity_in_image', FitEntityInImage)\nself._entity_str = entity_str", "self._robot.head.reset()\nself._robot.head.wait_for_motion_done(5.0)\nrospy.sleep(rospy.Duration(1.0)...
<|body_start_0|> smach.State.__init__(self, outcomes=['succeeded', 'failed']) self._robot = robot self._srv = rospy.ServiceProxy(robot.robot_name + '/ed/fit_entity_in_image', FitEntityInImage) self._entity_str = entity_str <|end_body_0|> <|body_start_1|> self._robot.head.reset()...
Fits an entity
FitEntity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FitEntity: """Fits an entity""" def __init__(self, robot, entity_str): """Constructor :param robot: robot object :param entity_str: string with the entity type to fit""" <|body_0|> def execute(self, userdata=None): """Executes the state""" <|body_1|> <|e...
stack_v2_sparse_classes_10k_train_008329
1,370
no_license
[ { "docstring": "Constructor :param robot: robot object :param entity_str: string with the entity type to fit", "name": "__init__", "signature": "def __init__(self, robot, entity_str)" }, { "docstring": "Executes the state", "name": "execute", "signature": "def execute(self, userdata=None...
2
stack_v2_sparse_classes_30k_train_004006
Implement the Python class `FitEntity` described below. Class description: Fits an entity Method signatures and docstrings: - def __init__(self, robot, entity_str): Constructor :param robot: robot object :param entity_str: string with the entity type to fit - def execute(self, userdata=None): Executes the state
Implement the Python class `FitEntity` described below. Class description: Fits an entity Method signatures and docstrings: - def __init__(self, robot, entity_str): Constructor :param robot: robot object :param entity_str: string with the entity type to fit - def execute(self, userdata=None): Executes the state <|sk...
d4705c553f4711be792b37730658b481cc05eca1
<|skeleton|> class FitEntity: """Fits an entity""" def __init__(self, robot, entity_str): """Constructor :param robot: robot object :param entity_str: string with the entity type to fit""" <|body_0|> def execute(self, userdata=None): """Executes the state""" <|body_1|> <|e...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FitEntity: """Fits an entity""" def __init__(self, robot, entity_str): """Constructor :param robot: robot object :param entity_str: string with the entity type to fit""" smach.State.__init__(self, outcomes=['succeeded', 'failed']) self._robot = robot self._srv = rospy.Serv...
the_stack_v2_python_sparse
challenge_storing_groceries/src/challenge_storing_groceries/fit_entity.py
SamAlexandrov/tue_robocup
train
0
6f7b9a779abd8fe5f117f7610525cc19a0a63d52
[ "super().__init__()\nself._initialize_arguments(args)\nself.temperature = args.temperature\nself.adj_type = args.adj_type\nif args.adj_type == 'fixed':\n self.adj_mx = adj_mx.to(device)\nelif args.adj_type == 'empty':\n self.adj_mx = torch.zeros(size=(args.num_nodes, args.num_nodes, args.num_relation_types), ...
<|body_start_0|> super().__init__() self._initialize_arguments(args) self.temperature = args.temperature self.adj_type = args.adj_type if args.adj_type == 'fixed': self.adj_mx = adj_mx.to(device) elif args.adj_type == 'empty': self.adj_mx = torch.z...
Implements the GATRNN model.
GATRNN
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GATRNN: """Implements the GATRNN model.""" def __init__(self, adj_mx, args): """Instantiates the GATRNN encoder model. Args: adj_mx: adjacency matrix, with shape (self.num_nodes, self.num_nodes). args: python argparse.ArgumentParser class, we only use model-related arguments here."""...
stack_v2_sparse_classes_10k_train_008330
13,550
permissive
[ { "docstring": "Instantiates the GATRNN encoder model. Args: adj_mx: adjacency matrix, with shape (self.num_nodes, self.num_nodes). args: python argparse.ArgumentParser class, we only use model-related arguments here.", "name": "__init__", "signature": "def __init__(self, adj_mx, args)" }, { "do...
4
stack_v2_sparse_classes_30k_train_000201
Implement the Python class `GATRNN` described below. Class description: Implements the GATRNN model. Method signatures and docstrings: - def __init__(self, adj_mx, args): Instantiates the GATRNN encoder model. Args: adj_mx: adjacency matrix, with shape (self.num_nodes, self.num_nodes). args: python argparse.ArgumentP...
Implement the Python class `GATRNN` described below. Class description: Implements the GATRNN model. Method signatures and docstrings: - def __init__(self, adj_mx, args): Instantiates the GATRNN encoder model. Args: adj_mx: adjacency matrix, with shape (self.num_nodes, self.num_nodes). args: python argparse.ArgumentP...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class GATRNN: """Implements the GATRNN model.""" def __init__(self, adj_mx, args): """Instantiates the GATRNN encoder model. Args: adj_mx: adjacency matrix, with shape (self.num_nodes, self.num_nodes). args: python argparse.ArgumentParser class, we only use model-related arguments here."""...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GATRNN: """Implements the GATRNN model.""" def __init__(self, adj_mx, args): """Instantiates the GATRNN encoder model. Args: adj_mx: adjacency matrix, with shape (self.num_nodes, self.num_nodes). args: python argparse.ArgumentParser class, we only use model-related arguments here.""" supe...
the_stack_v2_python_sparse
editable_graph_temporal/model/gat_model.py
Jimmy-INL/google-research
train
1
feebcb9cfc57c504dbc296f2677cae605537abbc
[ "super().__init__()\nself.label = label\nself.tag_set = tag_set\nself.setText(str(label))\nfont = QFont('SansSerif', 9)\nfont.setBold(False)\nself.setFont(font)\nfont_metric = QFontMetrics(font)\nwidth = font_metric.width(str(label)) + 20\nif tooltip_lbl is not None:\n self.setToolTip(str(tooltip_lbl))\n self...
<|body_start_0|> super().__init__() self.label = label self.tag_set = tag_set self.setText(str(label)) font = QFont('SansSerif', 9) font.setBold(False) self.setFont(font) font_metric = QFontMetrics(font) width = font_metric.width(str(label)) + 20 ...
QTagButton
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QTagButton: def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): """Formats the tag button :param label: String of tag. :param tag_set: set of tag strings""" <|body_0|> def mousePressEvent(self, event): """Overides existing mousepressevent. If a right...
stack_v2_sparse_classes_10k_train_008331
1,526
no_license
[ { "docstring": "Formats the tag button :param label: String of tag. :param tag_set: set of tag strings", "name": "__init__", "signature": "def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None)" }, { "docstring": "Overides existing mousepressevent. If a right click occurs the tag is...
2
stack_v2_sparse_classes_30k_train_000721
Implement the Python class `QTagButton` described below. Class description: Implement the QTagButton class. Method signatures and docstrings: - def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): Formats the tag button :param label: String of tag. :param tag_set: set of tag strings - def mousePressEv...
Implement the Python class `QTagButton` described below. Class description: Implement the QTagButton class. Method signatures and docstrings: - def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): Formats the tag button :param label: String of tag. :param tag_set: set of tag strings - def mousePressEv...
ab04ca1c67839a8269f5275323907c5bc7f9af46
<|skeleton|> class QTagButton: def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): """Formats the tag button :param label: String of tag. :param tag_set: set of tag strings""" <|body_0|> def mousePressEvent(self, event): """Overides existing mousepressevent. If a right...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class QTagButton: def __init__(self, label: str, tag_set: set, tooltip_lbl: str=None): """Formats the tag button :param label: String of tag. :param tag_set: set of tag strings""" super().__init__() self.label = label self.tag_set = tag_set self.setText(str(label)) fo...
the_stack_v2_python_sparse
custom_widgets/tag_button.py
tobias-gill/Figshare_desktop
train
0
e932213877e11870036b0aeda1d2e19c63bbfdf0
[ "res = 0\n\ndef dfs(node, sumVal):\n nonlocal res\n if not node:\n return\n sumVal = sumVal * 10 + node.val\n if not node.left and (not node.right):\n res += sumVal\n dfs(node.left, sumVal)\n dfs(node.right, sumVal)\ndfs(root, 0)\nreturn res", "if not root:\n return False\n\ndef...
<|body_start_0|> res = 0 def dfs(node, sumVal): nonlocal res if not node: return sumVal = sumVal * 10 + node.val if not node.left and (not node.right): res += sumVal dfs(node.left, sumVal) dfs(node.r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sumNumbers(self, root): """https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int""" <|body_0|> def hasPathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: bool""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_10k_train_008332
1,662
no_license
[ { "docstring": "https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int", "name": "sumNumbers", "signature": "def sumNumbers(self, root)" }, { "docstring": ":type root: TreeNode :type sum: int :rtype: bool", "name": "hasPathSum", "signature": "def hasP...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sumNumbers(self, root): https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int - def hasPathSum(self, root, sum): :type root: TreeNode :t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sumNumbers(self, root): https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int - def hasPathSum(self, root, sum): :type root: TreeNode :t...
63ac5a0921835b1e9d65f71e1346bbb7d66dad9b
<|skeleton|> class Solution: def sumNumbers(self, root): """https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int""" <|body_0|> def hasPathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: bool""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def sumNumbers(self, root): """https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int""" res = 0 def dfs(node, sumVal): nonlocal res if not node: return sumVal = sumVal * 10 + node.val ...
the_stack_v2_python_sparse
LeetCode/中等/树/129. 求根到叶子节点数字之和.py
homezzm/leetcode
train
1
85b64b8c19b12e6c1aad5839e39e5e9348d634ea
[ "INT_MAX = 2 ** 31 - 1\nm = len(matrix)\nif m < 1:\n return matrix\nn = len(matrix[0])\nfor i in range(m):\n for j in range(n):\n if matrix[i][j] != 0:\n matrix[i][j] = INT_MAX - 1\nfor i in range(m):\n for j in range(n):\n if matrix[i][j] != 0:\n if i > 0:\n ...
<|body_start_0|> INT_MAX = 2 ** 31 - 1 m = len(matrix) if m < 1: return matrix n = len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] != 0: matrix[i][j] = INT_MAX - 1 for i in range(m): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def updateMatrix(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def updateMatrix2(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_008333
3,369
no_license
[ { "docstring": ":type matrix: List[List[int]] :rtype: List[List[int]]", "name": "updateMatrix", "signature": "def updateMatrix(self, matrix)" }, { "docstring": ":type matrix: List[List[int]] :rtype: List[List[int]]", "name": "updateMatrix2", "signature": "def updateMatrix2(self, matrix)"...
2
stack_v2_sparse_classes_30k_train_003742
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def updateMatrix(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]] - def updateMatrix2(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def updateMatrix(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]] - def updateMatrix2(self, matrix): :type matrix: List[List[int]] :rtype: List[List[int]] <|...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def updateMatrix(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]]""" <|body_0|> def updateMatrix2(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def updateMatrix(self, matrix): """:type matrix: List[List[int]] :rtype: List[List[int]]""" INT_MAX = 2 ** 31 - 1 m = len(matrix) if m < 1: return matrix n = len(matrix[0]) for i in range(m): for j in range(n): i...
the_stack_v2_python_sparse
code542_01Matrix.py
cybelewang/leetcode-python
train
0
bca6a453a41ba655dafcabc99bc1a5d9f2101500
[ "self.logger = logging.getLogger(__name__)\nself.enabled = enabled\nself.rank = rank\nself.profiler_output_tmp_dir = None\nself.profiler = None", "if self.enabled:\n self.profiler_output_tmp_dir = tempfile.TemporaryDirectory()\n self.logger.info(f'Starting profiler (enabled=True) with tmp dir {self.profiler...
<|body_start_0|> self.logger = logging.getLogger(__name__) self.enabled = enabled self.rank = rank self.profiler_output_tmp_dir = None self.profiler = None <|end_body_0|> <|body_start_1|> if self.enabled: self.profiler_output_tmp_dir = tempfile.TemporaryDirec...
This class handles the initialization and setup of PyTorch profiler
PyTorchProfilerHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyTorchProfilerHandler: """This class handles the initialization and setup of PyTorch profiler""" def __init__(self, enabled=False, rank=None): """Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow arti...
stack_v2_sparse_classes_10k_train_008334
6,804
permissive
[ { "docstring": "Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow artifacts rank (int): rank of the current process/node", "name": "__init__", "signature": "def __init__(self, enabled=False, rank=None)" }, { "docs...
3
null
Implement the Python class `PyTorchProfilerHandler` described below. Class description: This class handles the initialization and setup of PyTorch profiler Method signatures and docstrings: - def __init__(self, enabled=False, rank=None): Constructor. Args: enabled (bool): is profiling enabled? export_format (str): ge...
Implement the Python class `PyTorchProfilerHandler` described below. Class description: This class handles the initialization and setup of PyTorch profiler Method signatures and docstrings: - def __init__(self, enabled=False, rank=None): Constructor. Args: enabled (bool): is profiling enabled? export_format (str): ge...
e5f7b247d4753f115a8f7da30cbe25294f71f9d7
<|skeleton|> class PyTorchProfilerHandler: """This class handles the initialization and setup of PyTorch profiler""" def __init__(self, enabled=False, rank=None): """Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow arti...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PyTorchProfilerHandler: """This class handles the initialization and setup of PyTorch profiler""" def __init__(self, enabled=False, rank=None): """Constructor. Args: enabled (bool): is profiling enabled? export_format (str): generate 'markdown' or 'tensorboard' profile in mlflow artifacts rank (i...
the_stack_v2_python_sparse
tutorials/e2e-distributed-pytorch-image/src/pytorch_dl_train/profiling.py
Azure/azureml-examples
train
1,219
6cecbce301a792eb28d87a5e8ac57cac14f9b3ec
[ "if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))", "def top_down(root, depth):\n if not root:\n return depth\n return max(top_down(root.left, depth + 1), top_down(root.right, depth + 1))\nreturn top_down(root, 0)", "if not root:\n return 0\nwhite, ...
<|body_start_0|> if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) <|end_body_0|> <|body_start_1|> def top_down(root, depth): if not root: return depth return max(top_down(root.left, depth + 1), top_down...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxDepth(self, root: TreeNode) -> int: """递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层""" <|body_0|> def maxDepth_1(self, root: TreeNode) -> int: """递归法(自顶向下)""" <|body_1|> def maxDepth_2(self, root: TreeNode) -> int: """层次遍历...
stack_v2_sparse_classes_10k_train_008335
1,701
no_license
[ { "docstring": "递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层", "name": "maxDepth", "signature": "def maxDepth(self, root: TreeNode) -> int" }, { "docstring": "递归法(自顶向下)", "name": "maxDepth_1", "signature": "def maxDepth_1(self, root: TreeNode) -> int" }, { "docstring": "层次...
3
stack_v2_sparse_classes_30k_train_001685
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root: TreeNode) -> int: 递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层 - def maxDepth_1(self, root: TreeNode) -> int: 递归法(自顶向下) - def maxDepth_2(self, roo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root: TreeNode) -> int: 递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层 - def maxDepth_1(self, root: TreeNode) -> int: 递归法(自顶向下) - def maxDepth_2(self, roo...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def maxDepth(self, root: TreeNode) -> int: """递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层""" <|body_0|> def maxDepth_1(self, root: TreeNode) -> int: """递归法(自顶向下)""" <|body_1|> def maxDepth_2(self, root: TreeNode) -> int: """层次遍历...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def maxDepth(self, root: TreeNode) -> int: """递归法(自底向上) 分别计算出左子树的深度,右子树的深度,再计算其最大值 最后+1,是加上根节点这一层""" if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) def maxDepth_1(self, root: TreeNode) -> int: """递归法(自顶向下)"""...
the_stack_v2_python_sparse
algorithm/leetcode/tree/07-二叉树的最大深度.py
lxconfig/UbuntuCode_bak
train
0
1b6f047e9ae92ee4b46bf17206fa5402cbab9305
[ "self.signup('healer')\nresponse = self.rest_client.get(reverse('provider_setup_intro'))\nself.assertEqual(response.status_code, 200)\nresponse = self.rest_client.get(reverse('notes'))\nself.assertEqual(response.status_code, 302)", "self.signup()\nresponse = self.rest_client.get(reverse('provider_setup_intro'))\n...
<|body_start_0|> self.signup('healer') response = self.rest_client.get(reverse('provider_setup_intro')) self.assertEqual(response.status_code, 200) response = self.rest_client.get(reverse('notes')) self.assertEqual(response.status_code, 302) <|end_body_0|> <|body_start_1|> ...
SignupAccessTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignupAccessTest: def test_healer_not_confirmed(self): """Only setup should be available for healers without confirmed emails on signup.""" <|body_0|> def test_client_not_confirmed(self): """Clients should not login on signup if email is not confirmed.""" <|b...
stack_v2_sparse_classes_10k_train_008336
38,593
no_license
[ { "docstring": "Only setup should be available for healers without confirmed emails on signup.", "name": "test_healer_not_confirmed", "signature": "def test_healer_not_confirmed(self)" }, { "docstring": "Clients should not login on signup if email is not confirmed.", "name": "test_client_not...
2
stack_v2_sparse_classes_30k_train_004179
Implement the Python class `SignupAccessTest` described below. Class description: Implement the SignupAccessTest class. Method signatures and docstrings: - def test_healer_not_confirmed(self): Only setup should be available for healers without confirmed emails on signup. - def test_client_not_confirmed(self): Clients...
Implement the Python class `SignupAccessTest` described below. Class description: Implement the SignupAccessTest class. Method signatures and docstrings: - def test_healer_not_confirmed(self): Only setup should be available for healers without confirmed emails on signup. - def test_client_not_confirmed(self): Clients...
681ef09e4044879840f7f0c8bccc836c3cffec3c
<|skeleton|> class SignupAccessTest: def test_healer_not_confirmed(self): """Only setup should be available for healers without confirmed emails on signup.""" <|body_0|> def test_client_not_confirmed(self): """Clients should not login on signup if email is not confirmed.""" <|b...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SignupAccessTest: def test_healer_not_confirmed(self): """Only setup should be available for healers without confirmed emails on signup.""" self.signup('healer') response = self.rest_client.get(reverse('provider_setup_intro')) self.assertEqual(response.status_code, 200) ...
the_stack_v2_python_sparse
apps/account_hs/tests.py
RumorIO/healersource
train
0
295dfed522f472e30dac1cc6219bac27a9ad0ac8
[ "b = torch.div(f, 1000.0)\nb = torch.pow(b, 2.0) * 1.4\nb = torch.pow(b + 1.0, 0.69)\nreturn b * 75.0 + 25.0", "f = torch.div(x - 25.0, 75.0)\nf = torch.pow(f, 1.0 / 0.69)\nf = torch.div(f - 1.0, 1.4)\nf = torch.pow(f, 0.5)\nreturn f * 1000.0", "assert check_argument_types()\nmin_center_frequency = torch.tensor...
<|body_start_0|> b = torch.div(f, 1000.0) b = torch.pow(b, 2.0) * 1.4 b = torch.pow(b + 1.0, 0.69) return b * 75.0 + 25.0 <|end_body_0|> <|body_start_1|> f = torch.div(x - 25.0, 75.0) f = torch.pow(f, 1.0 / 0.69) f = torch.div(f - 1.0, 1.4) f = torch.pow(...
Bark frequency scale. Has wider bandwidths at lower frequencies, see: Critical bandwidth: BARK Zwicker and Terhardt, 1980
BarkScale
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BarkScale: """Bark frequency scale. Has wider bandwidths at lower frequencies, see: Critical bandwidth: BARK Zwicker and Terhardt, 1980""" def convert(f): """Convert Hz to Bark.""" <|body_0|> def invert(x): """Convert Bark to Hz.""" <|body_1|> def ba...
stack_v2_sparse_classes_10k_train_008337
9,034
permissive
[ { "docstring": "Convert Hz to Bark.", "name": "convert", "signature": "def convert(f)" }, { "docstring": "Convert Bark to Hz.", "name": "invert", "signature": "def invert(x)" }, { "docstring": "Obtain initialization values for the Bark scale. Args: channels: Number of channels. f...
3
stack_v2_sparse_classes_30k_train_002577
Implement the Python class `BarkScale` described below. Class description: Bark frequency scale. Has wider bandwidths at lower frequencies, see: Critical bandwidth: BARK Zwicker and Terhardt, 1980 Method signatures and docstrings: - def convert(f): Convert Hz to Bark. - def invert(x): Convert Bark to Hz. - def bank(c...
Implement the Python class `BarkScale` described below. Class description: Bark frequency scale. Has wider bandwidths at lower frequencies, see: Critical bandwidth: BARK Zwicker and Terhardt, 1980 Method signatures and docstrings: - def convert(f): Convert Hz to Bark. - def invert(x): Convert Bark to Hz. - def bank(c...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class BarkScale: """Bark frequency scale. Has wider bandwidths at lower frequencies, see: Critical bandwidth: BARK Zwicker and Terhardt, 1980""" def convert(f): """Convert Hz to Bark.""" <|body_0|> def invert(x): """Convert Bark to Hz.""" <|body_1|> def ba...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BarkScale: """Bark frequency scale. Has wider bandwidths at lower frequencies, see: Critical bandwidth: BARK Zwicker and Terhardt, 1980""" def convert(f): """Convert Hz to Bark.""" b = torch.div(f, 1000.0) b = torch.pow(b, 2.0) * 1.4 b = torch.pow(b + 1.0, 0.69) re...
the_stack_v2_python_sparse
espnet2/layers/sinc_conv.py
espnet/espnet
train
7,242
a141ec628b5b6d9fcd3d9af3bf0f485ea2e7d2d6
[ "if not nums:\n return nums\nred = 0\nwhite = 0\nblue = 0\nindex = 0\nfor item in nums:\n if item == 0:\n red += 1\n elif item == 1:\n white += 1\n else:\n blue += 1\nwhile red > 0:\n nums[index] = 0\n index += 1\n red -= 1\nwhile white > 0:\n nums[index] = 1\n index ...
<|body_start_0|> if not nums: return nums red = 0 white = 0 blue = 0 index = 0 for item in nums: if item == 0: red += 1 elif item == 1: white += 1 else: blue += 1 while...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sortColors(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" <|body_0|> def sortColors2(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""...
stack_v2_sparse_classes_10k_train_008338
2,355
no_license
[ { "docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.", "name": "sortColors", "signature": "def sortColors(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.", "name": "so...
2
stack_v2_sparse_classes_30k_train_006024
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. - def sortColors2(self, nums): :type nums: List[int] :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. - def sortColors2(self, nums): :type nums: List[int] :rtype: ...
2866df7587ee867a958a2b4fc02345bc3ef56999
<|skeleton|> class Solution: def sortColors(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" <|body_0|> def sortColors2(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def sortColors(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" if not nums: return nums red = 0 white = 0 blue = 0 index = 0 for item in nums: if item == 0: ...
the_stack_v2_python_sparse
中级算法/sortColors.py
OrangeJessie/Fighting_Leetcode
train
1
09222643100a3693261a4aa64611fff7bd981946
[ "try:\n return Post.objects.get(id=id)\nexcept Post.DoesNotExist:\n raise Http404", "postObject = self.get_object(id)\nresponse = self.serializer_class(postObject)\nreturn Response(response.data)", "posts = self.get_object(id)\nposts.delete()\nreturn Response(status=status.HTTP_204_NO_CONTENT)" ]
<|body_start_0|> try: return Post.objects.get(id=id) except Post.DoesNotExist: raise Http404 <|end_body_0|> <|body_start_1|> postObject = self.get_object(id) response = self.serializer_class(postObject) return Response(response.data) <|end_body_1|> <|bod...
This class is an API for geting newsfeed posts information.
PostViewDetail
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PostViewDetail: """This class is an API for geting newsfeed posts information.""" def get_object(self, id): """Get post by id. Args: id: id of post. Return: post object.""" <|body_0|> def get(self, request, id=None, format=None): """Get single post object by id. ...
stack_v2_sparse_classes_10k_train_008339
17,464
no_license
[ { "docstring": "Get post by id. Args: id: id of post. Return: post object.", "name": "get_object", "signature": "def get_object(self, id)" }, { "docstring": "Get single post object by id. Args: request: Django Rest Framework request object. id: id of post. format: pattern for Web APIs. Return: S...
3
stack_v2_sparse_classes_30k_train_002734
Implement the Python class `PostViewDetail` described below. Class description: This class is an API for geting newsfeed posts information. Method signatures and docstrings: - def get_object(self, id): Get post by id. Args: id: id of post. Return: post object. - def get(self, request, id=None, format=None): Get singl...
Implement the Python class `PostViewDetail` described below. Class description: This class is an API for geting newsfeed posts information. Method signatures and docstrings: - def get_object(self, id): Get post by id. Args: id: id of post. Return: post object. - def get(self, request, id=None, format=None): Get singl...
1d01b8133669208cdd35d4aa61a41521ecd52720
<|skeleton|> class PostViewDetail: """This class is an API for geting newsfeed posts information.""" def get_object(self, id): """Get post by id. Args: id: id of post. Return: post object.""" <|body_0|> def get(self, request, id=None, format=None): """Get single post object by id. ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PostViewDetail: """This class is an API for geting newsfeed posts information.""" def get_object(self, id): """Get post by id. Args: id: id of post. Return: post object.""" try: return Post.objects.get(id=id) except Post.DoesNotExist: raise Http404 def...
the_stack_v2_python_sparse
newsfeed/views.py
whsatku/social
train
10
3a170742570a1bdd95daf55499a98b63a475e575
[ "if self._attrMap is not None:\n for key in self.__dict__.keys():\n if key[0] != '_':\n msg = 'Unexpected attribute %s found in %s' % (key, self)\n assert key in self._attrMap, msg\n for attr, metavalue in self._attrMap.items():\n msg = 'Missing attribute %s from %s' % (att...
<|body_start_0|> if self._attrMap is not None: for key in self.__dict__.keys(): if key[0] != '_': msg = 'Unexpected attribute %s found in %s' % (key, self) assert key in self._attrMap, msg for attr, metavalue in self._attrMap.items(...
Base for property holders
PropHolder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PropHolder: """Base for property holders""" def verify(self): """If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds ...
stack_v2_sparse_classes_10k_train_008340
18,700
permissive
[ { "docstring": "If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds or raises an informative exception.", "name": "verify", "signature": ...
4
null
Implement the Python class `PropHolder` described below. Class description: Base for property holders Method signatures and docstrings: - def verify(self): If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) ...
Implement the Python class `PropHolder` described below. Class description: Base for property holders Method signatures and docstrings: - def verify(self): If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) ...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class PropHolder: """Base for property holders""" def verify(self): """If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PropHolder: """Base for property holders""" def verify(self): """If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds or raises an ...
the_stack_v2_python_sparse
Pdf_docx_pptx_xlsx_epub_png/source/reportlab/graphics/widgetbase.py
ryfeus/lambda-packs
train
1,283
861b7761560f515ea622702bf5094957313ced07
[ "self.index = 0\nself.twitters = dict()\nself.followers = dict()", "if userId in self.twitters:\n self.twitters[userId].append((tweetId, self.index))\nelse:\n self.twitters.setdefault(userId, [(tweetId, self.index)])\nself.index += 1", "tweets = []\nif userId in self.twitters:\n tweets += self.twitters...
<|body_start_0|> self.index = 0 self.twitters = dict() self.followers = dict() <|end_body_0|> <|body_start_1|> if userId in self.twitters: self.twitters[userId].append((tweetId, self.index)) else: self.twitters.setdefault(userId, [(tweetId, self.index)]) ...
Twitter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Twitter: def __init__(self): """Initialize your data structure here.""" <|body_0|> def postTweet(self, userId: int, tweetId: int) -> None: """Compose a new tweet.""" <|body_1|> def getNewsFeed(self, userId: int) -> list: """Retrieve the 10 most r...
stack_v2_sparse_classes_10k_train_008341
2,372
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Compose a new tweet.", "name": "postTweet", "signature": "def postTweet(self, userId: int, tweetId: int) -> None" }, { "docstring": "Retrieve the 10 mos...
5
stack_v2_sparse_classes_30k_train_000908
Implement the Python class `Twitter` described below. Class description: Implement the Twitter class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet. - def getNewsFeed(self, userId: int) -> list...
Implement the Python class `Twitter` described below. Class description: Implement the Twitter class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet. - def getNewsFeed(self, userId: int) -> list...
4416d0c711b8978f12de960c29d00a9d9792b9e0
<|skeleton|> class Twitter: def __init__(self): """Initialize your data structure here.""" <|body_0|> def postTweet(self, userId: int, tweetId: int) -> None: """Compose a new tweet.""" <|body_1|> def getNewsFeed(self, userId: int) -> list: """Retrieve the 10 most r...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Twitter: def __init__(self): """Initialize your data structure here.""" self.index = 0 self.twitters = dict() self.followers = dict() def postTweet(self, userId: int, tweetId: int) -> None: """Compose a new tweet.""" if userId in self.twitters: ...
the_stack_v2_python_sparse
301-400/355. Design Twitter.py
Ys-Zhou/leetcode-medi-p3
train
0
bac192a712995eb015617aa410cf905788ae7070
[ "super().__init__()\nself.input_dim = input_dim\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.num_classes = num_classes\nself.output_dim = output_dim\nself.lstm_layer = nn.LSTM(input_dim, hidden_size, num_layers, batch_first=True)\nself.linear = nn.Linear(self.hidden_size, output_dim)\nself.ou...
<|body_start_0|> super().__init__() self.input_dim = input_dim self.hidden_size = hidden_size self.num_layers = num_layers self.num_classes = num_classes self.output_dim = output_dim self.lstm_layer = nn.LSTM(input_dim, hidden_size, num_layers, batch_first=True) ...
Simple LSTM decoder.
LSTM_attention_embedding_decoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSTM_attention_embedding_decoder: """Simple LSTM decoder.""" def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): """Initialize model with params.""" <|body_0|> def forward(self, inp, hidden): """Forward pass through LSTM layer. shap...
stack_v2_sparse_classes_10k_train_008342
1,863
permissive
[ { "docstring": "Initialize model with params.", "name": "__init__", "signature": "def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1)" }, { "docstring": "Forward pass through LSTM layer. shape of lstm_out: [input_size, batch_size, hidden_dim] shape of self.hidden: (...
2
stack_v2_sparse_classes_30k_train_005900
Implement the Python class `LSTM_attention_embedding_decoder` described below. Class description: Simple LSTM decoder. Method signatures and docstrings: - def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): Initialize model with params. - def forward(self, inp, hidden): Forward pass thr...
Implement the Python class `LSTM_attention_embedding_decoder` described below. Class description: Simple LSTM decoder. Method signatures and docstrings: - def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): Initialize model with params. - def forward(self, inp, hidden): Forward pass thr...
9cdbf270487751a0ad6862b2fea2ccc0e23a0b67
<|skeleton|> class LSTM_attention_embedding_decoder: """Simple LSTM decoder.""" def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): """Initialize model with params.""" <|body_0|> def forward(self, inp, hidden): """Forward pass through LSTM layer. shap...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class LSTM_attention_embedding_decoder: """Simple LSTM decoder.""" def __init__(self, input_dim, hidden_size, output_dim, num_classes, num_layers=1): """Initialize model with params.""" super().__init__() self.input_dim = input_dim self.hidden_size = hidden_size self.num...
the_stack_v2_python_sparse
caspr/models/lstm_decoder.py
microsoft/CASPR
train
29
9923f29d3cc88b68ee931e8f9406b423c8e0f587
[ "try:\n article = Articles.objects.get(slug=self.kwargs['slug'])\nexcept Articles.DoesNotExist:\n return Response({'errors': COMMENTS_MSG['ARTICLE_DOES_NOT_EXIST']}, status=status.HTTP_404_NOT_FOUND)\ntry:\n comment = Comment.objects.get(pk=self.kwargs['id'])\n serializer = self.serializer_class(comment...
<|body_start_0|> try: article = Articles.objects.get(slug=self.kwargs['slug']) except Articles.DoesNotExist: return Response({'errors': COMMENTS_MSG['ARTICLE_DOES_NOT_EXIST']}, status=status.HTTP_404_NOT_FOUND) try: comment = Comment.objects.get(pk=self.kwargs...
Handles viewing of a specific comment if not authenticated and Handles replying to a comment on an article if authenticated Handles Deleting a comment from an article
RetrieveUpdateDeleteCommentAPIView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RetrieveUpdateDeleteCommentAPIView: """Handles viewing of a specific comment if not authenticated and Handles replying to a comment on an article if authenticated Handles Deleting a comment from an article""" def get(self, request, *args, **kwargs): """Handles retrieving a specific c...
stack_v2_sparse_classes_10k_train_008343
7,543
permissive
[ { "docstring": "Handles retrieving a specific comment and all their replies :param request: :param args: :param kwargs: :return:", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Handles updating a comment if author is same as the requester :param request...
3
stack_v2_sparse_classes_30k_val_000083
Implement the Python class `RetrieveUpdateDeleteCommentAPIView` described below. Class description: Handles viewing of a specific comment if not authenticated and Handles replying to a comment on an article if authenticated Handles Deleting a comment from an article Method signatures and docstrings: - def get(self, r...
Implement the Python class `RetrieveUpdateDeleteCommentAPIView` described below. Class description: Handles viewing of a specific comment if not authenticated and Handles replying to a comment on an article if authenticated Handles Deleting a comment from an article Method signatures and docstrings: - def get(self, r...
5a31840856de4b361fe2594dfa7a33d7774d3fe2
<|skeleton|> class RetrieveUpdateDeleteCommentAPIView: """Handles viewing of a specific comment if not authenticated and Handles replying to a comment on an article if authenticated Handles Deleting a comment from an article""" def get(self, request, *args, **kwargs): """Handles retrieving a specific c...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RetrieveUpdateDeleteCommentAPIView: """Handles viewing of a specific comment if not authenticated and Handles replying to a comment on an article if authenticated Handles Deleting a comment from an article""" def get(self, request, *args, **kwargs): """Handles retrieving a specific comment and al...
the_stack_v2_python_sparse
authors/apps/comments/views.py
bl4ck4ndbr0wn/ah-centauri-backend
train
0
fbea40680de29349759c2331af73f633b42a45b0
[ "try:\n self.UDPlist = UDPlist_p\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.bind(('', UDP_PORT))\n hasUDP = True\nexcept socket.error:\n hasUDP = False\n print('AHF_UDPTrig failed to create a socket.')", "try:\n for address in self.UDPlist:\n self.sock.s...
<|body_start_0|> try: self.UDPlist = UDPlist_p self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('', UDP_PORT)) hasUDP = True except socket.error: hasUDP = False print('AHF_UDPTrig failed to create a socke...
Sends/receives UDP signals as to another pi to start/stop recording AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install
AHF_UDPTrig
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AHF_UDPTrig: """Sends/receives UDP signals as to another pi to start/stop recording AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install""" def __init__(self, UDPlist_p): """Makes a new AHF_UDPtrig object using passed in list of ip addr...
stack_v2_sparse_classes_10k_train_008344
1,743
no_license
[ { "docstring": "Makes a new AHF_UDPtrig object using passed in list of ip addresses. stores UDPlist in the new object sets hasUDP to false if object creation fails because of network error, else True", "name": "__init__", "signature": "def __init__(self, UDPlist_p)" }, { "docstring": "Sends a UD...
3
stack_v2_sparse_classes_30k_test_000344
Implement the Python class `AHF_UDPTrig` described below. Class description: Sends/receives UDP signals as to another pi to start/stop recording AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install Method signatures and docstrings: - def __init__(self, UDPlist_p): Makes...
Implement the Python class `AHF_UDPTrig` described below. Class description: Sends/receives UDP signals as to another pi to start/stop recording AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install Method signatures and docstrings: - def __init__(self, UDPlist_p): Makes...
a7fa58f47cfbb92de1f6c33d003bc290f1f37d86
<|skeleton|> class AHF_UDPTrig: """Sends/receives UDP signals as to another pi to start/stop recording AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install""" def __init__(self, UDPlist_p): """Makes a new AHF_UDPtrig object using passed in list of ip addr...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AHF_UDPTrig: """Sends/receives UDP signals as to another pi to start/stop recording AHF_UDPTrig uses the socket module to do the UDP stuff, but it should be part of the default install""" def __init__(self, UDPlist_p): """Makes a new AHF_UDPtrig object using passed in list of ip addresses. stores...
the_stack_v2_python_sparse
moreModules/AutoHeadFix/AHF_UDPTrig.py
ilangold/AutoHeadFix
train
0
b80e52d2f5ae92891d6486075e20d9a98e04a0e0
[ "x, y, z = self.coords\nif self.orientation == '+x':\n yield (x - 1, y, z)\nelif self.orientation == '-x':\n yield (x + 1, y, z)\nelif self.orientation == '+z':\n yield (x, y, z - 1)\nelif self.orientation == '-z':\n yield (x, y, z + 1)\nelif self.orientation == '+y':\n yield (x, y - 1, z)", "x, y,...
<|body_start_0|> x, y, z = self.coords if self.orientation == '+x': yield (x - 1, y, z) elif self.orientation == '-x': yield (x + 1, y, z) elif self.orientation == '+z': yield (x, y, z - 1) elif self.orientation == '-z': yield (x, y...
A redstone torch. Torches do a NOT operation from their input.
Torch
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Torch: """A redstone torch. Torches do a NOT operation from their input.""" def iter_inputs(self): """Provide the input corresponding to the block upon which this torch is mounted.""" <|body_0|> def iter_outputs(self): """Provide the outputs corresponding to the ...
stack_v2_sparse_classes_10k_train_008345
13,022
permissive
[ { "docstring": "Provide the input corresponding to the block upon which this torch is mounted.", "name": "iter_inputs", "signature": "def iter_inputs(self)" }, { "docstring": "Provide the outputs corresponding to the block upon which this torch is mounted.", "name": "iter_outputs", "sign...
2
stack_v2_sparse_classes_30k_train_001262
Implement the Python class `Torch` described below. Class description: A redstone torch. Torches do a NOT operation from their input. Method signatures and docstrings: - def iter_inputs(self): Provide the input corresponding to the block upon which this torch is mounted. - def iter_outputs(self): Provide the outputs ...
Implement the Python class `Torch` described below. Class description: A redstone torch. Torches do a NOT operation from their input. Method signatures and docstrings: - def iter_inputs(self): Provide the input corresponding to the block upon which this torch is mounted. - def iter_outputs(self): Provide the outputs ...
7be5d792871a8447499911fa1502c6a7c1437dc3
<|skeleton|> class Torch: """A redstone torch. Torches do a NOT operation from their input.""" def iter_inputs(self): """Provide the input corresponding to the block upon which this torch is mounted.""" <|body_0|> def iter_outputs(self): """Provide the outputs corresponding to the ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Torch: """A redstone torch. Torches do a NOT operation from their input.""" def iter_inputs(self): """Provide the input corresponding to the block upon which this torch is mounted.""" x, y, z = self.coords if self.orientation == '+x': yield (x - 1, y, z) elif s...
the_stack_v2_python_sparse
bravo/utilities/redstone.py
CyberFlameGO/bravo
train
0
a0c71bebfec8a4e9c5f85e6dda4a021f3bd32c9f
[ "if start_time is None:\n self.started = time.time()\nelse:\n self.started = start_time", "ended = time.time()\nstarted_wait = datetime.datetime.fromtimestamp(self.started).strftime('%Y-%m-%d %H:%M:%S')\nraised_date = datetime.datetime.fromtimestamp(ended).strftime('%Y-%m-%d %H:%M:%S')\nduration = ended - s...
<|body_start_0|> if start_time is None: self.started = time.time() else: self.started = start_time <|end_body_0|> <|body_start_1|> ended = time.time() started_wait = datetime.datetime.fromtimestamp(self.started).strftime('%Y-%m-%d %H:%M:%S') raised_date =...
Holds timeout exception information.
TimeoutExceptionInfo
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeoutExceptionInfo: """Holds timeout exception information.""" def __init__(self, start_time=None): """Mark the time for started waiting.""" <|body_0|> def msg(self): """Return a message to be used by TimeoutException containing timing information.""" <...
stack_v2_sparse_classes_10k_train_008346
14,890
permissive
[ { "docstring": "Mark the time for started waiting.", "name": "__init__", "signature": "def __init__(self, start_time=None)" }, { "docstring": "Return a message to be used by TimeoutException containing timing information.", "name": "msg", "signature": "def msg(self)" } ]
2
stack_v2_sparse_classes_30k_train_004308
Implement the Python class `TimeoutExceptionInfo` described below. Class description: Holds timeout exception information. Method signatures and docstrings: - def __init__(self, start_time=None): Mark the time for started waiting. - def msg(self): Return a message to be used by TimeoutException containing timing info...
Implement the Python class `TimeoutExceptionInfo` described below. Class description: Holds timeout exception information. Method signatures and docstrings: - def __init__(self, start_time=None): Mark the time for started waiting. - def msg(self): Return a message to be used by TimeoutException containing timing info...
69c082d2bf9b9985db77d1d25a3f423ecf016e00
<|skeleton|> class TimeoutExceptionInfo: """Holds timeout exception information.""" def __init__(self, start_time=None): """Mark the time for started waiting.""" <|body_0|> def msg(self): """Return a message to be used by TimeoutException containing timing information.""" <...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TimeoutExceptionInfo: """Holds timeout exception information.""" def __init__(self, start_time=None): """Mark the time for started waiting.""" if start_time is None: self.started = time.time() else: self.started = start_time def msg(self): """R...
the_stack_v2_python_sparse
testplan/common/utils/timing.py
morganstanley/testplan
train
78
a966b5b6e49d1b8dd50721541fe866b7c4c5a03b
[ "self.day = day\nself.month = month\nself.year = year", "if cls.is_valid_date(astring):\n day, month, year = map(int, astring.split('-'))\n return cls(day, month, year)\nelse:\n raise IOError(f'{astring!r} is not a valid date string.')", "try:\n day, month, year = map(int, astring.split('-'))\nexcep...
<|body_start_0|> self.day = day self.month = month self.year = year <|end_body_0|> <|body_start_1|> if cls.is_valid_date(astring): day, month, year = map(int, astring.split('-')) return cls(day, month, year) else: raise IOError(f'{astring!r} i...
Source: https://stackoverflow.com/questions/12179271
Date
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Date: """Source: https://stackoverflow.com/questions/12179271""" def __init__(self, day=0, month=0, year=0): """Initialize from day, month and year values (no verification).""" <|body_0|> def from_string(cls, astring): """Initialize from (verified) 'day-month-yea...
stack_v2_sparse_classes_10k_train_008347
3,912
no_license
[ { "docstring": "Initialize from day, month and year values (no verification).", "name": "__init__", "signature": "def __init__(self, day=0, month=0, year=0)" }, { "docstring": "Initialize from (verified) 'day-month-year' string.", "name": "from_string", "signature": "def from_string(cls,...
3
stack_v2_sparse_classes_30k_train_001046
Implement the Python class `Date` described below. Class description: Source: https://stackoverflow.com/questions/12179271 Method signatures and docstrings: - def __init__(self, day=0, month=0, year=0): Initialize from day, month and year values (no verification). - def from_string(cls, astring): Initialize from (ver...
Implement the Python class `Date` described below. Class description: Source: https://stackoverflow.com/questions/12179271 Method signatures and docstrings: - def __init__(self, day=0, month=0, year=0): Initialize from day, month and year values (no verification). - def from_string(cls, astring): Initialize from (ver...
dd931c09fe5229907a93f3c3992924650abb3315
<|skeleton|> class Date: """Source: https://stackoverflow.com/questions/12179271""" def __init__(self, day=0, month=0, year=0): """Initialize from day, month and year values (no verification).""" <|body_0|> def from_string(cls, astring): """Initialize from (verified) 'day-month-yea...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Date: """Source: https://stackoverflow.com/questions/12179271""" def __init__(self, day=0, month=0, year=0): """Initialize from day, month and year values (no verification).""" self.day = day self.month = month self.year = year def from_string(cls, astring): "...
the_stack_v2_python_sparse
Cours/avance.py
ycopin/Informatique-Python
train
3
b15fc00fca98dc8e6cd574dd22bd024021e6d4f6
[ "data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_data_stage02_isotopomer_measuredFluxes(data.data)\ndata.clear_data()", "data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_data_stage02_isotopomer_measuredFragments(data.data)\ndata.clear_data()", "data...
<|body_start_0|> data = base_importData() data.read_csv(filename) data.format_data() self.add_data_stage02_isotopomer_measuredFluxes(data.data) data.clear_data() <|end_body_0|> <|body_start_1|> data = base_importData() data.read_csv(filename) data.format_...
stage02_isotopomer_measuredData_io
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class stage02_isotopomer_measuredData_io: def import_data_stage02_isotopomer_measuredFluxes_add(self, filename): """table adds""" <|body_0|> def import_data_stage02_isotopomer_measuredFragments_add(self, filename): """table adds""" <|body_1|> def export_data_s...
stack_v2_sparse_classes_10k_train_008348
3,229
permissive
[ { "docstring": "table adds", "name": "import_data_stage02_isotopomer_measuredFluxes_add", "signature": "def import_data_stage02_isotopomer_measuredFluxes_add(self, filename)" }, { "docstring": "table adds", "name": "import_data_stage02_isotopomer_measuredFragments_add", "signature": "def...
4
stack_v2_sparse_classes_30k_train_004456
Implement the Python class `stage02_isotopomer_measuredData_io` described below. Class description: Implement the stage02_isotopomer_measuredData_io class. Method signatures and docstrings: - def import_data_stage02_isotopomer_measuredFluxes_add(self, filename): table adds - def import_data_stage02_isotopomer_measure...
Implement the Python class `stage02_isotopomer_measuredData_io` described below. Class description: Implement the stage02_isotopomer_measuredData_io class. Method signatures and docstrings: - def import_data_stage02_isotopomer_measuredFluxes_add(self, filename): table adds - def import_data_stage02_isotopomer_measure...
005e1d34c2ace7e28c53dffcab3e9cb8c7e7ce18
<|skeleton|> class stage02_isotopomer_measuredData_io: def import_data_stage02_isotopomer_measuredFluxes_add(self, filename): """table adds""" <|body_0|> def import_data_stage02_isotopomer_measuredFragments_add(self, filename): """table adds""" <|body_1|> def export_data_s...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class stage02_isotopomer_measuredData_io: def import_data_stage02_isotopomer_measuredFluxes_add(self, filename): """table adds""" data = base_importData() data.read_csv(filename) data.format_data() self.add_data_stage02_isotopomer_measuredFluxes(data.data) data.clear_...
the_stack_v2_python_sparse
SBaaS_MFA/stage02_isotopomer_measuredData_io.py
dmccloskey/SBaaS_MFA
train
0
4abd4942fd2439d6baf79daba82575febd901a5e
[ "super(EncodingLayer, self).__init__(**kwargs)\nself._initial_keep_rate = initial_keep_rate\nself._decay_interval = decay_interval\nself._decay_rate = decay_rate\nself._w_itr_att = None\nself._w1 = None\nself._w2 = None\nself._w3 = None\nself._b1 = None\nself._b2 = None\nself._b3 = None", "d = input_shape[-1]\nse...
<|body_start_0|> super(EncodingLayer, self).__init__(**kwargs) self._initial_keep_rate = initial_keep_rate self._decay_interval = decay_interval self._decay_rate = decay_rate self._w_itr_att = None self._w1 = None self._w2 = None self._w3 = None se...
Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval parameter of DecayingDropoutLayer. :param decay_rate: the decay_rate parameter of Dec...
EncodingLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncodingLayer: """Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval parameter of DecayingDropoutLayer. :param de...
stack_v2_sparse_classes_10k_train_008349
4,198
permissive
[ { "docstring": ":class: 'EncodingLayer' constructor.", "name": "__init__", "signature": "def __init__(self, initial_keep_rate: float, decay_interval: int, decay_rate: float, **kwargs)" }, { "docstring": "Build the layer. :param input_shape: the shape of the input tensor, for EncodingLayer we nee...
3
stack_v2_sparse_classes_30k_train_007034
Implement the Python class `EncodingLayer` described below. Class description: Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval param...
Implement the Python class `EncodingLayer` described below. Class description: Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval param...
1f763062c6cc861e93ccdba23d0f1f0171f74145
<|skeleton|> class EncodingLayer: """Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval parameter of DecayingDropoutLayer. :param de...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EncodingLayer: """Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval parameter of DecayingDropoutLayer. :param decay_rate: the...
the_stack_v2_python_sparse
matchzoo/contrib/layers/semantic_composite_layer.py
JRetza/MatchZoo
train
1
fe562d7ac4da2a2da9688a3d2e4a78a790565a36
[ "if not isinstance(other, Tag):\n return -1\nif other.name != self.name:\n return cmp(self.name, other.name)\nif other.attributes != self.attributes:\n return cmp(self.attributes, other.attributes)\nif other.content != self.content:\n return cmp(self.content, other.content)\nreturn 0", "fragments = []...
<|body_start_0|> if not isinstance(other, Tag): return -1 if other.name != self.name: return cmp(self.name, other.name) if other.attributes != self.attributes: return cmp(self.attributes, other.attributes) if other.content != self.content: ...
Represents a particular tag within a document
Tag
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tag: """Represents a particular tag within a document""" def __cmp__(self, other): """Compare this tag to another""" <|body_0|> def __repr__(self): """Create a decent representation of this tag""" <|body_1|> <|end_skeleton|> <|body_start_0|> if ...
stack_v2_sparse_classes_10k_train_008350
2,813
no_license
[ { "docstring": "Compare this tag to another", "name": "__cmp__", "signature": "def __cmp__(self, other)" }, { "docstring": "Create a decent representation of this tag", "name": "__repr__", "signature": "def __repr__(self)" } ]
2
stack_v2_sparse_classes_30k_train_005488
Implement the Python class `Tag` described below. Class description: Represents a particular tag within a document Method signatures and docstrings: - def __cmp__(self, other): Compare this tag to another - def __repr__(self): Create a decent representation of this tag
Implement the Python class `Tag` described below. Class description: Represents a particular tag within a document Method signatures and docstrings: - def __cmp__(self, other): Compare this tag to another - def __repr__(self): Create a decent representation of this tag <|skeleton|> class Tag: """Represents a par...
496fc33954072147c379b8a9a1957bb04fd93670
<|skeleton|> class Tag: """Represents a particular tag within a document""" def __cmp__(self, other): """Compare this tag to another""" <|body_0|> def __repr__(self): """Create a decent representation of this tag""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Tag: """Represents a particular tag within a document""" def __cmp__(self, other): """Compare this tag to another""" if not isinstance(other, Tag): return -1 if other.name != self.name: return cmp(self.name, other.name) if other.attributes != self.a...
the_stack_v2_python_sparse
basicproperty/xmlencoder.py
eshikvtumane/basicproperty
train
0
e804863764cd51b6008c332a5771ab1b96329ca7
[ "dataset = m.device\nif not dataset_exists(dataset, 'filesystem'):\n raise ex.syncNotSnapable\nsnapdev = dataset + '@osvc_sync'\nmount_point = m.mount_point\nsnap_mount_point = mount_point + '/.zfs/snapshot/osvc_sync/'\nif dataset_exists(snapdev, 'snapshot'):\n ret, buff, err = self.vcall([rcEnv.syspaths.zfs,...
<|body_start_0|> dataset = m.device if not dataset_exists(dataset, 'filesystem'): raise ex.syncNotSnapable snapdev = dataset + '@osvc_sync' mount_point = m.mount_point snap_mount_point = mount_point + '/.zfs/snapshot/osvc_sync/' if dataset_exists(snapdev, 'sna...
Defines a snap object with ZFS
Snap
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Snap: """Defines a snap object with ZFS""" def snapcreate(self, m): """create a snapshot for m add self.snaps[m] with dict(snapinfo key val)""" <|body_0|> def snapdestroykey(self, snap_key): """destroy a snapshot for a mount_point""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_10k_train_008351
1,445
no_license
[ { "docstring": "create a snapshot for m add self.snaps[m] with dict(snapinfo key val)", "name": "snapcreate", "signature": "def snapcreate(self, m)" }, { "docstring": "destroy a snapshot for a mount_point", "name": "snapdestroykey", "signature": "def snapdestroykey(self, snap_key)" } ]
2
stack_v2_sparse_classes_30k_train_000480
Implement the Python class `Snap` described below. Class description: Defines a snap object with ZFS Method signatures and docstrings: - def snapcreate(self, m): create a snapshot for m add self.snaps[m] with dict(snapinfo key val) - def snapdestroykey(self, snap_key): destroy a snapshot for a mount_point
Implement the Python class `Snap` described below. Class description: Defines a snap object with ZFS Method signatures and docstrings: - def snapcreate(self, m): create a snapshot for m add self.snaps[m] with dict(snapinfo key val) - def snapdestroykey(self, snap_key): destroy a snapshot for a mount_point <|skeleton...
75baeb19e0d26d5e150e770aef4d615c2327f32e
<|skeleton|> class Snap: """Defines a snap object with ZFS""" def snapcreate(self, m): """create a snapshot for m add self.snaps[m] with dict(snapinfo key val)""" <|body_0|> def snapdestroykey(self, snap_key): """destroy a snapshot for a mount_point""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Snap: """Defines a snap object with ZFS""" def snapcreate(self, m): """create a snapshot for m add self.snaps[m] with dict(snapinfo key val)""" dataset = m.device if not dataset_exists(dataset, 'filesystem'): raise ex.syncNotSnapable snapdev = dataset + '@osvc_...
the_stack_v2_python_sparse
lib/snapZfsSunOS.py
SLB-DeN/opensvc
train
1
e04f857ccfad76cbf06f8c74727bc55653faa71a
[ "self.cardinality = cardinality\nif norm_factory is None:\n norm_factory = nn.BatchNorm2d\nself.norm_factory = norm_factory\nself.resnext_class = copy(models.resnet.Bottleneck)\nself.resnext_class.expansion = 2", "stride = 1\nprojection = None\nif downsample > 1:\n stride = downsample\nif downsample > 1 or ...
<|body_start_0|> self.cardinality = cardinality if norm_factory is None: norm_factory = nn.BatchNorm2d self.norm_factory = norm_factory self.resnext_class = copy(models.resnet.Bottleneck) self.resnext_class.expansion = 2 <|end_body_0|> <|body_start_1|> stride...
Factory wrapper for ``torchvision`` ResNeXt blocks.
ResNeXtBlockFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResNeXtBlockFactory: """Factory wrapper for ``torchvision`` ResNeXt blocks.""" def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): """Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory obje...
stack_v2_sparse_classes_10k_train_008352
6,999
permissive
[ { "docstring": "Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory object to produce the normalization layers used in the ResNet blocks. Defaults to batch norm.", "name": "__init__", "signature": "def __init__(self, cardinality=32, norm_factory: Opti...
2
stack_v2_sparse_classes_30k_train_001934
Implement the Python class `ResNeXtBlockFactory` described below. Class description: Factory wrapper for ``torchvision`` ResNeXt blocks. Method signatures and docstrings: - def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): Args: cardinality: The cardinality of the block as d...
Implement the Python class `ResNeXtBlockFactory` described below. Class description: Factory wrapper for ``torchvision`` ResNeXt blocks. Method signatures and docstrings: - def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): Args: cardinality: The cardinality of the block as d...
a27e329cd30337995c359160a0d878bf331c13fb
<|skeleton|> class ResNeXtBlockFactory: """Factory wrapper for ``torchvision`` ResNeXt blocks.""" def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): """Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory obje...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ResNeXtBlockFactory: """Factory wrapper for ``torchvision`` ResNeXt blocks.""" def __init__(self, cardinality=32, norm_factory: Optional[Callable[[int], nn.Module]]=None): """Args: cardinality: The cardinality of the block as defined in the ResNeXt paper. norm_factory: A factory object to produce...
the_stack_v2_python_sparse
quantnn/models/pytorch/torchvision.py
simonpf/quantnn
train
7
a4e2e7ef5c28a9d9fed11a70909fa91c9dfed64a
[ "super(ObservationGroupEncoder, self).__init__()\nassert isinstance(observation_group_shapes, OrderedDict)\nassert np.all([isinstance(observation_group_shapes[k], OrderedDict) for k in observation_group_shapes])\nself.observation_group_shapes = observation_group_shapes\nself.nets = nn.ModuleDict()\nfor obs_group in...
<|body_start_0|> super(ObservationGroupEncoder, self).__init__() assert isinstance(observation_group_shapes, OrderedDict) assert np.all([isinstance(observation_group_shapes[k], OrderedDict) for k in observation_group_shapes]) self.observation_group_shapes = observation_group_shapes ...
This class allows networks to encode multiple observation dictionaries into a single flat, concatenated vector representation. It does this by assigning each observation dictionary (observation group) an @ObservationEncoder object. The class takes a dictionary of dictionaries, @observation_group_shapes. Each key corres...
ObservationGroupEncoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObservationGroupEncoder: """This class allows networks to encode multiple observation dictionaries into a single flat, concatenated vector representation. It does this by assigning each observation dictionary (observation group) an @ObservationEncoder object. The class takes a dictionary of dicti...
stack_v2_sparse_classes_10k_train_008353
37,945
permissive
[ { "docstring": "Args: observation_group_shapes (OrderedDict): a dictionary of dictionaries. Each key in this dictionary should specify an observation group, and the value should be an OrderedDict that maps modalities to expected shapes. visual_feature_dimension (int): feature dimension to encode images into vis...
4
stack_v2_sparse_classes_30k_train_004403
Implement the Python class `ObservationGroupEncoder` described below. Class description: This class allows networks to encode multiple observation dictionaries into a single flat, concatenated vector representation. It does this by assigning each observation dictionary (observation group) an @ObservationEncoder object...
Implement the Python class `ObservationGroupEncoder` described below. Class description: This class allows networks to encode multiple observation dictionaries into a single flat, concatenated vector representation. It does this by assigning each observation dictionary (observation group) an @ObservationEncoder object...
2804dd97dd1625ec861298a35cb677129d3bfacc
<|skeleton|> class ObservationGroupEncoder: """This class allows networks to encode multiple observation dictionaries into a single flat, concatenated vector representation. It does this by assigning each observation dictionary (observation group) an @ObservationEncoder object. The class takes a dictionary of dicti...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ObservationGroupEncoder: """This class allows networks to encode multiple observation dictionaries into a single flat, concatenated vector representation. It does this by assigning each observation dictionary (observation group) an @ObservationEncoder object. The class takes a dictionary of dictionaries, @obs...
the_stack_v2_python_sparse
robomimic/models/obs_nets.py
sohams-MASS/robomimic
train
0
668fc6b8d41dc44d72aea56c92eb0e6c3e297b4c
[ "self.data_frame: Optional[pd.DataFrame] = None\nself.frame_info = None\nself.workflow = kwargs.pop(str('workflow'), None)\nsuper().__init__(*args, **kwargs)", "try:\n pandas.verify_data_frame(self.data_frame)\nexcept OnTaskDataFrameNoKey as exc:\n self.add_error(None, str(exc))\n return\ntry:\n self....
<|body_start_0|> self.data_frame: Optional[pd.DataFrame] = None self.frame_info = None self.workflow = kwargs.pop(str('workflow'), None) super().__init__(*args, **kwargs) <|end_body_0|> <|body_start_1|> try: pandas.verify_data_frame(self.data_frame) except On...
Basic class to use for inheritance.
UploadBasic
[ "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "Apache-2.0", "LGPL-2.1-only", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadBasic: """Basic class to use for inheritance.""" def __init__(self, *args, **kwargs): """Store the workflow for further processing.""" <|body_0|> def validate_data_frame(self): """Check that the dataframe can be properly stored. :return: The cleaned data"""...
stack_v2_sparse_classes_10k_train_008354
10,714
permissive
[ { "docstring": "Store the workflow for further processing.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Check that the dataframe can be properly stored. :return: The cleaned data", "name": "validate_data_frame", "signature": "def validate_da...
2
stack_v2_sparse_classes_30k_train_002079
Implement the Python class `UploadBasic` described below. Class description: Basic class to use for inheritance. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Store the workflow for further processing. - def validate_data_frame(self): Check that the dataframe can be properly stored. :return...
Implement the Python class `UploadBasic` described below. Class description: Basic class to use for inheritance. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Store the workflow for further processing. - def validate_data_frame(self): Check that the dataframe can be properly stored. :return...
c432745dfff932cbe7397100422d49df78f0a882
<|skeleton|> class UploadBasic: """Basic class to use for inheritance.""" def __init__(self, *args, **kwargs): """Store the workflow for further processing.""" <|body_0|> def validate_data_frame(self): """Check that the dataframe can be properly stored. :return: The cleaned data"""...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class UploadBasic: """Basic class to use for inheritance.""" def __init__(self, *args, **kwargs): """Store the workflow for further processing.""" self.data_frame: Optional[pd.DataFrame] = None self.frame_info = None self.workflow = kwargs.pop(str('workflow'), None) supe...
the_stack_v2_python_sparse
ontask/dataops/forms/upload.py
abelardopardo/ontask_b
train
43
c678bf6e311c441d9545e094dd1cb14e85c4091c
[ "self.problem = problem\nself.pp = post.PostProcessor(dict(casedir='Results', clean_casedir=True))\nself.pp.add_field(post.SolutionField('Solution', dict(save=True, save_as=['hdf5', 'xdmf'], plot=True, plot_args=dict(range_min=float(u_min), range_max=float(u_max)))))\nself.pp.add_field(post.SolutionField('Flux', di...
<|body_start_0|> self.problem = problem self.pp = post.PostProcessor(dict(casedir='Results', clean_casedir=True)) self.pp.add_field(post.SolutionField('Solution', dict(save=True, save_as=['hdf5', 'xdmf'], plot=True, plot_args=dict(range_min=float(u_min), range_max=float(u_max))))) self.p...
user_action function for storing the solution and flux.
ProcessSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProcessSolution: """user_action function for storing the solution and flux.""" def __init__(self, problem, u_min=0, u_max=1): """Define fields to be stored/plotted.""" <|body_0|> def __call__(self, t, u, timestep): """Store u and its flux to file.""" <|bo...
stack_v2_sparse_classes_10k_train_008355
19,607
no_license
[ { "docstring": "Define fields to be stored/plotted.", "name": "__init__", "signature": "def __init__(self, problem, u_min=0, u_max=1)" }, { "docstring": "Store u and its flux to file.", "name": "__call__", "signature": "def __call__(self, t, u, timestep)" } ]
2
null
Implement the Python class `ProcessSolution` described below. Class description: user_action function for storing the solution and flux. Method signatures and docstrings: - def __init__(self, problem, u_min=0, u_max=1): Define fields to be stored/plotted. - def __call__(self, t, u, timestep): Store u and its flux to ...
Implement the Python class `ProcessSolution` described below. Class description: user_action function for storing the solution and flux. Method signatures and docstrings: - def __init__(self, problem, u_min=0, u_max=1): Define fields to be stored/plotted. - def __call__(self, t, u, timestep): Store u and its flux to ...
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
<|skeleton|> class ProcessSolution: """user_action function for storing the solution and flux.""" def __init__(self, problem, u_min=0, u_max=1): """Define fields to be stored/plotted.""" <|body_0|> def __call__(self, t, u, timestep): """Store u and its flux to file.""" <|bo...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ProcessSolution: """user_action function for storing the solution and flux.""" def __init__(self, problem, u_min=0, u_max=1): """Define fields to be stored/plotted.""" self.problem = problem self.pp = post.PostProcessor(dict(casedir='Results', clean_casedir=True)) self.pp....
the_stack_v2_python_sparse
Solving_PDEs_in_Python_Langtangen/src/src/heat_class.py
burakbayramli/books
train
223
30f5da1e8c105f688997e87cb4a598a63ef4cf17
[ "self.countTable = ChainingHashMap(1000)\nself.totalTable = ChainingHashMap(1000)\nself.totalWords = 0", "textList = text.split()\nfor i in range(len(textList) - 1):\n self.totalWords += 1\n if self.totalTable[textList[i]] == None:\n self.totalTable[textList[i]] = 1\n else:\n self.totalTabl...
<|body_start_0|> self.countTable = ChainingHashMap(1000) self.totalTable = ChainingHashMap(1000) self.totalWords = 0 <|end_body_0|> <|body_start_1|> textList = text.split() for i in range(len(textList) - 1): self.totalWords += 1 if self.totalTable[textLis...
A class that allows one to generate random text in the style of some provided source text
TextGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextGenerator: """A class that allows one to generate random text in the style of some provided source text""" def __init__(self): """Initializes the text generator""" <|body_0|> def train(self, text): """Takes a body of text (as a string) and increases the appro...
stack_v2_sparse_classes_10k_train_008356
6,228
no_license
[ { "docstring": "Initializes the text generator", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Takes a body of text (as a string) and increases the appropriate frequency counts", "name": "train", "signature": "def train(self, text)" }, { "docstring": "C...
4
stack_v2_sparse_classes_30k_train_002735
Implement the Python class `TextGenerator` described below. Class description: A class that allows one to generate random text in the style of some provided source text Method signatures and docstrings: - def __init__(self): Initializes the text generator - def train(self, text): Takes a body of text (as a string) an...
Implement the Python class `TextGenerator` described below. Class description: A class that allows one to generate random text in the style of some provided source text Method signatures and docstrings: - def __init__(self): Initializes the text generator - def train(self, text): Takes a body of text (as a string) an...
0290deb3e1f008305fb2da353eda86210a7ba1e6
<|skeleton|> class TextGenerator: """A class that allows one to generate random text in the style of some provided source text""" def __init__(self): """Initializes the text generator""" <|body_0|> def train(self, text): """Takes a body of text (as a string) and increases the appro...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TextGenerator: """A class that allows one to generate random text in the style of some provided source text""" def __init__(self): """Initializes the text generator""" self.countTable = ChainingHashMap(1000) self.totalTable = ChainingHashMap(1000) self.totalWords = 0 ...
the_stack_v2_python_sparse
Random Text Generation/textgenerator.py
mbastola/Algorithms-Data-Structures-in-Python
train
0
828b995dff7e6938a3411aa97e8d64c8de3907e4
[ "self.mapper = {}\nself.names = []\nfor param in space:\n if param['name'] in self.names:\n raise ValueError('Duplicated name {}'.format(param['name']))\n self.names.append(param['name'])\n if param['type'] == TYPE.CATEGORICAL or param['type'] is TYPE.DISCRETE:\n self.mapper[param['name']] = ...
<|body_start_0|> self.mapper = {} self.names = [] for param in space: if param['name'] in self.names: raise ValueError('Duplicated name {}'.format(param['name'])) self.names.append(param['name']) if param['type'] == TYPE.CATEGORICAL or param['t...
Converter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Converter: def __init__(self, space): """Initialize the converter. Save the sequence of labels for keeping the same output and input order within the dict. Save the table used to convert the categorical and discrete parameters. Args: :param space: input space""" <|body_0|> d...
stack_v2_sparse_classes_10k_train_008357
10,066
no_license
[ { "docstring": "Initialize the converter. Save the sequence of labels for keeping the same output and input order within the dict. Save the table used to convert the categorical and discrete parameters. Args: :param space: input space", "name": "__init__", "signature": "def __init__(self, space)" }, ...
3
stack_v2_sparse_classes_30k_train_004247
Implement the Python class `Converter` described below. Class description: Implement the Converter class. Method signatures and docstrings: - def __init__(self, space): Initialize the converter. Save the sequence of labels for keeping the same output and input order within the dict. Save the table used to convert the...
Implement the Python class `Converter` described below. Class description: Implement the Converter class. Method signatures and docstrings: - def __init__(self, space): Initialize the converter. Save the sequence of labels for keeping the same output and input order within the dict. Save the table used to convert the...
27f861c09615aedfd96cffdebf7d9653f72b4d7b
<|skeleton|> class Converter: def __init__(self, space): """Initialize the converter. Save the sequence of labels for keeping the same output and input order within the dict. Save the table used to convert the categorical and discrete parameters. Args: :param space: input space""" <|body_0|> d...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Converter: def __init__(self, space): """Initialize the converter. Save the sequence of labels for keeping the same output and input order within the dict. Save the table used to convert the categorical and discrete parameters. Args: :param space: input space""" self.mapper = {} self.n...
the_stack_v2_python_sparse
API/Algorithms/BayesianOptimization.py
AndreaCorsini1/Ahmet
train
1
6f3979926a7fcc962601e2867f7d6c01bc51fe5f
[ "i = 0\nfor user, msg in self._queue:\n if user == nick:\n return i\n i += 1\nreturn -1", "outfile = self.registryValue('dumpFile')\nwith open(outfile, 'w') as h:\n i = 1\n for nick, msg in self._queue:\n if msg is None:\n msg = '[no message]'\n h.write('% 2d\\t%s\\t%s\...
<|body_start_0|> i = 0 for user, msg in self._queue: if user == nick: return i i += 1 return -1 <|end_body_0|> <|body_start_1|> outfile = self.registryValue('dumpFile') with open(outfile, 'w') as h: i = 1 for nick, ...
A simple queue manager for meetings. You can add yourself to the queue by using the queue command, giving an optional notice that the bot can display when it's your turn. If you call the queue command again, you can change the saved notice. Doing so won't make you lose your queue position. In case you changed your mind...
Queue
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Queue: """A simple queue manager for meetings. You can add yourself to the queue by using the queue command, giving an optional notice that the bot can display when it's your turn. If you call the queue command again, you can change the saved notice. Doing so won't make you lose your queue positi...
stack_v2_sparse_classes_10k_train_008358
5,983
permissive
[ { "docstring": "Check if a given user is in the queue", "name": "_find_in_queue", "signature": "def _find_in_queue(self, nick)" }, { "docstring": "Dump the queue to a file", "name": "_dump_queue", "signature": "def _dump_queue(self)" }, { "docstring": "[<notice>] Queue up for say...
6
stack_v2_sparse_classes_30k_train_005680
Implement the Python class `Queue` described below. Class description: A simple queue manager for meetings. You can add yourself to the queue by using the queue command, giving an optional notice that the bot can display when it's your turn. If you call the queue command again, you can change the saved notice. Doing s...
Implement the Python class `Queue` described below. Class description: A simple queue manager for meetings. You can add yourself to the queue by using the queue command, giving an optional notice that the bot can display when it's your turn. If you call the queue command again, you can change the saved notice. Doing s...
656f42f8d6b3fe4544a5270e0dab816fd3603118
<|skeleton|> class Queue: """A simple queue manager for meetings. You can add yourself to the queue by using the queue command, giving an optional notice that the bot can display when it's your turn. If you call the queue command again, you can change the saved notice. Doing so won't make you lose your queue positi...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Queue: """A simple queue manager for meetings. You can add yourself to the queue by using the queue command, giving an optional notice that the bot can display when it's your turn. If you call the queue command again, you can change the saved notice. Doing so won't make you lose your queue position. In case y...
the_stack_v2_python_sparse
plugins/Queue/plugin.py
kblin/supybot-gsoc
train
2
ef7dca91aee565f74bda816faac028eb4f4feab4
[ "if head == None:\n return None\ndic = {}\ndummy = head\nwhile dummy != None:\n dic[dummy] = RandomListNode(dummy.label)\n dummy = dummy.next\ndummy = head\nwhile dummy != None:\n dic[dummy].next = dic.get(dummy.next)\n dic[dummy].random = dic.get(dummy.random)\n dummy = dummy.next\nreturn dic.get...
<|body_start_0|> if head == None: return None dic = {} dummy = head while dummy != None: dic[dummy] = RandomListNode(dummy.label) dummy = dummy.next dummy = head while dummy != None: dic[dummy].next = dic.get(dummy.next) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def copyRandomList(self, head): """:type head: RandomListNode :rtype: RandomListNode""" <|body_0|> def copyRandomList(self, head): """:type head: RandomListNode :rtype: RandomListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if head...
stack_v2_sparse_classes_10k_train_008359
1,676
no_license
[ { "docstring": ":type head: RandomListNode :rtype: RandomListNode", "name": "copyRandomList", "signature": "def copyRandomList(self, head)" }, { "docstring": ":type head: RandomListNode :rtype: RandomListNode", "name": "copyRandomList", "signature": "def copyRandomList(self, head)" } ]
2
stack_v2_sparse_classes_30k_test_000349
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode - def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode - def copyRandomList(self, head): :type head: RandomListNode :rtype: RandomListNode <|skeleton|...
10798e5b9c33c3f177594ea17cf0398fc117f0a1
<|skeleton|> class Solution: def copyRandomList(self, head): """:type head: RandomListNode :rtype: RandomListNode""" <|body_0|> def copyRandomList(self, head): """:type head: RandomListNode :rtype: RandomListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def copyRandomList(self, head): """:type head: RandomListNode :rtype: RandomListNode""" if head == None: return None dic = {} dummy = head while dummy != None: dic[dummy] = RandomListNode(dummy.label) dummy = dummy.next ...
the_stack_v2_python_sparse
copy-list-with-random-node/copyListWithRandomNode.py
NanXiangPU/leetcode
train
0
93fcea611e99e3137b1b6047c362ac72cb988275
[ "row = g.db.query(Machine).get(machine_id)\nif not row:\n log.warning('Requested a non-existant machine: %s', machine_id)\n abort(http_client.NOT_FOUND, description='Machine not found')\nrecord = row.as_dict()\nrecord['url'] = url_for('machines.entry', machine_id=machine_id, _external=True)\nrecord['servers_u...
<|body_start_0|> row = g.db.query(Machine).get(machine_id) if not row: log.warning('Requested a non-existant machine: %s', machine_id) abort(http_client.NOT_FOUND, description='Machine not found') record = row.as_dict() record['url'] = url_for('machines.entry', ma...
Information about specific machines
MachineAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MachineAPI: """Information about specific machines""" def get(self, machine_id): """Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json""" <|body_0|> def put(self, machine_id): """Update machine Heartbeat and...
stack_v2_sparse_classes_10k_train_008360
8,672
permissive
[ { "docstring": "Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json", "name": "get", "signature": "def get(self, machine_id)" }, { "docstring": "Update machine Heartbeat and update the machine reference", "name": "put", "signature": ...
2
stack_v2_sparse_classes_30k_train_002684
Implement the Python class `MachineAPI` described below. Class description: Information about specific machines Method signatures and docstrings: - def get(self, machine_id): Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json - def put(self, machine_id): Update ...
Implement the Python class `MachineAPI` described below. Class description: Information about specific machines Method signatures and docstrings: - def get(self, machine_id): Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json - def put(self, machine_id): Update ...
9825cb22b26b577b715f2ce95453363bf90ecc7e
<|skeleton|> class MachineAPI: """Information about specific machines""" def get(self, machine_id): """Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json""" <|body_0|> def put(self, machine_id): """Update machine Heartbeat and...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MachineAPI: """Information about specific machines""" def get(self, machine_id): """Find machine by ID Get information about a single battle server machine. Just dumps out the DB row as json""" row = g.db.query(Machine).get(machine_id) if not row: log.warning('Requeste...
the_stack_v2_python_sparse
driftbase/api/machines.py
dgnorth/drift-base
train
1
88000392ff7ed945a764d5d379e590379727bad8
[ "super().__init__()\nself.enc = enc\nself.mlp = mlp", "_, (hn, _) = self.enc(*args)\ny_pred = self.mlp(hn)\nreturn y_pred", "data = (seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat_data)\nnonempty_tensors, nonempty_idx = get_nonempty_tensors(data)\ny_pred = self(*nonempty_tensors, nonempty_idx)\nlos...
<|body_start_0|> super().__init__() self.enc = enc self.mlp = mlp <|end_body_0|> <|body_start_1|> _, (hn, _) = self.enc(*args) y_pred = self.mlp(hn) return y_pred <|end_body_1|> <|body_start_2|> data = (seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat...
ChurnModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChurnModel: def __init__(self, enc, mlp): """Initialize model with params.""" <|body_0|> def forward(self, *args): """Run a forward pass of model over the data.""" <|body_1|> def run(self, y, seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat_da...
stack_v2_sparse_classes_10k_train_008361
15,906
permissive
[ { "docstring": "Initialize model with params.", "name": "__init__", "signature": "def __init__(self, enc, mlp)" }, { "docstring": "Run a forward pass of model over the data.", "name": "forward", "signature": "def forward(self, *args)" }, { "docstring": "Run model on data and prop...
3
stack_v2_sparse_classes_30k_train_000185
Implement the Python class `ChurnModel` described below. Class description: Implement the ChurnModel class. Method signatures and docstrings: - def __init__(self, enc, mlp): Initialize model with params. - def forward(self, *args): Run a forward pass of model over the data. - def run(self, y, seq_cont_data, seq_cat_d...
Implement the Python class `ChurnModel` described below. Class description: Implement the ChurnModel class. Method signatures and docstrings: - def __init__(self, enc, mlp): Initialize model with params. - def forward(self, *args): Run a forward pass of model over the data. - def run(self, y, seq_cont_data, seq_cat_d...
9cdbf270487751a0ad6862b2fea2ccc0e23a0b67
<|skeleton|> class ChurnModel: def __init__(self, enc, mlp): """Initialize model with params.""" <|body_0|> def forward(self, *args): """Run a forward pass of model over the data.""" <|body_1|> def run(self, y, seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat_da...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ChurnModel: def __init__(self, enc, mlp): """Initialize model with params.""" super().__init__() self.enc = enc self.mlp = mlp def forward(self, *args): """Run a forward pass of model over the data.""" _, (hn, _) = self.enc(*args) y_pred = self.mlp(...
the_stack_v2_python_sparse
caspr/models/model_wrapper.py
microsoft/CASPR
train
29
bc05bd0b36dbe5416c7371340719c386255a58ac
[ "if root is None:\n return\nself.stack.append(root)\nl = root.left\nwhile l:\n self.stack.append(l)\n l = l.left", "if len(self.stack) > 0:\n return True\nreturn False", "smallest = self.stack.pop()\nr = smallest.right\nif r is not None:\n self.stack.append(r)\n l = r.left\n while l:\n ...
<|body_start_0|> if root is None: return self.stack.append(root) l = root.left while l: self.stack.append(l) l = l.left <|end_body_0|> <|body_start_1|> if len(self.stack) > 0: return True return False <|end_body_1|> <|body...
BSTIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def hasNext(self): """:rtype: bool""" <|body_1|> def next(self): """:rtype: int""" <|body_2|> <|end_skeleton|> <|body_start_0|> if root is None: ...
stack_v2_sparse_classes_10k_train_008362
1,487
no_license
[ { "docstring": ":type root: TreeNode", "name": "__init__", "signature": "def __init__(self, root)" }, { "docstring": ":rtype: bool", "name": "hasNext", "signature": "def hasNext(self)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" } ]
3
null
Implement the Python class `BSTIterator` described below. Class description: Implement the BSTIterator class. Method signatures and docstrings: - def __init__(self, root): :type root: TreeNode - def hasNext(self): :rtype: bool - def next(self): :rtype: int
Implement the Python class `BSTIterator` described below. Class description: Implement the BSTIterator class. Method signatures and docstrings: - def __init__(self, root): :type root: TreeNode - def hasNext(self): :rtype: bool - def next(self): :rtype: int <|skeleton|> class BSTIterator: def __init__(self, root...
dd268af242d18bc2fd9527661c71d2e51af1039d
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def hasNext(self): """:rtype: bool""" <|body_1|> def next(self): """:rtype: int""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BSTIterator: def __init__(self, root): """:type root: TreeNode""" if root is None: return self.stack.append(root) l = root.left while l: self.stack.append(l) l = l.left def hasNext(self): """:rtype: bool""" if len...
the_stack_v2_python_sparse
DS/Tree/Medium/R__173.Binary_Search_Tree_Iterator.py
HotsauceLee/Leetcode
train
2
01d38d164a9b8314bf8d1090e64174179ddac863
[ "if not strs:\n return None\nif strs == ['']:\n return ''\nx = chr(258).join(strs)\nreturn x", "if s is None:\n return None\nif s == '':\n return ['']\nres = s.split(chr(258))\nreturn res" ]
<|body_start_0|> if not strs: return None if strs == ['']: return '' x = chr(258).join(strs) return x <|end_body_0|> <|body_start_1|> if s is None: return None if s == '': return [''] res = s.split(chr(258)) ...
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_10k_train_008363
515
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
null
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...
fb5a930b5ad27e7ed405e5787346327d9b3bf957
<|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_10k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" if not strs: return None if strs == ['']: return '' x = chr(258).join(strs) return x def decode(self, s: str) -> [str]: """Decodes a sin...
the_stack_v2_python_sparse
Jiuzhang_practice/encode_decode_str.py
armstrong019/coding_n_project
train
0
b19f22e532f77f77ab5cf5d38a4012e3cc854230
[ "pos, angle = controller.odometry(10, 10, Vector2(0, 0), 0)\nassert pos == Vector2(0, 0)\nassert angle == 0", "pos, angle = controller.odometry(20, 20, Vector2(0, 0), 0)\nassert pos == Vector2(2 * math.pi * WHEEL_RADIUS * 10 / TICK_PER_REVOLUTION, 0)\nassert angle == 0\npos, angle = controller.odometry(10, 10, Ve...
<|body_start_0|> pos, angle = controller.odometry(10, 10, Vector2(0, 0), 0) assert pos == Vector2(0, 0) assert angle == 0 <|end_body_0|> <|body_start_1|> pos, angle = controller.odometry(20, 20, Vector2(0, 0), 0) assert pos == Vector2(2 * math.pi * WHEEL_RADIUS * 10 / TICK_PER_R...
Test the odometry function.
TestOdometry
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestOdometry: """Test the odometry function.""" def test_did_not_move(controller): """Robot did not move.""" <|body_0|> def test_move_straight(controller): """Robot moved in a straight line.""" <|body_1|> def test_rotate_without_moving(controller): ...
stack_v2_sparse_classes_10k_train_008364
3,622
permissive
[ { "docstring": "Robot did not move.", "name": "test_did_not_move", "signature": "def test_did_not_move(controller)" }, { "docstring": "Robot moved in a straight line.", "name": "test_move_straight", "signature": "def test_move_straight(controller)" }, { "docstring": "Robot rotate...
5
stack_v2_sparse_classes_30k_train_001956
Implement the Python class `TestOdometry` described below. Class description: Test the odometry function. Method signatures and docstrings: - def test_did_not_move(controller): Robot did not move. - def test_move_straight(controller): Robot moved in a straight line. - def test_rotate_without_moving(controller): Robot...
Implement the Python class `TestOdometry` described below. Class description: Test the odometry function. Method signatures and docstrings: - def test_did_not_move(controller): Robot did not move. - def test_move_straight(controller): Robot moved in a straight line. - def test_rotate_without_moving(controller): Robot...
b55d1ce6143ee7ef248fa7a9d6675c693b727d91
<|skeleton|> class TestOdometry: """Test the odometry function.""" def test_did_not_move(controller): """Robot did not move.""" <|body_0|> def test_move_straight(controller): """Robot moved in a straight line.""" <|body_1|> def test_rotate_without_moving(controller): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestOdometry: """Test the odometry function.""" def test_did_not_move(controller): """Robot did not move.""" pos, angle = controller.odometry(10, 10, Vector2(0, 0), 0) assert pos == Vector2(0, 0) assert angle == 0 def test_move_straight(controller): """Robot m...
the_stack_v2_python_sparse
highlevel/robot/controller/motion/odometry_test.py
outech-robotic/hl-flowing-clean-arch
train
2
c5299f241f5cb8708a1411d24e2d406780bd89d1
[ "self.head = Node(0)\nself.tail = Node(0)\nself.head.insert(self.tail)\nself.dic = {}", "if key in self.dic:\n node = self.dic[key]\n if node.next.value == node.value + 1:\n node.next.keys.add(key)\n self.dic[key] = node.next\n node.keys.remove(key)\n if len(node.keys) == 0:\n ...
<|body_start_0|> self.head = Node(0) self.tail = Node(0) self.head.insert(self.tail) self.dic = {} <|end_body_0|> <|body_start_1|> if key in self.dic: node = self.dic[key] if node.next.value == node.value + 1: node.next.keys.add(key) ...
AllOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -> None: """Decr...
stack_v2_sparse_classes_10k_train_008365
3,186
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.", "name": "inc", "signature": "def inc(self, key: str) -> None" }, { "docstrin...
5
null
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, ...
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, ...
920b65db80031fad45d495431eda8d3fb4ef06e5
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -> None: """Decr...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AllOne: def __init__(self): """Initialize your data structure here.""" self.head = Node(0) self.tail = Node(0) self.head.insert(self.tail) self.dic = {} def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key ...
the_stack_v2_python_sparse
hard/ex432.py
ziyuan-shen/leetcode_algorithm_python_solution
train
2
da34c3f5ebfb7c342b52fd829cbd21838c150cf6
[ "super(Filterer, self).__init__()\nself.expression = expression\nself.target = target\nself._event = event\nself._regex = None\nreturn", "if self._event is None:\n self._event = DummyEvent()\nreturn self._event", "if self._regex is None:\n self._regex = re.compile(self.expression)\nreturn self._regex", ...
<|body_start_0|> super(Filterer, self).__init__() self.expression = expression self.target = target self._event = event self._regex = None return <|end_body_0|> <|body_start_1|> if self._event is None: self._event = DummyEvent() return self._e...
A Filterer filters out strings that don't match an expression.
Filterer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Filterer: """A Filterer filters out strings that don't match an expression.""" def __init__(self, expression, target, event=None): """:param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter...
stack_v2_sparse_classes_10k_train_008366
1,774
permissive
[ { "docstring": ":param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter", "name": "__init__", "signature": "def __init__(self, expression, target, event=None)" }, { "docstring": ":return: threading eve...
4
null
Implement the Python class `Filterer` described below. Class description: A Filterer filters out strings that don't match an expression. Method signatures and docstrings: - def __init__(self, expression, target, event=None): :param: - `expression`: A regular expression. - `target`: a target to send matching strings t...
Implement the Python class `Filterer` described below. Class description: A Filterer filters out strings that don't match an expression. Method signatures and docstrings: - def __init__(self, expression, target, event=None): :param: - `expression`: A regular expression. - `target`: a target to send matching strings t...
b4d1c77e1d611fe2b30768b42bdc7493afb0ea95
<|skeleton|> class Filterer: """A Filterer filters out strings that don't match an expression.""" def __init__(self, expression, target, event=None): """:param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Filterer: """A Filterer filters out strings that don't match an expression.""" def __init__(self, expression, target, event=None): """:param: - `expression`: A regular expression. - `target`: a target to send matching strings to - `event`: an Event to activate flow through the filter""" s...
the_stack_v2_python_sparse
apetools/commons/filterer.py
russell-n/oldape
train
0
5a866f7ed3243b014c36d9fffeec10b9cd2b94f3
[ "if db_field.name == 'author':\n kwargs['initial'] = request.user.id\nreturn super().formfield_for_foreignkey(db_field, request, **kwargs)", "try:\n profile = Profile.objects.get(user=request.user)\nexcept Profile.DoesNotExist:\n if request.user.is_superuser:\n return Mark.objects.all()\nif profil...
<|body_start_0|> if db_field.name == 'author': kwargs['initial'] = request.user.id return super().formfield_for_foreignkey(db_field, request, **kwargs) <|end_body_0|> <|body_start_1|> try: profile = Profile.objects.get(user=request.user) except Profile.DoesNotExi...
MarksAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarksAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" <|body_0|> def get_queryset(self, request): """Get all marks for current profile""" <|body_1|> <|end_skeleton|> <|body_start_0|> if db_field.name ...
stack_v2_sparse_classes_10k_train_008367
2,628
no_license
[ { "docstring": "Set default teacher", "name": "formfield_for_foreignkey", "signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)" }, { "docstring": "Get all marks for current profile", "name": "get_queryset", "signature": "def get_queryset(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_000901
Implement the Python class `MarksAdmin` described below. Class description: Implement the MarksAdmin class. Method signatures and docstrings: - def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher - def get_queryset(self, request): Get all marks for current profile
Implement the Python class `MarksAdmin` described below. Class description: Implement the MarksAdmin class. Method signatures and docstrings: - def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher - def get_queryset(self, request): Get all marks for current profile <|skeleton|> class ...
76c0df6f07f41f4baf7346acdbbf316b4dd13ee5
<|skeleton|> class MarksAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" <|body_0|> def get_queryset(self, request): """Get all marks for current profile""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MarksAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" if db_field.name == 'author': kwargs['initial'] = request.user.id return super().formfield_for_foreignkey(db_field, request, **kwargs) def get_queryset(self, request)...
the_stack_v2_python_sparse
journal/admin.py
HallrizonX/api_chpk
train
3
d2ae0f4ebdae9ea9bd656d6280854923752afeb8
[ "def dfs(node):\n if not node:\n return\n eq = node.val == p.val or node.val == q.val\n l = dfs(node.left)\n if eq and l:\n return node\n r = dfs(node.right)\n if eq and r:\n return node\n if l and r:\n return node\n return eq and node or l or r\nreturn dfs(root)"...
<|body_start_0|> def dfs(node): if not node: return eq = node.val == p.val or node.val == q.val l = dfs(node.left) if eq and l: return node r = dfs(node.right) if eq and r: return node ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lowestCommonAncestor(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" <|body_0|> def test(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" <|body...
stack_v2_sparse_classes_10k_train_008368
1,406
no_license
[ { "docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode", "name": "lowestCommonAncestor", "signature": "def lowestCommonAncestor(self, root, p, q)" }, { "docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode", "name": "test",...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode - def test(self, root, p, q): :type root: TreeNode :type p: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode - def test(self, root, p, q): :type root: TreeNode :type p: ...
4599634f31d78a0372cf0ff6fb7935d054d5ecb5
<|skeleton|> class Solution: def lowestCommonAncestor(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" <|body_0|> def test(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" <|body...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def lowestCommonAncestor(self, root, p, q): """:type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""" def dfs(node): if not node: return eq = node.val == p.val or node.val == q.val l = dfs(node.left) ...
the_stack_v2_python_sparse
leetcode_python/201-300/236.py
jhgdike/leetCode
train
3
765e942119ad5c735ba49c67ca98f3ce40a55ace
[ "node_list = response.xpath(\"//tr[@class='even'] | //tr[@class='odd']\")\nfor node in node_list:\n item = TencentItem()\n item['position_name'] = node.xpath('./td[1]/a/text()').extract_first()\n item['position_link'] = 'https://hr.tencent.com/' + node.xpath('./td[1]/a/@href').extract_first()\n item['po...
<|body_start_0|> node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for node in node_list: item = TencentItem() item['position_name'] = node.xpath('./td[1]/a/text()').extract_first() item['position_link'] = 'https://hr.tencent.com/' + node.xpath('....
TencentSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TencentSpider: def parse(self, response): """默认列表页的解析方法""" <|body_0|> def parse_detail(self, response): """解析详情页的响应内容""" <|body_1|> <|end_skeleton|> <|body_start_0|> node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for ...
stack_v2_sparse_classes_10k_train_008369
2,985
no_license
[ { "docstring": "默认列表页的解析方法", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "解析详情页的响应内容", "name": "parse_detail", "signature": "def parse_detail(self, response)" } ]
2
stack_v2_sparse_classes_30k_train_001900
Implement the Python class `TencentSpider` described below. Class description: Implement the TencentSpider class. Method signatures and docstrings: - def parse(self, response): 默认列表页的解析方法 - def parse_detail(self, response): 解析详情页的响应内容
Implement the Python class `TencentSpider` described below. Class description: Implement the TencentSpider class. Method signatures and docstrings: - def parse(self, response): 默认列表页的解析方法 - def parse_detail(self, response): 解析详情页的响应内容 <|skeleton|> class TencentSpider: def parse(self, response): """默认列表页...
a51e31acff41292e568ac22b0e213e6cb48218fa
<|skeleton|> class TencentSpider: def parse(self, response): """默认列表页的解析方法""" <|body_0|> def parse_detail(self, response): """解析详情页的响应内容""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TencentSpider: def parse(self, response): """默认列表页的解析方法""" node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']") for node in node_list: item = TencentItem() item['position_name'] = node.xpath('./td[1]/a/text()').extract_first() item[...
the_stack_v2_python_sparse
爬虫项目/code10/2.Spider类多级页面数据采集/Tencent2/Tencent2/spiders/tencent2.py
byst4nder/his_spider
train
1
87c34a5ceb0c54dde76385d13c44a47e4f08876a
[ "username = 'test@test.com'\npassword = 'toto'\nself.client.post(reverse(register), {'username': username, 'password': password})\nresponse = self.client.post(reverse(obtain_auth_token), {'username': username, 'password': password}, format='json')\nself.token = json.loads(response.content)['token']\nself.client.get...
<|body_start_0|> username = 'test@test.com' password = 'toto' self.client.post(reverse(register), {'username': username, 'password': password}) response = self.client.post(reverse(obtain_auth_token), {'username': username, 'password': password}, format='json') self.token = json.l...
Test the Django/Vue interface.
TestDjangoVueInterface
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDjangoVueInterface: """Test the Django/Vue interface.""" def setUp(self): """Register and log user in.""" <|body_0|> def test_default_monthly_requests_amount(self): """Test that default amount of monthly requests is correct.""" <|body_1|> def tes...
stack_v2_sparse_classes_10k_train_008370
8,751
no_license
[ { "docstring": "Register and log user in.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that default amount of monthly requests is correct.", "name": "test_default_monthly_requests_amount", "signature": "def test_default_monthly_requests_amount(self)" }, {...
4
stack_v2_sparse_classes_30k_train_007118
Implement the Python class `TestDjangoVueInterface` described below. Class description: Test the Django/Vue interface. Method signatures and docstrings: - def setUp(self): Register and log user in. - def test_default_monthly_requests_amount(self): Test that default amount of monthly requests is correct. - def test_de...
Implement the Python class `TestDjangoVueInterface` described below. Class description: Test the Django/Vue interface. Method signatures and docstrings: - def setUp(self): Register and log user in. - def test_default_monthly_requests_amount(self): Test that default amount of monthly requests is correct. - def test_de...
9c0027b84d8dee6044ff28362e2b2b90c1759b90
<|skeleton|> class TestDjangoVueInterface: """Test the Django/Vue interface.""" def setUp(self): """Register and log user in.""" <|body_0|> def test_default_monthly_requests_amount(self): """Test that default amount of monthly requests is correct.""" <|body_1|> def tes...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestDjangoVueInterface: """Test the Django/Vue interface.""" def setUp(self): """Register and log user in.""" username = 'test@test.com' password = 'toto' self.client.post(reverse(register), {'username': username, 'password': password}) response = self.client.post(...
the_stack_v2_python_sparse
django_project/api_core/tests.py
juliensalinas/python-django-api-reactjs-frontend-slate-documentation-various-client-libs
train
3
56ba4a33a842cfedb21b752c31b4dfaeeca1e292
[ "super(OperatorLookupError, self).__init__(operator)\nself.operator = operator\nself.filename = filename\nself.lineno = lineno\nself.block = block", "op = self.operator\ntext = '%s\\n\\n' % op\ntext += _format_source_error(self.filename, self.lineno, self.block)\noptext = \"'%s'\" % op\nif op in self.op_map:\n ...
<|body_start_0|> super(OperatorLookupError, self).__init__(operator) self.operator = operator self.filename = filename self.lineno = lineno self.block = block <|end_body_0|> <|body_start_1|> op = self.operator text = '%s\n\n' % op text += _format_source_e...
A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree.
OperatorLookupError
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OperatorLookupError: """A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree.""" def __init__(self, operator, filename, lineno, block): "...
stack_v2_sparse_classes_10k_train_008371
4,784
permissive
[ { "docstring": "Initialize an OperatorLookupError. Parameters ---------- operator : str The name of the operator which was not found. filename : str The filename where the lookup failed. lineno : int The line number of the error. block : str The name of the lexical block in which the lookup failed.", "name"...
2
null
Implement the Python class `OperatorLookupError` described below. Class description: A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree. Method signatures and docstrings...
Implement the Python class `OperatorLookupError` described below. Class description: A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree. Method signatures and docstrings...
424bba29219de58fe9e47196de6763de8b2009f2
<|skeleton|> class OperatorLookupError: """A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree.""" def __init__(self, operator, filename, lineno, block): "...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class OperatorLookupError: """A LookupError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed operator lookups when building the object tree.""" def __init__(self, operator, filename, lineno, block): """Initialize ...
the_stack_v2_python_sparse
enaml/core/exceptions.py
enthought/enaml
train
17
bba4634fb9d35cce790010d4d057a4be4ea00b86
[ "qs = self.queryset.filter(expiry_date__gt=timezone.now())\nif not self.request.user.groups.filter(name=REGISTRIES_VIEWER_ROLE).exists():\n qs = qs.filter(Q(applications__current_status__code='A'), Q(applications__removal_date__isnull=True))\nreturn qs", "instance = self.get_object()\ninstance.expiry_date = ti...
<|body_start_0|> qs = self.queryset.filter(expiry_date__gt=timezone.now()) if not self.request.user.groups.filter(name=REGISTRIES_VIEWER_ROLE).exists(): qs = qs.filter(Q(applications__current_status__code='A'), Q(applications__removal_date__isnull=True)) return qs <|end_body_0|> <|b...
get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record
PersonDetailView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PersonDetailView: """get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record""" def get_queryset(self): """Returns only registere...
stack_v2_sparse_classes_10k_train_008372
35,975
permissive
[ { "docstring": "Returns only registered people (i.e. drillers with active registration) to anonymous users", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Set expiry_date to current date", "name": "destroy", "signature": "def destroy(self, request, *arg...
2
stack_v2_sparse_classes_30k_train_004005
Implement the Python class `PersonDetailView` described below. Class description: get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record Method signatures and doc...
Implement the Python class `PersonDetailView` described below. Class description: get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record Method signatures and doc...
6be3701a8e0085d0c6fa199b2672b7f9f1266a03
<|skeleton|> class PersonDetailView: """get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record""" def get_queryset(self): """Returns only registere...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PersonDetailView: """get: Returns the specified person put: Replaces the specified person record with a new one patch: Updates a person with the fields/values provided in the request body delete: Removes the specified person record""" def get_queryset(self): """Returns only registered people (i.e...
the_stack_v2_python_sparse
app/backend/registries/views.py
bcgov/gwells
train
39
435f48322403ca8e571f3bccfe8cc3a0a1677b7e
[ "super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries", "self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nsignal = convert_to_tensor(self.magnitude * signal)\nreturn signal" ]
<|body_start_0|> super().__init__() check_boundaries(boundaries) self.boundaries = boundaries <|end_body_0|> <|body_start_1|> self.randomize(None) self.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1]) signal = convert_to_tensor(self.magnitude *...
Apply a random rescaling on a signal
SignalRandScale
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignalRandScale: """Apply a random rescaling on a signal""" def __init__(self, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: """Args: boundaries: list defining lower and upper boundaries for the signal scaling, default : ``[-1.0, 1.0]``""" <|body_0|> def __call__(sel...
stack_v2_sparse_classes_10k_train_008373
16,322
permissive
[ { "docstring": "Args: boundaries: list defining lower and upper boundaries for the signal scaling, default : ``[-1.0, 1.0]``", "name": "__init__", "signature": "def __init__(self, boundaries: Sequence[float]=(-1.0, 1.0)) -> None" }, { "docstring": "Args: signal: input 1 dimension signal to be sc...
2
stack_v2_sparse_classes_30k_train_000948
Implement the Python class `SignalRandScale` described below. Class description: Apply a random rescaling on a signal Method signatures and docstrings: - def __init__(self, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: Args: boundaries: list defining lower and upper boundaries for the signal scaling, default : ``...
Implement the Python class `SignalRandScale` described below. Class description: Apply a random rescaling on a signal Method signatures and docstrings: - def __init__(self, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: Args: boundaries: list defining lower and upper boundaries for the signal scaling, default : ``...
e48c3e2c741fa3fc705c4425d17ac4a5afac6c47
<|skeleton|> class SignalRandScale: """Apply a random rescaling on a signal""" def __init__(self, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: """Args: boundaries: list defining lower and upper boundaries for the signal scaling, default : ``[-1.0, 1.0]``""" <|body_0|> def __call__(sel...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SignalRandScale: """Apply a random rescaling on a signal""" def __init__(self, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: """Args: boundaries: list defining lower and upper boundaries for the signal scaling, default : ``[-1.0, 1.0]``""" super().__init__() check_boundaries(b...
the_stack_v2_python_sparse
monai/transforms/signal/array.py
Project-MONAI/MONAI
train
4,805
471343fb66f19a525015d924c3895bfb6579e480
[ "self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t...
<|body_start_0|> self.client = Client() self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword') self.test_user.is_superuser = True self.test_user.is_active = True self.test_user.save() self.assertEqual(self.test_user.is_superuser, True) ...
This class covers the setup and tear down for all unit tests
BasicTests
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicTests: """This class covers the setup and tear down for all unit tests""" def setUp(self): """Instantiate the test client. Creates a test user.""" <|body_0|> def tearDown(self): """Depopulate created model instances from test database.""" <|body_1|> ...
stack_v2_sparse_classes_10k_train_008374
2,724
permissive
[ { "docstring": "Instantiate the test client. Creates a test user.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Depopulate created model instances from test database.", "name": "tearDown", "signature": "def tearDown(self)" } ]
2
stack_v2_sparse_classes_30k_train_003909
Implement the Python class `BasicTests` described below. Class description: This class covers the setup and tear down for all unit tests Method signatures and docstrings: - def setUp(self): Instantiate the test client. Creates a test user. - def tearDown(self): Depopulate created model instances from test database.
Implement the Python class `BasicTests` described below. Class description: This class covers the setup and tear down for all unit tests Method signatures and docstrings: - def setUp(self): Instantiate the test client. Creates a test user. - def tearDown(self): Depopulate created model instances from test database. ...
d6f6c9c068bbf668c253e5943d9514947023e66d
<|skeleton|> class BasicTests: """This class covers the setup and tear down for all unit tests""" def setUp(self): """Instantiate the test client. Creates a test user.""" <|body_0|> def tearDown(self): """Depopulate created model instances from test database.""" <|body_1|> ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BasicTests: """This class covers the setup and tear down for all unit tests""" def setUp(self): """Instantiate the test client. Creates a test user.""" self.client = Client() self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword') self.test_u...
the_stack_v2_python_sparse
lab_website/tests.py
BridgesLab/Lab-Website
train
0
641fc5ccae14d39fcb46af24add83e19271d92d7
[ "self.abbr_dict = dict()\nfor word in dictionary:\n if len(word) < 3:\n abbr = word\n else:\n abbr = word[0] + str(len(word) - 2) + word[-1]\n if abbr not in self.abbr_dict.keys():\n self.abbr_dict[abbr] = set()\n self.abbr_dict[abbr].add(word)", "if len(word) < 3:\n abbr = wor...
<|body_start_0|> self.abbr_dict = dict() for word in dictionary: if len(word) < 3: abbr = word else: abbr = word[0] + str(len(word) - 2) + word[-1] if abbr not in self.abbr_dict.keys(): self.abbr_dict[abbr] = set() ...
ValidWordAbbr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 1) empty abbr_dict, r...
stack_v2_sparse_classes_10k_train_008375
1,314
no_license
[ { "docstring": ":type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": ":type word: str :rtype: bool A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 1) empty abbr_dict, return True for all ...
2
null
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool A word's abbreviation is unique if no other word fr...
Implement the Python class `ValidWordAbbr` described below. Class description: Implement the ValidWordAbbr class. Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, word): :type word: str :rtype: bool A word's abbreviation is unique if no other word fr...
08c6d27498e35f636045fed05a6f94b760ab69ca
<|skeleton|> class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, word): """:type word: str :rtype: bool A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 1) empty abbr_dict, r...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ValidWordAbbr: def __init__(self, dictionary): """:type dictionary: List[str]""" self.abbr_dict = dict() for word in dictionary: if len(word) < 3: abbr = word else: abbr = word[0] + str(len(word) - 2) + word[-1] if abb...
the_stack_v2_python_sparse
solutions/design/288.Unique.Word.Abbreviation.py
ljia2/leetcode.py
train
0
4763bebac4d86b4e61cbce3d297de04ebbcc7d01
[ "self.domain_obj = domains.DiscreteNumericDomain([4, 5, 207.2, -2.3])\nself.points = [207.2, 5, -2.3]\nself.non_points = [5.4, -1.1, 'kky', None]", "self.report('Testing if exception is raised for non numeric elements in a ' + 'discrete domain.')\nexception_raised = False\ntry:\n domains.DiscreteNumericDomain(...
<|body_start_0|> self.domain_obj = domains.DiscreteNumericDomain([4, 5, 207.2, -2.3]) self.points = [207.2, 5, -2.3] self.non_points = [5.4, -1.1, 'kky', None] <|end_body_0|> <|body_start_1|> self.report('Testing if exception is raised for non numeric elements in a ' + 'discrete domain....
Discrete Numeric Domain.
DiscreteNumericDomainTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiscreteNumericDomainTestCase: """Discrete Numeric Domain.""" def _child_set_up(self): """Child set up.""" <|body_0|> def test_non_numeric_discrete_domain(self): """Constructor.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.domain_obj = d...
stack_v2_sparse_classes_10k_train_008376
5,755
permissive
[ { "docstring": "Child set up.", "name": "_child_set_up", "signature": "def _child_set_up(self)" }, { "docstring": "Constructor.", "name": "test_non_numeric_discrete_domain", "signature": "def test_non_numeric_discrete_domain(self)" } ]
2
stack_v2_sparse_classes_30k_train_005081
Implement the Python class `DiscreteNumericDomainTestCase` described below. Class description: Discrete Numeric Domain. Method signatures and docstrings: - def _child_set_up(self): Child set up. - def test_non_numeric_discrete_domain(self): Constructor.
Implement the Python class `DiscreteNumericDomainTestCase` described below. Class description: Discrete Numeric Domain. Method signatures and docstrings: - def _child_set_up(self): Child set up. - def test_non_numeric_discrete_domain(self): Constructor. <|skeleton|> class DiscreteNumericDomainTestCase: """Discre...
3eef7d30bcc2e56f2221a624bd8ec7f933f81e40
<|skeleton|> class DiscreteNumericDomainTestCase: """Discrete Numeric Domain.""" def _child_set_up(self): """Child set up.""" <|body_0|> def test_non_numeric_discrete_domain(self): """Constructor.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DiscreteNumericDomainTestCase: """Discrete Numeric Domain.""" def _child_set_up(self): """Child set up.""" self.domain_obj = domains.DiscreteNumericDomain([4, 5, 207.2, -2.3]) self.points = [207.2, 5, -2.3] self.non_points = [5.4, -1.1, 'kky', None] def test_non_numer...
the_stack_v2_python_sparse
dragonfly/exd/unittest_domains.py
dragonfly/dragonfly
train
868
b8398bf58bd93cd1a684f97de3d308f3e884b86e
[ "p = PizzaList()\np.create(Pizza('alegg1', 'alegg2'))\nself.assertEqual(1, len(p.pizza_list))", "p = PizzaList()\np.create(Pizza('alegg1', 'alegg2', 'alegg3'))\np.create(Pizza('alegg1', 'alegg2', 'alegg3'))\np.create(Pizza('alegg1', 'alegg2', 'alegg3'))\np.serve(2)\nself.assertEqual(p.getPizza(2).servedStatus, 's...
<|body_start_0|> p = PizzaList() p.create(Pizza('alegg1', 'alegg2')) self.assertEqual(1, len(p.pizza_list)) <|end_body_0|> <|body_start_1|> p = PizzaList() p.create(Pizza('alegg1', 'alegg2', 'alegg3')) p.create(Pizza('alegg1', 'alegg2', 'alegg3')) p.create(Pizza(...
MyTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyTest: def createTest(self): """Tests the create function""" <|body_0|> def serveTest(self): """Tests the serve function""" <|body_1|> def removeTest(self): """Tests the remove function""" <|body_2|> def testPrint(self): """...
stack_v2_sparse_classes_10k_train_008377
3,166
no_license
[ { "docstring": "Tests the create function", "name": "createTest", "signature": "def createTest(self)" }, { "docstring": "Tests the serve function", "name": "serveTest", "signature": "def serveTest(self)" }, { "docstring": "Tests the remove function", "name": "removeTest", ...
4
stack_v2_sparse_classes_30k_train_001083
Implement the Python class `MyTest` described below. Class description: Implement the MyTest class. Method signatures and docstrings: - def createTest(self): Tests the create function - def serveTest(self): Tests the serve function - def removeTest(self): Tests the remove function - def testPrint(self): Tests the pri...
Implement the Python class `MyTest` described below. Class description: Implement the MyTest class. Method signatures and docstrings: - def createTest(self): Tests the create function - def serveTest(self): Tests the serve function - def removeTest(self): Tests the remove function - def testPrint(self): Tests the pri...
567b129db4ede8d45dec599fc844274bf0953301
<|skeleton|> class MyTest: def createTest(self): """Tests the create function""" <|body_0|> def serveTest(self): """Tests the serve function""" <|body_1|> def removeTest(self): """Tests the remove function""" <|body_2|> def testPrint(self): """...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MyTest: def createTest(self): """Tests the create function""" p = PizzaList() p.create(Pizza('alegg1', 'alegg2')) self.assertEqual(1, len(p.pizza_list)) def serveTest(self): """Tests the serve function""" p = PizzaList() p.create(Pizza('alegg1', 'al...
the_stack_v2_python_sparse
Tímadæmi/Tímadæmi 3/pizzaz.py
helenaj18/Gagnaskipan
train
0
495ab6017d9190fdc4e604d4ee1cfa16f7bf5d67
[ "if not username:\n raise ValueError('Users must have an username.')\nuser = self.model(username=username)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(username=username, password=password)\nuser.is_admin = True\nuser.save(using=self._db)\nreturn user" ]
<|body_start_0|> if not username: raise ValueError('Users must have an username.') user = self.model(username=username) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user = self.create_user(username=username...
MyUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyUserManager: def create_user(self, username, password=None): """Creates and saves a User with the given username and password.""" <|body_0|> def create_superuser(self, username, password): """Creates and saves a superuser with the given username and password.""" ...
stack_v2_sparse_classes_10k_train_008378
5,720
no_license
[ { "docstring": "Creates and saves a User with the given username and password.", "name": "create_user", "signature": "def create_user(self, username, password=None)" }, { "docstring": "Creates and saves a superuser with the given username and password.", "name": "create_superuser", "sign...
2
stack_v2_sparse_classes_30k_train_006401
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, username, password=None): Creates and saves a User with the given username and password. - def create_superuser(self, username, password): Creates...
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, username, password=None): Creates and saves a User with the given username and password. - def create_superuser(self, username, password): Creates...
a92f30a77ad3ba9f97e916d2c0a355641c9397ba
<|skeleton|> class MyUserManager: def create_user(self, username, password=None): """Creates and saves a User with the given username and password.""" <|body_0|> def create_superuser(self, username, password): """Creates and saves a superuser with the given username and password.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MyUserManager: def create_user(self, username, password=None): """Creates and saves a User with the given username and password.""" if not username: raise ValueError('Users must have an username.') user = self.model(username=username) user.set_password(password) ...
the_stack_v2_python_sparse
app/models.py
nlattessi/inspt_tp_final_cpe
train
0
cf58fcdc9b8992c75065587a53a9f5a42e6610bf
[ "well = WellService.get_by_well_id(well_id)\nif well is None:\n return self.format_failure(404, 'Well Not Found')\nreturn self.format_success(200, {'well': well})", "well = WellService.get_by_well_id(well_id)\nif well is None:\n self.format_failure(404, 'Well Not Found')\nreturn self.format_success(200, {'w...
<|body_start_0|> well = WellService.get_by_well_id(well_id) if well is None: return self.format_failure(404, 'Well Not Found') return self.format_success(200, {'well': well}) <|end_body_0|> <|body_start_1|> well = WellService.get_by_well_id(well_id) if well is None: ...
API Resource for /wells/<well_id>/hygiene
WellHygiene
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WellHygiene: """API Resource for /wells/<well_id>/hygiene""" def get(self, well_id, **_): """GET /wells/<well_id>/hygiene""" <|body_0|> def post(self, well_id: str): """POST /wells/<well_id>/hygiene""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_008379
1,884
no_license
[ { "docstring": "GET /wells/<well_id>/hygiene", "name": "get", "signature": "def get(self, well_id, **_)" }, { "docstring": "POST /wells/<well_id>/hygiene", "name": "post", "signature": "def post(self, well_id: str)" } ]
2
stack_v2_sparse_classes_30k_train_005353
Implement the Python class `WellHygiene` described below. Class description: API Resource for /wells/<well_id>/hygiene Method signatures and docstrings: - def get(self, well_id, **_): GET /wells/<well_id>/hygiene - def post(self, well_id: str): POST /wells/<well_id>/hygiene
Implement the Python class `WellHygiene` described below. Class description: API Resource for /wells/<well_id>/hygiene Method signatures and docstrings: - def get(self, well_id, **_): GET /wells/<well_id>/hygiene - def post(self, well_id: str): POST /wells/<well_id>/hygiene <|skeleton|> class WellHygiene: """API...
8ab4034413262ff2271740d73df72b3d83ce5918
<|skeleton|> class WellHygiene: """API Resource for /wells/<well_id>/hygiene""" def get(self, well_id, **_): """GET /wells/<well_id>/hygiene""" <|body_0|> def post(self, well_id: str): """POST /wells/<well_id>/hygiene""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WellHygiene: """API Resource for /wells/<well_id>/hygiene""" def get(self, well_id, **_): """GET /wells/<well_id>/hygiene""" well = WellService.get_by_well_id(well_id) if well is None: return self.format_failure(404, 'Well Not Found') return self.format_success...
the_stack_v2_python_sparse
app/main/controllers/wells/well_hygiene_controller.py
Malawi-Water-Wells-project/malawi-auth-api
train
1
9eeb378858e67d613479fa41aed968acb7d98a55
[ "student = g.user\napply = StayApplyModel.objects(student=student).first()\nreturn self.unicode_safe_json_response({'value': apply.value}, 200)", "student = g.user\nnow = datetime.now()\nif current_app.testing or (now.weekday() == 6 and now.time() > time(20, 30)) or 0 <= now.weekday() < 3 or (now.weekday() == 3 a...
<|body_start_0|> student = g.user apply = StayApplyModel.objects(student=student).first() return self.unicode_safe_json_response({'value': apply.value}, 200) <|end_body_0|> <|body_start_1|> student = g.user now = datetime.now() if current_app.testing or (now.weekday() ==...
Stay
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Stay: def get(self): """잔류신청 정보 조회""" <|body_0|> def post(self): """잔류신청""" <|body_1|> <|end_skeleton|> <|body_start_0|> student = g.user apply = StayApplyModel.objects(student=student).first() return self.unicode_safe_json_response(...
stack_v2_sparse_classes_10k_train_008380
1,418
permissive
[ { "docstring": "잔류신청 정보 조회", "name": "get", "signature": "def get(self)" }, { "docstring": "잔류신청", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_002545
Implement the Python class `Stay` described below. Class description: Implement the Stay class. Method signatures and docstrings: - def get(self): 잔류신청 정보 조회 - def post(self): 잔류신청
Implement the Python class `Stay` described below. Class description: Implement the Stay class. Method signatures and docstrings: - def get(self): 잔류신청 정보 조회 - def post(self): 잔류신청 <|skeleton|> class Stay: def get(self): """잔류신청 정보 조회""" <|body_0|> def post(self): """잔류신청""" ...
de585fe904a2bf15f9fc74219eae176151a0f8ca
<|skeleton|> class Stay: def get(self): """잔류신청 정보 조회""" <|body_0|> def post(self): """잔류신청""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Stay: def get(self): """잔류신청 정보 조회""" student = g.user apply = StayApplyModel.objects(student=student).first() return self.unicode_safe_json_response({'value': apply.value}, 200) def post(self): """잔류신청""" student = g.user now = datetime.now() ...
the_stack_v2_python_sparse
Server/app/views/v1/student/apply/stay.py
miraedbswo/DMS-Backend
train
2
8def3f581639a798530279009a9154d96ef2f8dd
[ "prec_edges = main_model.external_precursor_nodes_names\ngraph_inputs = GlobalContext().onnx_graph_info.get('graph_inputs')\ninputs = dict()\nfor edge in graph_inputs:\n if not edge in inputs and edge in prec_edges:\n regular_edge = MatcherHelper.regular_edge_name(edge)\n inputs[edge] = regular_edg...
<|body_start_0|> prec_edges = main_model.external_precursor_nodes_names graph_inputs = GlobalContext().onnx_graph_info.get('graph_inputs') inputs = dict() for edge in graph_inputs: if not edge in inputs and edge in prec_edges: regular_edge = MatcherHelper.regu...
Helper function for matching processing.
MatcherHelper
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MatcherHelper: """Helper function for matching processing.""" def main_model_special_process_inputs(main_model: ModuleStruct): """Call in preprocess""" <|body_0|> def regular_edge_name(name: str) -> str: """Regular the edge name to adapt the python grammar.""" ...
stack_v2_sparse_classes_10k_train_008381
8,903
permissive
[ { "docstring": "Call in preprocess", "name": "main_model_special_process_inputs", "signature": "def main_model_special_process_inputs(main_model: ModuleStruct)" }, { "docstring": "Regular the edge name to adapt the python grammar.", "name": "regular_edge_name", "signature": "def regular_...
6
stack_v2_sparse_classes_30k_train_003329
Implement the Python class `MatcherHelper` described below. Class description: Helper function for matching processing. Method signatures and docstrings: - def main_model_special_process_inputs(main_model: ModuleStruct): Call in preprocess - def regular_edge_name(name: str) -> str: Regular the edge name to adapt the ...
Implement the Python class `MatcherHelper` described below. Class description: Helper function for matching processing. Method signatures and docstrings: - def main_model_special_process_inputs(main_model: ModuleStruct): Call in preprocess - def regular_edge_name(name: str) -> str: Regular the edge name to adapt the ...
9073ef36d7f750c72262c87779e77e7c3602dd83
<|skeleton|> class MatcherHelper: """Helper function for matching processing.""" def main_model_special_process_inputs(main_model: ModuleStruct): """Call in preprocess""" <|body_0|> def regular_edge_name(name: str) -> str: """Regular the edge name to adapt the python grammar.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MatcherHelper: """Helper function for matching processing.""" def main_model_special_process_inputs(main_model: ModuleStruct): """Call in preprocess""" prec_edges = main_model.external_precursor_nodes_names graph_inputs = GlobalContext().onnx_graph_info.get('graph_inputs') ...
the_stack_v2_python_sparse
mindinsight/mindconverter/graph_based_converter/generator/matcher.py
nimengliusha/mindinsight
train
0
62b33bf62ce4d87ded30504248ac66f7871778a0
[ "if namespace is None:\n self.use_main_ns = 1\nelse:\n self.use_main_ns = 0\n self.namespace = namespace\nif global_namespace is None:\n self.global_namespace = {}\nelse:\n self.global_namespace = global_namespace", "if self.use_main_ns:\n raise RuntimeError('Namespace must be provided!')\nif '....
<|body_start_0|> if namespace is None: self.use_main_ns = 1 else: self.use_main_ns = 0 self.namespace = namespace if global_namespace is None: self.global_namespace = {} else: self.global_namespace = global_namespace <|end_body_...
Completer
[ "EPL-1.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Completer: def __init__(self, namespace=None, global_namespace=None): """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__...
stack_v2_sparse_classes_10k_train_008382
6,762
permissive
[ { "docstring": "Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. An optional second namespace...
4
null
Implement the Python class `Completer` described below. Class description: Implement the Completer class. Method signatures and docstrings: - def __init__(self, namespace=None, global_namespace=None): Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspec...
Implement the Python class `Completer` described below. Class description: Implement the Completer class. Method signatures and docstrings: - def __init__(self, namespace=None, global_namespace=None): Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspec...
05dbd4575d01a213f3f4d69aa4968473f2536142
<|skeleton|> class Completer: def __init__(self, namespace=None, global_namespace=None): """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Completer: def __init__(self, namespace=None, global_namespace=None): """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Names...
the_stack_v2_python_sparse
python/helpers/pydev/_pydev_bundle/_pydev_completer.py
JetBrains/intellij-community
train
16,288
04ce70de1e5ebc55ae65200088df561b8c34761a
[ "self.alive: bool = False\nself.console: Console = console\nsession = requests.session()\nretry = Retry(total=OtRobot.RETRIES, read=OtRobot.RETRIES, connect=OtRobot.RETRIES, backoff_factor=OtRobot.BACK_OFF_FACTOR, status_forcelist=OtRobot.ERROR_CODES)\nadapter = HTTPAdapter(max_retries=retry)\nsession.mount('http:/...
<|body_start_0|> self.alive: bool = False self.console: Console = console session = requests.session() retry = Retry(total=OtRobot.RETRIES, read=OtRobot.RETRIES, connect=OtRobot.RETRIES, backoff_factor=OtRobot.BACK_OFF_FACTOR, status_forcelist=OtRobot.ERROR_CODES) adapter = HTTPA...
Opentrons Robot.
OtRobot
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OtRobot: """Opentrons Robot.""" def __init__(self, console: Console, robot_data: RobotDataType) -> None: """Initialize the robot.""" <|body_0|> def is_alive(self) -> bool: """Is a robot available by http - request the openapi.json.""" <|body_1|> def ...
stack_v2_sparse_classes_10k_train_008383
5,029
permissive
[ { "docstring": "Initialize the robot.", "name": "__init__", "signature": "def __init__(self, console: Console, robot_data: RobotDataType) -> None" }, { "docstring": "Is a robot available by http - request the openapi.json.", "name": "is_alive", "signature": "def is_alive(self) -> bool" ...
6
null
Implement the Python class `OtRobot` described below. Class description: Opentrons Robot. Method signatures and docstrings: - def __init__(self, console: Console, robot_data: RobotDataType) -> None: Initialize the robot. - def is_alive(self) -> bool: Is a robot available by http - request the openapi.json. - def get_...
Implement the Python class `OtRobot` described below. Class description: Opentrons Robot. Method signatures and docstrings: - def __init__(self, console: Console, robot_data: RobotDataType) -> None: Initialize the robot. - def is_alive(self) -> bool: Is a robot available by http - request the openapi.json. - def get_...
026b523c8c9e5d45910c490efb89194d72595be9
<|skeleton|> class OtRobot: """Opentrons Robot.""" def __init__(self, console: Console, robot_data: RobotDataType) -> None: """Initialize the robot.""" <|body_0|> def is_alive(self) -> bool: """Is a robot available by http - request the openapi.json.""" <|body_1|> def ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class OtRobot: """Opentrons Robot.""" def __init__(self, console: Console, robot_data: RobotDataType) -> None: """Initialize the robot.""" self.alive: bool = False self.console: Console = console session = requests.session() retry = Retry(total=OtRobot.RETRIES, read=OtRo...
the_stack_v2_python_sparse
app-testing/automation/resources/ot_robot.py
Opentrons/opentrons
train
326
7eae07e3f21efe42555adc9f7c3cc9b06fc4e13c
[ "assert 0 < eta, 'Efficiency of boiler should be greater 0.' + ' Check your input for eta.'\nassert eta <= 1, 'Efficiency of boiler should smaller or equal to 1.' + ' Check your input for eta.'\nsuper(BoilerExtended, self).__init__(environment=environment, qNominal=q_nominal, tMax=t_max, lowerActivationLimit=lower_...
<|body_start_0|> assert 0 < eta, 'Efficiency of boiler should be greater 0.' + ' Check your input for eta.' assert eta <= 1, 'Efficiency of boiler should smaller or equal to 1.' + ' Check your input for eta.' super(BoilerExtended, self).__init__(environment=environment, qNominal=q_nominal, tMax=...
BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power
BoilerExtended
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BoilerExtended: """BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power""" def __init__(self, environment, q_nominal, eta, t_max=85, lower_activation_limit=0.2): """Parameters ---------- env...
stack_v2_sparse_classes_10k_train_008384
6,053
permissive
[ { "docstring": "Parameters ---------- environment : Extended environment object Common to all other objects. Includes time and weather instances q_nominal : float nominal heat output in W eta : float efficiency (without unit) t_max : Integer, optional maximum provided temperature in °C (default : 85 °C) lower_a...
5
stack_v2_sparse_classes_30k_train_005077
Implement the Python class `BoilerExtended` described below. Class description: BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power Method signatures and docstrings: - def __init__(self, environment, q_nominal, eta, t_max=8...
Implement the Python class `BoilerExtended` described below. Class description: BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power Method signatures and docstrings: - def __init__(self, environment, q_nominal, eta, t_max=8...
99fd0dab7f9a9030fd84ba4715753364662927ec
<|skeleton|> class BoilerExtended: """BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power""" def __init__(self, environment, q_nominal, eta, t_max=85, lower_activation_limit=0.2): """Parameters ---------- env...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BoilerExtended: """BoilerExtended class (inheritance from pycity Boiler class) Derives from boiler (HeatingDevice) of pycity. self.totalQOutput self.array_fuel_power""" def __init__(self, environment, q_nominal, eta, t_max=85, lower_activation_limit=0.2): """Parameters ---------- environment : Ex...
the_stack_v2_python_sparse
pycity_calc/energysystems/boiler.py
RWTH-EBC/pyCity_calc
train
4
490b8cb3534d501c235da6e93a5d649dbb153400
[ "resp = req.get_response(self.app, method='HEAD')\nacl = resp.object_acl if req.is_object_request else resp.bucket_acl\nresp = HTTPOk()\nresp.body = tostring(acl.elem())\nreturn resp", "if req.is_object_request:\n headers = {}\n src_path = '/%s/%s' % (req.container_name, req.object_name)\n headers['X-Cop...
<|body_start_0|> resp = req.get_response(self.app, method='HEAD') acl = resp.object_acl if req.is_object_request else resp.bucket_acl resp = HTTPOk() resp.body = tostring(acl.elem()) return resp <|end_body_0|> <|body_start_1|> if req.is_object_request: header...
Handles the following APIs: * GET Bucket acl * PUT Bucket acl * GET Object acl * PUT Object acl Those APIs are logged as ACL operations in the S3 server log.
S3AclController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class S3AclController: """Handles the following APIs: * GET Bucket acl * PUT Bucket acl * GET Object acl * PUT Object acl Those APIs are logged as ACL operations in the S3 server log.""" def GET(self, req): """Handles GET Bucket acl and GET Object acl.""" <|body_0|> def PUT(se...
stack_v2_sparse_classes_10k_train_008385
2,097
permissive
[ { "docstring": "Handles GET Bucket acl and GET Object acl.", "name": "GET", "signature": "def GET(self, req)" }, { "docstring": "Handles PUT Bucket acl and PUT Object acl.", "name": "PUT", "signature": "def PUT(self, req)" } ]
2
stack_v2_sparse_classes_30k_train_001369
Implement the Python class `S3AclController` described below. Class description: Handles the following APIs: * GET Bucket acl * PUT Bucket acl * GET Object acl * PUT Object acl Those APIs are logged as ACL operations in the S3 server log. Method signatures and docstrings: - def GET(self, req): Handles GET Bucket acl ...
Implement the Python class `S3AclController` described below. Class description: Handles the following APIs: * GET Bucket acl * PUT Bucket acl * GET Object acl * PUT Object acl Those APIs are logged as ACL operations in the S3 server log. Method signatures and docstrings: - def GET(self, req): Handles GET Bucket acl ...
f06e5369579599648cc78e4b556887bc6d978c2b
<|skeleton|> class S3AclController: """Handles the following APIs: * GET Bucket acl * PUT Bucket acl * GET Object acl * PUT Object acl Those APIs are logged as ACL operations in the S3 server log.""" def GET(self, req): """Handles GET Bucket acl and GET Object acl.""" <|body_0|> def PUT(se...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class S3AclController: """Handles the following APIs: * GET Bucket acl * PUT Bucket acl * GET Object acl * PUT Object acl Those APIs are logged as ACL operations in the S3 server log.""" def GET(self, req): """Handles GET Bucket acl and GET Object acl.""" resp = req.get_response(self.app, metho...
the_stack_v2_python_sparse
swift/common/middleware/s3api/controllers/s3_acl.py
openstack/swift
train
2,370
897a5b25f1ee712c2048b3ec66837a56cdfc0bf5
[ "pip_manager = PipManager.get_singleton()\npip_manager.install_pip(lazy=True, op=op)\nadd_command_line_sys_path()\ndependency_install_command = [_get_python_exe_path(), '-m', 'pip', 'install', '--no-cache-dir', self.package_name]\nlog_report('INFO', f'Installing dependency with {dependency_install_command}', op)\ns...
<|body_start_0|> pip_manager = PipManager.get_singleton() pip_manager.install_pip(lazy=True, op=op) add_command_line_sys_path() dependency_install_command = [_get_python_exe_path(), '-m', 'pip', 'install', '--no-cache-dir', self.package_name] log_report('INFO', f'Installing depen...
Class that describes an optional Python dependency of the addon.
OptionalDependency
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptionalDependency: """Class that describes an optional Python dependency of the addon.""" def install(self, op=None): """Install this dependency.""" <|body_0|> def uninstall(self, remove_sys_path=True, op=None): """Uninstall this dependency.""" <|body_1|...
stack_v2_sparse_classes_10k_train_008386
14,831
permissive
[ { "docstring": "Install this dependency.", "name": "install", "signature": "def install(self, op=None)" }, { "docstring": "Uninstall this dependency.", "name": "uninstall", "signature": "def uninstall(self, remove_sys_path=True, op=None)" } ]
2
stack_v2_sparse_classes_30k_train_004546
Implement the Python class `OptionalDependency` described below. Class description: Class that describes an optional Python dependency of the addon. Method signatures and docstrings: - def install(self, op=None): Install this dependency. - def uninstall(self, remove_sys_path=True, op=None): Uninstall this dependency.
Implement the Python class `OptionalDependency` described below. Class description: Class that describes an optional Python dependency of the addon. Method signatures and docstrings: - def install(self, op=None): Install this dependency. - def uninstall(self, remove_sys_path=True, op=None): Uninstall this dependency....
da404ebf8d4412196c2740f0b569cbf9e542952d
<|skeleton|> class OptionalDependency: """Class that describes an optional Python dependency of the addon.""" def install(self, op=None): """Install this dependency.""" <|body_0|> def uninstall(self, remove_sys_path=True, op=None): """Uninstall this dependency.""" <|body_1|...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class OptionalDependency: """Class that describes an optional Python dependency of the addon.""" def install(self, op=None): """Install this dependency.""" pip_manager = PipManager.get_singleton() pip_manager.install_pip(lazy=True, op=op) add_command_line_sys_path() depe...
the_stack_v2_python_sparse
photogrammetry_importer/preferences/dependency.py
SBCV/Blender-Addon-Photogrammetry-Importer
train
718
435f48322403ca8e571f3bccfe8cc3a0a1677b7e
[ "super().__init__()\ncheck_boundaries(boundaries)\nself.boundaries = boundaries", "self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nlength = signal.shape[1]\ngaussiannoise = self.magnitude * torch.randn(length)\nsignal = convert_to_tensor(signal) + gaussianno...
<|body_start_0|> super().__init__() check_boundaries(boundaries) self.boundaries = boundaries <|end_body_0|> <|body_start_1|> self.randomize(None) self.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1]) length = signal.shape[1] gaussianno...
Add a random gaussian noise to the input signal
SignalRandAddGaussianNoise
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignalRandAddGaussianNoise: """Add a random gaussian noise to the input signal""" def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: """Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``""" <|bod...
stack_v2_sparse_classes_10k_train_008387
16,322
permissive
[ { "docstring": "Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``", "name": "__init__", "signature": "def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None" }, { "docstring": "Args: signal: input 1 dimension signal to ...
2
stack_v2_sparse_classes_30k_train_002501
Implement the Python class `SignalRandAddGaussianNoise` described below. Class description: Add a random gaussian noise to the input signal Method signatures and docstrings: - def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: Args: boundaries: list defining lower and upper boundaries for the sign...
Implement the Python class `SignalRandAddGaussianNoise` described below. Class description: Add a random gaussian noise to the input signal Method signatures and docstrings: - def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: Args: boundaries: list defining lower and upper boundaries for the sign...
e48c3e2c741fa3fc705c4425d17ac4a5afac6c47
<|skeleton|> class SignalRandAddGaussianNoise: """Add a random gaussian noise to the input signal""" def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: """Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``""" <|bod...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SignalRandAddGaussianNoise: """Add a random gaussian noise to the input signal""" def __init__(self, boundaries: Sequence[float]=(0.001, 0.02)) -> None: """Args: boundaries: list defining lower and upper boundaries for the signal magnitude, default : ``[0.001,0.02]``""" super().__init__()...
the_stack_v2_python_sparse
monai/transforms/signal/array.py
Project-MONAI/MONAI
train
4,805
555e4586db963ddad37b0f87e242791794d8ecf9
[ "self.encode_res = ''\nfor i in strs:\n self.encode_res += str(len(i)) + ','\n self.encode_res += i + ','\nreturn self.encode_res[:-1]", "self.decode_res = []\ni = 0\nwhile i < len(s):\n len_word = ''\n while s[i] != ',':\n len_word += s[i]\n i += 1\n start = i + 1\n end = start + ...
<|body_start_0|> self.encode_res = '' for i in strs: self.encode_res += str(len(i)) + ',' self.encode_res += i + ',' return self.encode_res[:-1] <|end_body_0|> <|body_start_1|> self.decode_res = [] i = 0 while i < len(s): len_word = ''...
Codec
[ "MIT" ]
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|> self.enco...
stack_v2_sparse_classes_10k_train_008388
2,072
permissive
[ { "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
null
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...
1dbd18114ed688ddeaa3ee83181d373dcc1429e5
<|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_10k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, strs: [str]) -> str: """Encodes a list of strings to a single string.""" self.encode_res = '' for i in strs: self.encode_res += str(len(i)) + ',' self.encode_res += i + ',' return self.encode_res[:-1] def decode(self, s: str)...
the_stack_v2_python_sparse
source/Clarification/Array/271.字符串的编码与解码.py
zhangwang0537/LeetCode-Notebook
train
0
1451ccf5ff0951b9c8a222db4384a22ec0166fec
[ "super(ConvolutionModule, self).__init__()\nassert (depthwise_kernel_size - 1) % 2 == 0, \"kernel_size should be a odd number for 'SAME' padding\"\nself.layer_norm = LayerNorm(embed_dim, export=export)\nself.pointwise_conv1 = torch.nn.Conv1d(embed_dim, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias)\ns...
<|body_start_0|> super(ConvolutionModule, self).__init__() assert (depthwise_kernel_size - 1) % 2 == 0, "kernel_size should be a odd number for 'SAME' padding" self.layer_norm = LayerNorm(embed_dim, export=export) self.pointwise_conv1 = torch.nn.Conv1d(embed_dim, 2 * channels, kernel_siz...
Convolution block used in the conformer block
ConvolutionModule
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LGPL-2.1-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvolutionModule: """Convolution block used in the conformer block""" def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): """Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv laye...
stack_v2_sparse_classes_10k_train_008389
9,087
permissive
[ { "docstring": "Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv layers depthwise_kernel_size: Depthwise conv layer kernel size dropout: dropout value activation_fn: Activation function to use after depthwise convolution kernel bias: If bias should be added to conv layers expo...
2
null
Implement the Python class `ConvolutionModule` described below. Class description: Convolution block used in the conformer block Method signatures and docstrings: - def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): Args: embed_dim: Embedding dime...
Implement the Python class `ConvolutionModule` described below. Class description: Convolution block used in the conformer block Method signatures and docstrings: - def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): Args: embed_dim: Embedding dime...
b60c741f746877293bb85eed6806736fc8fa0ffd
<|skeleton|> class ConvolutionModule: """Convolution block used in the conformer block""" def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): """Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv laye...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ConvolutionModule: """Convolution block used in the conformer block""" def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): """Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv layers depthwise_...
the_stack_v2_python_sparse
kosmos-2/fairseq/fairseq/modules/conformer_layer.py
microsoft/unilm
train
15,313
0a763de92b0b0258170c07b8b039d823b632ce69
[ "self.logger.debug('Start unzipping the file: %s.' % zip_file)\ndir_name = os.path.basename(zip_file).rsplit('.', 1)[0]\nif not unzip_path:\n if add_dir:\n unzip_path = zip_file.rsplit('.', 1)[0]\n else:\n unzip_path = os.path.dirname(zip_file)\nwith zipfile.ZipFile(zip_file, 'r') as f:\n for...
<|body_start_0|> self.logger.debug('Start unzipping the file: %s.' % zip_file) dir_name = os.path.basename(zip_file).rsplit('.', 1)[0] if not unzip_path: if add_dir: unzip_path = zip_file.rsplit('.', 1)[0] else: unzip_path = os.path.dirname...
cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17
MyZip
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyZip: """cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17""" def unzip_file(self, zip_file, unzip_path='', add_dir=False): """unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(s...
stack_v2_sparse_classes_10k_train_008390
2,756
no_license
[ { "docstring": "unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(str) unzipped path add_dir type(bool) whether to add a layer of directory when unzip the file Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-23", "name": "unz...
2
null
Implement the Python class `MyZip` described below. Class description: cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17 Method signatures and docstrings: - def unzip_file(self, zip_file, unzip_path='', add_dir=False): unzip the file. Args: zip_file type(str) ...
Implement the Python class `MyZip` described below. Class description: cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17 Method signatures and docstrings: - def unzip_file(self, zip_file, unzip_path='', add_dir=False): unzip the file. Args: zip_file type(str) ...
2d3490393737b3e5f086cb6623369b988ffce67f
<|skeleton|> class MyZip: """cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17""" def unzip_file(self, zip_file, unzip_path='', add_dir=False): """unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(s...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MyZip: """cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17""" def unzip_file(self, zip_file, unzip_path='', add_dir=False): """unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(str) unzipped ...
the_stack_v2_python_sparse
lib/tools/public/my_zip.py
Lewescaiyong/auto_test_framework
train
1
312588e7ffe7dd1fc6b11cd866583e8563f9c34f
[ "if m >= n:\n return head\nparent = None\np = head\nfor _ in range(m - 1):\n parent = p\n p = p.next\nt = p\ntmp = p.next\nchild = tmp\nfor _ in range(n - m):\n child = tmp\n if child:\n tmp = child.next\n child.next = p\n p = child\n else:\n break\nt.next = tmp\nif par...
<|body_start_0|> if m >= n: return head parent = None p = head for _ in range(m - 1): parent = p p = p.next t = p tmp = p.next child = tmp for _ in range(n - m): child = tmp if child: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseBetween(self, head, m, n): """05/06/2018 01:00""" <|body_0|> def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: """08/08/2021 17:38""" <|body_1|> def reverseBetween(self, head: Optional[L...
stack_v2_sparse_classes_10k_train_008391
3,687
no_license
[ { "docstring": "05/06/2018 01:00", "name": "reverseBetween", "signature": "def reverseBetween(self, head, m, n)" }, { "docstring": "08/08/2021 17:38", "name": "reverseBetween", "signature": "def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]" ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseBetween(self, head, m, n): 05/06/2018 01:00 - def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 08/08/2021 17:38 - def r...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseBetween(self, head, m, n): 05/06/2018 01:00 - def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 08/08/2021 17:38 - def r...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def reverseBetween(self, head, m, n): """05/06/2018 01:00""" <|body_0|> def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: """08/08/2021 17:38""" <|body_1|> def reverseBetween(self, head: Optional[L...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def reverseBetween(self, head, m, n): """05/06/2018 01:00""" if m >= n: return head parent = None p = head for _ in range(m - 1): parent = p p = p.next t = p tmp = p.next child = tmp for _ in ...
the_stack_v2_python_sparse
leetcode/solved/92_Reverse_Linked_List_II/solution.py
sungminoh/algorithms
train
0
d59f52e8b4a45e98cb06fdfd00dfee331091988e
[ "pic_np = pic_tensor.asnumpy()[0]\nif pic_np.shape[0] == 1:\n pic_np = (pic_np[0] + 1) / 2.0 * 255.0\nelif pic_np.shape[0] == 3:\n pic_np = (np.transpose(pic_np, (1, 2, 0)) + 1) / 2.0 * 255.0\npic = Image.fromarray(pic_np)\npic = pic.convert('RGB')\npic.save(pic_path)\nprint(pic_path + ' is saved.')", "real...
<|body_start_0|> pic_np = pic_tensor.asnumpy()[0] if pic_np.shape[0] == 1: pic_np = (pic_np[0] + 1) / 2.0 * 255.0 elif pic_np.shape[0] == 3: pic_np = (np.transpose(pic_np, (1, 2, 0)) + 1) / 2.0 * 255.0 pic = Image.fromarray(pic_np) pic = pic.convert('RGB')...
Eval
Eval
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Eval: """Eval""" def save_image(pic_tensor, pic_path='test.png'): """save image""" <|body_0|> def infer_one_image(net, all_data): """infer one image""" <|body_1|> def expand_tensor_data(data_tensor): """expand_tensor_data""" <|body_2|...
stack_v2_sparse_classes_10k_train_008392
4,422
permissive
[ { "docstring": "save image", "name": "save_image", "signature": "def save_image(pic_tensor, pic_path='test.png')" }, { "docstring": "infer one image", "name": "infer_one_image", "signature": "def infer_one_image(net, all_data)" }, { "docstring": "expand_tensor_data", "name": ...
4
null
Implement the Python class `Eval` described below. Class description: Eval Method signatures and docstrings: - def save_image(pic_tensor, pic_path='test.png'): save image - def infer_one_image(net, all_data): infer one image - def expand_tensor_data(data_tensor): expand_tensor_data - def process_input(all_data, resul...
Implement the Python class `Eval` described below. Class description: Eval Method signatures and docstrings: - def save_image(pic_tensor, pic_path='test.png'): save image - def infer_one_image(net, all_data): infer one image - def expand_tensor_data(data_tensor): expand_tensor_data - def process_input(all_data, resul...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class Eval: """Eval""" def save_image(pic_tensor, pic_path='test.png'): """save image""" <|body_0|> def infer_one_image(net, all_data): """infer one image""" <|body_1|> def expand_tensor_data(data_tensor): """expand_tensor_data""" <|body_2|...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Eval: """Eval""" def save_image(pic_tensor, pic_path='test.png'): """save image""" pic_np = pic_tensor.asnumpy()[0] if pic_np.shape[0] == 1: pic_np = (pic_np[0] + 1) / 2.0 * 255.0 elif pic_np.shape[0] == 3: pic_np = (np.transpose(pic_np, (1, 2, 0)) ...
the_stack_v2_python_sparse
research/cv/APDrawingGAN/eval.py
mindspore-ai/models
train
301
e6164e470ea8b3e7fb60a21db9dd465ee5738e07
[ "miner = Miner(name='Miner', version='1.0.b')\nminer.slug = get_unique_slug(miner, 'slug', 'name', 'version')\nminer.save()\nother_miner = Miner(name='MineR', version='1.0.b')\nother_miner.slug = get_unique_slug(other_miner, 'slug', 'name', 'version')\nself.assertNotEqual(miner.slug, other_miner.slug)", "miner = ...
<|body_start_0|> miner = Miner(name='Miner', version='1.0.b') miner.slug = get_unique_slug(miner, 'slug', 'name', 'version') miner.save() other_miner = Miner(name='MineR', version='1.0.b') other_miner.slug = get_unique_slug(other_miner, 'slug', 'name', 'version') self.ass...
Тестирование гнерератора slug
GetSlugTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetSlugTest: """Тестирование гнерератора slug""" def test_get_unique_slug(self): """Генерация уникального slug""" <|body_0|> def test_get_unique_slug_conflict(self): """Генерация уникального slug недопустимого значения""" <|body_1|> def test_get_slug...
stack_v2_sparse_classes_10k_train_008393
13,105
permissive
[ { "docstring": "Генерация уникального slug", "name": "test_get_unique_slug", "signature": "def test_get_unique_slug(self)" }, { "docstring": "Генерация уникального slug недопустимого значения", "name": "test_get_unique_slug_conflict", "signature": "def test_get_unique_slug_conflict(self)...
5
stack_v2_sparse_classes_30k_train_004693
Implement the Python class `GetSlugTest` described below. Class description: Тестирование гнерератора slug Method signatures and docstrings: - def test_get_unique_slug(self): Генерация уникального slug - def test_get_unique_slug_conflict(self): Генерация уникального slug недопустимого значения - def test_get_slug(sel...
Implement the Python class `GetSlugTest` described below. Class description: Тестирование гнерератора slug Method signatures and docstrings: - def test_get_unique_slug(self): Генерация уникального slug - def test_get_unique_slug_conflict(self): Генерация уникального slug недопустимого значения - def test_get_slug(sel...
d173f1bee44d0752eefb53b1a0da847a3882a352
<|skeleton|> class GetSlugTest: """Тестирование гнерератора slug""" def test_get_unique_slug(self): """Генерация уникального slug""" <|body_0|> def test_get_unique_slug_conflict(self): """Генерация уникального slug недопустимого значения""" <|body_1|> def test_get_slug...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GetSlugTest: """Тестирование гнерератора slug""" def test_get_unique_slug(self): """Генерация уникального slug""" miner = Miner(name='Miner', version='1.0.b') miner.slug = get_unique_slug(miner, 'slug', 'name', 'version') miner.save() other_miner = Miner(name='Mine...
the_stack_v2_python_sparse
miningstatistic/core/tests.py
crowmurk/miners
train
0
ee7b959f12a81d2d981a9ebf5c2fdb4cef154f76
[ "super(ImprovedGAN_Discriminator, self).__init__()\nself.use_gpu = use_gpu\nself.n_B = n_B\nself.n_C = n_C\nself.featmap_dim = featmap_dim\nself.conv1 = nn.Conv2d(n_channel, featmap_dim / 4, 5, stride=2, padding=2)\nself.conv2 = nn.Conv2d(featmap_dim / 4, featmap_dim / 2, 5, stride=2, padding=2)\nself.BN2 = nn.Batc...
<|body_start_0|> super(ImprovedGAN_Discriminator, self).__init__() self.use_gpu = use_gpu self.n_B = n_B self.n_C = n_C self.featmap_dim = featmap_dim self.conv1 = nn.Conv2d(n_channel, featmap_dim / 4, 5, stride=2, padding=2) self.conv2 = nn.Conv2d(featmap_dim / 4...
ImprovedGAN_Discriminator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImprovedGAN_Discriminator: def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): """Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch.""" <|body_0|> def forward(self, x): """Archi...
stack_v2_sparse_classes_10k_train_008394
19,546
no_license
[ { "docstring": "Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch.", "name": "__init__", "signature": "def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16)" }, { "docstring": "Architecture is similar to DCGAN...
2
null
Implement the Python class `ImprovedGAN_Discriminator` described below. Class description: Implement the ImprovedGAN_Discriminator class. Method signatures and docstrings: - def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): Minibatch discrimination: learn a tensor to encode side inform...
Implement the Python class `ImprovedGAN_Discriminator` described below. Class description: Implement the ImprovedGAN_Discriminator class. Method signatures and docstrings: - def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): Minibatch discrimination: learn a tensor to encode side inform...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class ImprovedGAN_Discriminator: def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): """Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch.""" <|body_0|> def forward(self, x): """Archi...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ImprovedGAN_Discriminator: def __init__(self, featmap_dim=512, n_channel=1, use_gpu=False, n_B=128, n_C=16): """Minibatch discrimination: learn a tensor to encode side information from other examples in the same minibatch.""" super(ImprovedGAN_Discriminator, self).__init__() self.use_g...
the_stack_v2_python_sparse
generated/test_AaronYALai_Generative_Adversarial_Networks_PyTorch.py
jansel/pytorch-jit-paritybench
train
35
0cec5c6ceb1df809854e5dd36576a5b0c1e6acc7
[ "super(COMACriticNetwork, self).__init__()\nself.action_shape = action_shape\nself.act = nn.ReLU()\nself.mlp = nn.Sequential(MLP(input_size, hidden_size, hidden_size, 2, activation=self.act), nn.Linear(hidden_size, action_shape))", "x = self._preprocess_data(data)\nq = self.mlp(x)\nreturn {'q_value': q}", "t_si...
<|body_start_0|> super(COMACriticNetwork, self).__init__() self.action_shape = action_shape self.act = nn.ReLU() self.mlp = nn.Sequential(MLP(input_size, hidden_size, hidden_size, 2, activation=self.act), nn.Linear(hidden_size, action_shape)) <|end_body_0|> <|body_start_1|> x = ...
Overview: Centralized critic network in COMA Interface: __init__, forward
COMACriticNetwork
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class COMACriticNetwork: """Overview: Centralized critic network in COMA Interface: __init__, forward""" def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): """Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global ...
stack_v2_sparse_classes_10k_train_008395
7,790
permissive
[ { "docstring": "Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global observation - action_shape (:obj:`int`): the dimension of action shape - hidden_size_list (:obj:`list`): the list of hidden size, default to 128", "name": "__init__", "signature": "def...
3
stack_v2_sparse_classes_30k_train_006520
Implement the Python class `COMACriticNetwork` described below. Class description: Overview: Centralized critic network in COMA Interface: __init__, forward Method signatures and docstrings: - def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): Overview: initialize COMA critic network Argume...
Implement the Python class `COMACriticNetwork` described below. Class description: Overview: Centralized critic network in COMA Interface: __init__, forward Method signatures and docstrings: - def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): Overview: initialize COMA critic network Argume...
eb483fa6e46602d58c8e7d2ca1e566adca28e703
<|skeleton|> class COMACriticNetwork: """Overview: Centralized critic network in COMA Interface: __init__, forward""" def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): """Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class COMACriticNetwork: """Overview: Centralized critic network in COMA Interface: __init__, forward""" def __init__(self, input_size: int, action_shape: int, hidden_size: int=128): """Overview: initialize COMA critic network Arguments: - input_size (:obj:`int`): the size of input global observation -...
the_stack_v2_python_sparse
ding/model/template/coma.py
shengxuesun/DI-engine
train
1
f0576a541c8b0f7223af88b7c2a251597800cec0
[ "signed_up = self.calc_signup(events)\nconsented, cohort = self.calc_consent(events)\nehr_consented = self.calc_ehr_consent(events)\ngror_received = self.calc_gror_received(events)\nbiobank_samples = self.calc_biobank_samples(events)\nphysical_measurements = self.calc_physical_measurements(events)\nthebasics_module...
<|body_start_0|> signed_up = self.calc_signup(events) consented, cohort = self.calc_consent(events) ehr_consented = self.calc_ehr_consent(events) gror_received = self.calc_gror_received(events) biobank_samples = self.calc_biobank_samples(events) physical_measurements = se...
Calculate participant enrollment status. Changes: * Implement Participant PM&B Eligible status * Never downgrade participant status * (v3.1 Feature) : If participant has "Ever" consented to EHR sharing, participant EHR sharing stays "Yes" even if there is a negative EHR consent later.
EnrollmentStatusCalculator_v3_0
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnrollmentStatusCalculator_v3_0: """Calculate participant enrollment status. Changes: * Implement Participant PM&B Eligible status * Never downgrade participant status * (v3.1 Feature) : If participant has "Ever" consented to EHR sharing, participant EHR sharing stays "Yes" even if there is a neg...
stack_v2_sparse_classes_10k_train_008396
6,672
permissive
[ { "docstring": "Use the events list to calculate the participant enrolment status and status timestamps. :param events: List of events to use in calculations", "name": "calculate_from_events", "signature": "def calculate_from_events(self, events)" }, { "docstring": "Save the status timestamp whe...
4
null
Implement the Python class `EnrollmentStatusCalculator_v3_0` described below. Class description: Calculate participant enrollment status. Changes: * Implement Participant PM&B Eligible status * Never downgrade participant status * (v3.1 Feature) : If participant has "Ever" consented to EHR sharing, participant EHR sha...
Implement the Python class `EnrollmentStatusCalculator_v3_0` described below. Class description: Calculate participant enrollment status. Changes: * Implement Participant PM&B Eligible status * Never downgrade participant status * (v3.1 Feature) : If participant has "Ever" consented to EHR sharing, participant EHR sha...
461ae46aeda21d54de8a91aa5ef677676d5db541
<|skeleton|> class EnrollmentStatusCalculator_v3_0: """Calculate participant enrollment status. Changes: * Implement Participant PM&B Eligible status * Never downgrade participant status * (v3.1 Feature) : If participant has "Ever" consented to EHR sharing, participant EHR sharing stays "Yes" even if there is a neg...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class EnrollmentStatusCalculator_v3_0: """Calculate participant enrollment status. Changes: * Implement Participant PM&B Eligible status * Never downgrade participant status * (v3.1 Feature) : If participant has "Ever" consented to EHR sharing, participant EHR sharing stays "Yes" even if there is a negative EHR con...
the_stack_v2_python_sparse
rdr_service/resource/calculators/participant_enrollment_status_v30.py
all-of-us/raw-data-repository
train
46
74f152c6f1c0b1b497fec4f5b1185c1a4c3a4356
[ "user = request.user\nif user:\n ser = self.serializer_class(user)\n return Response({'data': ser.data}, status=status.HTTP_200_OK)\nelse:\n return Response({'status': status.HTTP_404_NOT_FOUND, 'error': 'User not found'})", "ser_params = self.serializer_class(data=request.data)\nser_params.is_valid(rais...
<|body_start_0|> user = request.user if user: ser = self.serializer_class(user) return Response({'data': ser.data}, status=status.HTTP_200_OK) else: return Response({'status': status.HTTP_404_NOT_FOUND, 'error': 'User not found'}) <|end_body_0|> <|body_start_...
AuthViewSet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthViewSet: def user(self, request): """User profile information""" <|body_0|> def register(self, request): """User registration""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = request.user if user: ser = self.serializer_...
stack_v2_sparse_classes_10k_train_008397
3,325
permissive
[ { "docstring": "User profile information", "name": "user", "signature": "def user(self, request)" }, { "docstring": "User registration", "name": "register", "signature": "def register(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_000652
Implement the Python class `AuthViewSet` described below. Class description: Implement the AuthViewSet class. Method signatures and docstrings: - def user(self, request): User profile information - def register(self, request): User registration
Implement the Python class `AuthViewSet` described below. Class description: Implement the AuthViewSet class. Method signatures and docstrings: - def user(self, request): User profile information - def register(self, request): User registration <|skeleton|> class AuthViewSet: def user(self, request): ""...
05daac6bc1504658909dc396e48cc8100ec1747c
<|skeleton|> class AuthViewSet: def user(self, request): """User profile information""" <|body_0|> def register(self, request): """User registration""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class AuthViewSet: def user(self, request): """User profile information""" user = request.user if user: ser = self.serializer_class(user) return Response({'data': ser.data}, status=status.HTTP_200_OK) else: return Response({'status': status.HTTP_40...
the_stack_v2_python_sparse
backend/authentication/views.py
vindem22/work-hour-registration
train
0
4d0c70af6593109ec214ddf4a46e2b3a38aae4fd
[ "n = len(nums)\nnums.sort()\nsubset = []\nfor i in range(2 ** n, 2 ** (n + 1)):\n bitmask = bin(i)[3:]\n sub = []\n for j in range(n):\n if bitmask[j] == '1':\n sub.append(nums[j])\n if sub not in subset:\n subset.append(sub)\nreturn subset", "def back_track(nums, index, path,...
<|body_start_0|> n = len(nums) nums.sort() subset = [] for i in range(2 ** n, 2 ** (n + 1)): bitmask = bin(i)[3:] sub = [] for j in range(n): if bitmask[j] == '1': sub.append(nums[j]) if sub not in subset...
Subset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subset: def get_all_via_bit_manipulation(self, nums: List[int]) -> List[List[int]]: """Approach: Lexicographic (Binary Sorted) subsets Time Complexity: O(N * 2^N) Space Complexity: O(N * 2^N) :param nums: :return:""" <|body_0|> def get_all(self, nums: List[int]) -> List[List...
stack_v2_sparse_classes_10k_train_008398
1,439
no_license
[ { "docstring": "Approach: Lexicographic (Binary Sorted) subsets Time Complexity: O(N * 2^N) Space Complexity: O(N * 2^N) :param nums: :return:", "name": "get_all_via_bit_manipulation", "signature": "def get_all_via_bit_manipulation(self, nums: List[int]) -> List[List[int]]" }, { "docstring": "Ap...
2
stack_v2_sparse_classes_30k_train_003534
Implement the Python class `Subset` described below. Class description: Implement the Subset class. Method signatures and docstrings: - def get_all_via_bit_manipulation(self, nums: List[int]) -> List[List[int]]: Approach: Lexicographic (Binary Sorted) subsets Time Complexity: O(N * 2^N) Space Complexity: O(N * 2^N) :...
Implement the Python class `Subset` described below. Class description: Implement the Subset class. Method signatures and docstrings: - def get_all_via_bit_manipulation(self, nums: List[int]) -> List[List[int]]: Approach: Lexicographic (Binary Sorted) subsets Time Complexity: O(N * 2^N) Space Complexity: O(N * 2^N) :...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Subset: def get_all_via_bit_manipulation(self, nums: List[int]) -> List[List[int]]: """Approach: Lexicographic (Binary Sorted) subsets Time Complexity: O(N * 2^N) Space Complexity: O(N * 2^N) :param nums: :return:""" <|body_0|> def get_all(self, nums: List[int]) -> List[List...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Subset: def get_all_via_bit_manipulation(self, nums: List[int]) -> List[List[int]]: """Approach: Lexicographic (Binary Sorted) subsets Time Complexity: O(N * 2^N) Space Complexity: O(N * 2^N) :param nums: :return:""" n = len(nums) nums.sort() subset = [] for i in range(...
the_stack_v2_python_sparse
revisited/math_and_strings/recursion_memoization_dp/subset_ii.py
Shiv2157k/leet_code
train
1
90e8c7804115a43dcecf8095d145941766d59127
[ "self.record_value = dict()\nself.max_length = capacity\nself.queue = collections.deque()", "if key not in self.record_value:\n return -1\nif key in self.queue:\n self.queue.remove(key)\nself.queue.append(key)\nreturn self.record_value.get(key)", "if key in self.record_value:\n self.record_value[key] =...
<|body_start_0|> self.record_value = dict() self.max_length = capacity self.queue = collections.deque() <|end_body_0|> <|body_start_1|> if key not in self.record_value: return -1 if key in self.queue: self.queue.remove(key) self.queue.append(key) ...
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: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_10k_train_008399
1,517
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: None", "name": "pu...
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
f43d70cac56bdf6377b22b865174af822902ff78
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.record_value = dict() self.max_length = capacity self.queue = collections.deque() def get(self, key): """:type key: int :rtype: int""" if key not in self.record_value: return...
the_stack_v2_python_sparse
队列/LeetCode146_LRU缓存机制.py
ltzp/LeetCode
train
0