blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
dc60cee322703e5b35e0f79b25a03572ec843277
[ "if len(s) == 1:\n return 1\nelif len(s) == 0:\n return 0\nmax_count = 1\nres = []\nfor left in range(len(s)):\n for right in range(left, len(s)):\n if s[right] not in res:\n res.append(s[right])\n else:\n if len(res) > max_count:\n max_count = len(res)\n ...
<|body_start_0|> if len(s) == 1: return 1 elif len(s) == 0: return 0 max_count = 1 res = [] for left in range(len(s)): for right in range(left, len(s)): if s[right] not in res: res.append(s[right]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """常规做法,时间复杂度为O(n^2),空间复杂度为O(n)""" <|body_0|> def lengthOfLongestSubstring_2(self, s: str) -> int: """优化上诉代码,使用滑动窗口,时间复杂度为O(n)""" <|body_1|> def lengthOfLongestSubstring_3(self, s: str) -> int:...
stack_v2_sparse_classes_36k_train_024100
2,931
no_license
[ { "docstring": "常规做法,时间复杂度为O(n^2),空间复杂度为O(n)", "name": "lengthOfLongestSubstring", "signature": "def lengthOfLongestSubstring(self, s: str) -> int" }, { "docstring": "优化上诉代码,使用滑动窗口,时间复杂度为O(n)", "name": "lengthOfLongestSubstring_2", "signature": "def lengthOfLongestSubstring_2(self, s: st...
3
stack_v2_sparse_classes_30k_train_007109
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring(self, s: str) -> int: 常规做法,时间复杂度为O(n^2),空间复杂度为O(n) - def lengthOfLongestSubstring_2(self, s: str) -> int: 优化上诉代码,使用滑动窗口,时间复杂度为O(n) - def lengthOfLong...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring(self, s: str) -> int: 常规做法,时间复杂度为O(n^2),空间复杂度为O(n) - def lengthOfLongestSubstring_2(self, s: str) -> int: 优化上诉代码,使用滑动窗口,时间复杂度为O(n) - def lengthOfLong...
13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08
<|skeleton|> class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """常规做法,时间复杂度为O(n^2),空间复杂度为O(n)""" <|body_0|> def lengthOfLongestSubstring_2(self, s: str) -> int: """优化上诉代码,使用滑动窗口,时间复杂度为O(n)""" <|body_1|> def lengthOfLongestSubstring_3(self, s: str) -> int:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: """常规做法,时间复杂度为O(n^2),空间复杂度为O(n)""" if len(s) == 1: return 1 elif len(s) == 0: return 0 max_count = 1 res = [] for left in range(len(s)): for right in range(left, len...
the_stack_v2_python_sparse
Algorithms/3_Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.py
lirui-ML/my_leetcode
train
1
57e1e5413180d717ac9677d49a89ebf17f99fafc
[ "super().__init__(**kwargs)\nself.batch = batch\nself.targets = list()\nif not (self.user and self.password):\n msg = 'A ClickSend user/pass was not provided.'\n self.logger.warning(msg)\n raise TypeError(msg)\nfor target in parse_phone_no(targets):\n result = is_phone_no(target)\n if not result:\n ...
<|body_start_0|> super().__init__(**kwargs) self.batch = batch self.targets = list() if not (self.user and self.password): msg = 'A ClickSend user/pass was not provided.' self.logger.warning(msg) raise TypeError(msg) for target in parse_phone_n...
A wrapper for ClickSend Notifications
NotifyClickSend
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotifyClickSend: """A wrapper for ClickSend Notifications""" def __init__(self, targets=None, batch=False, **kwargs): """Initialize ClickSend Object""" <|body_0|> def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): """Perform ClickSend Notifica...
stack_v2_sparse_classes_36k_train_024101
11,434
permissive
[ { "docstring": "Initialize ClickSend Object", "name": "__init__", "signature": "def __init__(self, targets=None, batch=False, **kwargs)" }, { "docstring": "Perform ClickSend Notification", "name": "send", "signature": "def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs)...
5
stack_v2_sparse_classes_30k_train_003761
Implement the Python class `NotifyClickSend` described below. Class description: A wrapper for ClickSend Notifications Method signatures and docstrings: - def __init__(self, targets=None, batch=False, **kwargs): Initialize ClickSend Object - def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): Perfo...
Implement the Python class `NotifyClickSend` described below. Class description: A wrapper for ClickSend Notifications Method signatures and docstrings: - def __init__(self, targets=None, batch=False, **kwargs): Initialize ClickSend Object - def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): Perfo...
be3baed7e3d33bae973f1714df4ebbf65aa33f85
<|skeleton|> class NotifyClickSend: """A wrapper for ClickSend Notifications""" def __init__(self, targets=None, batch=False, **kwargs): """Initialize ClickSend Object""" <|body_0|> def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): """Perform ClickSend Notifica...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NotifyClickSend: """A wrapper for ClickSend Notifications""" def __init__(self, targets=None, batch=False, **kwargs): """Initialize ClickSend Object""" super().__init__(**kwargs) self.batch = batch self.targets = list() if not (self.user and self.password): ...
the_stack_v2_python_sparse
apprise/plugins/NotifyClickSend.py
caronc/apprise
train
8,426
1873e840c22c5678876bad7ad8f4cce71d8de4fd
[ "try:\n result = service.JobStateLoader().set_request_time(nnid, json.loads(request.body))\n return_data = {'status': '200', 'result': str(result)}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(retur...
<|body_start_0|> try: result = service.JobStateLoader().set_request_time(nnid, json.loads(request.body)) return_data = {'status': '200', 'result': str(result)} return Response(json.dumps(return_data)) except Exception as e: return_data = {'status': '400', ...
1. POST : 2. GET : 3. PUT : 4. DELETE :
CommonJobInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommonJobInfo: """1. POST : 2. GET : 3. PUT : 4. DELETE :""" def post(self, request, nnid): """set the time on the job :param request: :return:""" <|body_0|> def get(self, request): """get all job list :param request: :return:""" <|body_1|> def put(s...
stack_v2_sparse_classes_36k_train_024102
2,335
no_license
[ { "docstring": "set the time on the job :param request: :return:", "name": "post", "signature": "def post(self, request, nnid)" }, { "docstring": "get all job list :param request: :return:", "name": "get", "signature": "def get(self, request)" }, { "docstring": "set the time on t...
4
stack_v2_sparse_classes_30k_train_011956
Implement the Python class `CommonJobInfo` described below. Class description: 1. POST : 2. GET : 3. PUT : 4. DELETE : Method signatures and docstrings: - def post(self, request, nnid): set the time on the job :param request: :return: - def get(self, request): get all job list :param request: :return: - def put(self,...
Implement the Python class `CommonJobInfo` described below. Class description: 1. POST : 2. GET : 3. PUT : 4. DELETE : Method signatures and docstrings: - def post(self, request, nnid): set the time on the job :param request: :return: - def get(self, request): get all job list :param request: :return: - def put(self,...
17216fd58619b56b6a397178d327687c274c238c
<|skeleton|> class CommonJobInfo: """1. POST : 2. GET : 3. PUT : 4. DELETE :""" def post(self, request, nnid): """set the time on the job :param request: :return:""" <|body_0|> def get(self, request): """get all job list :param request: :return:""" <|body_1|> def put(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommonJobInfo: """1. POST : 2. GET : 3. PUT : 4. DELETE :""" def post(self, request, nnid): """set the time on the job :param request: :return:""" try: result = service.JobStateLoader().set_request_time(nnid, json.loads(request.body)) return_data = {'status': '200'...
the_stack_v2_python_sparse
tfmsarest/views/common_job.py
TensorMSA/tensormsa_server_old
train
0
d59c5bcbf86acd4fe52fa3f4d700dfa09fb8783a
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Run()", "from ..entity import Entity\nfrom .lifecycle_workflow_processing_status import LifecycleWorkflowProcessingStatus\nfrom .task_processing_result import TaskProcessingResult\nfrom .user_processing_result import UserProcessingResu...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return Run() <|end_body_0|> <|body_start_1|> from ..entity import Entity from .lifecycle_workflow_processing_status import LifecycleWorkflowProcessingStatus from .task_processing_result...
Run
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Run: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Run: """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: Run""" <|b...
stack_v2_sparse_classes_36k_train_024103
7,160
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: Run", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(parse_nod...
3
stack_v2_sparse_classes_30k_train_007087
Implement the Python class `Run` described below. Class description: Implement the Run class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Run: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n...
Implement the Python class `Run` described below. Class description: Implement the Run class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Run: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class Run: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Run: """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: Run""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Run: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Run: """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: Run""" if not parse_node...
the_stack_v2_python_sparse
msgraph/generated/models/identity_governance/run.py
microsoftgraph/msgraph-sdk-python
train
135
d7d574cfedebdc55b5c0059f62bf0aa2b3f973fd
[ "output = []\ntemp = []\nfor i in range(1, n):\n temp.append(i)\n for j in range(i + 1, n + 1):\n temp.append(j)\n for k in range(j + 1, n + 1):\n temp.append(k)\n output.append(temp[:])\n temp.pop()\n temp.pop()\n temp.pop()\nreturn output", "output ...
<|body_start_0|> output = [] temp = [] for i in range(1, n): temp.append(i) for j in range(i + 1, n + 1): temp.append(j) for k in range(j + 1, n + 1): temp.append(k) output.append(temp[:]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combination(self, n): """Example of how to arrange combinations of 3 with numbers 1 -> n""" <|body_0|> def combine(self, n, k): """Creates all combos of size k using numbers 1 -> n. Does so by starting with lowest possible values in each slot. Increase ...
stack_v2_sparse_classes_36k_train_024104
1,918
no_license
[ { "docstring": "Example of how to arrange combinations of 3 with numbers 1 -> n", "name": "combination", "signature": "def combination(self, n)" }, { "docstring": "Creates all combos of size k using numbers 1 -> n. Does so by starting with lowest possible values in each slot. Increase last slot ...
3
stack_v2_sparse_classes_30k_train_004992
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combination(self, n): Example of how to arrange combinations of 3 with numbers 1 -> n - def combine(self, n, k): Creates all combos of size k using numbers 1 -> n. Does so by...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combination(self, n): Example of how to arrange combinations of 3 with numbers 1 -> n - def combine(self, n, k): Creates all combos of size k using numbers 1 -> n. Does so by...
f33d004d7629d46fbc5670f5b384f8a604d7f1e7
<|skeleton|> class Solution: def combination(self, n): """Example of how to arrange combinations of 3 with numbers 1 -> n""" <|body_0|> def combine(self, n, k): """Creates all combos of size k using numbers 1 -> n. Does so by starting with lowest possible values in each slot. Increase ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def combination(self, n): """Example of how to arrange combinations of 3 with numbers 1 -> n""" output = [] temp = [] for i in range(1, n): temp.append(i) for j in range(i + 1, n + 1): temp.append(j) for k in ran...
the_stack_v2_python_sparse
Combinations.py
aulee888/LeetCode
train
0
cd8bef09dad13b5d09caf15c25b217c00d78559d
[ "self.response.set_status(code, message)\nself.response.out.write(message)\nreturn", "self.response.headers['Content-Type'] = self.JSON_MIMETYPE\nif obj is not None:\n if isinstance(obj, basestring):\n self.response.out.write(obj)\n else:\n self.response.out.write(json.dumps(obj, cls=model.Jso...
<|body_start_0|> self.response.set_status(code, message) self.response.out.write(message) return <|end_body_0|> <|body_start_1|> self.response.headers['Content-Type'] = self.JSON_MIMETYPE if obj is not None: if isinstance(obj, basestring): self.respon...
Base RequestHandler type which provides convenience methods for writing JSON HTTP responses.
JsonRestHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsonRestHandler: """Base RequestHandler type which provides convenience methods for writing JSON HTTP responses.""" def send_error(self, code, message): """Convenience method to format an HTTP error response in a standard format.""" <|body_0|> def send_success(self, obj=...
stack_v2_sparse_classes_36k_train_024105
32,317
no_license
[ { "docstring": "Convenience method to format an HTTP error response in a standard format.", "name": "send_error", "signature": "def send_error(self, code, message)" }, { "docstring": "Convenience method to format a PhotoHunt JSON HTTP response in a standard format.", "name": "send_success", ...
2
stack_v2_sparse_classes_30k_train_016768
Implement the Python class `JsonRestHandler` described below. Class description: Base RequestHandler type which provides convenience methods for writing JSON HTTP responses. Method signatures and docstrings: - def send_error(self, code, message): Convenience method to format an HTTP error response in a standard forma...
Implement the Python class `JsonRestHandler` described below. Class description: Base RequestHandler type which provides convenience methods for writing JSON HTTP responses. Method signatures and docstrings: - def send_error(self, code, message): Convenience method to format an HTTP error response in a standard forma...
f236a8cd20af89e889caf1049217fdbb5c45e536
<|skeleton|> class JsonRestHandler: """Base RequestHandler type which provides convenience methods for writing JSON HTTP responses.""" def send_error(self, code, message): """Convenience method to format an HTTP error response in a standard format.""" <|body_0|> def send_success(self, obj=...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JsonRestHandler: """Base RequestHandler type which provides convenience methods for writing JSON HTTP responses.""" def send_error(self, code, message): """Convenience method to format an HTTP error response in a standard format.""" self.response.set_status(code, message) self.res...
the_stack_v2_python_sparse
handlers.py
creationexus/django-x
train
0
d0d6c82a0961feb100260b07864f0f72deb5dd69
[ "N = len(a0)\nself.N = N\nself.nt = [[None] * N for i in range(M.bit_length() + 1)]\nfor i, a in enumerate(a0):\n self.nt[0][i] = a\nfor i in range(1, len(self.nt)):\n for j in range(N):\n if self.nt[i - 1][j] is None:\n self.nt[i][j] = None\n else:\n self.nt[i][j] = self.n...
<|body_start_0|> N = len(a0) self.N = N self.nt = [[None] * N for i in range(M.bit_length() + 1)] for i, a in enumerate(a0): self.nt[0][i] = a for i in range(1, len(self.nt)): for j in range(N): if self.nt[i - 1][j] is None: ...
Doubling
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Doubling: def __init__(self, a0, M): """a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i.""" <|body_0|> def apply(self, i, n): """Apply n times from i""" <|body_1|> <|end_skeleton|> <|body_start_0|> N = len(a0) ...
stack_v2_sparse_classes_36k_train_024106
4,141
permissive
[ { "docstring": "a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i.", "name": "__init__", "signature": "def __init__(self, a0, M)" }, { "docstring": "Apply n times from i", "name": "apply", "signature": "def apply(self, i, n)" } ]
2
stack_v2_sparse_classes_30k_train_016973
Implement the Python class `Doubling` described below. Class description: Implement the Doubling class. Method signatures and docstrings: - def __init__(self, a0, M): a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i. - def apply(self, i, n): Apply n times from i
Implement the Python class `Doubling` described below. Class description: Implement the Doubling class. Method signatures and docstrings: - def __init__(self, a0, M): a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i. - def apply(self, i, n): Apply n times from i <|skeleton|> class ...
79a16474a8f21310e0fb47e536d527dd5dc6d655
<|skeleton|> class Doubling: def __init__(self, a0, M): """a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i.""" <|body_0|> def apply(self, i, n): """Apply n times from i""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Doubling: def __init__(self, a0, M): """a0 is an array-like object which contains ai, 0 <= i < N. ai is the next value of i.""" N = len(a0) self.N = N self.nt = [[None] * N for i in range(M.bit_length() + 1)] for i, a in enumerate(a0): self.nt[0][i] = a ...
the_stack_v2_python_sparse
src/data/1224.py
NULLCT/LOMC
train
0
c504142bed01a0aa46a494aeb7782f110d64b957
[ "attachment = super(ir_attachment, self).create(vals)\nif vals.get('res_model', '') == 'hr.travel.request' and vals.get('res_id', False):\n model_obj = self.env['hr.travel.request']\n model = model_obj.browse(vals['res_id'])\n model.attachments_count = model.attachments_count + 1\nreturn attachment", "re...
<|body_start_0|> attachment = super(ir_attachment, self).create(vals) if vals.get('res_model', '') == 'hr.travel.request' and vals.get('res_id', False): model_obj = self.env['hr.travel.request'] model = model_obj.browse(vals['res_id']) model.attachments_count = model....
ir_attachment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ir_attachment: def create(self, vals): """When a document of a travel request is attached, increase a counting field of documents of that travel request.""" <|body_0|> def unlink(self): """When a document of a travel request is removed, decrease a counting field of d...
stack_v2_sparse_classes_36k_train_024107
2,682
no_license
[ { "docstring": "When a document of a travel request is attached, increase a counting field of documents of that travel request.", "name": "create", "signature": "def create(self, vals)" }, { "docstring": "When a document of a travel request is removed, decrease a counting field of documents of t...
3
null
Implement the Python class `ir_attachment` described below. Class description: Implement the ir_attachment class. Method signatures and docstrings: - def create(self, vals): When a document of a travel request is attached, increase a counting field of documents of that travel request. - def unlink(self): When a docum...
Implement the Python class `ir_attachment` described below. Class description: Implement the ir_attachment class. Method signatures and docstrings: - def create(self, vals): When a document of a travel request is attached, increase a counting field of documents of that travel request. - def unlink(self): When a docum...
673dd0f2a7c0b69a984342b20f55164a97a00529
<|skeleton|> class ir_attachment: def create(self, vals): """When a document of a travel request is attached, increase a counting field of documents of that travel request.""" <|body_0|> def unlink(self): """When a document of a travel request is removed, decrease a counting field of d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ir_attachment: def create(self, vals): """When a document of a travel request is attached, increase a counting field of documents of that travel request.""" attachment = super(ir_attachment, self).create(vals) if vals.get('res_model', '') == 'hr.travel.request' and vals.get('res_id', F...
the_stack_v2_python_sparse
addons/app-trobz-hr/trobz_hr_travel_request/model/base/ir_attachment.py
TinPlusIT05/tms
train
0
7641f4b73688680421b09ed923321f641ef0eb81
[ "class K:\n\n def __init__(self, obj, *args):\n self.obj = obj\n\n def __lt__(self, other):\n return mycmp(self.obj, other.obj) < 0\n\n def __gt__(self, other):\n return mycmp(self.obj, other.obj) > 0\n\n def __eq__(self, other):\n return mycmp(self.obj, other.obj) == 0\n\n ...
<|body_start_0|> class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(se...
Utilities for graph processing
NLPGraphProcessingUtils
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NLPGraphProcessingUtils: """Utilities for graph processing""" def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" <|body_0|> def LoadGraphFromContents(graphStrContents): """Loads netwokx graph from json string""" <|body_1|> def ...
stack_v2_sparse_classes_36k_train_024108
2,394
no_license
[ { "docstring": "Convert a cmp= function into a key= function", "name": "cmp_to_key", "signature": "def cmp_to_key(mycmp)" }, { "docstring": "Loads netwokx graph from json string", "name": "LoadGraphFromContents", "signature": "def LoadGraphFromContents(graphStrContents)" }, { "do...
6
stack_v2_sparse_classes_30k_train_017562
Implement the Python class `NLPGraphProcessingUtils` described below. Class description: Utilities for graph processing Method signatures and docstrings: - def cmp_to_key(mycmp): Convert a cmp= function into a key= function - def LoadGraphFromContents(graphStrContents): Loads netwokx graph from json string - def Load...
Implement the Python class `NLPGraphProcessingUtils` described below. Class description: Utilities for graph processing Method signatures and docstrings: - def cmp_to_key(mycmp): Convert a cmp= function into a key= function - def LoadGraphFromContents(graphStrContents): Loads netwokx graph from json string - def Load...
fe4aba5b20169754b717b77b5197d589270ca09a
<|skeleton|> class NLPGraphProcessingUtils: """Utilities for graph processing""" def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" <|body_0|> def LoadGraphFromContents(graphStrContents): """Loads netwokx graph from json string""" <|body_1|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NLPGraphProcessingUtils: """Utilities for graph processing""" def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(s...
the_stack_v2_python_sparse
PrefabOptimizationServer/NLPDataProcessing/NLPGraphProcessingUtils.py
waterbooo/Crane-optimization
train
3
99a87cf4dd8dec1c60589536347e0d301d593081
[ "super().__init__()\nif not isinstance(filename, str):\n raise RuntimeError(\"'{}' is not a valid file name.\".format(filename))\nif not os.path.isfile(filename):\n raise RuntimeError('File not found: {}'.format(filename))\nself._filename = filename", "name_map = {}\nwith open(self._filename, 'r') as f:\n ...
<|body_start_0|> super().__init__() if not isinstance(filename, str): raise RuntimeError("'{}' is not a valid file name.".format(filename)) if not os.path.isfile(filename): raise RuntimeError('File not found: {}'.format(filename)) self._filename = filename <|end_b...
DOE case generator that reads cases from a CSV file. This DOE case generator will accept an existing data set in the form of a CSV file containing DOE cases. The CSV file should have one column per design variable and the header row should have the names of the design variables. Attributes ---------- _filename : str th...
CSVGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CSVGenerator: """DOE case generator that reads cases from a CSV file. This DOE case generator will accept an existing data set in the form of a CSV file containing DOE cases. The CSV file should have one column per design variable and the header row should have the names of the design variables. ...
stack_v2_sparse_classes_36k_train_024109
21,019
no_license
[ { "docstring": "Initialize the CSVGenerator. Parameters ---------- filename : str the name of the file from which to read cases", "name": "__init__", "signature": "def __init__(self, filename)" }, { "docstring": "Generate case. Parameters ---------- design_vars : OrderedDict Dictionary of design...
2
stack_v2_sparse_classes_30k_train_000968
Implement the Python class `CSVGenerator` described below. Class description: DOE case generator that reads cases from a CSV file. This DOE case generator will accept an existing data set in the form of a CSV file containing DOE cases. The CSV file should have one column per design variable and the header row should h...
Implement the Python class `CSVGenerator` described below. Class description: DOE case generator that reads cases from a CSV file. This DOE case generator will accept an existing data set in the form of a CSV file containing DOE cases. The CSV file should have one column per design variable and the header row should h...
d9e89fe017f1131d554599c248247f73bb9b534d
<|skeleton|> class CSVGenerator: """DOE case generator that reads cases from a CSV file. This DOE case generator will accept an existing data set in the form of a CSV file containing DOE cases. The CSV file should have one column per design variable and the header row should have the names of the design variables. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CSVGenerator: """DOE case generator that reads cases from a CSV file. This DOE case generator will accept an existing data set in the form of a CSV file containing DOE cases. The CSV file should have one column per design variable and the header row should have the names of the design variables. Attributes --...
the_stack_v2_python_sparse
venv/Lib/site-packages/openmdao/drivers/doe_generators.py
ManojDjs/Heart-rate-estimation
train
1
b3a45ba5dce18927329522e664da80e338f76f77
[ "import copy\nh = head\nl = []\nwhile h:\n l.append(h.val)\n h = h.next\nl_re = copy.copy(l)\nl_re.reverse()\nreturn l == l_re", "if not head:\n return True\nfast = head\nslow = head\nwhile fast and fast.next:\n fast = fast.next.next\n slow = slow.next\npre = None\nif fast:\n slow = slow.next\nw...
<|body_start_0|> import copy h = head l = [] while h: l.append(h.val) h = h.next l_re = copy.copy(l) l_re.reverse() return l == l_re <|end_body_0|> <|body_start_1|> if not head: return True fast = head s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def isPalindrome_fs(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> import copy h = head l =...
stack_v2_sparse_classes_36k_train_024110
1,397
no_license
[ { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, head)" }, { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome_fs", "signature": "def isPalindrome_fs(self, head)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head): :type head: ListNode :rtype: bool - def isPalindrome_fs(self, head): :type head: ListNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head): :type head: ListNode :rtype: bool - def isPalindrome_fs(self, head): :type head: ListNode :rtype: bool <|skeleton|> class Solution: def isPali...
9f949ae6b5ee178c7153f1c402a92accbf710111
<|skeleton|> class Solution: def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def isPalindrome_fs(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" import copy h = head l = [] while h: l.append(h.val) h = h.next l_re = copy.copy(l) l_re.reverse() return l == l_re def isPalindrome_fs(s...
the_stack_v2_python_sparse
算法题/判断回文链表.py
yllzxzyq/Nick-life-of-code
train
1
dbda750097e52195b1c42f6dffb73a604189bf48
[ "ans = collections.defaultdict(list)\nfor s in strs:\n ans[tuple(sorted(s))].append(s)\nreturn list(ans.values())", "ans = collections.defaultdict(list)\nfor s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n ans[tuple(count)].append(s)\nreturn list(ans.values())" ]
<|body_start_0|> ans = collections.defaultdict(list) for s in strs: ans[tuple(sorted(s))].append(s) return list(ans.values()) <|end_body_0|> <|body_start_1|> ans = collections.defaultdict(list) for s in strs: count = [0] * 26 for c in s: ...
Solution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: """时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:""" <|body_0|> def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]: """时间复杂度:O(NK) 空间复杂度:O(NK) :param strs: :return:""" <|b...
stack_v2_sparse_classes_36k_train_024111
1,552
permissive
[ { "docstring": "时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:", "name": "groupAnagrams_1", "signature": "def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]" }, { "docstring": "时间复杂度:O(NK) 空间复杂度:O(NK) :param strs: :return:", "name": "groupAnagrams_2", "signature": "def gro...
2
stack_v2_sparse_classes_30k_train_006319
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: 时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return: - def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: 时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return: - def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:...
62419b49000e79962bcdc99cd98afd2fb82ea345
<|skeleton|> class Solution: def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: """时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:""" <|body_0|> def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]: """时间复杂度:O(NK) 空间复杂度:O(NK) :param strs: :return:""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: """时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:""" ans = collections.defaultdict(list) for s in strs: ans[tuple(sorted(s))].append(s) return list(ans.values()) def groupAnagrams_2(se...
the_stack_v2_python_sparse
LeetCode 热题 HOT 100/groupAnagrams.py
MaoningGuan/LeetCode
train
3
c64def0f7699e1cad3a372b3efada128e44e97ec
[ "self._old_layer = old_layer\nself._new_layer = new_layer\nif filter_fn is None:\n self._filter_fn = lambda s: True\nelse:\n self._filter_fn = filter_fn", "del meta_state\nshould_change = [self._filter_fn(s) for s in state[self._old_layer]]\nchange_inds = np.argwhere(should_change)[:, 0]\ncount_changed_alre...
<|body_start_0|> self._old_layer = old_layer self._new_layer = new_layer if filter_fn is None: self._filter_fn = lambda s: True else: self._filter_fn = filter_fn <|end_body_0|> <|body_start_1|> del meta_state should_change = [self._filter_fn(s) fo...
ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color.
ChangeLayer
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChangeLayer: """ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color.""" def __init__(self, old_layer, new_layer, filter_fn=None): """Cons...
stack_v2_sparse_classes_36k_train_024112
1,651
permissive
[ { "docstring": "Constructor. Args: old_layer: String. Must be a key in the environment state. Sprites in this layer will be considered for the layer change. new_layer: String. Must be a key in the environment state. Layer to which sprites in old_layer may be moved. filter_fn: Function sprite -> bool. Whether to...
2
stack_v2_sparse_classes_30k_train_003984
Implement the Python class `ChangeLayer` described below. Class description: ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color. Method signatures and docstrings: - def _...
Implement the Python class `ChangeLayer` described below. Class description: ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color. Method signatures and docstrings: - def _...
3e89e46a5918d59475851f9d4f1558956c110d38
<|skeleton|> class ChangeLayer: """ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color.""" def __init__(self, old_layer, new_layer, filter_fn=None): """Cons...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChangeLayer: """ChangeLayer rule. This rule is used to change the layer of a sprite based on a filter of the sprite. For example, it could be used to change a sprite's layer if the sprite has changed to a new color.""" def __init__(self, old_layer, new_layer, filter_fn=None): """Constructor. Args...
the_stack_v2_python_sparse
moog/game_rules/change_layer.py
hokysung/moog.github.io
train
0
53b585661ac092105f6e7ccf316db3a58239104a
[ "super().__init__(label='Start Plotting')\nself.protocol = linear_actuator_protocol\nself.plotters = plotters\nself.plotting = False\nself.interval = plotting_interval", "if self.plotting:\n await self.stop_plotting()\nelse:\n await self.start_plotting()", "if self.plotting:\n return\nawait self.protoc...
<|body_start_0|> super().__init__(label='Start Plotting') self.protocol = linear_actuator_protocol self.plotters = plotters self.plotting = False self.interval = plotting_interval <|end_body_0|> <|body_start_1|> if self.plotting: await self.stop_plotting() ...
Linear actuator plotter functionality toggle, synchronized across documents.
ToggleStatePlottingButton
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ToggleStatePlottingButton: """Linear actuator plotter functionality toggle, synchronized across documents.""" def __init__(self, linear_actuator_protocol, plotters, plotting_interval=20): """Initialize member variables.""" <|body_0|> async def toggle_plotting(self): ...
stack_v2_sparse_classes_36k_train_024113
23,462
permissive
[ { "docstring": "Initialize member variables.", "name": "__init__", "signature": "def __init__(self, linear_actuator_protocol, plotters, plotting_interval=20)" }, { "docstring": "Toggle plotting.", "name": "toggle_plotting", "signature": "async def toggle_plotting(self)" }, { "doc...
5
stack_v2_sparse_classes_30k_train_008339
Implement the Python class `ToggleStatePlottingButton` described below. Class description: Linear actuator plotter functionality toggle, synchronized across documents. Method signatures and docstrings: - def __init__(self, linear_actuator_protocol, plotters, plotting_interval=20): Initialize member variables. - async...
Implement the Python class `ToggleStatePlottingButton` described below. Class description: Linear actuator plotter functionality toggle, synchronized across documents. Method signatures and docstrings: - def __init__(self, linear_actuator_protocol, plotters, plotting_interval=20): Initialize member variables. - async...
fc7043558072e77981206ae123dfd3a24ef89029
<|skeleton|> class ToggleStatePlottingButton: """Linear actuator plotter functionality toggle, synchronized across documents.""" def __init__(self, linear_actuator_protocol, plotters, plotting_interval=20): """Initialize member variables.""" <|body_0|> async def toggle_plotting(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ToggleStatePlottingButton: """Linear actuator plotter functionality toggle, synchronized across documents.""" def __init__(self, linear_actuator_protocol, plotters, plotting_interval=20): """Initialize member variables.""" super().__init__(label='Start Plotting') self.protocol = l...
the_stack_v2_python_sparse
lhrhost/dashboard/linear_actuator/plots.py
ethanjli/liquid-handling-robotics
train
0
4f591ff1b4d2662d55479682e1cee2f827db8fb2
[ "super().__init__(params=params, modelparams={'phases': {'start': [0, 5], 'on': [5, 50], 'end': [50, 55]}, 'times': [0, 20, 55], 'tstep': 1})\n'\\n Here addflow() takes as input a unique name for the flow \"flowname\", a type for the flow, \"flowtype\"\\n and either: a dict with the initial flow att...
<|body_start_0|> super().__init__(params=params, modelparams={'phases': {'start': [0, 5], 'on': [5, 50], 'end': [50, 55]}, 'times': [0, 20, 55], 'tstep': 1}) '\n Here addflow() takes as input a unique name for the flow "flowname", a type for the flow, "flowtype"\n and either: a dict with...
This defines the pump model as a Model. Models take a dictionary of parameters as input defining any veriables and values to use in the model.
Pump
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pump: """This defines the pump model as a Model. Models take a dictionary of parameters as input defining any veriables and values to use in the model.""" def __init__(self, params={'cost': {'repair', 'water'}, 'delay': 10, 'units': 'hrs'}): """To sample the model, the timerange and ...
stack_v2_sparse_classes_36k_train_024114
13,659
permissive
[ { "docstring": "To sample the model, the timerange and operational phases need to be defined. Here we dod that by setting self.phases as a dictionary of each phase and its start and ending and self.times to the beginning and end time (and any times to sample in between in run_list() self.tstep is the timestep t...
2
null
Implement the Python class `Pump` described below. Class description: This defines the pump model as a Model. Models take a dictionary of parameters as input defining any veriables and values to use in the model. Method signatures and docstrings: - def __init__(self, params={'cost': {'repair', 'water'}, 'delay': 10, ...
Implement the Python class `Pump` described below. Class description: This defines the pump model as a Model. Models take a dictionary of parameters as input defining any veriables and values to use in the model. Method signatures and docstrings: - def __init__(self, params={'cost': {'repair', 'water'}, 'delay': 10, ...
2d87c415c036f44fe10310500788f5ab697e618d
<|skeleton|> class Pump: """This defines the pump model as a Model. Models take a dictionary of parameters as input defining any veriables and values to use in the model.""" def __init__(self, params={'cost': {'repair', 'water'}, 'delay': 10, 'units': 'hrs'}): """To sample the model, the timerange and ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Pump: """This defines the pump model as a Model. Models take a dictionary of parameters as input defining any veriables and values to use in the model.""" def __init__(self, params={'cost': {'repair', 'water'}, 'delay': 10, 'units': 'hrs'}): """To sample the model, the timerange and operational p...
the_stack_v2_python_sparse
pump example/ex_pump.py
DesignEngrLab/fmdtools
train
10
c4fbda88dbcc6b8521e16ac7bc0ab7498e269952
[ "self.__robot = robot\nself.__max_ang_speed = max_ang_speed\nself.__ang_speed_weight = ang_speed_weight\nself.__timer = 0\nself.__turn_around_delay = turn_around_delay", "if time.time() - self.__timer < self.__turn_around_delay:\n return\nelif force['x'] == 0 and force['y'] == 0:\n self.stop()\nelse:\n f...
<|body_start_0|> self.__robot = robot self.__max_ang_speed = max_ang_speed self.__ang_speed_weight = ang_speed_weight self.__timer = 0 self.__turn_around_delay = turn_around_delay <|end_body_0|> <|body_start_1|> if time.time() - self.__timer < self.__turn_around_delay: ...
Class that implements a Controller, used as an interface to communicate easily with the Robot object which communicates directly with the MRDS server.
Controller
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: """Class that implements a Controller, used as an interface to communicate easily with the Robot object which communicates directly with the MRDS server.""" def __init__(self, robot, max_ang_speed=3, ang_speed_weight=0.8, turn_around_delay=8): """Instantiates a Controller...
stack_v2_sparse_classes_36k_train_024115
2,629
permissive
[ { "docstring": "Instantiates a Controller. :param robot: The robot to interface. :type robot: Robot :param max_ang_speed: The robot max angular speed. :type max_ang_speed: float :param ang_speed_weight: The weight to apply to the angular speed. :type ang_speed_weight: float :param turn_around_delay: The delay a...
4
stack_v2_sparse_classes_30k_train_005190
Implement the Python class `Controller` described below. Class description: Class that implements a Controller, used as an interface to communicate easily with the Robot object which communicates directly with the MRDS server. Method signatures and docstrings: - def __init__(self, robot, max_ang_speed=3, ang_speed_we...
Implement the Python class `Controller` described below. Class description: Class that implements a Controller, used as an interface to communicate easily with the Robot object which communicates directly with the MRDS server. Method signatures and docstrings: - def __init__(self, robot, max_ang_speed=3, ang_speed_we...
e36ddcc7d5959957d83fae778d8ef715c79712e7
<|skeleton|> class Controller: """Class that implements a Controller, used as an interface to communicate easily with the Robot object which communicates directly with the MRDS server.""" def __init__(self, robot, max_ang_speed=3, ang_speed_weight=0.8, turn_around_delay=8): """Instantiates a Controller...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Controller: """Class that implements a Controller, used as an interface to communicate easily with the Robot object which communicates directly with the MRDS server.""" def __init__(self, robot, max_ang_speed=3, ang_speed_weight=0.8, turn_around_delay=8): """Instantiates a Controller. :param robo...
the_stack_v2_python_sparse
submission/controller.py
ThomasRanvier/map_maker
train
0
a47b2c0f6588425e067a75aebcbe91888dfd2065
[ "out = self.nanoutput()\nall = None\nfor cs in config.stimuli():\n trs = self.get_stimuli(date.runs('training'), cs, (0, 2), 'dff')\n all = trs if all is None else np.concatenate([all, (trs.T - np.nanmean(trs, axis=1)).T], axis=1)\n out['noisecorr_%s' % cs] = self.calc_noisecorr_cohen(trs)\nout['noisecorr_...
<|body_start_0|> out = self.nanoutput() all = None for cs in config.stimuli(): trs = self.get_stimuli(date.runs('training'), cs, (0, 2), 'dff') all = trs if all is None else np.concatenate([all, (trs.T - np.nanmean(trs, axis=1)).T], axis=1) out['noisecorr_%s' ...
Noisecorr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Noisecorr: def run(self, date): """Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values""" <|body_0|> def get_stimuli(runs, cs, trange=(0, 2), ttype='dff', nolick=False): """Get s...
stack_v2_sparse_classes_36k_train_024116
4,829
no_license
[ { "docstring": "Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values", "name": "run", "signature": "def run(self, date)" }, { "docstring": "Get stimulus responses from training runs Parameters ---------- runs...
4
stack_v2_sparse_classes_30k_train_000164
Implement the Python class `Noisecorr` described below. Class description: Implement the Noisecorr class. Method signatures and docstrings: - def run(self, date): Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values - def get_stim...
Implement the Python class `Noisecorr` described below. Class description: Implement the Noisecorr class. Method signatures and docstrings: - def run(self, date): Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values - def get_stim...
c4e9699fb78db7bd7cc14bc1bd6bd7d2b4e3a16b
<|skeleton|> class Noisecorr: def run(self, date): """Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values""" <|body_0|> def get_stimuli(runs, cs, trange=(0, 2), ttype='dff', nolick=False): """Get s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Noisecorr: def run(self, date): """Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values""" out = self.nanoutput() all = None for cs in config.stimuli(): trs = self.get_stimuli(da...
the_stack_v2_python_sparse
pool/analyses/noisecorr.py
jzaremba/pool
train
0
1c0cc1bb98f5c0b5c05583975d459874cf8455b5
[ "super(DiceLoss, self).__init__()\nself.register_buffer('weight', weight)\nself.weight = weight\nself.p = p\nself.epsilon = epsilon\nif activation is None:\n self.activation = None\nelse:\n self.activation = get_activation(activation)\nself.ignore_label = ignore_label", "if self.activation is not None:\n ...
<|body_start_0|> super(DiceLoss, self).__init__() self.register_buffer('weight', weight) self.weight = weight self.p = p self.epsilon = epsilon if activation is None: self.activation = None else: self.activation = get_activation(activation)...
Dice loss module.
DiceLoss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiceLoss: """Dice loss module.""" def __init__(self, weight=None, p=1.0, epsilon=1e-06, activation=None, ignore_label=-1): """Args: weight (Tensor, optional): tensor of the weight per class with shape (C,). Defaults to None. p (float): exponential to compute union term of dice coeff....
stack_v2_sparse_classes_36k_train_024117
3,995
permissive
[ { "docstring": "Args: weight (Tensor, optional): tensor of the weight per class with shape (C,). Defaults to None. p (float): exponential to compute union term of dice coeff. Defaults to 1.0. epsilon (float, optional): parameter to avoid zero division. Defaults to 1e-6. ignore_label (int): label assigned to the...
2
stack_v2_sparse_classes_30k_train_017907
Implement the Python class `DiceLoss` described below. Class description: Dice loss module. Method signatures and docstrings: - def __init__(self, weight=None, p=1.0, epsilon=1e-06, activation=None, ignore_label=-1): Args: weight (Tensor, optional): tensor of the weight per class with shape (C,). Defaults to None. p ...
Implement the Python class `DiceLoss` described below. Class description: Dice loss module. Method signatures and docstrings: - def __init__(self, weight=None, p=1.0, epsilon=1e-06, activation=None, ignore_label=-1): Args: weight (Tensor, optional): tensor of the weight per class with shape (C,). Defaults to None. p ...
871a24eaad388b8da427e0ab3c95f951629e36d6
<|skeleton|> class DiceLoss: """Dice loss module.""" def __init__(self, weight=None, p=1.0, epsilon=1e-06, activation=None, ignore_label=-1): """Args: weight (Tensor, optional): tensor of the weight per class with shape (C,). Defaults to None. p (float): exponential to compute union term of dice coeff....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiceLoss: """Dice loss module.""" def __init__(self, weight=None, p=1.0, epsilon=1e-06, activation=None, ignore_label=-1): """Args: weight (Tensor, optional): tensor of the weight per class with shape (C,). Defaults to None. p (float): exponential to compute union term of dice coeff. Defaults to ...
the_stack_v2_python_sparse
kits19_3d_segmentation/solvers/losses.py
rabbittuan/kits19_3d_segmentation
train
0
4982f6b20effaba5362371199a3398b444700f96
[ "self.ip = '0.0.0.0'\nself.mac = '00:00:00:00:00:00'\nself.iface = ''\nif entry_line != '':\n self.parse(entry_line)", "i = entry_line.split()\nif len(i) == 3:\n pass\nelif len(i) != 5:\n output.warn('ARP entry line should have 5 items but ' + str(len(i)) + ' found', self.__class__.__name__)\nelse:\n ...
<|body_start_0|> self.ip = '0.0.0.0' self.mac = '00:00:00:00:00:00' self.iface = '' if entry_line != '': self.parse(entry_line) <|end_body_0|> <|body_start_1|> i = entry_line.split() if len(i) == 3: pass elif len(i) != 5: outpu...
ARP entry in table @author ykk @date May 2011
arp_entry
[ "LicenseRef-scancode-x11-stanford" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class arp_entry: """ARP entry in table @author ykk @date May 2011""" def __init__(self, entry_line=''): """Initalize""" <|body_0|> def parse(self, entry_line): """Parse line""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.ip = '0.0.0.0' s...
stack_v2_sparse_classes_36k_train_024118
20,463
permissive
[ { "docstring": "Initalize", "name": "__init__", "signature": "def __init__(self, entry_line='')" }, { "docstring": "Parse line", "name": "parse", "signature": "def parse(self, entry_line)" } ]
2
null
Implement the Python class `arp_entry` described below. Class description: ARP entry in table @author ykk @date May 2011 Method signatures and docstrings: - def __init__(self, entry_line=''): Initalize - def parse(self, entry_line): Parse line
Implement the Python class `arp_entry` described below. Class description: ARP entry in table @author ykk @date May 2011 Method signatures and docstrings: - def __init__(self, entry_line=''): Initalize - def parse(self, entry_line): Parse line <|skeleton|> class arp_entry: """ARP entry in table @author ykk @date...
c3f5a31b74d5587671329eea9582ac8aed0c58a4
<|skeleton|> class arp_entry: """ARP entry in table @author ykk @date May 2011""" def __init__(self, entry_line=''): """Initalize""" <|body_0|> def parse(self, entry_line): """Parse line""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class arp_entry: """ARP entry in table @author ykk @date May 2011""" def __init__(self, entry_line=''): """Initalize""" self.ip = '0.0.0.0' self.mac = '00:00:00:00:00:00' self.iface = '' if entry_line != '': self.parse(entry_line) def parse(self, entry_l...
the_stack_v2_python_sparse
yapc/local/netintf.py
yapkke/yapc
train
1
fce9308830fc740cc28088e98204fa88fcf1297e
[ "assert os.path.isfile(filename)\nassert filename.endswith('.docx')\nself.__filename = filename", "try:\n pythoncom.CoInitialize()\n gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)\n w = Dispatch('Word.Application')\n try:\n doc = w.Documents.Open(self.__filename, ReadO...
<|body_start_0|> assert os.path.isfile(filename) assert filename.endswith('.docx') self.__filename = filename <|end_body_0|> <|body_start_1|> try: pythoncom.CoInitialize() gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4) w = Di...
Word (.docx) File Object.
WordFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordFile: """Word (.docx) File Object.""" def __init__(self, filename): """Create a Word file (.docx) object. Parameters ---------- filename: str Word file's (.docx) name. Returns ------- WordFile Return its case. Raises ------ AssertionError If the file does not exist and the suffix...
stack_v2_sparse_classes_36k_train_024119
2,390
no_license
[ { "docstring": "Create a Word file (.docx) object. Parameters ---------- filename: str Word file's (.docx) name. Returns ------- WordFile Return its case. Raises ------ AssertionError If the file does not exist and the suffix is not '.docx', raise it.", "name": "__init__", "signature": "def __init__(sel...
2
stack_v2_sparse_classes_30k_train_020119
Implement the Python class `WordFile` described below. Class description: Word (.docx) File Object. Method signatures and docstrings: - def __init__(self, filename): Create a Word file (.docx) object. Parameters ---------- filename: str Word file's (.docx) name. Returns ------- WordFile Return its case. Raises ------...
Implement the Python class `WordFile` described below. Class description: Word (.docx) File Object. Method signatures and docstrings: - def __init__(self, filename): Create a Word file (.docx) object. Parameters ---------- filename: str Word file's (.docx) name. Returns ------- WordFile Return its case. Raises ------...
dab562f762cd7abb87496bcae2e49f27179a417e
<|skeleton|> class WordFile: """Word (.docx) File Object.""" def __init__(self, filename): """Create a Word file (.docx) object. Parameters ---------- filename: str Word file's (.docx) name. Returns ------- WordFile Return its case. Raises ------ AssertionError If the file does not exist and the suffix...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordFile: """Word (.docx) File Object.""" def __init__(self, filename): """Create a Word file (.docx) object. Parameters ---------- filename: str Word file's (.docx) name. Returns ------- WordFile Return its case. Raises ------ AssertionError If the file does not exist and the suffix is not '.doc...
the_stack_v2_python_sparse
Files/WordFile.py
zhangletao/Tools
train
0
2723fb1ad8050a2b1f8a90964f12661e0e0ca92a
[ "super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(units=dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNo...
<|body_start_0|> super(EncoderBlock, self).__init__() self.mha = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu') self.dense_output = tf.keras.layers.Dense(units=dm) self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1...
Class MultiHeadAttention
EncoderBlock
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncoderBlock: """Class MultiHeadAttention""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate S...
stack_v2_sparse_classes_36k_train_024120
2,302
permissive
[ { "docstring": "Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate Sets the following public instance attributes: mha - a MultiHeadAttention layer dense_hidden - the hidden dense...
2
stack_v2_sparse_classes_30k_train_015856
Implement the Python class `EncoderBlock` described below. Class description: Class MultiHeadAttention Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in...
Implement the Python class `EncoderBlock` described below. Class description: Class MultiHeadAttention Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in...
eaf23423ec0f412f103f5931d6610fdd67bcc5be
<|skeleton|> class EncoderBlock: """Class MultiHeadAttention""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate S...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncoderBlock: """Class MultiHeadAttention""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate Sets the follo...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/7-transformer_encoder_block.py
ledbagholberton/holbertonschool-machine_learning
train
1
1edfe8a06b3738d103b1616feb314d3f9b6a7878
[ "q = collections.deque([root])\nresult = ['#']\nwhile q:\n node = q.popleft()\n if node:\n q.append(node.left)\n q.append(node.right)\n result.append(str(node.val))\n else:\n result.append('#')\nreturn ' '.join(result)", "if data == '# #':\n return None\nnodes = data.split(...
<|body_start_0|> q = collections.deque([root]) result = ['#'] while q: node = q.popleft() if node: q.append(node.left) q.append(node.right) result.append(str(node.val)) else: result.append('#') ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_024121
1,644
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
46c04e0f583d4c6ec4f51a24f19a373b173b3d5c
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" q = collections.deque([root]) result = ['#'] while q: node = q.popleft() if node: q.append(node.left) q.append(nod...
the_stack_v2_python_sparse
코테.py
hyeokjinson/algorithm
train
1
2ccc503f8a9efd4aa08f95ef77e3b4988adb1420
[ "comments = CommentsSongs.query.order_by(asc(CommentsSongs.SongID), asc(CommentsSongs.Created)).all()\ncontents = jsonify({'comments': [{'commentID': comment.CommentID, 'songID': comment.SongID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'createdAt': get_iso_format(c...
<|body_start_0|> comments = CommentsSongs.query.order_by(asc(CommentsSongs.SongID), asc(CommentsSongs.Created)).all() contents = jsonify({'comments': [{'commentID': comment.CommentID, 'songID': comment.SongID, 'userID': comment.UserID, 'name': get_username(comment.UserID), 'comment': comment.Comment, 'c...
SongCommentsView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SongCommentsView: def index(self): """Return all comments for all songs.""" <|body_0|> def get(self, song_id): """Return the comments for a specific song.""" <|body_1|> def post(self): """Add a comment to a song specified in the payload.""" ...
stack_v2_sparse_classes_36k_train_024122
26,847
permissive
[ { "docstring": "Return all comments for all songs.", "name": "index", "signature": "def index(self)" }, { "docstring": "Return the comments for a specific song.", "name": "get", "signature": "def get(self, song_id)" }, { "docstring": "Add a comment to a song specified in the payl...
5
stack_v2_sparse_classes_30k_train_011233
Implement the Python class `SongCommentsView` described below. Class description: Implement the SongCommentsView class. Method signatures and docstrings: - def index(self): Return all comments for all songs. - def get(self, song_id): Return the comments for a specific song. - def post(self): Add a comment to a song s...
Implement the Python class `SongCommentsView` described below. Class description: Implement the SongCommentsView class. Method signatures and docstrings: - def index(self): Return all comments for all songs. - def get(self, song_id): Return the comments for a specific song. - def post(self): Add a comment to a song s...
62f8e8e904e379541193f0cbb91a8434b47f538f
<|skeleton|> class SongCommentsView: def index(self): """Return all comments for all songs.""" <|body_0|> def get(self, song_id): """Return the comments for a specific song.""" <|body_1|> def post(self): """Add a comment to a song specified in the payload.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SongCommentsView: def index(self): """Return all comments for all songs.""" comments = CommentsSongs.query.order_by(asc(CommentsSongs.SongID), asc(CommentsSongs.Created)).all() contents = jsonify({'comments': [{'commentID': comment.CommentID, 'songID': comment.SongID, 'userID': comment...
the_stack_v2_python_sparse
apps/comments/views.py
Torniojaws/vortech-backend
train
0
0f4ca0ea5e83c4ea764f04cff625d2b01258e88f
[ "self._doc_class = doc_class\nself._cb = cb\nself._count_valid = False\nsuper(BaseQuery, self).__init__()\nself._total_results = 0", "if self._count_valid:\n return self._total_results\nresult = self._cb.get_object(self._doc_class.urlobject.format(self._cb.credentials.org_key))\nresults = result.get('results',...
<|body_start_0|> self._doc_class = doc_class self._cb = cb self._count_valid = False super(BaseQuery, self).__init__() self._total_results = 0 <|end_body_0|> <|body_start_1|> if self._count_valid: return self._total_results result = self._cb.get_objec...
Represents a query that is used to locate USBDeviceBlock objects.
USBDeviceBlockQuery
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class USBDeviceBlockQuery: """Represents a query that is used to locate USBDeviceBlock objects.""" def __init__(self, doc_class, cb): """Initialize the USBDeviceBlockQuery. Args: doc_class (class): The model class that will be returned by this query. cb (BaseAPI): Reference to API object u...
stack_v2_sparse_classes_36k_train_024123
31,170
permissive
[ { "docstring": "Initialize the USBDeviceBlockQuery. Args: doc_class (class): The model class that will be returned by this query. cb (BaseAPI): Reference to API object used to communicate with the server.", "name": "__init__", "signature": "def __init__(self, doc_class, cb)" }, { "docstring": "R...
4
stack_v2_sparse_classes_30k_train_003840
Implement the Python class `USBDeviceBlockQuery` described below. Class description: Represents a query that is used to locate USBDeviceBlock objects. Method signatures and docstrings: - def __init__(self, doc_class, cb): Initialize the USBDeviceBlockQuery. Args: doc_class (class): The model class that will be return...
Implement the Python class `USBDeviceBlockQuery` described below. Class description: Represents a query that is used to locate USBDeviceBlock objects. Method signatures and docstrings: - def __init__(self, doc_class, cb): Initialize the USBDeviceBlockQuery. Args: doc_class (class): The model class that will be return...
a8a2ec8ff6b9985b4fb4700d9d566e8e2a297381
<|skeleton|> class USBDeviceBlockQuery: """Represents a query that is used to locate USBDeviceBlock objects.""" def __init__(self, doc_class, cb): """Initialize the USBDeviceBlockQuery. Args: doc_class (class): The model class that will be returned by this query. cb (BaseAPI): Reference to API object u...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class USBDeviceBlockQuery: """Represents a query that is used to locate USBDeviceBlock objects.""" def __init__(self, doc_class, cb): """Initialize the USBDeviceBlockQuery. Args: doc_class (class): The model class that will be returned by this query. cb (BaseAPI): Reference to API object used to commun...
the_stack_v2_python_sparse
src/cbc_sdk/endpoint_standard/usb_device_control.py
fslds/carbon-black-cloud-sdk-python
train
0
ffbcf06dfb4ca6f267808f4235baf87d86dcaf11
[ "E0 = a0 * m_e * c ** 2 * k0 / e\nself.k0 = k0\nself.waist = waist\nself.inv_tau = 1.0 / tau\nself.t_peak = t_peak\nself.E0 = E0\nself.v_antenna = source_v\nself.boost = boost\nself.temporal_order = temporal_order\nself.theta_zx = theta_zx\nself.x_center = x_center\nself.geom_coeff = get_geometric_coeff(dim)", "t...
<|body_start_0|> E0 = a0 * m_e * c ** 2 * k0 / e self.k0 = k0 self.waist = waist self.inv_tau = 1.0 / tau self.t_peak = t_peak self.E0 = E0 self.v_antenna = source_v self.boost = boost self.temporal_order = temporal_order self.theta_zx = th...
Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.
JincGaussianAngleProfile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JincGaussianAngleProfile: """Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.""" def __init__(self, k0, waist, tau, t_peak, a0, dim, temporal_order=2, boost=None, source_v=0, theta_zx=0.0,...
stack_v2_sparse_classes_36k_train_024124
34,589
permissive
[ { "docstring": "Define a laser profile with is a Jinc function transversely and a supergaussian function longitudinally. The antenna is orthogonal to z, but this profile supports a non-zero angle in the (z, x) plane, and is compatible with the boosted frame and a moving window. Note 1: The focal plane is the pl...
2
null
Implement the Python class `JincGaussianAngleProfile` described below. Class description: Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z. Method signatures and docstrings: - def __init__(self, k0, waist, tau, t_pe...
Implement the Python class `JincGaussianAngleProfile` described below. Class description: Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z. Method signatures and docstrings: - def __init__(self, k0, waist, tau, t_pe...
091c982f82788209017315e13eb7d0e743687d46
<|skeleton|> class JincGaussianAngleProfile: """Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.""" def __init__(self, k0, waist, tau, t_peak, a0, dim, temporal_order=2, boost=None, source_v=0, theta_zx=0.0,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JincGaussianAngleProfile: """Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.""" def __init__(self, k0, waist, tau, t_peak, a0, dim, temporal_order=2, boost=None, source_v=0, theta_zx=0.0, x_center=0.0...
the_stack_v2_python_sparse
scripts/field_solvers/laser/laser_profiles.py
giadarol/warp
train
0
f8956b944efd1fa0f32cde7e248ea4a1a5f22f95
[ "n = len(data)\ndp = [1] * (n + 1)\nfor i in range(2, n + 1):\n for j in range(i - 1):\n if data[i - 1] == data[j] + 1:\n dp[i] = max(dp[j + 1] + 1, dp[i])\nreturn n - max(dp)", "if not data:\n return 0\nAList_map = []\nfor num in data:\n flag = 0\n if AList_map:\n for map_old...
<|body_start_0|> n = len(data) dp = [1] * (n + 1) for i in range(2, n + 1): for j in range(i - 1): if data[i - 1] == data[j] + 1: dp[i] = max(dp[j + 1] + 1, dp[i]) return n - max(dp) <|end_body_0|> <|body_start_1|> if not data: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def moveStoneMinNum(self, data): """分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp...
stack_v2_sparse_classes_36k_train_024125
1,613
no_license
[ { "docstring": "分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp) T:O(n^2) M:O(n)", "name": "moveStoneMinNum", ...
2
stack_v2_sparse_classes_30k_train_019878
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveStoneMinNum(self, data): 分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串....
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveStoneMinNum(self, data): 分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串....
57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb
<|skeleton|> class Solution: def moveStoneMinNum(self, data): """分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def moveStoneMinNum(self, data): """分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp) T:O(n^2) M:O...
the_stack_v2_python_sparse
4_LEETCODE/11_Interview/浪潮/石头排序.py
fzingithub/SwordRefers2Offer
train
1
f6b190448cd9d756c127d35f070bb804392b84cd
[ "prefix = f'{slugify(prefix)}_' if prefix else ''\nextension = f'.{extension}' if extension else ''\nreturn f'{prefix}{slugify(title)}{extension}'", "match = re.match('^(?P<title>.*)(\\\\.{extension_regex:s})$'.format(extension_regex=EXTENSION_REGEX), value)\nif match:\n return match.group('title')\nreturn val...
<|body_start_0|> prefix = f'{slugify(prefix)}_' if prefix else '' extension = f'.{extension}' if extension else '' return f'{prefix}{slugify(title)}{extension}' <|end_body_0|> <|body_start_1|> match = re.match('^(?P<title>.*)(\\.{extension_regex:s})$'.format(extension_regex=EXTENSION_RE...
Set of function used by uploadable files managing an extension.
UploadableFileWithExtensionSerializerMixin
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadableFileWithExtensionSerializerMixin: """Set of function used by uploadable files managing an extension.""" def _get_filename(self, title, extension=None, prefix=None): """Filename of an object. Parameters ---------- title : Type[string] The raw object title extension: Type[str...
stack_v2_sparse_classes_36k_train_024126
8,960
permissive
[ { "docstring": "Filename of an object. Parameters ---------- title : Type[string] The raw object title extension: Type[string] The file extension if any prefix: Type[string] The file prefix if any Returns ------- String The document's filename", "name": "_get_filename", "signature": "def _get_filename(s...
2
stack_v2_sparse_classes_30k_train_020683
Implement the Python class `UploadableFileWithExtensionSerializerMixin` described below. Class description: Set of function used by uploadable files managing an extension. Method signatures and docstrings: - def _get_filename(self, title, extension=None, prefix=None): Filename of an object. Parameters ---------- titl...
Implement the Python class `UploadableFileWithExtensionSerializerMixin` described below. Class description: Set of function used by uploadable files managing an extension. Method signatures and docstrings: - def _get_filename(self, title, extension=None, prefix=None): Filename of an object. Parameters ---------- titl...
f767f1bdc12c9712f26ea17cb8b19f536389f0ed
<|skeleton|> class UploadableFileWithExtensionSerializerMixin: """Set of function used by uploadable files managing an extension.""" def _get_filename(self, title, extension=None, prefix=None): """Filename of an object. Parameters ---------- title : Type[string] The raw object title extension: Type[str...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UploadableFileWithExtensionSerializerMixin: """Set of function used by uploadable files managing an extension.""" def _get_filename(self, title, extension=None, prefix=None): """Filename of an object. Parameters ---------- title : Type[string] The raw object title extension: Type[string] The file...
the_stack_v2_python_sparse
src/backend/marsha/core/serializers/base.py
openfun/marsha
train
92
55360ed8fba6d345f30ad6b272172cf01ef7c9ca
[ "self.num_players = num_players\nself.total_num_marbles = total_num_marbles\nself.marbles = deque([0])\nself.player_in_turn = 1\nself.scores = Counter()", "for marble_id in range(1, self.total_num_marbles + 1):\n if marble_id % 100000 == 0:\n print(marble_id)\n if marble_id % 23 == 0:\n self.m...
<|body_start_0|> self.num_players = num_players self.total_num_marbles = total_num_marbles self.marbles = deque([0]) self.player_in_turn = 1 self.scores = Counter() <|end_body_0|> <|body_start_1|> for marble_id in range(1, self.total_num_marbles + 1): if marb...
class for the marbles game as defined in the problem statement
Marbles
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Marbles: """class for the marbles game as defined in the problem statement""" def __init__(self, num_players: int, total_num_marbles: int): """input: how many players, how many marbles to play""" <|body_0|> def play(self): """Plays the game of marbles until finis...
stack_v2_sparse_classes_36k_train_024127
3,796
no_license
[ { "docstring": "input: how many players, how many marbles to play", "name": "__init__", "signature": "def __init__(self, num_players: int, total_num_marbles: int)" }, { "docstring": "Plays the game of marbles until finish. Returns scores Counter", "name": "play", "signature": "def play(s...
2
stack_v2_sparse_classes_30k_train_018589
Implement the Python class `Marbles` described below. Class description: class for the marbles game as defined in the problem statement Method signatures and docstrings: - def __init__(self, num_players: int, total_num_marbles: int): input: how many players, how many marbles to play - def play(self): Plays the game o...
Implement the Python class `Marbles` described below. Class description: class for the marbles game as defined in the problem statement Method signatures and docstrings: - def __init__(self, num_players: int, total_num_marbles: int): input: how many players, how many marbles to play - def play(self): Plays the game o...
a249b7092a1ae9b54b79eb4425036f45c7e04d74
<|skeleton|> class Marbles: """class for the marbles game as defined in the problem statement""" def __init__(self, num_players: int, total_num_marbles: int): """input: how many players, how many marbles to play""" <|body_0|> def play(self): """Plays the game of marbles until finis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Marbles: """class for the marbles game as defined in the problem statement""" def __init__(self, num_players: int, total_num_marbles: int): """input: how many players, how many marbles to play""" self.num_players = num_players self.total_num_marbles = total_num_marbles sel...
the_stack_v2_python_sparse
day09_marble_mania_v3.py
aleksiheikkila/AdventOfCode2018
train
0
73a08a944039b4fc8c0b18c7f70d89221dee9841
[ "_id = request.args.get('id', None)\nif not _id:\n return ({'msg': 'params error !'}, 400)\ntry:\n result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'data_section': 1})\n if not result:\n return ({'msg': 'id is not exist !'}, 200)\nexcept Exception as e:\n logging.error(e, e...
<|body_start_0|> _id = request.args.get('id', None) if not _id: return ({'msg': 'params error !'}, 400) try: result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'data_section': 1}) if not result: return ({'msg': 'id is not e...
DataSectionViews
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataSectionViews: def get(self): """get one data section through id :return:""" <|body_0|> def post(self): """add an data section record :return:""" <|body_1|> def put(self): """update data section record :return:""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_36k_train_024128
20,183
no_license
[ { "docstring": "get one data section through id :return:", "name": "get", "signature": "def get(self)" }, { "docstring": "add an data section record :return:", "name": "post", "signature": "def post(self)" }, { "docstring": "update data section record :return:", "name": "put"...
3
stack_v2_sparse_classes_30k_train_021615
Implement the Python class `DataSectionViews` described below. Class description: Implement the DataSectionViews class. Method signatures and docstrings: - def get(self): get one data section through id :return: - def post(self): add an data section record :return: - def put(self): update data section record :return:
Implement the Python class `DataSectionViews` described below. Class description: Implement the DataSectionViews class. Method signatures and docstrings: - def get(self): get one data section through id :return: - def post(self): add an data section record :return: - def put(self): update data section record :return:...
054324b50e807d6f4e98f4a1b67afac9a0653b06
<|skeleton|> class DataSectionViews: def get(self): """get one data section through id :return:""" <|body_0|> def post(self): """add an data section record :return:""" <|body_1|> def put(self): """update data section record :return:""" <|body_2|> <|end_ske...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataSectionViews: def get(self): """get one data section through id :return:""" _id = request.args.get('id', None) if not _id: return ({'msg': 'params error !'}, 400) try: result = mongo_algo.db.algo_info.find_one({'_id': bson.ObjectId(_id)}, {'data_sect...
the_stack_v2_python_sparse
services/AlgoVersion/views.py
condilin/DMS
train
0
f9c5bcea20a8d0bdd41c3c6b3dbd4eb347316576
[ "super().__init__()\nself.linear = LinearPolicy(inp_n, hidden_size, hidden_size, num_layers - 1, activation_fn)\nif num_layers > 1:\n self.linear = nn.Sequential(self.linear, activation_fn())\n last_in_n = hidden_size\nelse:\n last_in_n = inp_n\nself.mean = nn.Linear(last_in_n, out_n)\nself.log_std = nn.Li...
<|body_start_0|> super().__init__() self.linear = LinearPolicy(inp_n, hidden_size, hidden_size, num_layers - 1, activation_fn) if num_layers > 1: self.linear = nn.Sequential(self.linear, activation_fn()) last_in_n = hidden_size else: last_in_n = inp_n ...
A simple gaussian policy.
GaussianPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaussianPolicy: """A simple gaussian policy.""" def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): """Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the n...
stack_v2_sparse_classes_36k_train_024129
6,947
permissive
[ { "docstring": "Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the network. hidden_size: The number of units in each hidden layer. num_layers: The number of layers before the gaussian layer. activation_fn: The activation function in bet...
3
null
Implement the Python class `GaussianPolicy` described below. Class description: A simple gaussian policy. Method signatures and docstrings: - def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): Creates the gaussian policy. Args: inp_n: The number of input units to ...
Implement the Python class `GaussianPolicy` described below. Class description: A simple gaussian policy. Method signatures and docstrings: - def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): Creates the gaussian policy. Args: inp_n: The number of input units to ...
cde3be1c69bfd76fe4a78fa529e851d0a78318c7
<|skeleton|> class GaussianPolicy: """A simple gaussian policy.""" def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): """Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GaussianPolicy: """A simple gaussian policy.""" def __init__(self, inp_n: int, out_n: int, hidden_size: int, num_layers: int, activation_fn: nn.Module): """Creates the gaussian policy. Args: inp_n: The number of input units to the network. out_n: The number of output units from the network. hidde...
the_stack_v2_python_sparse
hlrl/torch/policies/distribution.py
Chainso/HLRL
train
3
41fa99d6de5ae139cacd40bb2788d0d5a93a4391
[ "if not root:\n return True\nreturn self.is_symmetric_recursive(root)", "def recursion(node1, node2):\n if not node1 and (not node2):\n return True\n return bool(node1) and bool(node2) and (node1.val == node2.val) and recursion(node1.left, node2.right) and recursion(node1.right, node2.left)\nretur...
<|body_start_0|> if not root: return True return self.is_symmetric_recursive(root) <|end_body_0|> <|body_start_1|> def recursion(node1, node2): if not node1 and (not node2): return True return bool(node1) and bool(node2) and (node1.val == node...
Solution to Leetcode problem 101: Symmetric Tree. Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Solution to Leetcode problem 101: Symmetric Tree. Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None""" def is_symmetric(self, root): """Determine whether a given binary tree is left-right sym...
stack_v2_sparse_classes_36k_train_024130
3,129
no_license
[ { "docstring": "Determine whether a given binary tree is left-right symmetric. :type root: TreeNode :rtype: bool", "name": "is_symmetric", "signature": "def is_symmetric(self, root)" }, { "docstring": "Symmetric tree: recursive solution.", "name": "is_symmetric_recursive", "signature": "...
3
stack_v2_sparse_classes_30k_train_000332
Implement the Python class `Solution` described below. Class description: Solution to Leetcode problem 101: Symmetric Tree. Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None Method signatures and docstrings: - def is_symmetric(self, root)...
Implement the Python class `Solution` described below. Class description: Solution to Leetcode problem 101: Symmetric Tree. Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None Method signatures and docstrings: - def is_symmetric(self, root)...
e11bfc454789e716055b80873af0817ec8588aea
<|skeleton|> class Solution: """Solution to Leetcode problem 101: Symmetric Tree. Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None""" def is_symmetric(self, root): """Determine whether a given binary tree is left-right sym...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Solution to Leetcode problem 101: Symmetric Tree. Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None""" def is_symmetric(self, root): """Determine whether a given binary tree is left-right symmetric. :type...
the_stack_v2_python_sparse
p101/problem101.py
stanl3y/leetcode
train
0
82a9f0351d5a2090536aa2ff868063a444b2a158
[ "self.resnet_size = resnet_size\nself.data_format = data_format\nself.dtype = dtype\nself.is_classification = is_classification\nself.block_stride = [1, 2, 2, 2]\nself.num_classes = num_classes", "choices = {18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24,...
<|body_start_0|> self.resnet_size = resnet_size self.data_format = data_format self.dtype = dtype self.is_classification = is_classification self.block_stride = [1, 2, 2, 2] self.num_classes = num_classes <|end_body_0|> <|body_start_1|> choices = {18: [2, 2, 2, 2...
ResNet_use
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResNet_use: def __init__(self, resnet_size, data_format='channels_first', dtype='float32', is_classification=False, num_classes=None): """:param inPuts: :param resnet_size: :param data_format: :param dtype: :param is_train: :param is_classification:""" <|body_0|> def size_2_...
stack_v2_sparse_classes_36k_train_024131
3,795
no_license
[ { "docstring": ":param inPuts: :param resnet_size: :param data_format: :param dtype: :param is_train: :param is_classification:", "name": "__init__", "signature": "def __init__(self, resnet_size, data_format='channels_first', dtype='float32', is_classification=False, num_classes=None)" }, { "doc...
3
stack_v2_sparse_classes_30k_train_009789
Implement the Python class `ResNet_use` described below. Class description: Implement the ResNet_use class. Method signatures and docstrings: - def __init__(self, resnet_size, data_format='channels_first', dtype='float32', is_classification=False, num_classes=None): :param inPuts: :param resnet_size: :param data_form...
Implement the Python class `ResNet_use` described below. Class description: Implement the ResNet_use class. Method signatures and docstrings: - def __init__(self, resnet_size, data_format='channels_first', dtype='float32', is_classification=False, num_classes=None): :param inPuts: :param resnet_size: :param data_form...
032cb39eb17f4ff4ec852027e0021031a3fc0433
<|skeleton|> class ResNet_use: def __init__(self, resnet_size, data_format='channels_first', dtype='float32', is_classification=False, num_classes=None): """:param inPuts: :param resnet_size: :param data_format: :param dtype: :param is_train: :param is_classification:""" <|body_0|> def size_2_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResNet_use: def __init__(self, resnet_size, data_format='channels_first', dtype='float32', is_classification=False, num_classes=None): """:param inPuts: :param resnet_size: :param data_format: :param dtype: :param is_train: :param is_classification:""" self.resnet_size = resnet_size se...
the_stack_v2_python_sparse
base/ResNet.py
YJHMITWEB/TensorBox
train
0
26c19746cde7be455a4386c1932ab17bc0a88507
[ "nr = choice(range(150))\ninput_file = open(filename).readlines()\nfilename = self._input_filename = 'mfold_in%d.txt' % nr\ndata_file = open(filename, 'w')\ndata_to_file = '\\n'.join([str(d).strip('\\n') for d in input_file])\ndata_file.write(data_to_file)\ndata_file.close()\ndata = '='.join(['SEQ', filename])\nret...
<|body_start_0|> nr = choice(range(150)) input_file = open(filename).readlines() filename = self._input_filename = 'mfold_in%d.txt' % nr data_file = open(filename, 'w') data_to_file = '\n'.join([str(d).strip('\n') for d in input_file]) data_file.write(data_to_file) ...
Application controller for mfold 3.2 application
Mfold
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mfold: """Application controller for mfold 3.2 application""" def _input_as_string(self, filename): """mfold dosen't take full paths so a tmp-file is created in the working dir for mfold to read.""" <|body_0|> def _input_as_lines(self, data): """Uses a fixed tmp ...
stack_v2_sparse_classes_36k_train_024132
4,259
permissive
[ { "docstring": "mfold dosen't take full paths so a tmp-file is created in the working dir for mfold to read.", "name": "_input_as_string", "signature": "def _input_as_string(self, filename)" }, { "docstring": "Uses a fixed tmp filename since weird truncation of the generated filename sometimes o...
3
null
Implement the Python class `Mfold` described below. Class description: Application controller for mfold 3.2 application Method signatures and docstrings: - def _input_as_string(self, filename): mfold dosen't take full paths so a tmp-file is created in the working dir for mfold to read. - def _input_as_lines(self, dat...
Implement the Python class `Mfold` described below. Class description: Application controller for mfold 3.2 application Method signatures and docstrings: - def _input_as_string(self, filename): mfold dosen't take full paths so a tmp-file is created in the working dir for mfold to read. - def _input_as_lines(self, dat...
fe6f8c8dfed86d39c80f2804a753c05bb2e485b4
<|skeleton|> class Mfold: """Application controller for mfold 3.2 application""" def _input_as_string(self, filename): """mfold dosen't take full paths so a tmp-file is created in the working dir for mfold to read.""" <|body_0|> def _input_as_lines(self, data): """Uses a fixed tmp ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mfold: """Application controller for mfold 3.2 application""" def _input_as_string(self, filename): """mfold dosen't take full paths so a tmp-file is created in the working dir for mfold to read.""" nr = choice(range(150)) input_file = open(filename).readlines() filename =...
the_stack_v2_python_sparse
scripts/venv/lib/python2.7/site-packages/cogent/app/mfold.py
sauloal/cnidaria
train
3
f4dd25fd5a088594d76f78e65976977852745640
[ "super().__init__()\nself.backbone_model = RobertaModel.from_cfg(backbone_cfg)\nif weight_initializer is None:\n weight_initializer = self.backbone_model.weight_initializer\nif bias_initializer is None:\n bias_initializer = self.backbone_model.bias_initializer\nself.units = self.backbone_model.units\nself.mlm...
<|body_start_0|> super().__init__() self.backbone_model = RobertaModel.from_cfg(backbone_cfg) if weight_initializer is None: weight_initializer = self.backbone_model.weight_initializer if bias_initializer is None: bias_initializer = self.backbone_model.bias_initia...
RobertaForMLM
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RobertaForMLM: def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None): """Parameters ---------- backbone_cfg weight_initializer bias_initializer""" <|body_0|> def forward(self, inputs, valid_length, masked_positions): """Getting the scores o...
stack_v2_sparse_classes_36k_train_024133
22,705
permissive
[ { "docstring": "Parameters ---------- backbone_cfg weight_initializer bias_initializer", "name": "__init__", "signature": "def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None)" }, { "docstring": "Getting the scores of the masked positions. Parameters ---------- inputs...
2
stack_v2_sparse_classes_30k_train_005279
Implement the Python class `RobertaForMLM` described below. Class description: Implement the RobertaForMLM class. Method signatures and docstrings: - def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None): Parameters ---------- backbone_cfg weight_initializer bias_initializer - def forward(s...
Implement the Python class `RobertaForMLM` described below. Class description: Implement the RobertaForMLM class. Method signatures and docstrings: - def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None): Parameters ---------- backbone_cfg weight_initializer bias_initializer - def forward(s...
1df42c561ae9552960e3f8b5f22e74de812a29c6
<|skeleton|> class RobertaForMLM: def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None): """Parameters ---------- backbone_cfg weight_initializer bias_initializer""" <|body_0|> def forward(self, inputs, valid_length, masked_positions): """Getting the scores o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RobertaForMLM: def __init__(self, backbone_cfg, weight_initializer=None, bias_initializer=None): """Parameters ---------- backbone_cfg weight_initializer bias_initializer""" super().__init__() self.backbone_model = RobertaModel.from_cfg(backbone_cfg) if weight_initializer is No...
the_stack_v2_python_sparse
src/gluonnlp/models/roberta.py
akshatgui/gluon-nlp
train
0
b763c1f00360f50874b7c0565f4f64de8f386e5f
[ "self.value = value\nself.left = left\nself.right = right", "sub = []\nif self.left:\n sub = sub + self.left.deconstruct(level + '@')\nif self.right:\n sub = sub + self.right.deconstruct(level + '@')\nreturn [level] + [self.value] + sub", "treeInString = self.deconstruct()\nlayers = {}\nfor e in treeInStr...
<|body_start_0|> self.value = value self.left = left self.right = right <|end_body_0|> <|body_start_1|> sub = [] if self.left: sub = sub + self.left.deconstruct(level + '@') if self.right: sub = sub + self.right.deconstruct(level + '@') re...
Node class for a binary tree.
Node
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Node: """Node class for a binary tree.""" def __init__(self, value, left=None, right=None): """Initialize the node.""" <|body_0|> def deconstruct(self, level='@'): """Deconstruct the binary tree into a string.""" <|body_1|> def printLevelWise(self): ...
stack_v2_sparse_classes_36k_train_024134
1,627
no_license
[ { "docstring": "Initialize the node.", "name": "__init__", "signature": "def __init__(self, value, left=None, right=None)" }, { "docstring": "Deconstruct the binary tree into a string.", "name": "deconstruct", "signature": "def deconstruct(self, level='@')" }, { "docstring": "Pri...
3
null
Implement the Python class `Node` described below. Class description: Node class for a binary tree. Method signatures and docstrings: - def __init__(self, value, left=None, right=None): Initialize the node. - def deconstruct(self, level='@'): Deconstruct the binary tree into a string. - def printLevelWise(self): Prin...
Implement the Python class `Node` described below. Class description: Node class for a binary tree. Method signatures and docstrings: - def __init__(self, value, left=None, right=None): Initialize the node. - def deconstruct(self, level='@'): Deconstruct the binary tree into a string. - def printLevelWise(self): Prin...
97eae3ee806756f4d646d600f434b1e68164ad34
<|skeleton|> class Node: """Node class for a binary tree.""" def __init__(self, value, left=None, right=None): """Initialize the node.""" <|body_0|> def deconstruct(self, level='@'): """Deconstruct the binary tree into a string.""" <|body_1|> def printLevelWise(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Node: """Node class for a binary tree.""" def __init__(self, value, left=None, right=None): """Initialize the node.""" self.value = value self.left = left self.right = right def deconstruct(self, level='@'): """Deconstruct the binary tree into a string.""" ...
the_stack_v2_python_sparse
Python/2019_05_02_Problem_107_Print_Binary_Tree_Level_Wise.py
BaoCaiH/Daily_Coding_Problem
train
0
bc98ad089e3c572c73f9786a3433f5e5beadd4c3
[ "task = self.images_behavior.create_new_task()\nresponse = self.images_client.get_task(task.id_)\nself.assertEqual(response.status_code, 200)\nget_task = response.entity\nself._validate_get_task_response(task, get_task)", "errors = []\nif get_task.status != TaskStatus.SUCCESS:\n errors.append(self.error_msg.fo...
<|body_start_0|> task = self.images_behavior.create_new_task() response = self.images_client.get_task(task.id_) self.assertEqual(response.status_code, 200) get_task = response.entity self._validate_get_task_response(task, get_task) <|end_body_0|> <|body_start_1|> errors ...
TestGetTask
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGetTask: def test_get_task(self): """@summary: Get task 1) Create task 2) Get task 3) Verify that the response code is 200 4) Verify that the task contains the expected data""" <|body_0|> def _validate_get_task_response(self, task, get_task): """@summary: Validat...
stack_v2_sparse_classes_36k_train_024135
3,923
permissive
[ { "docstring": "@summary: Get task 1) Create task 2) Get task 3) Verify that the response code is 200 4) Verify that the task contains the expected data", "name": "test_get_task", "signature": "def test_get_task(self)" }, { "docstring": "@summary: Validate that the task and get_task responses ma...
2
null
Implement the Python class `TestGetTask` described below. Class description: Implement the TestGetTask class. Method signatures and docstrings: - def test_get_task(self): @summary: Get task 1) Create task 2) Get task 3) Verify that the response code is 200 4) Verify that the task contains the expected data - def _val...
Implement the Python class `TestGetTask` described below. Class description: Implement the TestGetTask class. Method signatures and docstrings: - def test_get_task(self): @summary: Get task 1) Create task 2) Get task 3) Verify that the response code is 200 4) Verify that the task contains the expected data - def _val...
30f0e64672676c3f90b4a582fe90fac6621475b3
<|skeleton|> class TestGetTask: def test_get_task(self): """@summary: Get task 1) Create task 2) Get task 3) Verify that the response code is 200 4) Verify that the task contains the expected data""" <|body_0|> def _validate_get_task_response(self, task, get_task): """@summary: Validat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestGetTask: def test_get_task(self): """@summary: Get task 1) Create task 2) Get task 3) Verify that the response code is 200 4) Verify that the task contains the expected data""" task = self.images_behavior.create_new_task() response = self.images_client.get_task(task.id_) se...
the_stack_v2_python_sparse
cloudroast/images/v2/functional/test_get_task.py
RULCSoft/cloudroast
train
1
e51ea1e9cd9459421b9e5b847dc1dee6ceae7584
[ "count = [0] * 32\nfor num in nums:\n k = 0\n while k < 32:\n count[k] += num >> k & 1\n k += 1\nres = 0\nfor i in range(32):\n res += count[i] % 3 * 2 ** i\nreturn res", "ones, twos = (0, 0)\nfor num in nums:\n ones = (ones ^ num) & ~twos\n twos = (twos ^ num) & ~ones\nreturn ones" ]
<|body_start_0|> count = [0] * 32 for num in nums: k = 0 while k < 32: count[k] += num >> k & 1 k += 1 res = 0 for i in range(32): res += count[i] % 3 * 2 ** i return res <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findNumberAppearingOnce(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findNumberAppearingOnce_2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> count = [0] * 32 ...
stack_v2_sparse_classes_36k_train_024136
1,038
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "findNumberAppearingOnce", "signature": "def findNumberAppearingOnce(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "findNumberAppearingOnce_2", "signature": "def findNumberAppearingOnce_2(self, nums...
2
stack_v2_sparse_classes_30k_train_010275
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findNumberAppearingOnce(self, nums): :type nums: List[int] :rtype: int - def findNumberAppearingOnce_2(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 findNumberAppearingOnce(self, nums): :type nums: List[int] :rtype: int - def findNumberAppearingOnce_2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solu...
967b0fbb40ae491b552bc3365a481e66324cb6f2
<|skeleton|> class Solution: def findNumberAppearingOnce(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def findNumberAppearingOnce_2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findNumberAppearingOnce(self, nums): """:type nums: List[int] :rtype: int""" count = [0] * 32 for num in nums: k = 0 while k < 32: count[k] += num >> k & 1 k += 1 res = 0 for i in range(32): ...
the_stack_v2_python_sparse
jianzhi_offer/52_数组中唯一只出现一次的数字.py
ryanatgz/data_structure_and_algorithm
train
0
58267d18ea74cf0511604d99e7ee5072d91dc4e8
[ "QtCore.QObject.__init__(self)\nself.q = Queue()\nself.fit = fo.fit_object(self.q, options[3], options[0], options[1], options[2], data)\nname = 'run_' + str(run) + 'index_' + str(options[3]) + '.txt'\nself.savePath = os.path.join(path, name)\nself.data = data\nself.index = options[3]\nself.exp_data = exp_data", ...
<|body_start_0|> QtCore.QObject.__init__(self) self.q = Queue() self.fit = fo.fit_object(self.q, options[3], options[0], options[1], options[2], data) name = 'run_' + str(run) + 'index_' + str(options[3]) + '.txt' self.savePath = os.path.join(path, name) self.data = data ...
Processing object for threading purposes @parameters data: numpy array options: list of options for fit parameters [params, type_of_fit, ROI, index
ProcessImage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProcessImage: """Processing object for threading purposes @parameters data: numpy array options: list of options for fit parameters [params, type_of_fit, ROI, index""" def __init__(self, data, exp_data, options, path, run): """initialize fit_object""" <|body_0|> def run(...
stack_v2_sparse_classes_36k_train_024137
3,400
no_license
[ { "docstring": "initialize fit_object", "name": "__init__", "signature": "def __init__(self, data, exp_data, options, path, run)" }, { "docstring": "process results using methods from fit process and emit", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_012296
Implement the Python class `ProcessImage` described below. Class description: Processing object for threading purposes @parameters data: numpy array options: list of options for fit parameters [params, type_of_fit, ROI, index Method signatures and docstrings: - def __init__(self, data, exp_data, options, path, run): ...
Implement the Python class `ProcessImage` described below. Class description: Processing object for threading purposes @parameters data: numpy array options: list of options for fit parameters [params, type_of_fit, ROI, index Method signatures and docstrings: - def __init__(self, data, exp_data, options, path, run): ...
788fb964cdf7a5cfd747aa6e064ee31a4ffc3518
<|skeleton|> class ProcessImage: """Processing object for threading purposes @parameters data: numpy array options: list of options for fit parameters [params, type_of_fit, ROI, index""" def __init__(self, data, exp_data, options, path, run): """initialize fit_object""" <|body_0|> def run(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProcessImage: """Processing object for threading purposes @parameters data: numpy array options: list of options for fit parameters [params, type_of_fit, ROI, index""" def __init__(self, data, exp_data, options, path, run): """initialize fit_object""" QtCore.QObject.__init__(self) ...
the_stack_v2_python_sparse
BECMonitor/Image.py
ZachGlassman/BECMonitor
train
1
452536988a1cb2311d0aa37ba05d1021bea91f2e
[ "if not host1:\n raise ValueError('No first host given for the disease')\nif not host2:\n raise ValueError('No second host given for the disease')\nif not disease_name:\n raise ValueError('No name given to the disease')\nself.host1 = host1\nself.host2 = host2\nself.disease_name = disease_name\nself.host1.d...
<|body_start_0|> if not host1: raise ValueError('No first host given for the disease') if not host2: raise ValueError('No second host given for the disease') if not disease_name: raise ValueError('No name given to the disease') self.host1 = host1 ...
BaseTwoSpeciesDisease
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseTwoSpeciesDisease: def __init__(self, disease_name='', host1=None, host2=None): """todo :param host:""" <|body_0|> def count_nb_status_per_vertex(self, host, target_status, attribute_position='position'): """Count the number of agent having the targeted status in...
stack_v2_sparse_classes_36k_train_024138
1,818
no_license
[ { "docstring": "todo :param host:", "name": "__init__", "signature": "def __init__(self, disease_name='', host1=None, host2=None)" }, { "docstring": "Count the number of agent having the targeted status in each vertex. :param host: :param target_status: string in ['inf', 'con', 'imm'] :param att...
2
stack_v2_sparse_classes_30k_train_013759
Implement the Python class `BaseTwoSpeciesDisease` described below. Class description: Implement the BaseTwoSpeciesDisease class. Method signatures and docstrings: - def __init__(self, disease_name='', host1=None, host2=None): todo :param host: - def count_nb_status_per_vertex(self, host, target_status, attribute_pos...
Implement the Python class `BaseTwoSpeciesDisease` described below. Class description: Implement the BaseTwoSpeciesDisease class. Method signatures and docstrings: - def __init__(self, disease_name='', host1=None, host2=None): todo :param host: - def count_nb_status_per_vertex(self, host, target_status, attribute_pos...
b12aa0e546e51a2cd751d6c08a34250a3bfe9607
<|skeleton|> class BaseTwoSpeciesDisease: def __init__(self, disease_name='', host1=None, host2=None): """todo :param host:""" <|body_0|> def count_nb_status_per_vertex(self, host, target_status, attribute_position='position'): """Count the number of agent having the targeted status in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseTwoSpeciesDisease: def __init__(self, disease_name='', host1=None, host2=None): """todo :param host:""" if not host1: raise ValueError('No first host given for the disease') if not host2: raise ValueError('No second host given for the disease') if no...
the_stack_v2_python_sparse
sampy/disease/two_species/base.py
em-ach/sampy
train
0
30fb8651d31439ce3ecb27f1ff145e505262f949
[ "if not root:\n self.stack = []\n return\nself.stack = [root]\np = root\nwhile self.stack and self.stack[-1].left:\n self.stack.append(self.stack[-1].left)", "popNode = self.stack.pop()\nif popNode.right:\n self.stack.append(popNode.right)\n while self.stack and self.stack[-1].left:\n self.s...
<|body_start_0|> if not root: self.stack = [] return self.stack = [root] p = root while self.stack and self.stack[-1].left: self.stack.append(self.stack[-1].left) <|end_body_0|> <|body_start_1|> popNode = self.stack.pop() if popNode.ri...
BSTIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def next(self): """@return the next smallest number :rtype: int""" <|body_1|> def hasNext(self): """@return whether we have a next smallest number :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_024139
1,317
no_license
[ { "docstring": ":type root: TreeNode", "name": "__init__", "signature": "def __init__(self, root)" }, { "docstring": "@return the next smallest number :rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": "@return whether we have a next smallest number :rt...
3
stack_v2_sparse_classes_30k_val_000833
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 next(self): @return the next smallest number :rtype: int - def hasNext(self): @return whether we have a next smallest n...
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 next(self): @return the next smallest number :rtype: int - def hasNext(self): @return whether we have a next smallest n...
1d8821da01c9c200732a6b7037b8631689e2f7e7
<|skeleton|> class BSTIterator: def __init__(self, root): """:type root: TreeNode""" <|body_0|> def next(self): """@return the next smallest number :rtype: int""" <|body_1|> def hasNext(self): """@return whether we have a next smallest number :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BSTIterator: def __init__(self, root): """:type root: TreeNode""" if not root: self.stack = [] return self.stack = [root] p = root while self.stack and self.stack[-1].left: self.stack.append(self.stack[-1].left) def next(self): ...
the_stack_v2_python_sparse
Leetcode0173_InorderWithStack.py
xiaojinghu/Leetcode
train
0
72db73186aa0138166b0537ede5aa682abd29efc
[ "self.n = n\nself.k = k\nvar_list = []\nfor i in range(k, n + 1):\n num_cliques = comb(i, self.k, exact=True)\n for j in range(comb(i, k, exact=True) + 1):\n var_list.append((i, j))\nself.lp = lp_helper.LP_Helper(var_list)", "self.lp.add_constraint([((self.k, 0), 1.0)], '>', 0.0)\nself.lp.add_constra...
<|body_start_0|> self.n = n self.k = k var_list = [] for i in range(k, n + 1): num_cliques = comb(i, self.k, exact=True) for j in range(comb(i, k, exact=True) + 1): var_list.append((i, j)) self.lp = lp_helper.LP_Helper(var_list) <|end_body_...
Computes a bound on the number of gates for finding cliques. Here, we zero out a vertex at a time (as zeroing out edges seems complicated).
LpBound
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LpBound: """Computes a bound on the number of gates for finding cliques. Here, we zero out a vertex at a time (as zeroing out edges seems complicated).""" def __init__(self, n, k): """Constructor. ??? should I rename these? n: number of vertices k: size of clique we're looking for"""...
stack_v2_sparse_classes_36k_train_024140
10,652
permissive
[ { "docstring": "Constructor. ??? should I rename these? n: number of vertices k: size of clique we're looking for", "name": "__init__", "signature": "def __init__(self, n, k)" }, { "docstring": "Adds constraints based on zeroing out a vertex. This says that if a function finds some set of clique...
6
stack_v2_sparse_classes_30k_train_006890
Implement the Python class `LpBound` described below. Class description: Computes a bound on the number of gates for finding cliques. Here, we zero out a vertex at a time (as zeroing out edges seems complicated). Method signatures and docstrings: - def __init__(self, n, k): Constructor. ??? should I rename these? n: ...
Implement the Python class `LpBound` described below. Class description: Computes a bound on the number of gates for finding cliques. Here, we zero out a vertex at a time (as zeroing out edges seems complicated). Method signatures and docstrings: - def __init__(self, n, k): Constructor. ??? should I rename these? n: ...
ae7b736d5199085e6b4d0aadd7c05467920cc20e
<|skeleton|> class LpBound: """Computes a bound on the number of gates for finding cliques. Here, we zero out a vertex at a time (as zeroing out edges seems complicated).""" def __init__(self, n, k): """Constructor. ??? should I rename these? n: number of vertices k: size of clique we're looking for"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LpBound: """Computes a bound on the number of gates for finding cliques. Here, we zero out a vertex at a time (as zeroing out edges seems complicated).""" def __init__(self, n, k): """Constructor. ??? should I rename these? n: number of vertices k: size of clique we're looking for""" self...
the_stack_v2_python_sparse
countingBound/py/lp_gate_bound_2a.py
joshtburdick/misc
train
0
292b6152824f32b105728d4c1dc9e42c666eca79
[ "task_schema = TaskSchema()\ntask_data = request.get_json()\nvalidated_task_data, errors = task_schema.load(task_data)\nif errors:\n return (dict(status='fail', message=errors), 400)\ntask = Task(**validated_task_data)\nsaved_task = task.save()\nif not saved_task:\n return (dict(status='fail', message='Intern...
<|body_start_0|> task_schema = TaskSchema() task_data = request.get_json() validated_task_data, errors = task_schema.load(task_data) if errors: return (dict(status='fail', message=errors), 400) task = Task(**validated_task_data) saved_task = task.save() ...
TaskView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskView: def post(self): """Creating an Task ad""" <|body_0|> def get(self): """Getting All tasks""" <|body_1|> <|end_skeleton|> <|body_start_0|> task_schema = TaskSchema() task_data = request.get_json() validated_task_data, errors ...
stack_v2_sparse_classes_36k_train_024141
2,917
no_license
[ { "docstring": "Creating an Task ad", "name": "post", "signature": "def post(self)" }, { "docstring": "Getting All tasks", "name": "get", "signature": "def get(self)" } ]
2
stack_v2_sparse_classes_30k_train_002500
Implement the Python class `TaskView` described below. Class description: Implement the TaskView class. Method signatures and docstrings: - def post(self): Creating an Task ad - def get(self): Getting All tasks
Implement the Python class `TaskView` described below. Class description: Implement the TaskView class. Method signatures and docstrings: - def post(self): Creating an Task ad - def get(self): Getting All tasks <|skeleton|> class TaskView: def post(self): """Creating an Task ad""" <|body_0|> ...
015d70b8f79df6c1a5629add35767cee52f424f5
<|skeleton|> class TaskView: def post(self): """Creating an Task ad""" <|body_0|> def get(self): """Getting All tasks""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskView: def post(self): """Creating an Task ad""" task_schema = TaskSchema() task_data = request.get_json() validated_task_data, errors = task_schema.load(task_data) if errors: return (dict(status='fail', message=errors), 400) task = Task(**validat...
the_stack_v2_python_sparse
app/controllers/task.py
MutegekiHenry/project-cohort-backend
train
0
b9cd4e1ab9cb30bf63b8487027b548f0388e16b0
[ "super().__init__()\nself.out_channels = query_dim\nself.num_heads = num_heads\nproj_dim = head_dim * num_heads\nif cross_attention_dim is None:\n cross_attention_dim = query_dim\nself.to_q = nn.Linear(query_dim, proj_dim, bias=bias)\nself.to_k = nn.Linear(cross_attention_dim, proj_dim, bias=bias)\nself.to_v = n...
<|body_start_0|> super().__init__() self.out_channels = query_dim self.num_heads = num_heads proj_dim = head_dim * num_heads if cross_attention_dim is None: cross_attention_dim = query_dim self.to_q = nn.Linear(query_dim, proj_dim, bias=bias) self.to_k...
SelfAttention
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelfAttention: def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None: """Compute self-attention. Includes all the data wrangling...
stack_v2_sparse_classes_36k_train_024142
10,093
permissive
[ { "docstring": "Compute self-attention. Includes all the data wrangling on the input before attention computation. Input Shape: (B, H'*W', query_dim). Output Shape: (B, H'*W', query_dim). Parameters ---------- query_dim : int The number of channels in the query. Typically: num_heads*head_dim name : str Name of ...
5
stack_v2_sparse_classes_30k_train_020502
Implement the Python class `SelfAttention` described below. Class description: Implement the SelfAttention class. Method signatures and docstrings: - def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: boo...
Implement the Python class `SelfAttention` described below. Class description: Implement the SelfAttention class. Method signatures and docstrings: - def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: boo...
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class SelfAttention: def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None: """Compute self-attention. Includes all the data wrangling...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SelfAttention: def __init__(self, query_dim: int, name: str='exact', how: str='basic', cross_attention_dim: int=None, num_heads: int=8, head_dim: int=64, dropout: float=0.0, bias: bool=False, slice_size: int=4, **kwargs) -> None: """Compute self-attention. Includes all the data wrangling on the input ...
the_stack_v2_python_sparse
cellseg_models_pytorch/modules/self_attention_modules.py
okunator/cellseg_models.pytorch
train
43
986c9ee24b0f0fa54c77baaf71d188c6f623bef1
[ "for i in range(replays):\n lists = [states[:-1], states[1:], actions, rewards, list(range(len(actions)))]\n if update_order == 'forward':\n zipped = zip(*lists)\n elif update_order == 'reverse':\n zipped = zip(*[reversed(x) for x in lists])\n elif update_order == 'random':\n inds =...
<|body_start_0|> for i in range(replays): lists = [states[:-1], states[1:], actions, rewards, list(range(len(actions)))] if update_order == 'forward': zipped = zip(*lists) elif update_order == 'reverse': zipped = zip(*[reversed(x) for x in list...
QLearning
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QLearning: def update(self, states, actions, rewards, replays=1, alpha=0.05, gamma=1, update_order='forward'): """update Q function based on trajectory of states, actions, and rewards""" <|body_0|> def step_update(self, epsilon=0, alpha=0.05, gamma=1): """take a step...
stack_v2_sparse_classes_36k_train_024143
7,134
no_license
[ { "docstring": "update Q function based on trajectory of states, actions, and rewards", "name": "update", "signature": "def update(self, states, actions, rewards, replays=1, alpha=0.05, gamma=1, update_order='forward')" }, { "docstring": "take a step while updating Q for online learning", "n...
3
stack_v2_sparse_classes_30k_train_015942
Implement the Python class `QLearning` described below. Class description: Implement the QLearning class. Method signatures and docstrings: - def update(self, states, actions, rewards, replays=1, alpha=0.05, gamma=1, update_order='forward'): update Q function based on trajectory of states, actions, and rewards - def ...
Implement the Python class `QLearning` described below. Class description: Implement the QLearning class. Method signatures and docstrings: - def update(self, states, actions, rewards, replays=1, alpha=0.05, gamma=1, update_order='forward'): update Q function based on trajectory of states, actions, and rewards - def ...
ab6216a00f30cb5c3ea896b7a0fda7f01845c206
<|skeleton|> class QLearning: def update(self, states, actions, rewards, replays=1, alpha=0.05, gamma=1, update_order='forward'): """update Q function based on trajectory of states, actions, and rewards""" <|body_0|> def step_update(self, epsilon=0, alpha=0.05, gamma=1): """take a step...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QLearning: def update(self, states, actions, rewards, replays=1, alpha=0.05, gamma=1, update_order='forward'): """update Q function based on trajectory of states, actions, and rewards""" for i in range(replays): lists = [states[:-1], states[1:], actions, rewards, list(range(len(act...
the_stack_v2_python_sparse
gridworld/rickgrid/Agents.py
richard-warren/rl_sandbox
train
0
b297989a217f7aab4e59bbb4b52079f08a7e04d4
[ "self.client_id = client_id\nself.client_secret = client_secret\nself.project_key = project_key", "encoded = base64.b64encode('{}:{}'.format(self.client_id, self.client_secret))\nheaders = {'Authorization': 'Basic {}'.format(encoded), 'Content-Type': 'application/x-www-form-urlencoded'}\nbody = 'grant_type=client...
<|body_start_0|> self.client_id = client_id self.client_secret = client_secret self.project_key = project_key <|end_body_0|> <|body_start_1|> encoded = base64.b64encode('{}:{}'.format(self.client_id, self.client_secret)) headers = {'Authorization': 'Basic {}'.format(encoded), 'C...
SphereAPIAuthenticator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SphereAPIAuthenticator: def __init__(self, client_id, client_secret, project_key): """:type client_id: unicode :type client_secret: unicode :type project_key: unicode""" <|body_0|> def auth(self): """BÄÄÄM BÄ BÄÄÄÄÄMMMMMMM :returns Access token :rtype: dict""" ...
stack_v2_sparse_classes_36k_train_024144
2,676
no_license
[ { "docstring": ":type client_id: unicode :type client_secret: unicode :type project_key: unicode", "name": "__init__", "signature": "def __init__(self, client_id, client_secret, project_key)" }, { "docstring": "BÄÄÄM BÄ BÄÄÄÄÄMMMMMMM :returns Access token :rtype: dict", "name": "auth", "...
2
stack_v2_sparse_classes_30k_train_002410
Implement the Python class `SphereAPIAuthenticator` described below. Class description: Implement the SphereAPIAuthenticator class. Method signatures and docstrings: - def __init__(self, client_id, client_secret, project_key): :type client_id: unicode :type client_secret: unicode :type project_key: unicode - def auth...
Implement the Python class `SphereAPIAuthenticator` described below. Class description: Implement the SphereAPIAuthenticator class. Method signatures and docstrings: - def __init__(self, client_id, client_secret, project_key): :type client_id: unicode :type client_secret: unicode :type project_key: unicode - def auth...
0199789b2e2b0a9be8e3b00887e187b2ac97ea47
<|skeleton|> class SphereAPIAuthenticator: def __init__(self, client_id, client_secret, project_key): """:type client_id: unicode :type client_secret: unicode :type project_key: unicode""" <|body_0|> def auth(self): """BÄÄÄM BÄ BÄÄÄÄÄMMMMMMM :returns Access token :rtype: dict""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SphereAPIAuthenticator: def __init__(self, client_id, client_secret, project_key): """:type client_id: unicode :type client_secret: unicode :type project_key: unicode""" self.client_id = client_id self.client_secret = client_secret self.project_key = project_key def auth(s...
the_stack_v2_python_sparse
faces/lib/sphere_api/api.py
bartoszhernas/ecommhack.api
train
0
cc4f29a161eab13f9418823efcdea37e9c449c29
[ "from apps.users.serializers import FollowModelSerializer\nview = self.context.get('view', None)\nfields = ('email', 'username', 'phone_number', 'first_name', 'last_name')\nif view is not None:\n if view.view_name == 'users' and view.action in view.fields_to_return:\n fields = view.fields_to_return[view.a...
<|body_start_0|> from apps.users.serializers import FollowModelSerializer view = self.context.get('view', None) fields = ('email', 'username', 'phone_number', 'first_name', 'last_name') if view is not None: if view.view_name == 'users' and view.action in view.fields_to_return...
User model serializer.
UserModelSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserModelSerializer: """User model serializer.""" def get_followers(self, obj): """Return followers information.""" <|body_0|> def get_followeds(self, obj): """Return followers information.""" <|body_1|> def get_follow_requests(self, obj): ""...
stack_v2_sparse_classes_36k_train_024145
10,085
no_license
[ { "docstring": "Return followers information.", "name": "get_followers", "signature": "def get_followers(self, obj)" }, { "docstring": "Return followers information.", "name": "get_followeds", "signature": "def get_followeds(self, obj)" }, { "docstring": "Return follow requests."...
4
null
Implement the Python class `UserModelSerializer` described below. Class description: User model serializer. Method signatures and docstrings: - def get_followers(self, obj): Return followers information. - def get_followeds(self, obj): Return followers information. - def get_follow_requests(self, obj): Return follow ...
Implement the Python class `UserModelSerializer` described below. Class description: User model serializer. Method signatures and docstrings: - def get_followers(self, obj): Return followers information. - def get_followeds(self, obj): Return followers information. - def get_follow_requests(self, obj): Return follow ...
e2f4557e2a85405838c6c9f65f1cb8a5f60a35ba
<|skeleton|> class UserModelSerializer: """User model serializer.""" def get_followers(self, obj): """Return followers information.""" <|body_0|> def get_followeds(self, obj): """Return followers information.""" <|body_1|> def get_follow_requests(self, obj): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserModelSerializer: """User model serializer.""" def get_followers(self, obj): """Return followers information.""" from apps.users.serializers import FollowModelSerializer view = self.context.get('view', None) fields = ('email', 'username', 'phone_number', 'first_name', '...
the_stack_v2_python_sparse
apps/users/serializers/users.py
HebertFerrer/WebMaster-back-end
train
0
dac48cb07221cd71d02e6381d08eea2b33a0ed82
[ "self.use_wget = use_wget\nself.quic_binary_dir = quic_binary_dir\nself.quic_server_address = quic_server_address\nself.quic_server_port = quic_server_port\nif not use_wget and (not os.path.isfile(quic_binary_dir + '/quic_client')):\n raise IOError('There is no quic_client in the given dir: %s.' % quic_binary_di...
<|body_start_0|> self.use_wget = use_wget self.quic_binary_dir = quic_binary_dir self.quic_server_address = quic_server_address self.quic_server_port = quic_server_port if not use_wget and (not os.path.isfile(quic_binary_dir + '/quic_client')): raise IOError('There is...
PageloadExperiment
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PageloadExperiment: def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): """Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: P...
stack_v2_sparse_classes_36k_train_024146
6,722
permissive
[ { "docstring": "Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: Port of the quic server.", "name": "__init__", "signature": "def __init__(self, use_wget, quic_binary_dir, qui...
4
stack_v2_sparse_classes_30k_train_000719
Implement the Python class `PageloadExperiment` described below. Class description: Implement the PageloadExperiment class. Method signatures and docstrings: - def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic...
Implement the Python class `PageloadExperiment` described below. Class description: Implement the PageloadExperiment class. Method signatures and docstrings: - def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class PageloadExperiment: def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): """Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: P...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PageloadExperiment: def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): """Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: Port of the qui...
the_stack_v2_python_sparse
net/tools/quic/benchmark/run_client.py
chromium/chromium
train
17,408
d4797833a63681f1bacdd7b62fbb1864f21e5ddf
[ "if not options['username'] or not options['case'] or (not options['target']):\n print('Options -t (target), -c (case id) and -u (username) are mandatory. Exiting.')\n sys.exit(1)\nuser = Profile.objects.get(username=options['username'].strip())\ncase = Case.objects.get(pk=options['case'].strip())\nif os.path...
<|body_start_0|> if not options['username'] or not options['case'] or (not options['target']): print('Options -t (target), -c (case id) and -u (username) are mandatory. Exiting.') sys.exit(1) user = Profile.objects.get(username=options['username'].strip()) case = Case.obj...
Image submission via command line.
Command
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: """Image submission via command line.""" def handle(self, *args, **options): """Runs command.""" <|body_0|> def _add_task(self, target, case, user): """Wraps add_task() to catch errors.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if...
stack_v2_sparse_classes_36k_train_024147
2,584
no_license
[ { "docstring": "Runs command.", "name": "handle", "signature": "def handle(self, *args, **options)" }, { "docstring": "Wraps add_task() to catch errors.", "name": "_add_task", "signature": "def _add_task(self, target, case, user)" } ]
2
stack_v2_sparse_classes_30k_train_016090
Implement the Python class `Command` described below. Class description: Image submission via command line. Method signatures and docstrings: - def handle(self, *args, **options): Runs command. - def _add_task(self, target, case, user): Wraps add_task() to catch errors.
Implement the Python class `Command` described below. Class description: Image submission via command line. Method signatures and docstrings: - def handle(self, *args, **options): Runs command. - def _add_task(self, target, case, user): Wraps add_task() to catch errors. <|skeleton|> class Command: """Image submi...
c9ff33b6ed16eb1cd960822b8031baf9b84a8636
<|skeleton|> class Command: """Image submission via command line.""" def handle(self, *args, **options): """Runs command.""" <|body_0|> def _add_task(self, target, case, user): """Wraps add_task() to catch errors.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Command: """Image submission via command line.""" def handle(self, *args, **options): """Runs command.""" if not options['username'] or not options['case'] or (not options['target']): print('Options -t (target), -c (case id) and -u (username) are mandatory. Exiting.') ...
the_stack_v2_python_sparse
analyses/management/commands/submit.py
DanielKorsa/ghiro
train
1
8dfb7f8de3f494afcd16305f24e03775c9499a4f
[ "followers_users_list = [relationship.from_user for relationship in self.filter(to_user=user)]\nfriend_list = self.filter(from_user=user, to_user__in=followers_users_list)\nfriends_users_list = [relationship.to_user for relationship in friend_list]\nfollower_list = self.filter(to_user=user).exclude(from_user__in=fr...
<|body_start_0|> followers_users_list = [relationship.from_user for relationship in self.filter(to_user=user)] friend_list = self.filter(from_user=user, to_user__in=followers_users_list) friends_users_list = [relationship.to_user for relationship in friend_list] follower_list = self.filt...
RelationshipManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelationshipManager: def relationships_for_user(self, user): """Relationships for user Returns a list of friends, people you are following, and followers, people that are following you but you are not following.""" <|body_0|> def is_following(self, you, them): """Ans...
stack_v2_sparse_classes_36k_train_024148
1,799
no_license
[ { "docstring": "Relationships for user Returns a list of friends, people you are following, and followers, people that are following you but you are not following.", "name": "relationships_for_user", "signature": "def relationships_for_user(self, user)" }, { "docstring": "Answers the question, a...
3
stack_v2_sparse_classes_30k_train_003298
Implement the Python class `RelationshipManager` described below. Class description: Implement the RelationshipManager class. Method signatures and docstrings: - def relationships_for_user(self, user): Relationships for user Returns a list of friends, people you are following, and followers, people that are following...
Implement the Python class `RelationshipManager` described below. Class description: Implement the RelationshipManager class. Method signatures and docstrings: - def relationships_for_user(self, user): Relationships for user Returns a list of friends, people you are following, and followers, people that are following...
08f4210e3de77c4564fcc8c1a2e9b47a0088249f
<|skeleton|> class RelationshipManager: def relationships_for_user(self, user): """Relationships for user Returns a list of friends, people you are following, and followers, people that are following you but you are not following.""" <|body_0|> def is_following(self, you, them): """Ans...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelationshipManager: def relationships_for_user(self, user): """Relationships for user Returns a list of friends, people you are following, and followers, people that are following you but you are not following.""" followers_users_list = [relationship.from_user for relationship in self.filter(...
the_stack_v2_python_sparse
ninetyseven/apps/relationships/managers.py
syncopated/97bottles
train
0
3d08d16c6b89726d5f23fc621a41a929a9851002
[ "if args[0] is None or gfapy.is_placeholder(args[0]):\n return gfapy.AlignmentPlaceholder()\nif len(args) > 1:\n raise gfapy.ArgumentError('The Alignment() constructor requires ' + 'a single positional argument, {} found'.format(len(args)))\nif isinstance(args[0], gfapy.CIGAR) or isinstance(args[0], gfapy.Tra...
<|body_start_0|> if args[0] is None or gfapy.is_placeholder(args[0]): return gfapy.AlignmentPlaceholder() if len(args) > 1: raise gfapy.ArgumentError('The Alignment() constructor requires ' + 'a single positional argument, {} found'.format(len(args))) if isinstance(args[0...
Factory for instances of classes which represent alignments in GFA fields. Args: initializer (string, list): the alignment field content version (str): GFA version, either ``'gfa1'`` or ``'gfa2'`` (default: ``'gfa2'``) valid (bool): if ``True``, validation is skipped, when possible (default: ``False``) Returns: :class:...
Alignment
[ "ISC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Alignment: """Factory for instances of classes which represent alignments in GFA fields. Args: initializer (string, list): the alignment field content version (str): GFA version, either ``'gfa1'`` or ``'gfa2'`` (default: ``'gfa2'``) valid (bool): if ``True``, validation is skipped, when possible ...
stack_v2_sparse_classes_36k_train_024149
5,360
permissive
[ { "docstring": "Create an instance of an alignment field class.", "name": "__new__", "signature": "def __new__(cls, *args, **kargs)" }, { "docstring": "Parses an alignment field Parameters ---------- string : str The string to parse. version : str GFA version (gfa1 or gfa2) If *gfa1*, then CIGAR...
3
stack_v2_sparse_classes_30k_train_012805
Implement the Python class `Alignment` described below. Class description: Factory for instances of classes which represent alignments in GFA fields. Args: initializer (string, list): the alignment field content version (str): GFA version, either ``'gfa1'`` or ``'gfa2'`` (default: ``'gfa2'``) valid (bool): if ``True``...
Implement the Python class `Alignment` described below. Class description: Factory for instances of classes which represent alignments in GFA fields. Args: initializer (string, list): the alignment field content version (str): GFA version, either ``'gfa1'`` or ``'gfa2'`` (default: ``'gfa2'``) valid (bool): if ``True``...
12b31daac26ab137b6ee4a29b4f14554ba962dcb
<|skeleton|> class Alignment: """Factory for instances of classes which represent alignments in GFA fields. Args: initializer (string, list): the alignment field content version (str): GFA version, either ``'gfa1'`` or ``'gfa2'`` (default: ``'gfa2'``) valid (bool): if ``True``, validation is skipped, when possible ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Alignment: """Factory for instances of classes which represent alignments in GFA fields. Args: initializer (string, list): the alignment field content version (str): GFA version, either ``'gfa1'`` or ``'gfa2'`` (default: ``'gfa2'``) valid (bool): if ``True``, validation is skipped, when possible (default: ``F...
the_stack_v2_python_sparse
gfapy/alignment/alignment.py
ggonnella/gfapy
train
63
93ef74251ab544831a373fcdcb802fb71b1ec59a
[ "raw = cls.validate_payload(payload)\ntry:\n return cls.SUPPORTED_MODES[raw[0]]\nexcept KeyError:\n raise ConversionError(f'Payload not supported for {cls.__name__}', raw=raw)", "for knx_value, mode in cls.SUPPORTED_MODES.items():\n if mode == value:\n return DPTArray(knx_value)\nraise ConversionE...
<|body_start_0|> raw = cls.validate_payload(payload) try: return cls.SUPPORTED_MODES[raw[0]] except KeyError: raise ConversionError(f'Payload not supported for {cls.__name__}', raw=raw) <|end_body_0|> <|body_start_1|> for knx_value, mode in cls.SUPPORTED_MODES.it...
Base class for KNX Climate modes.
_DPTClimateMode
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _DPTClimateMode: """Base class for KNX Climate modes.""" def from_knx(cls, payload: DPTArray | DPTBinary) -> HVACModeT: """Parse/deserialize from KNX/IP raw data.""" <|body_0|> def to_knx(cls, value: HVACModeT) -> DPTArray: """Serialize to KNX/IP raw data.""" ...
stack_v2_sparse_classes_36k_train_024150
4,263
permissive
[ { "docstring": "Parse/deserialize from KNX/IP raw data.", "name": "from_knx", "signature": "def from_knx(cls, payload: DPTArray | DPTBinary) -> HVACModeT" }, { "docstring": "Serialize to KNX/IP raw data.", "name": "to_knx", "signature": "def to_knx(cls, value: HVACModeT) -> DPTArray" }...
2
stack_v2_sparse_classes_30k_train_006814
Implement the Python class `_DPTClimateMode` described below. Class description: Base class for KNX Climate modes. Method signatures and docstrings: - def from_knx(cls, payload: DPTArray | DPTBinary) -> HVACModeT: Parse/deserialize from KNX/IP raw data. - def to_knx(cls, value: HVACModeT) -> DPTArray: Serialize to KN...
Implement the Python class `_DPTClimateMode` described below. Class description: Base class for KNX Climate modes. Method signatures and docstrings: - def from_knx(cls, payload: DPTArray | DPTBinary) -> HVACModeT: Parse/deserialize from KNX/IP raw data. - def to_knx(cls, value: HVACModeT) -> DPTArray: Serialize to KN...
48d4e31365c15e632b275f0d129cd9f2b2b5717d
<|skeleton|> class _DPTClimateMode: """Base class for KNX Climate modes.""" def from_knx(cls, payload: DPTArray | DPTBinary) -> HVACModeT: """Parse/deserialize from KNX/IP raw data.""" <|body_0|> def to_knx(cls, value: HVACModeT) -> DPTArray: """Serialize to KNX/IP raw data.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _DPTClimateMode: """Base class for KNX Climate modes.""" def from_knx(cls, payload: DPTArray | DPTBinary) -> HVACModeT: """Parse/deserialize from KNX/IP raw data.""" raw = cls.validate_payload(payload) try: return cls.SUPPORTED_MODES[raw[0]] except KeyError: ...
the_stack_v2_python_sparse
xknx/dpt/dpt_hvac_mode.py
XKNX/xknx
train
248
b7255f0e985453353a583103119cfe29c6bd2f8a
[ "Spectrum.__init__(self, *args, **kwargs)\nself._filename = filename\nself._separator = separator\nself._header = header\nif filename:\n wave = []\n flux = []\n with open(filename, 'r') as txt:\n for i in range(skip_lines):\n txt.readline()\n for line in txt:\n if line[0...
<|body_start_0|> Spectrum.__init__(self, *args, **kwargs) self._filename = filename self._separator = separator self._header = header if filename: wave = [] flux = [] with open(filename, 'r') as txt: for i in range(skip_lines): ...
Handles spectra stored in ASCII files.
SpectrumAscii
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpectrumAscii: """Handles spectra stored in ASCII files.""" def __init__(self, filename: str=None, separator: str=',', skip_lines: int=0, comment: str='#', wave_column: int=0, flux_column: int=1, header: bool=True, *args, **kwargs): """Reads spectrum from ASCII file. Args: filename: ...
stack_v2_sparse_classes_36k_train_024151
46,205
permissive
[ { "docstring": "Reads spectrum from ASCII file. Args: filename: Filename to load spectrum from. separator: Separator in file. skip_lines: Number of lines to skip while reading file. comment: Character indicating a comment line. header: Whether to write a header.", "name": "__init__", "signature": "def _...
2
null
Implement the Python class `SpectrumAscii` described below. Class description: Handles spectra stored in ASCII files. Method signatures and docstrings: - def __init__(self, filename: str=None, separator: str=',', skip_lines: int=0, comment: str='#', wave_column: int=0, flux_column: int=1, header: bool=True, *args, **...
Implement the Python class `SpectrumAscii` described below. Class description: Handles spectra stored in ASCII files. Method signatures and docstrings: - def __init__(self, filename: str=None, separator: str=',', skip_lines: int=0, comment: str='#', wave_column: int=0, flux_column: int=1, header: bool=True, *args, **...
648eb1758e3744d9e3d6669edc4a0c4753559f17
<|skeleton|> class SpectrumAscii: """Handles spectra stored in ASCII files.""" def __init__(self, filename: str=None, separator: str=',', skip_lines: int=0, comment: str='#', wave_column: int=0, flux_column: int=1, header: bool=True, *args, **kwargs): """Reads spectrum from ASCII file. Args: filename: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpectrumAscii: """Handles spectra stored in ASCII files.""" def __init__(self, filename: str=None, separator: str=',', skip_lines: int=0, comment: str='#', wave_column: int=0, flux_column: int=1, header: bool=True, *args, **kwargs): """Reads spectrum from ASCII file. Args: filename: Filename to l...
the_stack_v2_python_sparse
spexxy/data/spectrum.py
thusser/spexxy
train
4
93d60f57cc66f9ce94190e5d6f34dcefa500a527
[ "self.srv_addr = (srv_host, srv_port)\nself.cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.cli_sock.connect(self.srv_addr)", "while True:\n try:\n data = input('> ')\n assert data\n except (EOFError, KeyboardInterrupt, AssertionError) as e:\n print('用户输入异常或为空, 退出...'...
<|body_start_0|> self.srv_addr = (srv_host, srv_port) self.cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.cli_sock.connect(self.srv_addr) <|end_body_0|> <|body_start_1|> while True: try: data = input('> ') assert data ...
基于TCP协议的回声客户端.
TCPEchoClient
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TCPEchoClient: """基于TCP协议的回声客户端.""" def __init__(self, srv_host='127.0.0.1', srv_port=12345): """Client初始化. 1. 创建socket 2. 连接socket到服务器地址+端口号""" <|body_0|> def mainloop(self): """主循环. 1. 发送信息 2. 接受信息 3. 关闭socket连接 异常处理: - 断言非空, 为空抛出异常 - 捕获3类异常(EOFError: UNIX上为Ctr...
stack_v2_sparse_classes_36k_train_024152
1,296
no_license
[ { "docstring": "Client初始化. 1. 创建socket 2. 连接socket到服务器地址+端口号", "name": "__init__", "signature": "def __init__(self, srv_host='127.0.0.1', srv_port=12345)" }, { "docstring": "主循环. 1. 发送信息 2. 接受信息 3. 关闭socket连接 异常处理: - 断言非空, 为空抛出异常 - 捕获3类异常(EOFError: UNIX上为Ctrl+d,Windows上为Ctrl+Z+Enter), 跳出循环 - 关闭s...
2
stack_v2_sparse_classes_30k_train_016195
Implement the Python class `TCPEchoClient` described below. Class description: 基于TCP协议的回声客户端. Method signatures and docstrings: - def __init__(self, srv_host='127.0.0.1', srv_port=12345): Client初始化. 1. 创建socket 2. 连接socket到服务器地址+端口号 - def mainloop(self): 主循环. 1. 发送信息 2. 接受信息 3. 关闭socket连接 异常处理: - 断言非空, 为空抛出异常 - 捕获3类异...
Implement the Python class `TCPEchoClient` described below. Class description: 基于TCP协议的回声客户端. Method signatures and docstrings: - def __init__(self, srv_host='127.0.0.1', srv_port=12345): Client初始化. 1. 创建socket 2. 连接socket到服务器地址+端口号 - def mainloop(self): 主循环. 1. 发送信息 2. 接受信息 3. 关闭socket连接 异常处理: - 断言非空, 为空抛出异常 - 捕获3类异...
43d2f943c703fe99966688c22de2d4493383feb9
<|skeleton|> class TCPEchoClient: """基于TCP协议的回声客户端.""" def __init__(self, srv_host='127.0.0.1', srv_port=12345): """Client初始化. 1. 创建socket 2. 连接socket到服务器地址+端口号""" <|body_0|> def mainloop(self): """主循环. 1. 发送信息 2. 接受信息 3. 关闭socket连接 异常处理: - 断言非空, 为空抛出异常 - 捕获3类异常(EOFError: UNIX上为Ctr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TCPEchoClient: """基于TCP协议的回声客户端.""" def __init__(self, srv_host='127.0.0.1', srv_port=12345): """Client初始化. 1. 创建socket 2. 连接socket到服务器地址+端口号""" self.srv_addr = (srv_host, srv_port) self.cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.cli_sock.connect(sel...
the_stack_v2_python_sparse
day14/tcp_echo_client.py
east4ming/pyEdu
train
0
31a4a12b348e3837db43254aff922a8ad4447f1c
[ "self.face_detector = face_detector\nself.face_generator = face_generator\nself.save_all = save_all\nself.config = config\nself.video_converter = None\nif 'video_smooth_filter' in self.config:\n self.video_converter = video_utils.VideoConverter(use_kalman_filter=self.config['video_smooth_filter'] == 'kalman', bb...
<|body_start_0|> self.face_detector = face_detector self.face_generator = face_generator self.save_all = save_all self.config = config self.video_converter = None if 'video_smooth_filter' in self.config: self.video_converter = video_utils.VideoConverter(use_ka...
Swapper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Swapper: def __init__(self, face_detector: FaceDetector, face_generator: FaceGenerator, config, save_all=False): """Utility object that holds and manages the components necessary for swapping faces in a picture. :param face_detector: :param face_generator: :param config: :param save_all:...
stack_v2_sparse_classes_36k_train_024153
14,636
permissive
[ { "docstring": "Utility object that holds and manages the components necessary for swapping faces in a picture. :param face_detector: :param face_generator: :param config: :param save_all:", "name": "__init__", "signature": "def __init__(self, face_detector: FaceDetector, face_generator: FaceGenerator, ...
2
stack_v2_sparse_classes_30k_train_002535
Implement the Python class `Swapper` described below. Class description: Implement the Swapper class. Method signatures and docstrings: - def __init__(self, face_detector: FaceDetector, face_generator: FaceGenerator, config, save_all=False): Utility object that holds and manages the components necessary for swapping ...
Implement the Python class `Swapper` described below. Class description: Implement the Swapper class. Method signatures and docstrings: - def __init__(self, face_detector: FaceDetector, face_generator: FaceGenerator, config, save_all=False): Utility object that holds and manages the components necessary for swapping ...
ada4803d4f1d53233ba4592beec75271254e5182
<|skeleton|> class Swapper: def __init__(self, face_detector: FaceDetector, face_generator: FaceGenerator, config, save_all=False): """Utility object that holds and manages the components necessary for swapping faces in a picture. :param face_detector: :param face_generator: :param config: :param save_all:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Swapper: def __init__(self, face_detector: FaceDetector, face_generator: FaceGenerator, config, save_all=False): """Utility object that holds and manages the components necessary for swapping faces in a picture. :param face_detector: :param face_generator: :param config: :param save_all:""" se...
the_stack_v2_python_sparse
face_swap/deep_swap.py
brahimbellahcen/face-swap
train
0
3a44b3761413c880fe481fb0de764ba1ff5b3464
[ "service_type = self.request.query_params.get('service_type')\nif service_type:\n service_type_validator(service_type)\n queryset = self.queryset.filter(service_type=service_type)\nelse:\n queryset = super(StatusTransitViewSet, self).get_queryset()\nreturn queryset", "queryset = self.get_queryset()\nauto...
<|body_start_0|> service_type = self.request.query_params.get('service_type') if service_type: service_type_validator(service_type) queryset = self.queryset.filter(service_type=service_type) else: queryset = super(StatusTransitViewSet, self).get_queryset() ...
StatusTransitViewSet
[ "MIT", "LGPL-2.1-or-later", "LGPL-3.0-only" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StatusTransitViewSet: def get_queryset(self): """支持额外过滤参数[service_type]""" <|body_0|> def is_auto(self, request, *args, **kwargs): """工单状态是否自动转换""" <|body_1|> def get_auto_detail(self, request, *args, **kwargs): """获取工单状态自动流转的详细信息""" <|bo...
stack_v2_sparse_classes_36k_train_024154
11,791
permissive
[ { "docstring": "支持额外过滤参数[service_type]", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "工单状态是否自动转换", "name": "is_auto", "signature": "def is_auto(self, request, *args, **kwargs)" }, { "docstring": "获取工单状态自动流转的详细信息", "name": "get_auto_detail",...
4
stack_v2_sparse_classes_30k_train_003040
Implement the Python class `StatusTransitViewSet` described below. Class description: Implement the StatusTransitViewSet class. Method signatures and docstrings: - def get_queryset(self): 支持额外过滤参数[service_type] - def is_auto(self, request, *args, **kwargs): 工单状态是否自动转换 - def get_auto_detail(self, request, *args, **kwa...
Implement the Python class `StatusTransitViewSet` described below. Class description: Implement the StatusTransitViewSet class. Method signatures and docstrings: - def get_queryset(self): 支持额外过滤参数[service_type] - def is_auto(self, request, *args, **kwargs): 工单状态是否自动转换 - def get_auto_detail(self, request, *args, **kwa...
2d708bd0d869d391456e0fb8d644af3b9f031acf
<|skeleton|> class StatusTransitViewSet: def get_queryset(self): """支持额外过滤参数[service_type]""" <|body_0|> def is_auto(self, request, *args, **kwargs): """工单状态是否自动转换""" <|body_1|> def get_auto_detail(self, request, *args, **kwargs): """获取工单状态自动流转的详细信息""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StatusTransitViewSet: def get_queryset(self): """支持额外过滤参数[service_type]""" service_type = self.request.query_params.get('service_type') if service_type: service_type_validator(service_type) queryset = self.queryset.filter(service_type=service_type) else:...
the_stack_v2_python_sparse
itsm/ticket_status/views.py
TencentBlueKing/bk-itsm
train
100
e0b24a068772e232fa25343576440fe06d19e39c
[ "self.content_type = CONTENT_TYPE\nself.root = partition_type\nself.headers_obj = HmcHeaders.HmcHeaders('web')\ndirectory_path = os.path.dirname(__file__)\nself.input = open(directory_path + '/data/poweron_lpar.xml', 'r').read()", "super().__init__(ip, self.root, self.content_type, session_id)\nlog_object.log_deb...
<|body_start_0|> self.content_type = CONTENT_TYPE self.root = partition_type self.headers_obj = HmcHeaders.HmcHeaders('web') directory_path = os.path.dirname(__file__) self.input = open(directory_path + '/data/poweron_lpar.xml', 'r').read() <|end_body_0|> <|body_start_1|> ...
PowerOnPartition
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PowerOnPartition: def __init__(self, partition_type): """initializes root and content_type Args: partition_type : type of object Logical Partition or VirtualIOServer""" <|body_0|> def poweron_Partition(self, ip, logicalpartition_object, session_id): """performs power...
stack_v2_sparse_classes_36k_train_024155
2,956
permissive
[ { "docstring": "initializes root and content_type Args: partition_type : type of object Logical Partition or VirtualIOServer", "name": "__init__", "signature": "def __init__(self, partition_type)" }, { "docstring": "performs poweron operation for the provided LogicalPartition object Args: ip : i...
2
null
Implement the Python class `PowerOnPartition` described below. Class description: Implement the PowerOnPartition class. Method signatures and docstrings: - def __init__(self, partition_type): initializes root and content_type Args: partition_type : type of object Logical Partition or VirtualIOServer - def poweron_Par...
Implement the Python class `PowerOnPartition` described below. Class description: Implement the PowerOnPartition class. Method signatures and docstrings: - def __init__(self, partition_type): initializes root and content_type Args: partition_type : type of object Logical Partition or VirtualIOServer - def poweron_Par...
8e46a5a25a57d07f0612404f4b978234d6d2cd4b
<|skeleton|> class PowerOnPartition: def __init__(self, partition_type): """initializes root and content_type Args: partition_type : type of object Logical Partition or VirtualIOServer""" <|body_0|> def poweron_Partition(self, ip, logicalpartition_object, session_id): """performs power...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PowerOnPartition: def __init__(self, partition_type): """initializes root and content_type Args: partition_type : type of object Logical Partition or VirtualIOServer""" self.content_type = CONTENT_TYPE self.root = partition_type self.headers_obj = HmcHeaders.HmcHeaders('web') ...
the_stack_v2_python_sparse
src/partition_operation_util/PowerOnPartition.py
Python3pkg/HmcRestClient
train
0
d3d068312c27744b34f3ed645696066683375e20
[ "self.minh, self.maxh, self.total = ([], [], 0)\nheapq.heapify(self.minh)\nheapq.heapify(self.maxh)", "heapq.heappush(self.maxh, num)\nheapq.heappush(self.minh, -heapq.heappop(self.maxh))\nif len(self.minh) > len(self.maxh):\n heapq.heappush(self.maxh, -heapq.heappop(self.minh))", "if len(self.maxh) > len(se...
<|body_start_0|> self.minh, self.maxh, self.total = ([], [], 0) heapq.heapify(self.minh) heapq.heapify(self.maxh) <|end_body_0|> <|body_start_1|> heapq.heappush(self.maxh, num) heapq.heappush(self.minh, -heapq.heappop(self.maxh)) if len(self.minh) > len(self.maxh): ...
MedianFinder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MedianFinder: def __init__(self): """initialize your data structure here.""" <|body_0|> def addNum(self, num): """:type num: int :rtype: None""" <|body_1|> def findMedian(self): """:rtype: float""" <|body_2|> <|end_skeleton|> <|body_sta...
stack_v2_sparse_classes_36k_train_024156
1,889
no_license
[ { "docstring": "initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ":type num: int :rtype: None", "name": "addNum", "signature": "def addNum(self, num)" }, { "docstring": ":rtype: float", "name": "findMedian", "s...
3
null
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. - def addNum(self, num): :type num: int :rtype: None - def findMedian(self): :rtype: float
Implement the Python class `MedianFinder` described below. Class description: Implement the MedianFinder class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. - def addNum(self, num): :type num: int :rtype: None - def findMedian(self): :rtype: float <|skeleton|> class Me...
6d012496b7f0279b3e2c31c1f444eebb7a7a20b9
<|skeleton|> class MedianFinder: def __init__(self): """initialize your data structure here.""" <|body_0|> def addNum(self, num): """:type num: int :rtype: None""" <|body_1|> def findMedian(self): """:rtype: float""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MedianFinder: def __init__(self): """initialize your data structure here.""" self.minh, self.maxh, self.total = ([], [], 0) heapq.heapify(self.minh) heapq.heapify(self.maxh) def addNum(self, num): """:type num: int :rtype: None""" heapq.heappush(self.maxh, ...
the_stack_v2_python_sparse
FindMedianFromDataStream.py
xmy7080/leetcode
train
0
e899bd664307d40bb06ca0eff4da0ade00d38689
[ "self.datetimestamp = kwargs.get('datetimestamp') or datetime.datetime.now().strftime('%Y%m%d%H%M%S')\nself.identifier = None\nself.force_no_cloudshell = bool(kwargs.get('no_cloudshell'))\nself.project_id = kwargs.get('project_id')\nif kwargs.get('composite_root_resources'):\n tmpcrr = kwargs.get('composite_root...
<|body_start_0|> self.datetimestamp = kwargs.get('datetimestamp') or datetime.datetime.now().strftime('%Y%m%d%H%M%S') self.identifier = None self.force_no_cloudshell = bool(kwargs.get('no_cloudshell')) self.project_id = kwargs.get('project_id') if kwargs.get('composite_root_resou...
Forseti installer config object.
Config
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Config: """Forseti installer config object.""" def __init__(self, **kwargs): """Initialize. Args: kwargs (dict): The kwargs.""" <|body_0|> def generate_identifier(self, organization_id): """Generate resource unique identifier. Hash the timestamp and organization ...
stack_v2_sparse_classes_36k_train_024157
2,847
permissive
[ { "docstring": "Initialize. Args: kwargs (dict): The kwargs.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Generate resource unique identifier. Hash the timestamp and organization id and take the first 7 characters. Lowercase is needed because some resource...
2
null
Implement the Python class `Config` described below. Class description: Forseti installer config object. Method signatures and docstrings: - def __init__(self, **kwargs): Initialize. Args: kwargs (dict): The kwargs. - def generate_identifier(self, organization_id): Generate resource unique identifier. Hash the timest...
Implement the Python class `Config` described below. Class description: Forseti installer config object. Method signatures and docstrings: - def __init__(self, **kwargs): Initialize. Args: kwargs (dict): The kwargs. - def generate_identifier(self, organization_id): Generate resource unique identifier. Hash the timest...
d4421afa50a17ed47cbebe942044ebab3720e0f5
<|skeleton|> class Config: """Forseti installer config object.""" def __init__(self, **kwargs): """Initialize. Args: kwargs (dict): The kwargs.""" <|body_0|> def generate_identifier(self, organization_id): """Generate resource unique identifier. Hash the timestamp and organization ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Config: """Forseti installer config object.""" def __init__(self, **kwargs): """Initialize. Args: kwargs (dict): The kwargs.""" self.datetimestamp = kwargs.get('datetimestamp') or datetime.datetime.now().strftime('%Y%m%d%H%M%S') self.identifier = None self.force_no_cloudsh...
the_stack_v2_python_sparse
install/gcp/installer/configs/config.py
kevensen/forseti-security
train
1
05e58d44db8f43cc9ff77601bb92ffce8223cdfd
[ "KratosMultiphysics.Process.__init__(self)\ndefault_settings = KratosMultiphysics.Parameters('\\n {\\n \"model_part_name\":\"\",\\n \"center_of_rotation\":[0.0,0.0,0.0],\\n \"calculate_torque\":false,\\n \"torque_model_part_name\":\"\",\\n ...
<|body_start_0|> KratosMultiphysics.Process.__init__(self) default_settings = KratosMultiphysics.Parameters('\n {\n "model_part_name":"",\n "center_of_rotation":[0.0,0.0,0.0],\n "calculate_torque":false,\n "torque_model_part_name":"",\n ...
This process applies a rotation to a given modelpart or a submodelpart Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.
ApplyRotateRegionProcess
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApplyRotateRegionProcess: """This process applies a rotation to a given modelpart or a submodelpart Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.""" def __init__(self, Model, settings): """The d...
stack_v2_sparse_classes_36k_train_024158
4,517
permissive
[ { "docstring": "The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.", "name": "__init__", "signature": "def __init__(self, Model, settings)" }...
3
null
Implement the Python class `ApplyRotateRegionProcess` described below. Class description: This process applies a rotation to a given modelpart or a submodelpart Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings. Method signatures and...
Implement the Python class `ApplyRotateRegionProcess` described below. Class description: This process applies a rotation to a given modelpart or a submodelpart Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings. Method signatures and...
366949ec4e3651702edc6ac3061d2988f10dd271
<|skeleton|> class ApplyRotateRegionProcess: """This process applies a rotation to a given modelpart or a submodelpart Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.""" def __init__(self, Model, settings): """The d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApplyRotateRegionProcess: """This process applies a rotation to a given modelpart or a submodelpart Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.""" def __init__(self, Model, settings): """The default constr...
the_stack_v2_python_sparse
applications/ChimeraApplication/python_scripts/rotate_region_process.py
KratosMultiphysics/Kratos
train
994
b6d477d862bd615f44e6299546155d82a5331d40
[ "with tf.variable_scope('generator'):\n encoder_layers, encoder_layer_channels = self._encoder(images)\n decoder_layers = self._decoder(encoder_layers, encoder_layer_channels)\n output = decoder_layers[-1]\n output = tf.identity(output, name='generated_images')\n return output", "layers = []\nlayer...
<|body_start_0|> with tf.variable_scope('generator'): encoder_layers, encoder_layer_channels = self._encoder(images) decoder_layers = self._decoder(encoder_layers, encoder_layer_channels) output = decoder_layers[-1] output = tf.identity(output, name='generated_ima...
Generator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: def create(self, images): """Generates fake images based off the input images. Uses a "U-net" architecture, an encoder-decoder with skip connections @images: A set of images normalized to [-1, 1], with shape [batch_size, img_size, img_size, input_channels] @returns: A set of g...
stack_v2_sparse_classes_36k_train_024159
5,008
no_license
[ { "docstring": "Generates fake images based off the input images. Uses a \"U-net\" architecture, an encoder-decoder with skip connections @images: A set of images normalized to [-1, 1], with shape [batch_size, img_size, img_size, input_channels] @returns: A set of generated images in range [-1, 1], with shape [...
3
stack_v2_sparse_classes_30k_train_003508
Implement the Python class `Generator` described below. Class description: Implement the Generator class. Method signatures and docstrings: - def create(self, images): Generates fake images based off the input images. Uses a "U-net" architecture, an encoder-decoder with skip connections @images: A set of images norma...
Implement the Python class `Generator` described below. Class description: Implement the Generator class. Method signatures and docstrings: - def create(self, images): Generates fake images based off the input images. Uses a "U-net" architecture, an encoder-decoder with skip connections @images: A set of images norma...
0d5c75877eecda2f812afa0576c0b947e3818b73
<|skeleton|> class Generator: def create(self, images): """Generates fake images based off the input images. Uses a "U-net" architecture, an encoder-decoder with skip connections @images: A set of images normalized to [-1, 1], with shape [batch_size, img_size, img_size, input_channels] @returns: A set of g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: def create(self, images): """Generates fake images based off the input images. Uses a "U-net" architecture, an encoder-decoder with skip connections @images: A set of images normalized to [-1, 1], with shape [batch_size, img_size, img_size, input_channels] @returns: A set of generated image...
the_stack_v2_python_sparse
trainer/generator.py
3a1b2c3/Image-to-Image-Translation
train
0
6f1f1b7cabf9af3b280400c866d29246dced6d20
[ "if docs.from_date and docs.to_date:\n rec = self.env['account.analytic.line'].search([('user_id', '=', docs.employee[0].id), ('date', '>=', docs.from_date), ('date', '<=', docs.to_date)])\nelif docs.from_date:\n rec = self.env['account.analytic.line'].search([('user_id', '=', docs.employee[0].id), ('date', '...
<|body_start_0|> if docs.from_date and docs.to_date: rec = self.env['account.analytic.line'].search([('user_id', '=', docs.employee[0].id), ('date', '>=', docs.from_date), ('date', '<=', docs.to_date)]) elif docs.from_date: rec = self.env['account.analytic.line'].search([('user_i...
ReportTimesheet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReportTimesheet: def get_timesheets(self, docs): """input : name of employee and the starting date and ending date output: timesheets by that particular employee within that period and the total duration""" <|body_0|> def _get_report_values(self, docids, data=None): ...
stack_v2_sparse_classes_36k_train_024160
4,467
no_license
[ { "docstring": "input : name of employee and the starting date and ending date output: timesheets by that particular employee within that period and the total duration", "name": "get_timesheets", "signature": "def get_timesheets(self, docs)" }, { "docstring": "we are overwriting this function be...
2
null
Implement the Python class `ReportTimesheet` described below. Class description: Implement the ReportTimesheet class. Method signatures and docstrings: - def get_timesheets(self, docs): input : name of employee and the starting date and ending date output: timesheets by that particular employee within that period and...
Implement the Python class `ReportTimesheet` described below. Class description: Implement the ReportTimesheet class. Method signatures and docstrings: - def get_timesheets(self, docs): input : name of employee and the starting date and ending date output: timesheets by that particular employee within that period and...
bb6453404e4f28060643f23c1c6311587f7d2925
<|skeleton|> class ReportTimesheet: def get_timesheets(self, docs): """input : name of employee and the starting date and ending date output: timesheets by that particular employee within that period and the total duration""" <|body_0|> def _get_report_values(self, docids, data=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReportTimesheet: def get_timesheets(self, docs): """input : name of employee and the starting date and ending date output: timesheets by that particular employee within that period and the total duration""" if docs.from_date and docs.to_date: rec = self.env['account.analytic.line']...
the_stack_v2_python_sparse
timesheets_by_employee/report/report_timesheets.py
aaltinisik/CybroAddons
train
1
6f91d47659a9ec242d4cb42f02a6de6f1b296116
[ "form = TagForm()\ntags = Tag.query.filter().all()\nif not tags:\n tags = None\ntemplate_return = flask.render_template('tags.html', table_data=tags, form=form)\nreturn flask.Response(template_return, mimetype='text/html')", "form = TagForm()\nif form.validate_on_submit():\n name = form.name.data\n tag_o...
<|body_start_0|> form = TagForm() tags = Tag.query.filter().all() if not tags: tags = None template_return = flask.render_template('tags.html', table_data=tags, form=form) return flask.Response(template_return, mimetype='text/html') <|end_body_0|> <|body_start_1|> ...
TagResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagResource: def get(self): """Handles the showing or not of the tags on the system. Returns: flask template.""" <|body_0|> def post(self): """Handles the showing or not of the tags on the system. Returns: flask template.""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_024161
3,873
no_license
[ { "docstring": "Handles the showing or not of the tags on the system. Returns: flask template.", "name": "get", "signature": "def get(self)" }, { "docstring": "Handles the showing or not of the tags on the system. Returns: flask template.", "name": "post", "signature": "def post(self)" ...
2
stack_v2_sparse_classes_30k_train_019526
Implement the Python class `TagResource` described below. Class description: Implement the TagResource class. Method signatures and docstrings: - def get(self): Handles the showing or not of the tags on the system. Returns: flask template. - def post(self): Handles the showing or not of the tags on the system. Return...
Implement the Python class `TagResource` described below. Class description: Implement the TagResource class. Method signatures and docstrings: - def get(self): Handles the showing or not of the tags on the system. Returns: flask template. - def post(self): Handles the showing or not of the tags on the system. Return...
865403e3b1717226b25c9d64aeb4c35c7220e7e3
<|skeleton|> class TagResource: def get(self): """Handles the showing or not of the tags on the system. Returns: flask template.""" <|body_0|> def post(self): """Handles the showing or not of the tags on the system. Returns: flask template.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TagResource: def get(self): """Handles the showing or not of the tags on the system. Returns: flask template.""" form = TagForm() tags = Tag.query.filter().all() if not tags: tags = None template_return = flask.render_template('tags.html', table_data=tags, f...
the_stack_v2_python_sparse
things_organizer/web_app/tags/resources.py
yeyeto2788/Things-Organizer
train
11
90e08401cf50ef80d42fcfa6c388650e5fc09d54
[ "favorite_nodes = UserFavoriteNode.get_favorite_nodes(get_jwt_identity())\nschema = GenericNodeSchema(many=True)\nresponse = json.loads(schema.dumps(favorite_nodes).data)\nreturn jsonify_response(response, 200)", "user_id = get_jwt_identity()\ndata = json.loads(request.data)\nif 'nodeId' not in data or 'nodeType'...
<|body_start_0|> favorite_nodes = UserFavoriteNode.get_favorite_nodes(get_jwt_identity()) schema = GenericNodeSchema(many=True) response = json.loads(schema.dumps(favorite_nodes).data) return jsonify_response(response, 200) <|end_body_0|> <|body_start_1|> user_id = get_jwt_ident...
Container for the LIST and CREATE endpoints for favorite nodes
ListCreateFavoriteNodes
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListCreateFavoriteNodes: """Container for the LIST and CREATE endpoints for favorite nodes""" def get(self): """Returns all of the user's favorite nodes that he has access to UNTESTED""" <|body_0|> def post(self): """Endpoint used for favoriting a node for the cu...
stack_v2_sparse_classes_36k_train_024162
44,865
no_license
[ { "docstring": "Returns all of the user's favorite nodes that he has access to UNTESTED", "name": "get", "signature": "def get(self)" }, { "docstring": "Endpoint used for favoriting a node for the currently authenticated user", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_015044
Implement the Python class `ListCreateFavoriteNodes` described below. Class description: Container for the LIST and CREATE endpoints for favorite nodes Method signatures and docstrings: - def get(self): Returns all of the user's favorite nodes that he has access to UNTESTED - def post(self): Endpoint used for favorit...
Implement the Python class `ListCreateFavoriteNodes` described below. Class description: Container for the LIST and CREATE endpoints for favorite nodes Method signatures and docstrings: - def get(self): Returns all of the user's favorite nodes that he has access to UNTESTED - def post(self): Endpoint used for favorit...
00434985013b65fe45b0a8c8a7f0b50bb727087a
<|skeleton|> class ListCreateFavoriteNodes: """Container for the LIST and CREATE endpoints for favorite nodes""" def get(self): """Returns all of the user's favorite nodes that he has access to UNTESTED""" <|body_0|> def post(self): """Endpoint used for favoriting a node for the cu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListCreateFavoriteNodes: """Container for the LIST and CREATE endpoints for favorite nodes""" def get(self): """Returns all of the user's favorite nodes that he has access to UNTESTED""" favorite_nodes = UserFavoriteNode.get_favorite_nodes(get_jwt_identity()) schema = GenericNodeS...
the_stack_v2_python_sparse
core/views.py
gingerComms/gingerCommsAPIs
train
0
0ec1ac4d4c9d60181fa0bcb9f9d23fe783a20444
[ "self.nums = collections.deque(maxlen=size)\nself.curr_sum = 0\nself.size = size", "self.curr_sum += val\nif len(self.nums) == self.size:\n self.curr_sum -= self.nums[0]\nself.nums.append(val)\nreturn self.curr_sum / len(self.nums)" ]
<|body_start_0|> self.nums = collections.deque(maxlen=size) self.curr_sum = 0 self.size = size <|end_body_0|> <|body_start_1|> self.curr_sum += val if len(self.nums) == self.size: self.curr_sum -= self.nums[0] self.nums.append(val) return self.curr_su...
MovingAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.nums = collections.deque(maxlen=...
stack_v2_sparse_classes_36k_train_024163
1,524
no_license
[ { "docstring": "Initialize your data structure here. :type size: int", "name": "__init__", "signature": "def __init__(self, size)" }, { "docstring": ":type val: int :rtype: float", "name": "next", "signature": "def next(self, val)" } ]
2
null
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float
Implement the Python class `MovingAverage` described below. Class description: Implement the MovingAverage class. Method signatures and docstrings: - def __init__(self, size): Initialize your data structure here. :type size: int - def next(self, val): :type val: int :rtype: float <|skeleton|> class MovingAverage: ...
98fb752c574a6ec5961a274e41a44275b56da194
<|skeleton|> class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" <|body_0|> def next(self, val): """:type val: int :rtype: float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingAverage: def __init__(self, size): """Initialize your data structure here. :type size: int""" self.nums = collections.deque(maxlen=size) self.curr_sum = 0 self.size = size def next(self, val): """:type val: int :rtype: float""" self.curr_sum += val ...
the_stack_v2_python_sparse
Challenges/movingAverageDataStream.py
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
train
0
153bb61a97bdc6de811aff603ebbe2318fcb5571
[ "if not os.path.exists(path):\n return {}\nRequestFileCom.mutex.acquire()\nwith open(path, 'r') as f:\n content = f.readlines()\n request_dict = {}\n for line in content:\n try:\n key = line.split('::')[0]\n value = line.split('::')[1]\n if value.endswith('\\n'):\...
<|body_start_0|> if not os.path.exists(path): return {} RequestFileCom.mutex.acquire() with open(path, 'r') as f: content = f.readlines() request_dict = {} for line in content: try: key = line.split('::')[0] ...
This class allows supplies methods to handle the request file.
RequestFileCom
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestFileCom: """This class allows supplies methods to handle the request file.""" def file_to_dict(path='current_request.txt'): """The function reads the file and return a dict as follow: {key, value}.""" <|body_0|> def get_value(key): """The function returns ...
stack_v2_sparse_classes_36k_train_024164
2,224
no_license
[ { "docstring": "The function reads the file and return a dict as follow: {key, value}.", "name": "file_to_dict", "signature": "def file_to_dict(path='current_request.txt')" }, { "docstring": "The function returns the value of the current title in request file.", "name": "get_value", "sig...
3
stack_v2_sparse_classes_30k_train_003388
Implement the Python class `RequestFileCom` described below. Class description: This class allows supplies methods to handle the request file. Method signatures and docstrings: - def file_to_dict(path='current_request.txt'): The function reads the file and return a dict as follow: {key, value}. - def get_value(key): ...
Implement the Python class `RequestFileCom` described below. Class description: This class allows supplies methods to handle the request file. Method signatures and docstrings: - def file_to_dict(path='current_request.txt'): The function reads the file and return a dict as follow: {key, value}. - def get_value(key): ...
f97386d7ba9ec639083c150706429b832fd288eb
<|skeleton|> class RequestFileCom: """This class allows supplies methods to handle the request file.""" def file_to_dict(path='current_request.txt'): """The function reads the file and return a dict as follow: {key, value}.""" <|body_0|> def get_value(key): """The function returns ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RequestFileCom: """This class allows supplies methods to handle the request file.""" def file_to_dict(path='current_request.txt'): """The function reads the file and return a dict as follow: {key, value}.""" if not os.path.exists(path): return {} RequestFileCom.mutex.a...
the_stack_v2_python_sparse
Project/Code/Client/client2/RequestFileCom.py
Maor2871/CodeDup
train
0
5a250a9ec313c3bd3678d44488730090ffa54a43
[ "super(ProcessRecipeInput, self).__init__('process_recipe_input')\nself.recipe_id = None\nself.forced_nodes = None", "json_dict = {'recipe_id': self.recipe_id}\nif self.forced_nodes:\n json_dict['forced_nodes'] = convert_forced_nodes_to_v6(self.forced_nodes).get_dict()\nreturn json_dict", "message = ProcessR...
<|body_start_0|> super(ProcessRecipeInput, self).__init__('process_recipe_input') self.recipe_id = None self.forced_nodes = None <|end_body_0|> <|body_start_1|> json_dict = {'recipe_id': self.recipe_id} if self.forced_nodes: json_dict['forced_nodes'] = convert_forced...
Command message that processes the input for a recipes
ProcessRecipeInput
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProcessRecipeInput: """Command message that processes the input for a recipes""" def __init__(self): """Constructor""" <|body_0|> def to_json(self): """See :meth:`messaging.messages.message.CommandMessage.to_json`""" <|body_1|> def from_json(json_dic...
stack_v2_sparse_classes_36k_train_024165
4,614
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "See :meth:`messaging.messages.message.CommandMessage.to_json`", "name": "to_json", "signature": "def to_json(self)" }, { "docstring": "See :meth:`messaging.messages.message.Comm...
5
null
Implement the Python class `ProcessRecipeInput` described below. Class description: Command message that processes the input for a recipes Method signatures and docstrings: - def __init__(self): Constructor - def to_json(self): See :meth:`messaging.messages.message.CommandMessage.to_json` - def from_json(json_dict): ...
Implement the Python class `ProcessRecipeInput` described below. Class description: Command message that processes the input for a recipes Method signatures and docstrings: - def __init__(self): Constructor - def to_json(self): See :meth:`messaging.messages.message.CommandMessage.to_json` - def from_json(json_dict): ...
28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b
<|skeleton|> class ProcessRecipeInput: """Command message that processes the input for a recipes""" def __init__(self): """Constructor""" <|body_0|> def to_json(self): """See :meth:`messaging.messages.message.CommandMessage.to_json`""" <|body_1|> def from_json(json_dic...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProcessRecipeInput: """Command message that processes the input for a recipes""" def __init__(self): """Constructor""" super(ProcessRecipeInput, self).__init__('process_recipe_input') self.recipe_id = None self.forced_nodes = None def to_json(self): """See :me...
the_stack_v2_python_sparse
scale/recipe/messages/process_recipe_input.py
kfconsultant/scale
train
0
2734a228aad4fffd4d748a1fb02dded9c9b287cd
[ "metadata = deepcopy(cube.metadata)\ncube += 273.15\ncube.metadata = metadata\nreturn cube", "cube = self.get_cube_from_list(cubes)\ncube.standard_name = 'sea_surface_temperature'\nreturn cubes" ]
<|body_start_0|> metadata = deepcopy(cube.metadata) cube += 273.15 cube.metadata = metadata return cube <|end_body_0|> <|body_start_1|> cube = self.get_cube_from_list(cubes) cube.standard_name = 'sea_surface_temperature' return cubes <|end_body_1|>
Fixes for tos.
Tos
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tos: """Fixes for tos.""" def fix_data(self, cube): """Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cube: iris.cube.Cube Returns ------- iris.cube.Cube""" <|body_0|> def fix_metadata(self, cubes): """Fix metadata. Fixes ...
stack_v2_sparse_classes_36k_train_024166
2,948
permissive
[ { "docstring": "Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cube: iris.cube.Cube Returns ------- iris.cube.Cube", "name": "fix_data", "signature": "def fix_data(self, cube)" }, { "docstring": "Fix metadata. Fixes wrong standard_name. Parameters -------...
2
null
Implement the Python class `Tos` described below. Class description: Fixes for tos. Method signatures and docstrings: - def fix_data(self, cube): Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cube: iris.cube.Cube Returns ------- iris.cube.Cube - def fix_metadata(self, cubes):...
Implement the Python class `Tos` described below. Class description: Fixes for tos. Method signatures and docstrings: - def fix_data(self, cube): Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cube: iris.cube.Cube Returns ------- iris.cube.Cube - def fix_metadata(self, cubes):...
d5187438fea2928644cb53ecb26c6adb1e4cc947
<|skeleton|> class Tos: """Fixes for tos.""" def fix_data(self, cube): """Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cube: iris.cube.Cube Returns ------- iris.cube.Cube""" <|body_0|> def fix_metadata(self, cubes): """Fix metadata. Fixes ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tos: """Fixes for tos.""" def fix_data(self, cube): """Fix data. Fixes discrepancy between declared units and real units Parameters ---------- cube: iris.cube.Cube Returns ------- iris.cube.Cube""" metadata = deepcopy(cube.metadata) cube += 273.15 cube.metadata = metadata ...
the_stack_v2_python_sparse
esmvalcore/cmor/_fixes/cmip5/gfdl_cm2p1.py
ESMValGroup/ESMValCore
train
41
ec07f6fa25e8536bc98f276fcf3f6582056efbc2
[ "flags.AddParentFlagsToParser(parser)\nparser.add_argument('RECOMMENDATION', type=str, help='Recommendation id which will be marked as active')\nparser.add_argument('--location', metavar='LOCATION', required=True, help='Location')\nparser.add_argument('--recommender', metavar='RECOMMENDER', required=True, help='Rec...
<|body_start_0|> flags.AddParentFlagsToParser(parser) parser.add_argument('RECOMMENDATION', type=str, help='Recommendation id which will be marked as active') parser.add_argument('--location', metavar='LOCATION', required=True, help='Location') parser.add_argument('--recommender', metava...
Mark Active operations for a recommendation. Mark a recommendation's state as ACTIVE. Can be applied to recommendations in DISMISSED state. This currently supports the following parent entities: project, billing account, folder, and organization. ## EXAMPLES To mark a recommenation as ACTIVE: $ {command} RECOMMENDATION...
MarkActive
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarkActive: """Mark Active operations for a recommendation. Mark a recommendation's state as ACTIVE. Can be applied to recommendations in DISMISSED state. This currently supports the following parent entities: project, billing account, folder, and organization. ## EXAMPLES To mark a recommenation...
stack_v2_sparse_classes_36k_train_024167
2,733
permissive
[ { "docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command.", "name": "Args", "signature": "def Args(parser)" }, { "docstring": "Run 'gcloud recommender recomme...
2
stack_v2_sparse_classes_30k_train_000758
Implement the Python class `MarkActive` described below. Class description: Mark Active operations for a recommendation. Mark a recommendation's state as ACTIVE. Can be applied to recommendations in DISMISSED state. This currently supports the following parent entities: project, billing account, folder, and organizati...
Implement the Python class `MarkActive` described below. Class description: Mark Active operations for a recommendation. Mark a recommendation's state as ACTIVE. Can be applied to recommendations in DISMISSED state. This currently supports the following parent entities: project, billing account, folder, and organizati...
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class MarkActive: """Mark Active operations for a recommendation. Mark a recommendation's state as ACTIVE. Can be applied to recommendations in DISMISSED state. This currently supports the following parent entities: project, billing account, folder, and organization. ## EXAMPLES To mark a recommenation...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MarkActive: """Mark Active operations for a recommendation. Mark a recommendation's state as ACTIVE. Can be applied to recommendations in DISMISSED state. This currently supports the following parent entities: project, billing account, folder, and organization. ## EXAMPLES To mark a recommenation as ACTIVE: $...
the_stack_v2_python_sparse
lib/surface/recommender/recommendations/mark_active.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
b1d217c48da1f80ffbbea6749dd6d83afb775db1
[ "include_inactive = request.args.get('include_inactive', '0') != '0'\nget_users_response = InternalApi().get(url_for('flexmeasures_api_v2_0.get_users', include_inactive=include_inactive))\nusers = [process_internal_api_response(user, make_obj=True) for user in get_users_response.json()]\nreturn render_flexmeasures_...
<|body_start_0|> include_inactive = request.args.get('include_inactive', '0') != '0' get_users_response = InternalApi().get(url_for('flexmeasures_api_v2_0.get_users', include_inactive=include_inactive)) users = [process_internal_api_response(user, make_obj=True) for user in get_users_response.js...
UserCrudUI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserCrudUI: def index(self): """/users""" <|body_0|> def get(self, id: str): """GET from /users/<id>""" <|body_1|> def toggle_active(self, id: str): """Toggle activation status via /users/toggle_active/<id>""" <|body_2|> def reset_pa...
stack_v2_sparse_classes_36k_train_024168
4,885
permissive
[ { "docstring": "/users", "name": "index", "signature": "def index(self)" }, { "docstring": "GET from /users/<id>", "name": "get", "signature": "def get(self, id: str)" }, { "docstring": "Toggle activation status via /users/toggle_active/<id>", "name": "toggle_active", "si...
4
stack_v2_sparse_classes_30k_train_020559
Implement the Python class `UserCrudUI` described below. Class description: Implement the UserCrudUI class. Method signatures and docstrings: - def index(self): /users - def get(self, id: str): GET from /users/<id> - def toggle_active(self, id: str): Toggle activation status via /users/toggle_active/<id> - def reset_...
Implement the Python class `UserCrudUI` described below. Class description: Implement the UserCrudUI class. Method signatures and docstrings: - def index(self): /users - def get(self, id: str): GET from /users/<id> - def toggle_active(self, id: str): Toggle activation status via /users/toggle_active/<id> - def reset_...
6ba518bae7e9b8a715b9a05f6fae19f5e4ade791
<|skeleton|> class UserCrudUI: def index(self): """/users""" <|body_0|> def get(self, id: str): """GET from /users/<id>""" <|body_1|> def toggle_active(self, id: str): """Toggle activation status via /users/toggle_active/<id>""" <|body_2|> def reset_pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserCrudUI: def index(self): """/users""" include_inactive = request.args.get('include_inactive', '0') != '0' get_users_response = InternalApi().get(url_for('flexmeasures_api_v2_0.get_users', include_inactive=include_inactive)) users = [process_internal_api_response(user, make_...
the_stack_v2_python_sparse
flexmeasures/ui/crud/users.py
meeseeksmachine/flexmeasures
train
0
873e7a28777a59b3626c9ae980a8ab124615f827
[ "self.x_driver = driver\nself.name = name\nself.x_elem_id = elem_id", "logging.info('Determine if ' + self.name + ' is enabled.')\nelement = self.x_driver.find_element(self.x_elem_id[0], self.x_elem_id[1])\nenabled = element.is_enabled()\nlogging.info('Enabled state of ' + self.name + ' is: ' + str(enabled))\nret...
<|body_start_0|> self.x_driver = driver self.name = name self.x_elem_id = elem_id <|end_body_0|> <|body_start_1|> logging.info('Determine if ' + self.name + ' is enabled.') element = self.x_driver.find_element(self.x_elem_id[0], self.x_elem_id[1]) enabled = element.is_en...
Common base class for al widgets/elements
BaseElement
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseElement: """Common base class for al widgets/elements""" def __init__(self, driver, name, elem_id): """Common code for all elements/widgets. :param driver: Interface to Website :param elem_id: Unique ID related to the element :return: None""" <|body_0|> def is_enable...
stack_v2_sparse_classes_36k_train_024169
1,411
no_license
[ { "docstring": "Common code for all elements/widgets. :param driver: Interface to Website :param elem_id: Unique ID related to the element :return: None", "name": "__init__", "signature": "def __init__(self, driver, name, elem_id)" }, { "docstring": "Determine if the element is enabled. :return:...
3
stack_v2_sparse_classes_30k_train_004711
Implement the Python class `BaseElement` described below. Class description: Common base class for al widgets/elements Method signatures and docstrings: - def __init__(self, driver, name, elem_id): Common code for all elements/widgets. :param driver: Interface to Website :param elem_id: Unique ID related to the eleme...
Implement the Python class `BaseElement` described below. Class description: Common base class for al widgets/elements Method signatures and docstrings: - def __init__(self, driver, name, elem_id): Common code for all elements/widgets. :param driver: Interface to Website :param elem_id: Unique ID related to the eleme...
c7ae5cd1c14defdbff57c2ed5e4a447c7799c495
<|skeleton|> class BaseElement: """Common base class for al widgets/elements""" def __init__(self, driver, name, elem_id): """Common code for all elements/widgets. :param driver: Interface to Website :param elem_id: Unique ID related to the element :return: None""" <|body_0|> def is_enable...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseElement: """Common base class for al widgets/elements""" def __init__(self, driver, name, elem_id): """Common code for all elements/widgets. :param driver: Interface to Website :param elem_id: Unique ID related to the element :return: None""" self.x_driver = driver self.name =...
the_stack_v2_python_sparse
support/common_controls/__base_element.py
chrisaroy/proj_selenium_python_dev
train
0
368f3d65b3dcbbfb9b9ff08b82a8748cb8826381
[ "super().setUp()\nself.signup(self.CURRICULUM_ADMIN_EMAIL, self.CURRICULUM_ADMIN_USERNAME)\nself.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)\nself.admin_id = self.get_user_id_from_email(self.CURRICULUM_ADMIN_EMAIL)\nself.albert_id = self.get_user_id_from_email(self.ALBERT_EMAIL)\nself.albert = user_services.get_use...
<|body_start_0|> super().setUp() self.signup(self.CURRICULUM_ADMIN_EMAIL, self.CURRICULUM_ADMIN_USERNAME) self.signup(self.ALBERT_EMAIL, self.ALBERT_NAME) self.admin_id = self.get_user_id_from_email(self.CURRICULUM_ADMIN_EMAIL) self.albert_id = self.get_user_id_from_email(self.AL...
Test functions for getting displayable recently published exploration summary dicts.
RecentlyPublishedExplorationDisplayableSummariesTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecentlyPublishedExplorationDisplayableSummariesTest: """Test functions for getting displayable recently published exploration summary dicts.""" def setUp(self) -> None: """Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_...
stack_v2_sparse_classes_36k_train_024170
47,358
permissive
[ { "docstring": "Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) Albert creates EXP_ID_2. - (3) Albert creates EXP_ID_3. - (4) Albert publishes EXP_ID_1. - (5) Albert publishes EXP_ID_2. - (6) Albert publishes EXP_ID_3. - (7) Admin user i...
2
stack_v2_sparse_classes_30k_train_002718
Implement the Python class `RecentlyPublishedExplorationDisplayableSummariesTest` described below. Class description: Test functions for getting displayable recently published exploration summary dicts. Method signatures and docstrings: - def setUp(self) -> None: Populate the database of explorations and their summar...
Implement the Python class `RecentlyPublishedExplorationDisplayableSummariesTest` described below. Class description: Test functions for getting displayable recently published exploration summary dicts. Method signatures and docstrings: - def setUp(self) -> None: Populate the database of explorations and their summar...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class RecentlyPublishedExplorationDisplayableSummariesTest: """Test functions for getting displayable recently published exploration summary dicts.""" def setUp(self) -> None: """Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RecentlyPublishedExplorationDisplayableSummariesTest: """Test functions for getting displayable recently published exploration summary dicts.""" def setUp(self) -> None: """Populate the database of explorations and their summaries. The sequence of events is: - (1) Albert creates EXP_ID_1. - (2) A...
the_stack_v2_python_sparse
core/domain/summary_services_test.py
oppia/oppia
train
6,172
f33a67fdfde8e4cf4cac95ab408652096b51a5df
[ "id_d = id(d)\nsc = self.manager.displayable_map.get(id_d, None)\nif sc is None:\n d = renpy.easy.displayable(d)\n sc = SpriteCache()\n sc.render = None\n sc.child = d\n sc.st = None\n if d._duplicatable:\n sc.child_copy = d._duplicate(None)\n sc.child_copy._unique()\n else:\n ...
<|body_start_0|> id_d = id(d) sc = self.manager.displayable_map.get(id_d, None) if sc is None: d = renpy.easy.displayable(d) sc = SpriteCache() sc.render = None sc.child = d sc.st = None if d._duplicatable: s...
:doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a sprite object are: `x`, `y` The x...
Sprite
[ "GPL-1.0-or-later", "LGPL-2.0-or-later", "LGPL-2.1-or-later", "IJG", "WxWindows-exception-3.1", "Zlib", "bzip2-1.0.6", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "Artistic-2.0", "LGPL-2.1-only", "Python-2.0", "LicenseRef-scancode-warran...
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sprite: """:doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a...
stack_v2_sparse_classes_36k_train_024171
18,129
permissive
[ { "docstring": ":doc: sprites method Changes the Displayable associated with this sprite to `d`.", "name": "set_child", "signature": "def set_child(self, d)" }, { "docstring": ":doc: sprites method Destroys this sprite, preventing it from being displayed and removing it from the SpriteManager.",...
2
null
Implement the Python class `Sprite` described below. Class description: :doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:...
Implement the Python class `Sprite` described below. Class description: :doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:...
e365b474e7df3f76ccc0853fd1665f6529a59304
<|skeleton|> class Sprite: """:doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sprite: """:doc: sprites class This represents a sprite that is managed by the SpriteManager. It contains fields that control the placement of the sprite on the screen. Sprites should not be created directly. Instead, they should be created by calling :meth:`SpriteManager.create`. The fields of a sprite objec...
the_stack_v2_python_sparse
TEST_PROJET-1.0-pc/renpy/display/particle.py
Dune0lyn/otome
train
0
bf432d82d93968be576231dfed80bdc5018d2a13
[ "dt_fpaths = list(self.dt_root_fpath.glob('*/per_sweep_annotations_amodal/*.json'))\ngt_fpaths = list(self.gt_root_fpath.glob('*/per_sweep_annotations_amodal/*.json'))\nassert len(dt_fpaths) == len(gt_fpaths)\ndata: DefaultDict[str, np.ndarray] = defaultdict(list)\ncls_to_ninst: DefaultDict[str, int] = defaultdict(...
<|body_start_0|> dt_fpaths = list(self.dt_root_fpath.glob('*/per_sweep_annotations_amodal/*.json')) gt_fpaths = list(self.gt_root_fpath.glob('*/per_sweep_annotations_amodal/*.json')) assert len(dt_fpaths) == len(gt_fpaths) data: DefaultDict[str, np.ndarray] = defaultdict(list) cl...
Instantiates a DetectionEvaluator object for evaluation. Args: dt_fpath_root: Path to the folder which contains the detections. gt_fpath_root: Path to the folder which contains the split of logs. figs_fpath: Path to the folder which will contain the output figures. cfg: Detection configuration settings.
DetectionEvaluator
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DetectionEvaluator: """Instantiates a DetectionEvaluator object for evaluation. Args: dt_fpath_root: Path to the folder which contains the detections. gt_fpath_root: Path to the folder which contains the split of logs. figs_fpath: Path to the folder which will contain the output figures. cfg: Det...
stack_v2_sparse_classes_36k_train_024172
8,609
permissive
[ { "docstring": "Evaluate detection output and return metrics. The multiprocessing library is used for parallel assignment between detections and ground truth annotations. Returns: Evaluation metrics of shape (C + 1, K) where C + 1 is the number of classes. plus a row for their means. K refers to the number of e...
2
null
Implement the Python class `DetectionEvaluator` described below. Class description: Instantiates a DetectionEvaluator object for evaluation. Args: dt_fpath_root: Path to the folder which contains the detections. gt_fpath_root: Path to the folder which contains the split of logs. figs_fpath: Path to the folder which wi...
Implement the Python class `DetectionEvaluator` described below. Class description: Instantiates a DetectionEvaluator object for evaluation. Args: dt_fpath_root: Path to the folder which contains the detections. gt_fpath_root: Path to the folder which contains the split of logs. figs_fpath: Path to the folder which wi...
2e2aed64d4a286821aece806134054c6d6e1d3cb
<|skeleton|> class DetectionEvaluator: """Instantiates a DetectionEvaluator object for evaluation. Args: dt_fpath_root: Path to the folder which contains the detections. gt_fpath_root: Path to the folder which contains the split of logs. figs_fpath: Path to the folder which will contain the output figures. cfg: Det...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DetectionEvaluator: """Instantiates a DetectionEvaluator object for evaluation. Args: dt_fpath_root: Path to the folder which contains the detections. gt_fpath_root: Path to the folder which contains the split of logs. figs_fpath: Path to the folder which will contain the output figures. cfg: Detection config...
the_stack_v2_python_sparse
argoverse/evaluation/detection/eval.py
ChenChenGith/argoverse-api-ccuse
train
1
1de468463bf8668cad8b622775669e28a42dd12d
[ "Fiscal = self.env['account.fiscalyear']\nSeq = self.env['ir.sequence']\nfiscalyear_id = self._context.get('fiscalyear_id', False)\nfor rec in self:\n if rec.code:\n continue\n if not fiscalyear_id:\n fiscalyear_id = rec.fiscalyear_id.id or Fiscal.find()\n ctx = {'fiscalyear_id': fiscalyear_i...
<|body_start_0|> Fiscal = self.env['account.fiscalyear'] Seq = self.env['ir.sequence'] fiscalyear_id = self._context.get('fiscalyear_id', False) for rec in self: if rec.code: continue if not fiscalyear_id: fiscalyear_id = rec.fiscal...
ResInvestAsset
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResInvestAsset: def generate_code(self): """Generate Asset Code based on context fiscalyear_id""" <|body_0|> def _add_name_search_domain(self): """only asset not being used in other budget control""" <|body_1|> <|end_skeleton|> <|body_start_0|> Fisc...
stack_v2_sparse_classes_36k_train_024173
1,727
no_license
[ { "docstring": "Generate Asset Code based on context fiscalyear_id", "name": "generate_code", "signature": "def generate_code(self)" }, { "docstring": "only asset not being used in other budget control", "name": "_add_name_search_domain", "signature": "def _add_name_search_domain(self)" ...
2
null
Implement the Python class `ResInvestAsset` described below. Class description: Implement the ResInvestAsset class. Method signatures and docstrings: - def generate_code(self): Generate Asset Code based on context fiscalyear_id - def _add_name_search_domain(self): only asset not being used in other budget control
Implement the Python class `ResInvestAsset` described below. Class description: Implement the ResInvestAsset class. Method signatures and docstrings: - def generate_code(self): Generate Asset Code based on context fiscalyear_id - def _add_name_search_domain(self): only asset not being used in other budget control <|...
e8c21082c187f4639373b29a7a0905d069d770f2
<|skeleton|> class ResInvestAsset: def generate_code(self): """Generate Asset Code based on context fiscalyear_id""" <|body_0|> def _add_name_search_domain(self): """only asset not being used in other budget control""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResInvestAsset: def generate_code(self): """Generate Asset Code based on context fiscalyear_id""" Fiscal = self.env['account.fiscalyear'] Seq = self.env['ir.sequence'] fiscalyear_id = self._context.get('fiscalyear_id', False) for rec in self: if rec.code: ...
the_stack_v2_python_sparse
pabi_budget_plan/models/res_invest_asset.py
pabi2/pb2_addons
train
6
2c7435e8268949ff0043dbaa385c93202378089e
[ "@lru_cache(None)\ndef f(i, cur_sum):\n if i == len(nums):\n if target == cur_sum:\n return 1\n return 0\n return f(i + 1, cur_sum + nums[i]) + f(i + 1, cur_sum - nums[i])\nreturn f(0, 0)", "if (sum(nums) + target) % 2 == 1:\n return 0\nt = (sum(nums) + target) // 2\ndp = [[0] * ...
<|body_start_0|> @lru_cache(None) def f(i, cur_sum): if i == len(nums): if target == cur_sum: return 1 return 0 return f(i + 1, cur_sum + nums[i]) + f(i + 1, cur_sum - nums[i]) return f(0, 0) <|end_body_0|> <|body_start...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: """method 1 recursion + memoize""" <|body_0|> def findTargetSumWays2(self, nums: List[int], target: int) -> int: """method 2 2D DP""" <|body_1|> def findTargetSumWays3(self, nums...
stack_v2_sparse_classes_36k_train_024174
2,087
no_license
[ { "docstring": "method 1 recursion + memoize", "name": "findTargetSumWays", "signature": "def findTargetSumWays(self, nums: List[int], target: int) -> int" }, { "docstring": "method 2 2D DP", "name": "findTargetSumWays2", "signature": "def findTargetSumWays2(self, nums: List[int], target...
3
stack_v2_sparse_classes_30k_train_008535
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findTargetSumWays(self, nums: List[int], target: int) -> int: method 1 recursion + memoize - def findTargetSumWays2(self, nums: List[int], target: int) -> int: method 2 2D DP...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findTargetSumWays(self, nums: List[int], target: int) -> int: method 1 recursion + memoize - def findTargetSumWays2(self, nums: List[int], target: int) -> int: method 2 2D DP...
3a5649357e0f21cbbc5e238351300cd706d533b3
<|skeleton|> class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: """method 1 recursion + memoize""" <|body_0|> def findTargetSumWays2(self, nums: List[int], target: int) -> int: """method 2 2D DP""" <|body_1|> def findTargetSumWays3(self, nums...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: """method 1 recursion + memoize""" @lru_cache(None) def f(i, cur_sum): if i == len(nums): if target == cur_sum: return 1 return 0 retu...
the_stack_v2_python_sparse
leetcode-py/leetcode494.py
cicihou/LearningProject
train
0
bd9bb501880bef1c80ebdb23285789fbc0d31007
[ "if pos < 2 or steps < 1 or start < 1 or (start > pos) or (target < 1) or (target > pos):\n return 0\nreturn self.process_a(pos, start, steps, target)", "if rest == 0:\n return 1 if cur == target else 0\nif cur == 1:\n return self.process_a(pos, cur + 1, rest - 1, target)\nif cur == pos:\n return self...
<|body_start_0|> if pos < 2 or steps < 1 or start < 1 or (start > pos) or (target < 1) or (target > pos): return 0 return self.process_a(pos, start, steps, target) <|end_body_0|> <|body_start_1|> if rest == 0: return 1 if cur == target else 0 if cur == 1: ...
RobotWalk
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RobotWalk: def ways_a(self, pos, steps, start, target): """:param pos: 总共有pos个位置 :param steps: 可以走的步数 :param start: 开始位置 :param target: 目标位置 :return:""" <|body_0|> def process_a(self, pos, cur, rest, target): """:param pos: 总共有pos个位置 :param cur: 当前来到的位置 :param rest: ...
stack_v2_sparse_classes_36k_train_024175
4,456
no_license
[ { "docstring": ":param pos: 总共有pos个位置 :param steps: 可以走的步数 :param start: 开始位置 :param target: 目标位置 :return:", "name": "ways_a", "signature": "def ways_a(self, pos, steps, start, target)" }, { "docstring": ":param pos: 总共有pos个位置 :param cur: 当前来到的位置 :param rest: 还剩下的步数 :param target: 目标位置 :return: ...
5
stack_v2_sparse_classes_30k_train_012389
Implement the Python class `RobotWalk` described below. Class description: Implement the RobotWalk class. Method signatures and docstrings: - def ways_a(self, pos, steps, start, target): :param pos: 总共有pos个位置 :param steps: 可以走的步数 :param start: 开始位置 :param target: 目标位置 :return: - def process_a(self, pos, cur, rest, ta...
Implement the Python class `RobotWalk` described below. Class description: Implement the RobotWalk class. Method signatures and docstrings: - def ways_a(self, pos, steps, start, target): :param pos: 总共有pos个位置 :param steps: 可以走的步数 :param start: 开始位置 :param target: 目标位置 :return: - def process_a(self, pos, cur, rest, ta...
45c26b4791fc95b19442b909b6744dbe07bf9a56
<|skeleton|> class RobotWalk: def ways_a(self, pos, steps, start, target): """:param pos: 总共有pos个位置 :param steps: 可以走的步数 :param start: 开始位置 :param target: 目标位置 :return:""" <|body_0|> def process_a(self, pos, cur, rest, target): """:param pos: 总共有pos个位置 :param cur: 当前来到的位置 :param rest: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RobotWalk: def ways_a(self, pos, steps, start, target): """:param pos: 总共有pos个位置 :param steps: 可以走的步数 :param start: 开始位置 :param target: 目标位置 :return:""" if pos < 2 or steps < 1 or start < 1 or (start > pos) or (target < 1) or (target > pos): return 0 return self.process_a(p...
the_stack_v2_python_sparse
basic/动态规划/机器人走路.py
imlifeilong/MyAlgorithm
train
0
b8066e3fb1e3ec7236a3cb3027cd872401134acc
[ "self.gateway_url = config.get('gateway_url')\nself.username = config.get('username')\nself.password = config.get('password')\nself.smsc = config.get('smsc')\nself.charset = config.get('charset')\nself.coding = config.get('coding')\nself.sender = config.get('from', '')", "gateway_params = {'username': self.userna...
<|body_start_0|> self.gateway_url = config.get('gateway_url') self.username = config.get('username') self.password = config.get('password') self.smsc = config.get('smsc') self.charset = config.get('charset') self.coding = config.get('coding') self.sender = config....
Kannel Gateway class
KannelGateway
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KannelGateway: """Kannel Gateway class""" def __init__(self, config): """initializes the kannel gateway object :param config: The configuration object obtained from the app settings""" <|body_0|> def send(self, text, recipient, sender=''): """Sends the message to...
stack_v2_sparse_classes_36k_train_024176
3,492
no_license
[ { "docstring": "initializes the kannel gateway object :param config: The configuration object obtained from the app settings", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "Sends the message to the specified recipients using this gateway :param text: Contents o...
2
null
Implement the Python class `KannelGateway` described below. Class description: Kannel Gateway class Method signatures and docstrings: - def __init__(self, config): initializes the kannel gateway object :param config: The configuration object obtained from the app settings - def send(self, text, recipient, sender=''):...
Implement the Python class `KannelGateway` described below. Class description: Kannel Gateway class Method signatures and docstrings: - def __init__(self, config): initializes the kannel gateway object :param config: The configuration object obtained from the app settings - def send(self, text, recipient, sender=''):...
e071b05b6122a756313c561643d343fa4d23b097
<|skeleton|> class KannelGateway: """Kannel Gateway class""" def __init__(self, config): """initializes the kannel gateway object :param config: The configuration object obtained from the app settings""" <|body_0|> def send(self, text, recipient, sender=''): """Sends the message to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KannelGateway: """Kannel Gateway class""" def __init__(self, config): """initializes the kannel gateway object :param config: The configuration object obtained from the app settings""" self.gateway_url = config.get('gateway_url') self.username = config.get('username') self...
the_stack_v2_python_sparse
apollo/messaging/outgoing.py
Ismail774403783/apollo
train
0
e44d0d0dd9f43be503e69674f8adb506510a67bf
[ "parser = linux_software_parser.DebianPackagesStatusParser(deb822)\npath = os.path.join(self.base_path, 'dpkg_status')\nwith open(path, 'rb') as data:\n out = list(parser.ParseFile(None, None, data))\nself.assertLen(out, 1)\npackage_list = out[0]\nself.assertLen(package_list.packages, 2)\npackage0 = package_list...
<|body_start_0|> parser = linux_software_parser.DebianPackagesStatusParser(deb822) path = os.path.join(self.base_path, 'dpkg_status') with open(path, 'rb') as data: out = list(parser.ParseFile(None, None, data)) self.assertLen(out, 1) package_list = out[0] sel...
Test parsing of linux software collection.
LinuxSoftwareParserTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinuxSoftwareParserTest: """Test parsing of linux software collection.""" def testDebianPackagesStatusParser(self): """Test parsing of a status file.""" <|body_0|> def testDebianPackagesStatusParserBadInput(self): """If the status file is broken, fail nicely.""" ...
stack_v2_sparse_classes_36k_train_024177
1,633
permissive
[ { "docstring": "Test parsing of a status file.", "name": "testDebianPackagesStatusParser", "signature": "def testDebianPackagesStatusParser(self)" }, { "docstring": "If the status file is broken, fail nicely.", "name": "testDebianPackagesStatusParserBadInput", "signature": "def testDebia...
2
null
Implement the Python class `LinuxSoftwareParserTest` described below. Class description: Test parsing of linux software collection. Method signatures and docstrings: - def testDebianPackagesStatusParser(self): Test parsing of a status file. - def testDebianPackagesStatusParserBadInput(self): If the status file is bro...
Implement the Python class `LinuxSoftwareParserTest` described below. Class description: Test parsing of linux software collection. Method signatures and docstrings: - def testDebianPackagesStatusParser(self): Test parsing of a status file. - def testDebianPackagesStatusParserBadInput(self): If the status file is bro...
44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6
<|skeleton|> class LinuxSoftwareParserTest: """Test parsing of linux software collection.""" def testDebianPackagesStatusParser(self): """Test parsing of a status file.""" <|body_0|> def testDebianPackagesStatusParserBadInput(self): """If the status file is broken, fail nicely.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinuxSoftwareParserTest: """Test parsing of linux software collection.""" def testDebianPackagesStatusParser(self): """Test parsing of a status file.""" parser = linux_software_parser.DebianPackagesStatusParser(deb822) path = os.path.join(self.base_path, 'dpkg_status') wit...
the_stack_v2_python_sparse
grr/core/grr_response_core/lib/parsers/linux_software_parser_test.py
google/grr
train
4,683
972b4d292e87e9380d32036e27864d5ad6d31eaf
[ "group = self.context['group']\nuser = data\nmembership = Membership.objects.filter(group=group, user=user)\nif membership.exists():\n raise serializers.ValidationError('User has already been invited to this group.')\nreturn data", "try:\n invitation = Invitation.objects.get(code=data, group=self.context['g...
<|body_start_0|> group = self.context['group'] user = data membership = Membership.objects.filter(group=group, user=user) if membership.exists(): raise serializers.ValidationError('User has already been invited to this group.') return data <|end_body_0|> <|body_start...
Add member serializer. Handle the addition of a new member to a group.
AddMemberSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddMemberSerializer: """Add member serializer. Handle the addition of a new member to a group.""" def validate_user(self, data): """Verify user is not already a member.""" <|body_0|> def validate_invitation_code(self, data): """Verify code exists and that it is r...
stack_v2_sparse_classes_36k_train_024178
2,279
no_license
[ { "docstring": "Verify user is not already a member.", "name": "validate_user", "signature": "def validate_user(self, data)" }, { "docstring": "Verify code exists and that it is related to the group.", "name": "validate_invitation_code", "signature": "def validate_invitation_code(self, d...
3
stack_v2_sparse_classes_30k_train_017544
Implement the Python class `AddMemberSerializer` described below. Class description: Add member serializer. Handle the addition of a new member to a group. Method signatures and docstrings: - def validate_user(self, data): Verify user is not already a member. - def validate_invitation_code(self, data): Verify code ex...
Implement the Python class `AddMemberSerializer` described below. Class description: Add member serializer. Handle the addition of a new member to a group. Method signatures and docstrings: - def validate_user(self, data): Verify user is not already a member. - def validate_invitation_code(self, data): Verify code ex...
fae5c0b2e388239e2e32a3fbf52aa7cfd48a7cbb
<|skeleton|> class AddMemberSerializer: """Add member serializer. Handle the addition of a new member to a group.""" def validate_user(self, data): """Verify user is not already a member.""" <|body_0|> def validate_invitation_code(self, data): """Verify code exists and that it is r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddMemberSerializer: """Add member serializer. Handle the addition of a new member to a group.""" def validate_user(self, data): """Verify user is not already a member.""" group = self.context['group'] user = data membership = Membership.objects.filter(group=group, user=us...
the_stack_v2_python_sparse
facebook/app/groups/serializers/memberships.py
ricagome/Api-Facebook-Clone
train
0
12677c6c07c58539c280d64698a3d3df35eb7da9
[ "self.is_training = is_training\nif not is_training:\n batch_size = 1\n min_dimension = params['min_dimension']\n assert min_dimension % DIVISOR == 0\n self.min_dimension = min_dimension\nelse:\n batch_size = params['batch_size']\n width, height = params['image_size']\n assert height % DIVISOR ...
<|body_start_0|> self.is_training = is_training if not is_training: batch_size = 1 min_dimension = params['min_dimension'] assert min_dimension % DIVISOR == 0 self.min_dimension = min_dimension else: batch_size = params['batch_size'] ...
Input pipeline for training or evaluating networks for heatmaps regression.
KeypointPipeline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeypointPipeline: """Input pipeline for training or evaluating networks for heatmaps regression.""" def __init__(self, filenames, is_training, params): """During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. i...
stack_v2_sparse_classes_36k_train_024179
17,983
permissive
[ { "docstring": "During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. is_training: a boolean. params: a dict.", "name": "__init__", "signature": "def __init__(self, filenames, is_training, params)" }, { "docstring": "All h...
3
stack_v2_sparse_classes_30k_train_006351
Implement the Python class `KeypointPipeline` described below. Class description: Input pipeline for training or evaluating networks for heatmaps regression. Method signatures and docstrings: - def __init__(self, filenames, is_training, params): During the evaluation we resize images keeping aspect ratio. Arguments: ...
Implement the Python class `KeypointPipeline` described below. Class description: Input pipeline for training or evaluating networks for heatmaps regression. Method signatures and docstrings: - def __init__(self, filenames, is_training, params): During the evaluation we resize images keeping aspect ratio. Arguments: ...
0a509a6f217e84342e54219e0ca8d2e4052127e9
<|skeleton|> class KeypointPipeline: """Input pipeline for training or evaluating networks for heatmaps regression.""" def __init__(self, filenames, is_training, params): """During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeypointPipeline: """Input pipeline for training or evaluating networks for heatmaps regression.""" def __init__(self, filenames, is_training, params): """During the evaluation we resize images keeping aspect ratio. Arguments: filenames: a list of strings, paths to tfrecords files. is_training: a...
the_stack_v2_python_sparse
detector/input_pipeline/keypoints_detector_pipeline.py
TropComplique/MultiPoseNet
train
12
179059de3a08256bcbca884f8cb24c47066e7ea0
[ "from GoogleDrive import files_list_command\nwith open('test_data/files_list_response.json', encoding='utf-8') as data:\n mock_response = json.load(data)\nmocker_http_request.return_value = mock_response\nargs = {'use_domain_admin_access': True}\nresult = files_list_command(gsuite_client, args)\nassert 'GoogleDr...
<|body_start_0|> from GoogleDrive import files_list_command with open('test_data/files_list_response.json', encoding='utf-8') as data: mock_response = json.load(data) mocker_http_request.return_value = mock_response args = {'use_domain_admin_access': True} result = fi...
TestFileMethods
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFileMethods: def test_files_list_command_success(self, mocker_http_request, gsuite_client): """Scenario: For google-drive-files-list command successful run. Given: - Command args. When: - Calling google-drive-files-list command with the parameters provided. Then: - Ensure command's r...
stack_v2_sparse_classes_36k_train_024180
33,071
permissive
[ { "docstring": "Scenario: For google-drive-files-list command successful run. Given: - Command args. When: - Calling google-drive-files-list command with the parameters provided. Then: - Ensure command's raw_response, outputs should be as expected.", "name": "test_files_list_command_success", "signature...
4
stack_v2_sparse_classes_30k_train_009729
Implement the Python class `TestFileMethods` described below. Class description: Implement the TestFileMethods class. Method signatures and docstrings: - def test_files_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-files-list command successful run. Given: - Command args. ...
Implement the Python class `TestFileMethods` described below. Class description: Implement the TestFileMethods class. Method signatures and docstrings: - def test_files_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-files-list command successful run. Given: - Command args. ...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestFileMethods: def test_files_list_command_success(self, mocker_http_request, gsuite_client): """Scenario: For google-drive-files-list command successful run. Given: - Command args. When: - Calling google-drive-files-list command with the parameters provided. Then: - Ensure command's r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestFileMethods: def test_files_list_command_success(self, mocker_http_request, gsuite_client): """Scenario: For google-drive-files-list command successful run. Given: - Command args. When: - Calling google-drive-files-list command with the parameters provided. Then: - Ensure command's raw_response, o...
the_stack_v2_python_sparse
Packs/GoogleDrive/Integrations/GoogleDrive/GoogleDrive_test.py
demisto/content
train
1,023
a7f2cfc2a00feec3a4656898afc46df083090709
[ "self.clerk = clerk\nself.fID = fID\nself.fclass = fclass", "if name == 'ID' or isinstance(getattr(stub.__class__, name), linkset):\n pass\nelse:\n stub.removeInjector(self.inject)\n stub.removeObserver(self.inject)\n if hasattr(stub.private, 'isStub'):\n pri = stub.private\n raw = self....
<|body_start_0|> self.clerk = clerk self.fID = fID self.fclass = fclass <|end_body_0|> <|body_start_1|> if name == 'ID' or isinstance(getattr(stub.__class__, name), linkset): pass else: stub.removeInjector(self.inject) stub.removeObserver(self...
LinkInjector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkInjector: def __init__(self, clerk, fclass, fID): """Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_024181
20,272
no_license
[ { "docstring": "Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen.", "name": "__init__", "signature": "def __init__(self, clerk, fclass, fID)" },...
2
stack_v2_sparse_classes_30k_train_007266
Implement the Python class `LinkInjector` described below. Class description: Implement the LinkInjector class. Method signatures and docstrings: - def __init__(self, clerk, fclass, fID): Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and i...
Implement the Python class `LinkInjector` described below. Class description: Implement the LinkInjector class. Method signatures and docstrings: - def __init__(self, clerk, fclass, fID): Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and i...
1ea55a754a7568b8df2bab297a8036c0b3a671e0
<|skeleton|> class LinkInjector: def __init__(self, clerk, fclass, fID): """Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinkInjector: def __init__(self, clerk, fclass, fID): """Registers a callback so that when getattr(box, atr) is called, the object of box.atr's type with given ID is loaded from sto and injected into box. In other words, this provides lazy loading for strongboxen.""" self.clerk = clerk ...
the_stack_v2_python_sparse
code/clerks.py
tangentstorm/workshop
train
0
457892631cd8804366663db4c350ca395b81253f
[ "LDC_Info.__init__(self)\nself.setTitle(self.name)\nself.status = compat_res[0]\nui = Ui_soundFrame()\nui.setupUi(self.frame)\nself.__fill_frame(ui, info_res, compat_res, diag_res)", "ui.productLineEdit.setText(QtGui.QApplication.translate('soundFrame', self._check_invalid_values(info_res.product[1]), None, QtGui...
<|body_start_0|> LDC_Info.__init__(self) self.setTitle(self.name) self.status = compat_res[0] ui = Ui_soundFrame() ui.setupUi(self.frame) self.__fill_frame(ui, info_res, compat_res, diag_res) <|end_body_0|> <|body_start_1|> ui.productLineEdit.setText(QtGui.QAppli...
Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som.
GUISound
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GUISound: """Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som.""" def __init__(self, info_res, compat_res, diag_res): """Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res...
stack_v2_sparse_classes_36k_train_024182
3,403
no_license
[ { "docstring": "Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista com as tuples de resultados de compatibilidade [(True, msg)] diag_res -- Lista com os resultados do diagnóstico (lista de 'DaigResSound')", "name": "__init__", "signature"...
2
null
Implement the Python class `GUISound` described below. Class description: Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som. Method signatures and docstrings: - def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os re...
Implement the Python class `GUISound` described below. Class description: Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som. Method signatures and docstrings: - def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os re...
bda0c2c8977dd1246339f1f0f4718d29e8795f21
<|skeleton|> class GUISound: """Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som.""" def __init__(self, info_res, compat_res, diag_res): """Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GUISound: """Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som.""" def __init__(self, info_res, compat_res, diag_res): """Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista com...
the_stack_v2_python_sparse
src/libs/sound/gui_sound.py
adrianomelo/ldc-desktop
train
1
9fafc61f6afbe3ccff2e5c4383b9f0508327e8a1
[ "super(JobWorker, self).__init__()\nself.cb = cb\nself.sensor_id = sensor_id\nself.job_queue = Queue()\nself.lr_session = None\nself.result_queue = result_queue", "try:\n self.lr_session = self.cb.live_response.request_session(self.sensor_id)\n self.result_queue.put(WorkerStatus(self.sensor_id, status='read...
<|body_start_0|> super(JobWorker, self).__init__() self.cb = cb self.sensor_id = sensor_id self.job_queue = Queue() self.lr_session = None self.result_queue = result_queue <|end_body_0|> <|body_start_1|> try: self.lr_session = self.cb.live_response.re...
Thread object that executes individual Live Response jobs.
JobWorker
[ "MIT", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobWorker: """Thread object that executes individual Live Response jobs.""" def __init__(self, cb, sensor_id, result_queue): """Initialize the JobWorker. Args: cb (BaseAPI): The CBAPI object reference. sensor_id (int): The ID of the sensor being used. result_queue (Queue): The queue ...
stack_v2_sparse_classes_36k_train_024183
44,074
permissive
[ { "docstring": "Initialize the JobWorker. Args: cb (BaseAPI): The CBAPI object reference. sensor_id (int): The ID of the sensor being used. result_queue (Queue): The queue where results are placed.", "name": "__init__", "signature": "def __init__(self, cb, sensor_id, result_queue)" }, { "docstri...
3
stack_v2_sparse_classes_30k_train_007855
Implement the Python class `JobWorker` described below. Class description: Thread object that executes individual Live Response jobs. Method signatures and docstrings: - def __init__(self, cb, sensor_id, result_queue): Initialize the JobWorker. Args: cb (BaseAPI): The CBAPI object reference. sensor_id (int): The ID o...
Implement the Python class `JobWorker` described below. Class description: Thread object that executes individual Live Response jobs. Method signatures and docstrings: - def __init__(self, cb, sensor_id, result_queue): Initialize the JobWorker. Args: cb (BaseAPI): The CBAPI object reference. sensor_id (int): The ID o...
32dd08d2185f7113f87834002e720db31c8c910e
<|skeleton|> class JobWorker: """Thread object that executes individual Live Response jobs.""" def __init__(self, cb, sensor_id, result_queue): """Initialize the JobWorker. Args: cb (BaseAPI): The CBAPI object reference. sensor_id (int): The ID of the sensor being used. result_queue (Queue): The queue ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JobWorker: """Thread object that executes individual Live Response jobs.""" def __init__(self, cb, sensor_id, result_queue): """Initialize the JobWorker. Args: cb (BaseAPI): The CBAPI object reference. sensor_id (int): The ID of the sensor being used. result_queue (Queue): The queue where results...
the_stack_v2_python_sparse
src/cbapi/live_response_api.py
carbonblack/cbapi-python
train
158
03ffbfa0de3ec63b03a1a7b9f9545ab078637dec
[ "def adjmul(arr, i):\n ret = arr[i]\n if 0 < i:\n ret *= arr[i - 1]\n if i < len(arr) - 1:\n ret *= arr[i + 1]\n return ret\n\n@lru_cache(None)\ndef dp(nums):\n ret = 0\n for i in range(len(nums)):\n cur = adjmul(nums, i)\n sub = dp(tuple(nums[:i] + nums[i + 1:]))\n ...
<|body_start_0|> def adjmul(arr, i): ret = arr[i] if 0 < i: ret *= arr[i - 1] if i < len(arr) - 1: ret *= arr[i + 1] return ret @lru_cache(None) def dp(nums): ret = 0 for i in range(len(nums)...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxCoins(self, nums: List[int]) -> int: """Brute-force TLE""" <|body_0|> def maxCoins(self, nums: List[int]) -> int: """Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)""" <|body_1|> def maxCoins(self, nums: List[int]...
stack_v2_sparse_classes_36k_train_024184
3,846
no_license
[ { "docstring": "Brute-force TLE", "name": "maxCoins", "signature": "def maxCoins(self, nums: List[int]) -> int" }, { "docstring": "Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)", "name": "maxCoins", "signature": "def maxCoins(self, nums: List[int]) -> int" }, ...
4
stack_v2_sparse_classes_30k_train_006113
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxCoins(self, nums: List[int]) -> int: Brute-force TLE - def maxCoins(self, nums: List[int]) -> int: Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2) ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxCoins(self, nums: List[int]) -> int: Brute-force TLE - def maxCoins(self, nums: List[int]) -> int: Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2) ...
1389a009a02e90e8700a7a00e0b7f797c129cdf4
<|skeleton|> class Solution: def maxCoins(self, nums: List[int]) -> int: """Brute-force TLE""" <|body_0|> def maxCoins(self, nums: List[int]) -> int: """Top-down DP, Recursive Time complexity: O(n^3) Space complexity: O(n^2)""" <|body_1|> def maxCoins(self, nums: List[int]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxCoins(self, nums: List[int]) -> int: """Brute-force TLE""" def adjmul(arr, i): ret = arr[i] if 0 < i: ret *= arr[i - 1] if i < len(arr) - 1: ret *= arr[i + 1] return ret @lru_cache(None) ...
the_stack_v2_python_sparse
leetcode/solved/312_Burst_Balloons/solution.py
sungminoh/algorithms
train
0
34c0d5018b622d6ad02c691db28797eca484d3fa
[ "super(TwoLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)", "h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred" ]
<|body_start_0|> super(TwoLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) <|end_body_0|> <|body_start_1|> h_relu = self.linear1(x).clamp(min=0) y_pred = self.linear2(h_relu) return y_pred <|end_body_1|>
TwoLayerNet
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwoLayerNet: def __init__(self, D_in, H, D_out): """在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。""" <|body_0|> def forward(self, x): """在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modules和 其他任意的Tensors上的算子来完成前馈函数的任务逻辑。""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_024185
2,326
permissive
[ { "docstring": "在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。", "name": "__init__", "signature": "def __init__(self, D_in, H, D_out)" }, { "docstring": "在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modules和 其他任意的Tensors上的算子来完成前馈函数的任务逻辑。", "name": "forward", "signature": ...
2
stack_v2_sparse_classes_30k_train_011734
Implement the Python class `TwoLayerNet` described below. Class description: Implement the TwoLayerNet class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): 在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。 - def forward(self, x): 在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modu...
Implement the Python class `TwoLayerNet` described below. Class description: Implement the TwoLayerNet class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): 在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。 - def forward(self, x): 在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modu...
631b817d2e98f351d1173b620d15c4a5efed11da
<|skeleton|> class TwoLayerNet: def __init__(self, D_in, H, D_out): """在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。""" <|body_0|> def forward(self, x): """在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modules和 其他任意的Tensors上的算子来完成前馈函数的任务逻辑。""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TwoLayerNet: def __init__(self, D_in, H, D_out): """在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。""" super(TwoLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) def forward(self, x): """在前馈函数中,我们接受一个输入数据的 Tensor, ...
the_stack_v2_python_sparse
build/_downloads/2e3e83652169c85c0c0972d072ffa8a2/two_layer_net_module.py
ScorpioDoctor/antares02
train
0
2bcdf18d379125b37f40b408c478e927f4fea4e1
[ "if fields is None:\n self._fields = []\nelse:\n self._fields = fields\nself.byte_order = byte_order", "current_offset = offset\nfor field_name, field_size in self._fields:\n value = int.from_bytes(data[current_offset:current_offset + field_size], byteorder=self.byte_order)\n setattr(self, field_name,...
<|body_start_0|> if fields is None: self._fields = [] else: self._fields = fields self.byte_order = byte_order <|end_body_0|> <|body_start_1|> current_offset = offset for field_name, field_size in self._fields: value = int.from_bytes(data[curr...
Base class for ELF headers. Provides methods for populating fields.
ElfEntry
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElfEntry: """Base class for ELF headers. Provides methods for populating fields.""" def __init__(self, byte_order, fields=None): """ElfEntry constructor. Args: byte_order: str. Either 'little' for little endian or 'big' for big endian. fields: List[Tuple[str, int]]. An ordered list o...
stack_v2_sparse_classes_36k_train_024186
14,032
permissive
[ { "docstring": "ElfEntry constructor. Args: byte_order: str. Either 'little' for little endian or 'big' for big endian. fields: List[Tuple[str, int]]. An ordered list of pairs of (attribute name, size in bytes). This list will be used for parsing data and automatically setting up those fields.", "name": "__...
6
stack_v2_sparse_classes_30k_train_020693
Implement the Python class `ElfEntry` described below. Class description: Base class for ELF headers. Provides methods for populating fields. Method signatures and docstrings: - def __init__(self, byte_order, fields=None): ElfEntry constructor. Args: byte_order: str. Either 'little' for little endian or 'big' for big...
Implement the Python class `ElfEntry` described below. Class description: Base class for ELF headers. Provides methods for populating fields. Method signatures and docstrings: - def __init__(self, byte_order, fields=None): ElfEntry constructor. Args: byte_order: str. Either 'little' for little endian or 'big' for big...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class ElfEntry: """Base class for ELF headers. Provides methods for populating fields.""" def __init__(self, byte_order, fields=None): """ElfEntry constructor. Args: byte_order: str. Either 'little' for little endian or 'big' for big endian. fields: List[Tuple[str, int]]. An ordered list o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ElfEntry: """Base class for ELF headers. Provides methods for populating fields.""" def __init__(self, byte_order, fields=None): """ElfEntry constructor. Args: byte_order: str. Either 'little' for little endian or 'big' for big endian. fields: List[Tuple[str, int]]. An ordered list of pairs of (a...
the_stack_v2_python_sparse
tools/android/elf_compression/elf_headers.py
chromium/chromium
train
17,408
ebc21112efdc108a7177ec13cc7119eb8c5e5ebd
[ "super(Mpstat, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.options = options\nself.ret_required = False\nself.current_ret['cpu'] = dict()", "cmd = 'mpstat'\nif self.options:\n cmd = '{} {}'.format(cmd, self.options)\nreturn cmd", "if is_full_line:\n ...
<|body_start_0|> super(Mpstat, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner) self.options = options self.ret_required = False self.current_ret['cpu'] = dict() <|end_body_0|> <|body_start_1|> cmd = 'mpstat' if self.option...
Unix mpstat command
Mpstat
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mpstat: """Unix mpstat command""" def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): """Unix mpstat command. :param connection: moler connection to device, terminal when command is executed. :param options: mpstat command options. :param promp...
stack_v2_sparse_classes_36k_train_024187
5,652
permissive
[ { "docstring": "Unix mpstat command. :param connection: moler connection to device, terminal when command is executed. :param options: mpstat command options. :param prompt: prompt on system where command is executed. :param newline_chars: characters to split lines. :param runner: Runner to run command.", "...
4
null
Implement the Python class `Mpstat` described below. Class description: Unix mpstat command Method signatures and docstrings: - def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): Unix mpstat command. :param connection: moler connection to device, terminal when command is execu...
Implement the Python class `Mpstat` described below. Class description: Unix mpstat command Method signatures and docstrings: - def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): Unix mpstat command. :param connection: moler connection to device, terminal when command is execu...
5a7bb06807b6e0124c77040367d0c20f42849a4c
<|skeleton|> class Mpstat: """Unix mpstat command""" def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): """Unix mpstat command. :param connection: moler connection to device, terminal when command is executed. :param options: mpstat command options. :param promp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mpstat: """Unix mpstat command""" def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): """Unix mpstat command. :param connection: moler connection to device, terminal when command is executed. :param options: mpstat command options. :param prompt: prompt on ...
the_stack_v2_python_sparse
moler/cmd/unix/mpstat.py
nokia/moler
train
60
8243dc62af7c2886b31ace2716aedf2f78dec7e2
[ "self.Wh = np.random.normal(size=(i + h, h))\nself.bh = np.zeros((1, h))\nself.Wy = np.random.normal(size=(h, o))\nself.by = np.zeros((1, o))", "X = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.matmul(X, self.Wh) + self.bh)\nz = np.matmul(h_next, self.Wy) + self.by\ny = np.exp(z) / np.sum(np.exp(z),...
<|body_start_0|> self.Wh = np.random.normal(size=(i + h, h)) self.bh = np.zeros((1, h)) self.Wy = np.random.normal(size=(h, o)) self.by = np.zeros((1, o)) <|end_body_0|> <|body_start_1|> X = np.concatenate((h_prev, x_t), axis=1) h_next = np.tanh(np.matmul(X, self.Wh) + s...
RNNCell class
RNNCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNCell: """RNNCell class""" def __init__(self, i, h, o): """Initializer.""" <|body_0|> def forward(self, h_prev, x_t): """performs forward propagation for one time step. Args: h_prev: (numpy.ndarray) contains the data input for the cell. x_t: (numpy.ndarray) con...
stack_v2_sparse_classes_36k_train_024188
986
no_license
[ { "docstring": "Initializer.", "name": "__init__", "signature": "def __init__(self, i, h, o)" }, { "docstring": "performs forward propagation for one time step. Args: h_prev: (numpy.ndarray) contains the data input for the cell. x_t: (numpy.ndarray) containing the previous hidden state. Returns:...
2
null
Implement the Python class `RNNCell` described below. Class description: RNNCell class Method signatures and docstrings: - def __init__(self, i, h, o): Initializer. - def forward(self, h_prev, x_t): performs forward propagation for one time step. Args: h_prev: (numpy.ndarray) contains the data input for the cell. x_t...
Implement the Python class `RNNCell` described below. Class description: RNNCell class Method signatures and docstrings: - def __init__(self, i, h, o): Initializer. - def forward(self, h_prev, x_t): performs forward propagation for one time step. Args: h_prev: (numpy.ndarray) contains the data input for the cell. x_t...
75274394adb52d740f6cd4000cc00bbde44b9b72
<|skeleton|> class RNNCell: """RNNCell class""" def __init__(self, i, h, o): """Initializer.""" <|body_0|> def forward(self, h_prev, x_t): """performs forward propagation for one time step. Args: h_prev: (numpy.ndarray) contains the data input for the cell. x_t: (numpy.ndarray) con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNNCell: """RNNCell class""" def __init__(self, i, h, o): """Initializer.""" self.Wh = np.random.normal(size=(i + h, h)) self.bh = np.zeros((1, h)) self.Wy = np.random.normal(size=(h, o)) self.by = np.zeros((1, o)) def forward(self, h_prev, x_t): """pe...
the_stack_v2_python_sparse
supervised_learning/0x0D-RNNs/0-rnn_cell.py
jdarangop/holbertonschool-machine_learning
train
2
ff2131a0364047d8bb38793ebf1ef585e4d6afc8
[ "self.pipeline_type = pipeline_type\nself.project = project\nself.location = location\nself.gcp_resources = gcp_resources\nself.client_options = client_options.ClientOptions(api_endpoint=location + '-aiplatform.googleapis.com')\nself.client_info = gapic_v1.client_info.ClientInfo(user_agent='google-cloud-pipeline-co...
<|body_start_0|> self.pipeline_type = pipeline_type self.project = project self.location = location self.gcp_resources = gcp_resources self.client_options = client_options.ClientOptions(api_endpoint=location + '-aiplatform.googleapis.com') self.client_info = gapic_v1.clie...
Common module for creating and polling pipelines on the Vertex Platform.
PipelineRemoteRunner
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PipelineRemoteRunner: """Common module for creating and polling pipelines on the Vertex Platform.""" def __init__(self, pipeline_type: str, project: str, location: str, gcp_resources: str): """Initializes a pipeline client and other common attributes.""" <|body_0|> def c...
stack_v2_sparse_classes_36k_train_024189
10,315
permissive
[ { "docstring": "Initializes a pipeline client and other common attributes.", "name": "__init__", "signature": "def __init__(self, pipeline_type: str, project: str, location: str, gcp_resources: str)" }, { "docstring": "Checks if the pipeline already exists. Returns: The pipeline name if the pipe...
5
null
Implement the Python class `PipelineRemoteRunner` described below. Class description: Common module for creating and polling pipelines on the Vertex Platform. Method signatures and docstrings: - def __init__(self, pipeline_type: str, project: str, location: str, gcp_resources: str): Initializes a pipeline client and ...
Implement the Python class `PipelineRemoteRunner` described below. Class description: Common module for creating and polling pipelines on the Vertex Platform. Method signatures and docstrings: - def __init__(self, pipeline_type: str, project: str, location: str, gcp_resources: str): Initializes a pipeline client and ...
3fb199658f68e7debf4906d9ce32a9a307e39243
<|skeleton|> class PipelineRemoteRunner: """Common module for creating and polling pipelines on the Vertex Platform.""" def __init__(self, pipeline_type: str, project: str, location: str, gcp_resources: str): """Initializes a pipeline client and other common attributes.""" <|body_0|> def c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PipelineRemoteRunner: """Common module for creating and polling pipelines on the Vertex Platform.""" def __init__(self, pipeline_type: str, project: str, location: str, gcp_resources: str): """Initializes a pipeline client and other common attributes.""" self.pipeline_type = pipeline_type...
the_stack_v2_python_sparse
components/google-cloud/google_cloud_pipeline_components/container/v1/gcp_launcher/pipeline_remote_runner.py
kubeflow/pipelines
train
3,434
4938dcbf091290061db6406f50ab802edf3959a6
[ "def search(node, total, current, output):\n if node and (not node.left) and (not node.right) and (total == node.val):\n output.append(current + [node.val])\n elif node:\n current.append(node.val)\n search(node.left, total - node.val, current, output)\n search(node.right, total - n...
<|body_start_0|> def search(node, total, current, output): if node and (not node.left) and (not node.right) and (total == node.val): output.append(current + [node.val]) elif node: current.append(node.val) search(node.left, total - node.val,...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def pathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: List[List[int]]""" <|body_0|> def pathSum_verbose(self, root, sum): """:type root: TreeNode :type sum: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_024190
2,451
no_license
[ { "docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]", "name": "pathSum", "signature": "def pathSum(self, root, sum)" }, { "docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]", "name": "pathSum_verbose", "signature": "def pathSum_verbose(self,...
2
stack_v2_sparse_classes_30k_test_001163
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]] - def pathSum_verbose(self, root, sum): :type root: TreeNode :type sum: int :rtype: List...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]] - def pathSum_verbose(self, root, sum): :type root: TreeNode :type sum: int :rtype: List...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def pathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: List[List[int]]""" <|body_0|> def pathSum_verbose(self, root, sum): """:type root: TreeNode :type sum: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def pathSum(self, root, sum): """:type root: TreeNode :type sum: int :rtype: List[List[int]]""" def search(node, total, current, output): if node and (not node.left) and (not node.right) and (total == node.val): output.append(current + [node.val]) ...
the_stack_v2_python_sparse
src/lt_113.py
oxhead/CodingYourWay
train
0
da84de39b7319616398549d32867c631cda8aa37
[ "verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')\nif verify_records:\n if now() - verify_records[0].add_time > timedelta(hours=0, minutes=1, seconds=0):\n raise serializers.ValidationError('验证码过期')\n if verify_records[0].code != code:\n rais...
<|body_start_0|> verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time') if verify_records: if now() - verify_records[0].add_time > timedelta(hours=0, minutes=1, seconds=0): raise serializers.ValidationError('验证码过期') ...
这个例子比较特殊应为使用了ModelSerializer,用户提交了多余code的字段,也就是该字段没有出现在Model中
UserRegSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRegSerializer: """这个例子比较特殊应为使用了ModelSerializer,用户提交了多余code的字段,也就是该字段没有出现在Model中""" def validate_code(self, code): """验证单个字段, 可以选择是否返回该字段,此处不需要返回,应为user数据表中没有这个字段""" <|body_0|> def validate(self, attrs): """1. 可以取到所有字段,验证所有字段, 并返回字段 2. 可以按需添加和减少保存到model的字段 3. ...
stack_v2_sparse_classes_36k_train_024191
5,055
no_license
[ { "docstring": "验证单个字段, 可以选择是否返回该字段,此处不需要返回,应为user数据表中没有这个字段", "name": "validate_code", "signature": "def validate_code(self, code)" }, { "docstring": "1. 可以取到所有字段,验证所有字段, 并返回字段 2. 可以按需添加和减少保存到model的字段 3. 可以进行字段间的联合验证 4. 验证顺序,先验证单独的后验证联合的", "name": "validate", "signature": "def validate(...
2
stack_v2_sparse_classes_30k_train_000828
Implement the Python class `UserRegSerializer` described below. Class description: 这个例子比较特殊应为使用了ModelSerializer,用户提交了多余code的字段,也就是该字段没有出现在Model中 Method signatures and docstrings: - def validate_code(self, code): 验证单个字段, 可以选择是否返回该字段,此处不需要返回,应为user数据表中没有这个字段 - def validate(self, attrs): 1. 可以取到所有字段,验证所有字段, 并返回字段 2. 可以按...
Implement the Python class `UserRegSerializer` described below. Class description: 这个例子比较特殊应为使用了ModelSerializer,用户提交了多余code的字段,也就是该字段没有出现在Model中 Method signatures and docstrings: - def validate_code(self, code): 验证单个字段, 可以选择是否返回该字段,此处不需要返回,应为user数据表中没有这个字段 - def validate(self, attrs): 1. 可以取到所有字段,验证所有字段, 并返回字段 2. 可以按...
837fcae8fbbe4d0b8a665666eb6d81d85a1b205f
<|skeleton|> class UserRegSerializer: """这个例子比较特殊应为使用了ModelSerializer,用户提交了多余code的字段,也就是该字段没有出现在Model中""" def validate_code(self, code): """验证单个字段, 可以选择是否返回该字段,此处不需要返回,应为user数据表中没有这个字段""" <|body_0|> def validate(self, attrs): """1. 可以取到所有字段,验证所有字段, 并返回字段 2. 可以按需添加和减少保存到model的字段 3. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserRegSerializer: """这个例子比较特殊应为使用了ModelSerializer,用户提交了多余code的字段,也就是该字段没有出现在Model中""" def validate_code(self, code): """验证单个字段, 可以选择是否返回该字段,此处不需要返回,应为user数据表中没有这个字段""" verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time') if verify...
the_stack_v2_python_sparse
apps/users/serializers.py
15051882416/MxShop
train
0
82eae91903eae504f1c4ddfaa51d327d32a920a7
[ "if s.count('A') > 1 or s.count('LLL') > 0:\n return False\nreturn True", "count_absent = 0\nfor chr in s:\n if chr == 'A':\n count_absent += 1\n if count_absent > 1:\n return False\nfor i in range(0, len(s) - 2):\n if s[i] == 'L' and s[i + 1] == 'L' and (s[i + 2] == 'L'):\n ...
<|body_start_0|> if s.count('A') > 1 or s.count('LLL') > 0: return False return True <|end_body_0|> <|body_start_1|> count_absent = 0 for chr in s: if chr == 'A': count_absent += 1 if count_absent > 1: return Fa...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def checkRecord(self, s): """:type s: str :rtype: bool Time Complexity: O(N)""" <|body_0|> def checkRecord1(self, s): """:type s: str :rtype: bool Time Complexity: O(N)""" <|body_1|> <|end_skeleton|> <|body_start_0|> if s.count('A') > 1 or...
stack_v2_sparse_classes_36k_train_024192
1,263
no_license
[ { "docstring": ":type s: str :rtype: bool Time Complexity: O(N)", "name": "checkRecord", "signature": "def checkRecord(self, s)" }, { "docstring": ":type s: str :rtype: bool Time Complexity: O(N)", "name": "checkRecord1", "signature": "def checkRecord1(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_012530
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkRecord(self, s): :type s: str :rtype: bool Time Complexity: O(N) - def checkRecord1(self, s): :type s: str :rtype: bool Time Complexity: O(N)
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def checkRecord(self, s): :type s: str :rtype: bool Time Complexity: O(N) - def checkRecord1(self, s): :type s: str :rtype: bool Time Complexity: O(N) <|skeleton|> class Solutio...
96dd15210bcf9efe1f8cf31ce0566a7eabb3e221
<|skeleton|> class Solution: def checkRecord(self, s): """:type s: str :rtype: bool Time Complexity: O(N)""" <|body_0|> def checkRecord1(self, s): """:type s: str :rtype: bool Time Complexity: O(N)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def checkRecord(self, s): """:type s: str :rtype: bool Time Complexity: O(N)""" if s.count('A') > 1 or s.count('LLL') > 0: return False return True def checkRecord1(self, s): """:type s: str :rtype: bool Time Complexity: O(N)""" count_absent =...
the_stack_v2_python_sparse
Python/Student_Attendance_Record_I.py
abhi-verma/LeetCode-Algo
train
0
2e77eb4d29fe1c87b52b1f9a05decb4429463b58
[ "assert not np.isinf(domain[1])\nx_pts, self.dx = get_asymmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=True, **kwargs)\nself.mid = (x_pts[:-1] + x_pts[1:]) / 2\nself.J = J\ntry:\n self.ignore_zeros = kwargs['ignore_zeros']\nexcept KeyError:\n self.ignore_zeros ...
<|body_start_0|> assert not np.isinf(domain[1]) x_pts, self.dx = get_asymmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=True, **kwargs) self.mid = (x_pts[:-1] + x_pts[1:]) / 2 self.J = J try: self.ignore_zeros = kwargs['i...
GKQuadDiscretizedAsymmetricBath
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GKQuadDiscretizedAsymmetricBath: def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): """Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ ...
stack_v2_sparse_classes_36k_train_024193
3,938
permissive
[ { "docstring": "Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density. A function defined on 'domain', must be >0 in the inner part of domain :param domain: List/tup...
2
stack_v2_sparse_classes_30k_train_018736
Implement the Python class `GKQuadDiscretizedAsymmetricBath` described below. Class description: Implement the GKQuadDiscretizedAsymmetricBath class. Method signatures and docstrings: - def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): Generates direct discretization coefficients...
Implement the Python class `GKQuadDiscretizedAsymmetricBath` described below. Class description: Implement the GKQuadDiscretizedAsymmetricBath class. Method signatures and docstrings: - def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): Generates direct discretization coefficients...
daf37f522f8acb6af2285d44f39cab31f34b01a4
<|skeleton|> class GKQuadDiscretizedAsymmetricBath: def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): """Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GKQuadDiscretizedAsymmetricBath: def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): """Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :par...
the_stack_v2_python_sparse
mapping/star/discretized_bath/asymmetric_gk_quad.py
fhoeb/py-mapping
train
2
f24d9e1202ce469f85a88fb6c7406b3303f43d27
[ "if len(name) == 7 and name[0] == '#':\n self.set_hex(name)\nelse:\n value = Color.colors.get(name, None)\n if value is None:\n raise ValueError(\"Unknown color name '{}'.\".format(name))\n if len(value) == 7:\n self.set_hex(value)\n else:\n self.red, self.green, self.blue = valu...
<|body_start_0|> if len(name) == 7 and name[0] == '#': self.set_hex(name) else: value = Color.colors.get(name, None) if value is None: raise ValueError("Unknown color name '{}'.".format(name)) if len(value) == 7: self.set_he...
Lists of known colors.
Color
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Color: """Lists of known colors.""" def __init__(self, name): """@param name hexadecimal or name""" <|body_0|> def set_hex(self, name): """Converts a string like ``#AABBCC`` into `(red, green, blue)`.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_024194
6,106
permissive
[ { "docstring": "@param name hexadecimal or name", "name": "__init__", "signature": "def __init__(self, name)" }, { "docstring": "Converts a string like ``#AABBCC`` into `(red, green, blue)`.", "name": "set_hex", "signature": "def set_hex(self, name)" } ]
2
stack_v2_sparse_classes_30k_train_002581
Implement the Python class `Color` described below. Class description: Lists of known colors. Method signatures and docstrings: - def __init__(self, name): @param name hexadecimal or name - def set_hex(self, name): Converts a string like ``#AABBCC`` into `(red, green, blue)`.
Implement the Python class `Color` described below. Class description: Lists of known colors. Method signatures and docstrings: - def __init__(self, name): @param name hexadecimal or name - def set_hex(self, name): Converts a string like ``#AABBCC`` into `(red, green, blue)`. <|skeleton|> class Color: """Lists o...
33af98adb093f525df7fac7c86613fa7cd181b44
<|skeleton|> class Color: """Lists of known colors.""" def __init__(self, name): """@param name hexadecimal or name""" <|body_0|> def set_hex(self, name): """Converts a string like ``#AABBCC`` into `(red, green, blue)`.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Color: """Lists of known colors.""" def __init__(self, name): """@param name hexadecimal or name""" if len(name) == 7 and name[0] == '#': self.set_hex(name) else: value = Color.colors.get(name, None) if value is None: raise Value...
the_stack_v2_python_sparse
src/pyensae/graphhelper/_colormap.py
sdpython/pyensae
train
33
c2c9ce14160360a314affb15f2cb2182929fdbc9
[ "form = EngineerAddForm(request.POST or None)\nif form.is_valid():\n instance = form.save(commit=False)\n instance.added_by = self.request.user\n instance.save()\n messages.add_message(request, messages.INFO, 'Success - Engineer added successfully')\n return redirect('engineers:engineer_view')\nmessa...
<|body_start_0|> form = EngineerAddForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.added_by = self.request.user instance.save() messages.add_message(request, messages.INFO, 'Success - Engineer added successfully')...
EngineerView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EngineerView: def post(self, request): """Adds new engineer from engineer_list_view page modal""" <|body_0|> def get(self, request): """Returns list of all engineers""" <|body_1|> <|end_skeleton|> <|body_start_0|> form = EngineerAddForm(request.POST...
stack_v2_sparse_classes_36k_train_024195
3,806
no_license
[ { "docstring": "Adds new engineer from engineer_list_view page modal", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Returns list of all engineers", "name": "get", "signature": "def get(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_017815
Implement the Python class `EngineerView` described below. Class description: Implement the EngineerView class. Method signatures and docstrings: - def post(self, request): Adds new engineer from engineer_list_view page modal - def get(self, request): Returns list of all engineers
Implement the Python class `EngineerView` described below. Class description: Implement the EngineerView class. Method signatures and docstrings: - def post(self, request): Adds new engineer from engineer_list_view page modal - def get(self, request): Returns list of all engineers <|skeleton|> class EngineerView: ...
bdd7c5ca9f00ce33be31609e5be9c2ccfcd8743a
<|skeleton|> class EngineerView: def post(self, request): """Adds new engineer from engineer_list_view page modal""" <|body_0|> def get(self, request): """Returns list of all engineers""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EngineerView: def post(self, request): """Adds new engineer from engineer_list_view page modal""" form = EngineerAddForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.added_by = self.request.user instance.save(...
the_stack_v2_python_sparse
engineers/views.py
mrmaheshrajput/htscrm
train
0
90a9ed3c1e74272b231c151469c24e9cad6dbc83
[ "if quadrant_letter == 'B' or quadrant_letter == 'C':\n return cls.left(parallel_size=parallel_size, serial_size=serial_size, serial_prescan_size=serial_prescan_size, parallel_overscan_size=parallel_overscan_size)\nelif quadrant_letter == 'A' or quadrant_letter == 'D':\n return cls.right(parallel_size=paralle...
<|body_start_0|> if quadrant_letter == 'B' or quadrant_letter == 'C': return cls.left(parallel_size=parallel_size, serial_size=serial_size, serial_prescan_size=serial_prescan_size, parallel_overscan_size=parallel_overscan_size) elif quadrant_letter == 'A' or quadrant_letter == 'D': ...
Layout2DACS
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Layout2DACS: def from_ccd(cls, quadrant_letter, parallel_size=2068, serial_size=2072, serial_prescan_size=24, parallel_overscan_size=20): """Using an input array of both quadrants in electrons, use the quadrant letter to extract the quadrant from the full CCD and perform the rotations re...
stack_v2_sparse_classes_36k_train_024196
13,170
permissive
[ { "docstring": "Using an input array of both quadrants in electrons, use the quadrant letter to extract the quadrant from the full CCD and perform the rotations required to give correct arctic. See the docstring of the `FrameACS` class for a complete description of the Euclid FPA, quadrants and rotations.", ...
3
stack_v2_sparse_classes_30k_test_000291
Implement the Python class `Layout2DACS` described below. Class description: Implement the Layout2DACS class. Method signatures and docstrings: - def from_ccd(cls, quadrant_letter, parallel_size=2068, serial_size=2072, serial_prescan_size=24, parallel_overscan_size=20): Using an input array of both quadrants in elect...
Implement the Python class `Layout2DACS` described below. Class description: Implement the Layout2DACS class. Method signatures and docstrings: - def from_ccd(cls, quadrant_letter, parallel_size=2068, serial_size=2072, serial_prescan_size=24, parallel_overscan_size=20): Using an input array of both quadrants in elect...
c21e8859bdb20737352147b9904797ac99985b73
<|skeleton|> class Layout2DACS: def from_ccd(cls, quadrant_letter, parallel_size=2068, serial_size=2072, serial_prescan_size=24, parallel_overscan_size=20): """Using an input array of both quadrants in electrons, use the quadrant letter to extract the quadrant from the full CCD and perform the rotations re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Layout2DACS: def from_ccd(cls, quadrant_letter, parallel_size=2068, serial_size=2072, serial_prescan_size=24, parallel_overscan_size=20): """Using an input array of both quadrants in electrons, use the quadrant letter to extract the quadrant from the full CCD and perform the rotations required to give...
the_stack_v2_python_sparse
autoarray/instruments/acs.py
jonathanfrawley/PyAutoArray_copy
train
0
2c94347df29165ac2a5109083de89f3ed8cec80b
[ "try:\n customer, _created = Customer.get_or_create(subscriber=subscriber_request_callback(self.request))\n serializer = SubscriptionSerializer(customer.subscription)\n return Response(serializer.data)\nexcept:\n return Response(status=status.HTTP_204_NO_CONTENT)", "serializer = CreateSubscriptionSeri...
<|body_start_0|> try: customer, _created = Customer.get_or_create(subscriber=subscriber_request_callback(self.request)) serializer = SubscriptionSerializer(customer.subscription) return Response(serializer.data) except: return Response(status=status.HTTP_2...
API Endpoints for the Subscription object.
SubscriptionRestView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubscriptionRestView: """API Endpoints for the Subscription object.""" def get(self, request, **kwargs): """Return the customer's valid subscriptions. Returns with status code 200.""" <|body_0|> def post(self, request, **kwargs): """Create a new current subscript...
stack_v2_sparse_classes_36k_train_024197
4,950
permissive
[ { "docstring": "Return the customer's valid subscriptions. Returns with status code 200.", "name": "get", "signature": "def get(self, request, **kwargs)" }, { "docstring": "Create a new current subscription for the user. Returns with status code 201.", "name": "post", "signature": "def p...
3
stack_v2_sparse_classes_30k_train_020253
Implement the Python class `SubscriptionRestView` described below. Class description: API Endpoints for the Subscription object. Method signatures and docstrings: - def get(self, request, **kwargs): Return the customer's valid subscriptions. Returns with status code 200. - def post(self, request, **kwargs): Create a ...
Implement the Python class `SubscriptionRestView` described below. Class description: API Endpoints for the Subscription object. Method signatures and docstrings: - def get(self, request, **kwargs): Return the customer's valid subscriptions. Returns with status code 200. - def post(self, request, **kwargs): Create a ...
325cc11fbc28eee7507778e387714e9465880d68
<|skeleton|> class SubscriptionRestView: """API Endpoints for the Subscription object.""" def get(self, request, **kwargs): """Return the customer's valid subscriptions. Returns with status code 200.""" <|body_0|> def post(self, request, **kwargs): """Create a new current subscript...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubscriptionRestView: """API Endpoints for the Subscription object.""" def get(self, request, **kwargs): """Return the customer's valid subscriptions. Returns with status code 200.""" try: customer, _created = Customer.get_or_create(subscriber=subscriber_request_callback(self....
the_stack_v2_python_sparse
djstripe/contrib/rest_framework/views.py
talpor/dj-stripe
train
1
cdd77d970a7410d0e667f5f9de62b8c45688df49
[ "super().__init__(env, name, agent_seed)\nself.mpc_policy = StationaryActionMPCPolicy(env.physical_constituency_matrix, mpc_seed)\nself.method = method\nself.binary_action = binary_action", "_, num_activities = self.constituency_matrix.shape\nz = cvx.Variable((num_activities, 1), boolean=self.binary_action)\ndiag...
<|body_start_0|> super().__init__(env, name, agent_seed) self.mpc_policy = StationaryActionMPCPolicy(env.physical_constituency_matrix, mpc_seed) self.method = method self.binary_action = binary_action <|end_body_0|> <|body_start_1|> _, num_activities = self.constituency_matrix.s...
MaxWeightLpAgent
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaxWeightLpAgent: def __init__(self, env: crw.ControlledRandomWalk, method: str='cvx.ECOS', name: str='MaxWeightLpAgent', binary_action: Optional[bool]=False, agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None: """MaxWeight policy for general push models. :param env: C...
stack_v2_sparse_classes_36k_train_024198
5,659
permissive
[ { "docstring": "MaxWeight policy for general push models. :param env: CRW environment. :param method: Optimisation method/solver that CVXPY should use to solve the LP. :param name: Agent identifier. :param binary_action: where the problem is an MIP with binary variables or not. :param agent_seed: Agent random s...
3
stack_v2_sparse_classes_30k_train_000911
Implement the Python class `MaxWeightLpAgent` described below. Class description: Implement the MaxWeightLpAgent class. Method signatures and docstrings: - def __init__(self, env: crw.ControlledRandomWalk, method: str='cvx.ECOS', name: str='MaxWeightLpAgent', binary_action: Optional[bool]=False, agent_seed: Optional[...
Implement the Python class `MaxWeightLpAgent` described below. Class description: Implement the MaxWeightLpAgent class. Method signatures and docstrings: - def __init__(self, env: crw.ControlledRandomWalk, method: str='cvx.ECOS', name: str='MaxWeightLpAgent', binary_action: Optional[bool]=False, agent_seed: Optional[...
b067eebaa5b57a96efdaed5796aca9f157d32214
<|skeleton|> class MaxWeightLpAgent: def __init__(self, env: crw.ControlledRandomWalk, method: str='cvx.ECOS', name: str='MaxWeightLpAgent', binary_action: Optional[bool]=False, agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None: """MaxWeight policy for general push models. :param env: C...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaxWeightLpAgent: def __init__(self, env: crw.ControlledRandomWalk, method: str='cvx.ECOS', name: str='MaxWeightLpAgent', binary_action: Optional[bool]=False, agent_seed: Optional[int]=None, mpc_seed: Optional[int]=None) -> None: """MaxWeight policy for general push models. :param env: CRW environment...
the_stack_v2_python_sparse
src/snc/agents/maxweight_variants/maxweight_lp.py
stochasticnetworkcontrol/snc
train
9
daa097f3dc119982264276f6744749f005b9cb91
[ "msg = await self._state.fetch_user_csgo_profile(self.id)\nif not msg.account_profiles:\n raise ValueError\nreturn ProfileInfo(self, msg.account_profiles[0])", "future = self._state.ws.gc_wait_for(cstrike.MatchList, check=lambda msg: msg.msgrequestid == cstrike.MatchListRequestRecentUserGames.MSG and msg.accou...
<|body_start_0|> msg = await self._state.fetch_user_csgo_profile(self.id) if not msg.account_profiles: raise ValueError return ProfileInfo(self, msg.account_profiles[0]) <|end_body_0|> <|body_start_1|> future = self._state.ws.gc_wait_for(cstrike.MatchList, check=lambda msg: ...
PartialUser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PartialUser: async def csgo_profile(self) -> ProfileInfo[Self]: """Fetches this users CSGO profile info.""" <|body_0|> async def recent_matches(self) -> Matches: """Fetches this user's recent games.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ms...
stack_v2_sparse_classes_36k_train_024199
7,623
permissive
[ { "docstring": "Fetches this users CSGO profile info.", "name": "csgo_profile", "signature": "async def csgo_profile(self) -> ProfileInfo[Self]" }, { "docstring": "Fetches this user's recent games.", "name": "recent_matches", "signature": "async def recent_matches(self) -> Matches" } ]
2
stack_v2_sparse_classes_30k_train_005015
Implement the Python class `PartialUser` described below. Class description: Implement the PartialUser class. Method signatures and docstrings: - async def csgo_profile(self) -> ProfileInfo[Self]: Fetches this users CSGO profile info. - async def recent_matches(self) -> Matches: Fetches this user's recent games.
Implement the Python class `PartialUser` described below. Class description: Implement the PartialUser class. Method signatures and docstrings: - async def csgo_profile(self) -> ProfileInfo[Self]: Fetches this users CSGO profile info. - async def recent_matches(self) -> Matches: Fetches this user's recent games. <|s...
3075c6065babcd8a67052593d4b31d10c20edabe
<|skeleton|> class PartialUser: async def csgo_profile(self) -> ProfileInfo[Self]: """Fetches this users CSGO profile info.""" <|body_0|> async def recent_matches(self) -> Matches: """Fetches this user's recent games.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PartialUser: async def csgo_profile(self) -> ProfileInfo[Self]: """Fetches this users CSGO profile info.""" msg = await self._state.fetch_user_csgo_profile(self.id) if not msg.account_profiles: raise ValueError return ProfileInfo(self, msg.account_profiles[0]) ...
the_stack_v2_python_sparse
steam/ext/csgo/models.py
Gobot1234/steam.py
train
144