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
f2c34ef40d68eb2743ca10f1918f274a84252625
[ "output = self.git('show-branch', '--no-color')\ntry:\n prelude, body = re.split('^-+$', output, flags=re.M)\nexcept ValueError:\n lines = filter_(output.splitlines())\nelse:\n match = re.search('^(\\\\s+)\\\\*', prelude, re.M)\n if not match:\n print('branch {} not found in header information'.f...
<|body_start_0|> output = self.git('show-branch', '--no-color') try: prelude, body = re.split('^-+$', output, flags=re.M) except ValueError: lines = filter_(output.splitlines()) else: match = re.search('^(\\s+)\\*', prelude, re.M) if not ma...
Provide reusable methods for detecting the nearest of a branch relatives
NearestBranchMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NearestBranchMixin: """Provide reusable methods for detecting the nearest of a branch relatives""" def branch_relatives(self, branch): """Get list of all relatives from ``git show-branch`` results""" <|body_0|> def nearest_branch(self, branch, default='master'): ...
stack_v2_sparse_classes_36k_train_022600
2,113
permissive
[ { "docstring": "Get list of all relatives from ``git show-branch`` results", "name": "branch_relatives", "signature": "def branch_relatives(self, branch)" }, { "docstring": "Find the nearest commit in current branch history that exists on a different branch and return that branch name. If no suc...
2
null
Implement the Python class `NearestBranchMixin` described below. Class description: Provide reusable methods for detecting the nearest of a branch relatives Method signatures and docstrings: - def branch_relatives(self, branch): Get list of all relatives from ``git show-branch`` results - def nearest_branch(self, bra...
Implement the Python class `NearestBranchMixin` described below. Class description: Provide reusable methods for detecting the nearest of a branch relatives Method signatures and docstrings: - def branch_relatives(self, branch): Get list of all relatives from ``git show-branch`` results - def nearest_branch(self, bra...
7f6eae583ba4a38749b14a6e348c6d4fcf6811e8
<|skeleton|> class NearestBranchMixin: """Provide reusable methods for detecting the nearest of a branch relatives""" def branch_relatives(self, branch): """Get list of all relatives from ``git show-branch`` results""" <|body_0|> def nearest_branch(self, branch, default='master'): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NearestBranchMixin: """Provide reusable methods for detecting the nearest of a branch relatives""" def branch_relatives(self, branch): """Get list of all relatives from ``git show-branch`` results""" output = self.git('show-branch', '--no-color') try: prelude, body = r...
the_stack_v2_python_sparse
core/git_mixins/rebase.py
timbrel/GitSavvy
train
174
187028f13021e96f2fb9973a4c1e2a86b9b7bc96
[ "res, index, stack = (0, 0, [])\nfor i, char in enumerate(s):\n if char == '(':\n stack.append(i)\n elif not stack:\n index = i + 1\n else:\n stack.pop()\n if stack:\n res = max(res, i - stack[-1])\n else:\n res = max(res, i - index + 1)\nreturn res"...
<|body_start_0|> res, index, stack = (0, 0, []) for i, char in enumerate(s): if char == '(': stack.append(i) elif not stack: index = i + 1 else: stack.pop() if stack: res = max(res, i ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestValidParentheses(self, s): """:type s: str :rtype: int""" <|body_0|> def longestValidParentheses1(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> res, index, stack = (0, 0, []) for i...
stack_v2_sparse_classes_36k_train_022601
1,446
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "longestValidParentheses", "signature": "def longestValidParentheses(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "longestValidParentheses1", "signature": "def longestValidParentheses1(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_000844
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s): :type s: str :rtype: int - def longestValidParentheses1(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestValidParentheses(self, s): :type s: str :rtype: int - def longestValidParentheses1(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def longestVal...
b8ec1350e904665f1375c29a53f443ecf262d723
<|skeleton|> class Solution: def longestValidParentheses(self, s): """:type s: str :rtype: int""" <|body_0|> def longestValidParentheses1(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestValidParentheses(self, s): """:type s: str :rtype: int""" res, index, stack = (0, 0, []) for i, char in enumerate(s): if char == '(': stack.append(i) elif not stack: index = i + 1 else: ...
the_stack_v2_python_sparse
leetcode/032最长有效括号.py
ShawDa/Coding
train
0
aa97e708f93a203c217bc197d0966c901ac51757
[ "super().__init__(contamination=contamination, **kwargs)\nself.contamination = contamination\nself.iforest_obj = None", "if self.iforest_obj is not None:\n f = open(path.join(self.output_dir, 'iforest_object.pickle'), 'wb')\n pickle.dump(self.iforest_obj, f)", "iforest = IsolationForest(contamination=self...
<|body_start_0|> super().__init__(contamination=contamination, **kwargs) self.contamination = contamination self.iforest_obj = None <|end_body_0|> <|body_start_1|> if self.iforest_obj is not None: f = open(path.join(self.output_dir, 'iforest_object.pickle'), 'wb') ...
IforestAlgorithm
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IforestAlgorithm: def __init__(self, contamination='auto', **kwargs): """Runs sklearn's isolation forest anomaly detection algorithm and returns the anomaly score for each instance. Parameters ---------- contamination : string or float, optional Hyperparameter to pass to IsolationForest....
stack_v2_sparse_classes_36k_train_022602
1,932
permissive
[ { "docstring": "Runs sklearn's isolation forest anomaly detection algorithm and returns the anomaly score for each instance. Parameters ---------- contamination : string or float, optional Hyperparameter to pass to IsolationForest. 'auto' is recommended", "name": "__init__", "signature": "def __init__(s...
3
stack_v2_sparse_classes_30k_test_000670
Implement the Python class `IforestAlgorithm` described below. Class description: Implement the IforestAlgorithm class. Method signatures and docstrings: - def __init__(self, contamination='auto', **kwargs): Runs sklearn's isolation forest anomaly detection algorithm and returns the anomaly score for each instance. P...
Implement the Python class `IforestAlgorithm` described below. Class description: Implement the IforestAlgorithm class. Method signatures and docstrings: - def __init__(self, contamination='auto', **kwargs): Runs sklearn's isolation forest anomaly detection algorithm and returns the anomaly score for each instance. P...
041391f4ef0667e555046fc66f5beb67b4975dda
<|skeleton|> class IforestAlgorithm: def __init__(self, contamination='auto', **kwargs): """Runs sklearn's isolation forest anomaly detection algorithm and returns the anomaly score for each instance. Parameters ---------- contamination : string or float, optional Hyperparameter to pass to IsolationForest....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IforestAlgorithm: def __init__(self, contamination='auto', **kwargs): """Runs sklearn's isolation forest anomaly detection algorithm and returns the anomaly score for each instance. Parameters ---------- contamination : string or float, optional Hyperparameter to pass to IsolationForest. 'auto' is rec...
the_stack_v2_python_sparse
astronomaly/anomaly_detection/isolation_forest.py
MichelleLochner/astronomaly
train
69
f685a91633999969774e35a9327691c4d348c50d
[ "if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=APUserManager.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email, password=password)\nuser.is_admin = True\nuser.is_staff = True\nuser.is_sup...
<|body_start_0|> if not email: raise ValueError('Users must have an email address') user = self.model(email=APUserManager.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user = self.cre...
APUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APUserManager: def create_user(self, email, password=None): """Creates a user, given an email and a password (optional)""" <|body_0|> def create_superuser(self, email, password): """Creates a super user, given an email and password (required)""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_022603
7,724
no_license
[ { "docstring": "Creates a user, given an email and a password (optional)", "name": "create_user", "signature": "def create_user(self, email, password=None)" }, { "docstring": "Creates a super user, given an email and password (required)", "name": "create_superuser", "signature": "def cre...
2
stack_v2_sparse_classes_30k_train_000218
Implement the Python class `APUserManager` described below. Class description: Implement the APUserManager class. Method signatures and docstrings: - def create_user(self, email, password=None): Creates a user, given an email and a password (optional) - def create_superuser(self, email, password): Creates a super use...
Implement the Python class `APUserManager` described below. Class description: Implement the APUserManager class. Method signatures and docstrings: - def create_user(self, email, password=None): Creates a user, given an email and a password (optional) - def create_superuser(self, email, password): Creates a super use...
a211a2f5005af6b90ea33876654d441885f8c6d7
<|skeleton|> class APUserManager: def create_user(self, email, password=None): """Creates a user, given an email and a password (optional)""" <|body_0|> def create_superuser(self, email, password): """Creates a super user, given an email and password (required)""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APUserManager: def create_user(self, email, password=None): """Creates a user, given an email and a password (optional)""" if not email: raise ValueError('Users must have an email address') user = self.model(email=APUserManager.normalize_email(email)) user.set_passw...
the_stack_v2_python_sparse
ap/accounts/models.py
burricks/djattendance
train
0
f11be15e69f1bb25a0a951903edc05e67e7a4839
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MeetingAttendanceReport()", "from .attendance_record import AttendanceRecord\nfrom .entity import Entity\nfrom .attendance_record import AttendanceRecord\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'attenda...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return MeetingAttendanceReport() <|end_body_0|> <|body_start_1|> from .attendance_record import AttendanceRecord from .entity import Entity from .attendance_record import AttendanceReco...
MeetingAttendanceReport
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MeetingAttendanceReport: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingAttendanceReport: """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 creat...
stack_v2_sparse_classes_36k_train_022604
3,237
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: MeetingAttendanceReport", "name": "create_from_discriminator_value", "signature": "def create_from_discrimin...
3
null
Implement the Python class `MeetingAttendanceReport` described below. Class description: Implement the MeetingAttendanceReport class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingAttendanceReport: Creates a new instance of the appropriate clas...
Implement the Python class `MeetingAttendanceReport` described below. Class description: Implement the MeetingAttendanceReport class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingAttendanceReport: Creates a new instance of the appropriate clas...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class MeetingAttendanceReport: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingAttendanceReport: """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 creat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MeetingAttendanceReport: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingAttendanceReport: """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 R...
the_stack_v2_python_sparse
msgraph/generated/models/meeting_attendance_report.py
microsoftgraph/msgraph-sdk-python
train
135
a61c860bcdb6fedbb18504f9701cee9246fa0762
[ "if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError('If degrees is a single number, it must be positive.')\n self.degrees = (-degrees, degrees)\nelse:\n if len(degrees) != 2:\n raise ValueError('If degrees is a sequence, it must be of len 2.')\n self.degrees = deg...
<|body_start_0|> if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError('If degrees is a single number, it must be positive.') self.degrees = (-degrees, degrees) else: if len(degrees) != 2: raise ValueError('If degrees...
随机旋转
RandomRotation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomRotation: """随机旋转""" def __init__(self, degrees=15, p=0.5, check=True): """随机旋转,BUG,loss出现inf,可能因为旋转导致部分box越界或者丢失 :param degrees: :param p:随机旋转的概率 :param check: True False:""" <|body_0|> def __call__(self, image, boxes, labels, **kwargs): """:param image: n...
stack_v2_sparse_classes_36k_train_022605
34,265
no_license
[ { "docstring": "随机旋转,BUG,loss出现inf,可能因为旋转导致部分box越界或者丢失 :param degrees: :param p:随机旋转的概率 :param check: True False:", "name": "__init__", "signature": "def __init__(self, degrees=15, p=0.5, check=True)" }, { "docstring": ":param image: nparray img :param boxes: np.array([[88, 176, 250, 312, 1222],...
2
stack_v2_sparse_classes_30k_train_017626
Implement the Python class `RandomRotation` described below. Class description: 随机旋转 Method signatures and docstrings: - def __init__(self, degrees=15, p=0.5, check=True): 随机旋转,BUG,loss出现inf,可能因为旋转导致部分box越界或者丢失 :param degrees: :param p:随机旋转的概率 :param check: True False: - def __call__(self, image, boxes, labels, **kwa...
Implement the Python class `RandomRotation` described below. Class description: 随机旋转 Method signatures and docstrings: - def __init__(self, degrees=15, p=0.5, check=True): 随机旋转,BUG,loss出现inf,可能因为旋转导致部分box越界或者丢失 :param degrees: :param p:随机旋转的概率 :param check: True False: - def __call__(self, image, boxes, labels, **kwa...
40400a6ff7376f933899e7f4fead9f994c39d3fe
<|skeleton|> class RandomRotation: """随机旋转""" def __init__(self, degrees=15, p=0.5, check=True): """随机旋转,BUG,loss出现inf,可能因为旋转导致部分box越界或者丢失 :param degrees: :param p:随机旋转的概率 :param check: True False:""" <|body_0|> def __call__(self, image, boxes, labels, **kwargs): """:param image: n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomRotation: """随机旋转""" def __init__(self, degrees=15, p=0.5, check=True): """随机旋转,BUG,loss出现inf,可能因为旋转导致部分box越界或者丢失 :param degrees: :param p:随机旋转的概率 :param check: True False:""" if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError('If de...
the_stack_v2_python_sparse
models/transforms/augment_bbox_landm.py
PanJinquan/torch-Slim-Detection-Landmark
train
0
6a9d3b8a6494ffa42099fa4d6404c01fb3b9d87b
[ "dtype = dtypes.as_dtype(dtype).base_dtype\nif dtype not in (dtypes.uint8, dtypes.float32):\n raise TypeError('Invalid dtype %r, expected uint8 or float32' % dtype)\nassert data_X.shape[0] == data_Y.shape[0], 'data_X.shape: %s data_Y.shape: %s' % (data_X.shape, data_Y.shape)\nself.num_examples = data_X.shape[0]\...
<|body_start_0|> dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError('Invalid dtype %r, expected uint8 or float32' % dtype) assert data_X.shape[0] == data_Y.shape[0], 'data_X.shape: %s data_Y.shape: %s' % (data_X.shape, data_Y.sha...
DataSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataSet: def __init__(self, data_X, data_Y, dtype=dtypes.float32): """Checks data and casts it into correct data type.""" <|body_0|> def next_batch(self, batch_size, seed=None): """Return the next `batch_size` examples from this data set.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_022606
19,030
no_license
[ { "docstring": "Checks data and casts it into correct data type.", "name": "__init__", "signature": "def __init__(self, data_X, data_Y, dtype=dtypes.float32)" }, { "docstring": "Return the next `batch_size` examples from this data set.", "name": "next_batch", "signature": "def next_batch...
2
stack_v2_sparse_classes_30k_train_017689
Implement the Python class `DataSet` described below. Class description: Implement the DataSet class. Method signatures and docstrings: - def __init__(self, data_X, data_Y, dtype=dtypes.float32): Checks data and casts it into correct data type. - def next_batch(self, batch_size, seed=None): Return the next `batch_siz...
Implement the Python class `DataSet` described below. Class description: Implement the DataSet class. Method signatures and docstrings: - def __init__(self, data_X, data_Y, dtype=dtypes.float32): Checks data and casts it into correct data type. - def next_batch(self, batch_size, seed=None): Return the next `batch_siz...
4514e7231ee36ad10030105db14333bd04ee7f72
<|skeleton|> class DataSet: def __init__(self, data_X, data_Y, dtype=dtypes.float32): """Checks data and casts it into correct data type.""" <|body_0|> def next_batch(self, batch_size, seed=None): """Return the next `batch_size` examples from this data set.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataSet: def __init__(self, data_X, data_Y, dtype=dtypes.float32): """Checks data and casts it into correct data type.""" dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError('Invalid dtype %r, expected uint8 or float32' ...
the_stack_v2_python_sparse
statmech/ising2d.py
HussainAther/physics
train
18
bc17a503755569341f0d1b8d0a28d97c6e2116d9
[ "def _isSymmetric(left, right):\n if left is None or right is None:\n return left == right\n if not left.val == right.val:\n return False\n return _isSymmetric(left.left, right.right) and _isSymmetric(left.right, right.left)\nif root is None:\n return True\nreturn _isSymmetric(root.left, r...
<|body_start_0|> def _isSymmetric(left, right): if left is None or right is None: return left == right if not left.val == right.val: return False return _isSymmetric(left.left, right.right) and _isSymmetric(left.right, right.left) if ro...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> def _isSymmetric(left, right): if...
stack_v2_sparse_classes_36k_train_022607
2,144
no_license
[ { "docstring": ":type root: TreeNode :rtype: bool", "name": "isSymmetric", "signature": "def isSymmetric(self, root)" }, { "docstring": ":type root: TreeNode :rtype: bool", "name": "isSymmetric", "signature": "def isSymmetric(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): :type root: TreeNode :rtype: bool - def isSymmetric(self, root): :type root: TreeNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): :type root: TreeNode :rtype: bool - def isSymmetric(self, root): :type root: TreeNode :rtype: bool <|skeleton|> class Solution: def isSymmetric...
18ed31a3edf20a3e5a0b7a0b56acca5b98939693
<|skeleton|> class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_0|> def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isSymmetric(self, root): """:type root: TreeNode :rtype: bool""" def _isSymmetric(left, right): if left is None or right is None: return left == right if not left.val == right.val: return False return _isSymmetri...
the_stack_v2_python_sparse
exercises/binary-tree/symmetric_tree.py
nahgnaw/data-structure
train
0
d8f2da941f0f28ce849d05c5b387b053fcb42a6d
[ "project_id = self.get_secure_cookie('project_id')\nif not project_id:\n return None\nproject_id = UUID(project_id.decode('UTF-8'))\nprojects_manager = srv_or_die('projectsmanager')\nif project_id not in projects_manager.projects:\n self.clear_cookie('project_id')\n return None\nreturn projects_manager.pro...
<|body_start_0|> project_id = self.get_secure_cookie('project_id') if not project_id: return None project_id = UUID(project_id.decode('UTF-8')) projects_manager = srv_or_die('projectsmanager') if project_id not in projects_manager.projects: self.clear_cook...
Index page handler.
IndexHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IndexHandler: """Index page handler.""" def get_project(self): """Get the current project or return None if not project is set.""" <|body_0|> def get(self, args=None): """Render index page.""" <|body_1|> <|end_skeleton|> <|body_start_0|> project...
stack_v2_sparse_classes_36k_train_022608
16,584
permissive
[ { "docstring": "Get the current project or return None if not project is set.", "name": "get_project", "signature": "def get_project(self)" }, { "docstring": "Render index page.", "name": "get", "signature": "def get(self, args=None)" } ]
2
stack_v2_sparse_classes_30k_train_019608
Implement the Python class `IndexHandler` described below. Class description: Index page handler. Method signatures and docstrings: - def get_project(self): Get the current project or return None if not project is set. - def get(self, args=None): Render index page.
Implement the Python class `IndexHandler` described below. Class description: Index page handler. Method signatures and docstrings: - def get_project(self): Get the current project or return None if not project is set. - def get(self, args=None): Render index page. <|skeleton|> class IndexHandler: """Index page ...
38eac8eebf57da4bec07518383ab65a5544445fe
<|skeleton|> class IndexHandler: """Index page handler.""" def get_project(self): """Get the current project or return None if not project is set.""" <|body_0|> def get(self, args=None): """Render index page.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IndexHandler: """Index page handler.""" def get_project(self): """Get the current project or return None if not project is set.""" project_id = self.get_secure_cookie('project_id') if not project_id: return None project_id = UUID(project_id.decode('UTF-8')) ...
the_stack_v2_python_sparse
empower_core/apimanager/apimanager.py
5g-empower/empower-core
train
3
b28584b8bbd98555f50b21a94c76f7dbfe38ef70
[ "super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{qemu_id}', update_interval=timedelta(seconds=UPDATE_INTERVAL))\nself.hass = hass\nself.config_entry: ConfigEntry = self.config_entry\nself.proxmox = proxmox\nself.node_name: str\nself.vm_id = qemu_id", "def poll_api() -> dict[str, Any] | None...
<|body_start_0|> super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{qemu_id}', update_interval=timedelta(seconds=UPDATE_INTERVAL)) self.hass = hass self.config_entry: ConfigEntry = self.config_entry self.proxmox = proxmox self.node_name: str self.vm_id...
Proxmox VE QEMU data update coordinator.
ProxmoxQEMUCoordinator
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProxmoxQEMUCoordinator: """Proxmox VE QEMU data update coordinator.""" def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, qemu_id: int) -> None: """Initialize the Proxmox QEMU coordinator.""" <|body_0|> async def _async_update_data(self) -> Prox...
stack_v2_sparse_classes_36k_train_022609
15,228
permissive
[ { "docstring": "Initialize the Proxmox QEMU coordinator.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, qemu_id: int) -> None" }, { "docstring": "Update data for Proxmox QEMU.", "name": "_async_update_data", "signature": "...
2
null
Implement the Python class `ProxmoxQEMUCoordinator` described below. Class description: Proxmox VE QEMU data update coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, qemu_id: int) -> None: Initialize the Proxmox QEMU coordinator. - async def ...
Implement the Python class `ProxmoxQEMUCoordinator` described below. Class description: Proxmox VE QEMU data update coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, qemu_id: int) -> None: Initialize the Proxmox QEMU coordinator. - async def ...
8548d9999ddd54f13d6a307e013abcb8c897a74e
<|skeleton|> class ProxmoxQEMUCoordinator: """Proxmox VE QEMU data update coordinator.""" def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, qemu_id: int) -> None: """Initialize the Proxmox QEMU coordinator.""" <|body_0|> async def _async_update_data(self) -> Prox...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProxmoxQEMUCoordinator: """Proxmox VE QEMU data update coordinator.""" def __init__(self, hass: HomeAssistant, proxmox: ProxmoxAPI, host_name: str, qemu_id: int) -> None: """Initialize the Proxmox QEMU coordinator.""" super().__init__(hass, LOGGER, name=f'proxmox_coordinator_{host_name}_{...
the_stack_v2_python_sparse
custom_components/proxmoxve/coordinator.py
bacco007/HomeAssistantConfig
train
98
44ea795864673761fd463e40f0c9b58c594c0631
[ "self.dim = dim\nself.palette = palette\nself.sin = sin\nself.width = dim[0]\nself.height = dim[1]\nself.pixel_surface = pygame.Surface((dim[0] * 2, dim[1] * 2))\nfor y in range(self.pixel_surface.get_height()):\n for x in range(self.pixel_surface.get_width()):\n value = 128 + int(127 * sin[y % 360] * sin...
<|body_start_0|> self.dim = dim self.palette = palette self.sin = sin self.width = dim[0] self.height = dim[1] self.pixel_surface = pygame.Surface((dim[0] * 2, dim[1] * 2)) for y in range(self.pixel_surface.get_height()): for x in range(self.pixel_surf...
interfering colors
ColorInterference
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ColorInterference: """interfering colors""" def __init__(self, dim, palette=PALETTE, sin=SIN): """(pygame.Surface) surface - surface to draw on""" <|body_0|> def update(self): """blit on background surface""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_022610
5,041
no_license
[ { "docstring": "(pygame.Surface) surface - surface to draw on", "name": "__init__", "signature": "def __init__(self, dim, palette=PALETTE, sin=SIN)" }, { "docstring": "blit on background surface", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_005532
Implement the Python class `ColorInterference` described below. Class description: interfering colors Method signatures and docstrings: - def __init__(self, dim, palette=PALETTE, sin=SIN): (pygame.Surface) surface - surface to draw on - def update(self): blit on background surface
Implement the Python class `ColorInterference` described below. Class description: interfering colors Method signatures and docstrings: - def __init__(self, dim, palette=PALETTE, sin=SIN): (pygame.Surface) surface - surface to draw on - def update(self): blit on background surface <|skeleton|> class ColorInterferenc...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class ColorInterference: """interfering colors""" def __init__(self, dim, palette=PALETTE, sin=SIN): """(pygame.Surface) surface - surface to draw on""" <|body_0|> def update(self): """blit on background surface""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ColorInterference: """interfering colors""" def __init__(self, dim, palette=PALETTE, sin=SIN): """(pygame.Surface) surface - surface to draw on""" self.dim = dim self.palette = palette self.sin = sin self.width = dim[0] self.height = dim[1] self.pix...
the_stack_v2_python_sparse
effects/Interference.py
gunny26/pygame
train
5
24c93d0875499ccd87866cba9c88aee62cff2894
[ "super().__init__(**kwargs)\nif preserve_dims <= 0:\n raise ValueError('Argument preserve_dims should be >= 1.')\nif output_shape.count(-1) > 1:\n raise ValueError('-1 can only occur once in `output_shape`.')\nself.output_shape = tuple(output_shape)\nself.preserve_dims = preserve_dims", "if inputs.ndim <= s...
<|body_start_0|> super().__init__(**kwargs) if preserve_dims <= 0: raise ValueError('Argument preserve_dims should be >= 1.') if output_shape.count(-1) > 1: raise ValueError('-1 can only occur once in `output_shape`.') self.output_shape = tuple(output_shape) ...
Reshapes input Tensor, preserving the batch dimension. For example, given an input tensor with shape `[B, H, W, C, D]`: ```python B, H, W, C, D = range(1, 6) x = jnp.ones([B, H, W, C, D]) ``` The default behavior when `output_shape` is `(-1, D)` is to flatten all dimensions between `B` and `D`: ```python mod = elegy.nn...
Reshape
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Reshape: """Reshapes input Tensor, preserving the batch dimension. For example, given an input tensor with shape `[B, H, W, C, D]`: ```python B, H, W, C, D = range(1, 6) x = jnp.ones([B, H, W, C, D]) ``` The default behavior when `output_shape` is `(-1, D)` is to flatten all dimensions between `B...
stack_v2_sparse_classes_36k_train_022611
4,093
permissive
[ { "docstring": "Constructs a `Reshape` module. Args: output_shape: Shape to reshape the input tensor to while preserving its first `preserve_dims` dimensions. When the special value -1 appears in `output_shape` the corresponding size is automatically inferred. Note that -1 can only appear once in `output_shape`...
2
stack_v2_sparse_classes_30k_train_016669
Implement the Python class `Reshape` described below. Class description: Reshapes input Tensor, preserving the batch dimension. For example, given an input tensor with shape `[B, H, W, C, D]`: ```python B, H, W, C, D = range(1, 6) x = jnp.ones([B, H, W, C, D]) ``` The default behavior when `output_shape` is `(-1, D)` ...
Implement the Python class `Reshape` described below. Class description: Reshapes input Tensor, preserving the batch dimension. For example, given an input tensor with shape `[B, H, W, C, D]`: ```python B, H, W, C, D = range(1, 6) x = jnp.ones([B, H, W, C, D]) ``` The default behavior when `output_shape` is `(-1, D)` ...
3494cc7d495198f4c383d3560ea05df65bb669ff
<|skeleton|> class Reshape: """Reshapes input Tensor, preserving the batch dimension. For example, given an input tensor with shape `[B, H, W, C, D]`: ```python B, H, W, C, D = range(1, 6) x = jnp.ones([B, H, W, C, D]) ``` The default behavior when `output_shape` is `(-1, D)` is to flatten all dimensions between `B...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Reshape: """Reshapes input Tensor, preserving the batch dimension. For example, given an input tensor with shape `[B, H, W, C, D]`: ```python B, H, W, C, D = range(1, 6) x = jnp.ones([B, H, W, C, D]) ``` The default behavior when `output_shape` is `(-1, D)` is to flatten all dimensions between `B` and `D`: ``...
the_stack_v2_python_sparse
elegy/nn/flatten.py
cgarciae/elegy
train
1
ebf37d5b11aa0bbedc85cdbd4d6eddc8c656c46e
[ "if type(dateTime) == datetime.datetime:\n return dateTime.isoformat()\nraise ValueError('dateTime value must be a datetime.datetime instance')", "if type(date) == datetime.date:\n return date.strftime('%m%Y')\nraise ValueError('date value must be a datetime.date instance')", "if amount is None or amount ...
<|body_start_0|> if type(dateTime) == datetime.datetime: return dateTime.isoformat() raise ValueError('dateTime value must be a datetime.datetime instance') <|end_body_0|> <|body_start_1|> if type(date) == datetime.date: return date.strftime('%m%Y') raise ValueEr...
Converts fields to the paypal required format.
FormatFields
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FormatFields: """Converts fields to the paypal required format.""" def get_datetime_field(self, dateTime): """This method is used inside main classes, if any classes needs date argument you can use Python datetime.datetime. In short - you will not need to use this method. Paypal need...
stack_v2_sparse_classes_36k_train_022612
3,991
no_license
[ { "docstring": "This method is used inside main classes, if any classes needs date argument you can use Python datetime.datetime. In short - you will not need to use this method. Paypal needs Coordinated Universal Time (UTC/GMT), using ISO 8601 format, and of type ns:dateTime for Date/Time formats. An example d...
3
stack_v2_sparse_classes_30k_train_018093
Implement the Python class `FormatFields` described below. Class description: Converts fields to the paypal required format. Method signatures and docstrings: - def get_datetime_field(self, dateTime): This method is used inside main classes, if any classes needs date argument you can use Python datetime.datetime. In ...
Implement the Python class `FormatFields` described below. Class description: Converts fields to the paypal required format. Method signatures and docstrings: - def get_datetime_field(self, dateTime): This method is used inside main classes, if any classes needs date argument you can use Python datetime.datetime. In ...
36573ab5b9ee305679ceba097b2953f52be670e4
<|skeleton|> class FormatFields: """Converts fields to the paypal required format.""" def get_datetime_field(self, dateTime): """This method is used inside main classes, if any classes needs date argument you can use Python datetime.datetime. In short - you will not need to use this method. Paypal need...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FormatFields: """Converts fields to the paypal required format.""" def get_datetime_field(self, dateTime): """This method is used inside main classes, if any classes needs date argument you can use Python datetime.datetime. In short - you will not need to use this method. Paypal needs Coordinated...
the_stack_v2_python_sparse
modules/paypalnvp/util.py
acidjunk/web2py-paypal
train
2
77ee5f94df8b4f32597096daf0a2c5715d48c3f6
[ "result = []\nothers = [\"'s\", 'the', 'that', 'this', 'to', '-PRON-']\nfor sent in text:\n sent = str(sent).lower()\n sent = re.sub('facebook', 'social media', sent)\n sent = re.sub('twitter', 'social media', sent)\n sent = re.sub('instagram', 'social media', sent)\n sent = re.sub('whatsapp', 'socia...
<|body_start_0|> result = [] others = ["'s", 'the', 'that', 'this', 'to', '-PRON-'] for sent in text: sent = str(sent).lower() sent = re.sub('facebook', 'social media', sent) sent = re.sub('twitter', 'social media', sent) sent = re.sub('instagram',...
Preprocessing
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Preprocessing: def general(self, text, min_token_len=2, irrelevant_pos=['PRON', 'SPACE', 'PUNCT', 'ADV', 'ADP', 'CCONJ', 'AUX', 'PRP'], avoid_entities=['PERSON', 'ORG', 'LOC', 'GPE']): """Function that identify sensible information, anonymize and transforms the data in a useful format fo...
stack_v2_sparse_classes_36k_train_022613
5,915
permissive
[ { "docstring": "Function that identify sensible information, anonymize and transforms the data in a useful format for using with tokens. Parameters ------------- text : (list) the list of text to be preprocessed irrelevant_pos : (list) a list of irrelevant 'pos' tags avoid_entities : (list) a list of entity lab...
2
stack_v2_sparse_classes_30k_train_006777
Implement the Python class `Preprocessing` described below. Class description: Implement the Preprocessing class. Method signatures and docstrings: - def general(self, text, min_token_len=2, irrelevant_pos=['PRON', 'SPACE', 'PUNCT', 'ADV', 'ADP', 'CCONJ', 'AUX', 'PRP'], avoid_entities=['PERSON', 'ORG', 'LOC', 'GPE'])...
Implement the Python class `Preprocessing` described below. Class description: Implement the Preprocessing class. Method signatures and docstrings: - def general(self, text, min_token_len=2, irrelevant_pos=['PRON', 'SPACE', 'PUNCT', 'ADV', 'ADP', 'CCONJ', 'AUX', 'PRP'], avoid_entities=['PERSON', 'ORG', 'LOC', 'GPE'])...
3a83cb05c0157639e84b1936a9b5656ae6b50e46
<|skeleton|> class Preprocessing: def general(self, text, min_token_len=2, irrelevant_pos=['PRON', 'SPACE', 'PUNCT', 'ADV', 'ADP', 'CCONJ', 'AUX', 'PRP'], avoid_entities=['PERSON', 'ORG', 'LOC', 'GPE']): """Function that identify sensible information, anonymize and transforms the data in a useful format fo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Preprocessing: def general(self, text, min_token_len=2, irrelevant_pos=['PRON', 'SPACE', 'PUNCT', 'ADV', 'ADP', 'CCONJ', 'AUX', 'PRP'], avoid_entities=['PERSON', 'ORG', 'LOC', 'GPE']): """Function that identify sensible information, anonymize and transforms the data in a useful format for using with t...
the_stack_v2_python_sparse
src/data/preprocess.py
Sukriti1312/UBC_MDS_Capstone
train
0
dce08be06260952a4eaf3364f8e2eefc5df1ee28
[ "if not heights:\n return 0\narea_to_right, area_to_left = ([0] * len(heights), [0] * len(heights))\nstack = [(-1, 0)]\nfor idx, height in enumerate(heights + [0]):\n while height < stack[-1][1]:\n l, h = stack.pop()\n area_to_right[l] = (idx - l) * h\n stack.append((idx, height))\nstack = [(...
<|body_start_0|> if not heights: return 0 area_to_right, area_to_left = ([0] * len(heights), [0] * len(heights)) stack = [(-1, 0)] for idx, height in enumerate(heights + [0]): while height < stack[-1][1]: l, h = stack.pop() area_to_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def largestRectangleArea(self, heights): """:type heights: List[int] :rtype: int""" <|body_0|> def maximalRectangle(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not heights:...
stack_v2_sparse_classes_36k_train_022614
1,859
no_license
[ { "docstring": ":type heights: List[int] :rtype: int", "name": "largestRectangleArea", "signature": "def largestRectangleArea(self, heights)" }, { "docstring": ":type matrix: List[List[str]] :rtype: int", "name": "maximalRectangle", "signature": "def maximalRectangle(self, matrix)" } ]
2
stack_v2_sparse_classes_30k_train_003144
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int - def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int - def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int <|skeleton|> class ...
64b9e452371d989f6061d89c6b96af2ba7fe5990
<|skeleton|> class Solution: def largestRectangleArea(self, heights): """:type heights: List[int] :rtype: int""" <|body_0|> def maximalRectangle(self, matrix): """:type matrix: List[List[str]] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def largestRectangleArea(self, heights): """:type heights: List[int] :rtype: int""" if not heights: return 0 area_to_right, area_to_left = ([0] * len(heights), [0] * len(heights)) stack = [(-1, 0)] for idx, height in enumerate(heights + [0]): ...
the_stack_v2_python_sparse
51-100/85.py
hurenjun/LeetCode
train
1
2ffc85f667416e90328724a38c88dfb47342715a
[ "self.auth = auth\nself._group = group\nself._overall_situation = True if not group else False", "with connection.cursor() as cursor:\n cursor.execute(f'\\n SELECT makeup.face_uuid \\n FROM faceU_faceufacialmakeupmapping AS mapping \\n JOIN faceU_faceufacialmakeup A...
<|body_start_0|> self.auth = auth self._group = group self._overall_situation = True if not group else False <|end_body_0|> <|body_start_1|> with connection.cursor() as cursor: cursor.execute(f'\n SELECT makeup.face_uuid \n FROM faceU_faceufacia...
FaceUDistinguishLogic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FaceUDistinguishLogic: def __init__(self, auth, group=0): """人脸识别逻辑 :param auth: :param group:""" <|body_0|> def to_face_uuid(self): """获取分组或全局成员脸谱uuid :return:""" <|body_1|> def from_face_uuid(self, face_uuid): """从uuid获取成员信息 :param face_uuid: :...
stack_v2_sparse_classes_36k_train_022615
1,765
no_license
[ { "docstring": "人脸识别逻辑 :param auth: :param group:", "name": "__init__", "signature": "def __init__(self, auth, group=0)" }, { "docstring": "获取分组或全局成员脸谱uuid :return:", "name": "to_face_uuid", "signature": "def to_face_uuid(self)" }, { "docstring": "从uuid获取成员信息 :param face_uuid: :r...
3
stack_v2_sparse_classes_30k_train_004620
Implement the Python class `FaceUDistinguishLogic` described below. Class description: Implement the FaceUDistinguishLogic class. Method signatures and docstrings: - def __init__(self, auth, group=0): 人脸识别逻辑 :param auth: :param group: - def to_face_uuid(self): 获取分组或全局成员脸谱uuid :return: - def from_face_uuid(self, face_...
Implement the Python class `FaceUDistinguishLogic` described below. Class description: Implement the FaceUDistinguishLogic class. Method signatures and docstrings: - def __init__(self, auth, group=0): 人脸识别逻辑 :param auth: :param group: - def to_face_uuid(self): 获取分组或全局成员脸谱uuid :return: - def from_face_uuid(self, face_...
7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b
<|skeleton|> class FaceUDistinguishLogic: def __init__(self, auth, group=0): """人脸识别逻辑 :param auth: :param group:""" <|body_0|> def to_face_uuid(self): """获取分组或全局成员脸谱uuid :return:""" <|body_1|> def from_face_uuid(self, face_uuid): """从uuid获取成员信息 :param face_uuid: :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FaceUDistinguishLogic: def __init__(self, auth, group=0): """人脸识别逻辑 :param auth: :param group:""" self.auth = auth self._group = group self._overall_situation = True if not group else False def to_face_uuid(self): """获取分组或全局成员脸谱uuid :return:""" with connect...
the_stack_v2_python_sparse
FireHydrant/server/faceU/logic/distinguish.py
shoogoome/FireHydrant
train
4
f4ce8677448eb71d27f82f1ae215dbb98e1dee79
[ "if isinstance(pattern, str):\n self.pattern = re.compile(pattern)\nelse:\n self.pattern = pattern\nself.optimistic = optimistic\nself._count = count\nself._period = period\nself._actual_usage = 0\nself._next_flush = None", "now = time()\nif self._next_flush is None:\n self._next_flush = now + self._peri...
<|body_start_0|> if isinstance(pattern, str): self.pattern = re.compile(pattern) else: self.pattern = pattern self.optimistic = optimistic self._count = count self._period = period self._actual_usage = 0 self._next_flush = None <|end_body_0...
RequestRate
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestRate: def __init__(self, count: int, period: int, pattern=None, optimistic: bool=False): """:param count: How many requests per period are allowed. If the request rate is 10 requests per minute than count=10 with period=60. :param period: How many seconds between each cycle. If th...
stack_v2_sparse_classes_36k_train_022616
1,882
permissive
[ { "docstring": ":param count: How many requests per period are allowed. If the request rate is 10 requests per minute than count=10 with period=60. :param period: How many seconds between each cycle. If the request rate is 10 requests per minute than the period is 60. :param pattern: A pattern to match against ...
2
stack_v2_sparse_classes_30k_train_009130
Implement the Python class `RequestRate` described below. Class description: Implement the RequestRate class. Method signatures and docstrings: - def __init__(self, count: int, period: int, pattern=None, optimistic: bool=False): :param count: How many requests per period are allowed. If the request rate is 10 request...
Implement the Python class `RequestRate` described below. Class description: Implement the RequestRate class. Method signatures and docstrings: - def __init__(self, count: int, period: int, pattern=None, optimistic: bool=False): :param count: How many requests per period are allowed. If the request rate is 10 request...
345e5325f76c3d1e9e2c23e499e7ec2f1383252b
<|skeleton|> class RequestRate: def __init__(self, count: int, period: int, pattern=None, optimistic: bool=False): """:param count: How many requests per period are allowed. If the request rate is 10 requests per minute than count=10 with period=60. :param period: How many seconds between each cycle. If th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RequestRate: def __init__(self, count: int, period: int, pattern=None, optimistic: bool=False): """:param count: How many requests per period are allowed. If the request rate is 10 requests per minute than count=10 with period=60. :param period: How many seconds between each cycle. If the request rate...
the_stack_v2_python_sparse
vibora/client/limits.py
PranayJain/vibora
train
0
3812656732651614bf1c775f7c0a756ecf21571b
[ "if type(metrics) == list:\n metrics = [m + '@' + str(n) for m in metrics for n in n_ranks]\nsuper(DiversityEvaluation, self).__init__(sep=sep, metrics=metrics, all_but_one_eval=all_but_one_eval, verbose=verbose, as_table=as_table, table_sep=table_sep)\nself.n_ranks = n_ranks", "eval_results = {}\nnum_user = l...
<|body_start_0|> if type(metrics) == list: metrics = [m + '@' + str(n) for m in metrics for n in n_ranks] super(DiversityEvaluation, self).__init__(sep=sep, metrics=metrics, all_but_one_eval=all_but_one_eval, verbose=verbose, as_table=as_table, table_sep=table_sep) self.n_ranks = n_r...
DiversityEvaluation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiversityEvaluation: def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'): """Class to evaluate predictions in a item recommendation (ranking) sce...
stack_v2_sparse_classes_36k_train_022617
14,557
no_license
[ { "docstring": "Class to evaluate predictions in a item recommendation (ranking) scenario :param sep: Delimiter for input files :type sep: str, default ' ' :param n_ranks: List of positions to evaluate the ranking :type n_ranks: list, default [1, 3, 5, 10] :param metrics: List of evaluation metrics :type metric...
2
stack_v2_sparse_classes_30k_val_000148
Implement the Python class `DiversityEvaluation` described below. Class description: Implement the DiversityEvaluation class. Method signatures and docstrings: - def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose...
Implement the Python class `DiversityEvaluation` described below. Class description: Implement the DiversityEvaluation class. Method signatures and docstrings: - def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose...
b5f870abbe5b5e4311e8f22370af487d2570d9b6
<|skeleton|> class DiversityEvaluation: def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'): """Class to evaluate predictions in a item recommendation (ranking) sce...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiversityEvaluation: def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'): """Class to evaluate predictions in a item recommendation (ranking) scenario :param s...
the_stack_v2_python_sparse
evaluation/diversity_evaluation.py
juarezsacenti/kg-summ-rec
train
1
0f6b7d1c823356ec6c03f157a711a2d26bc7a735
[ "if not quota_max_calls:\n use_rate_limiter = False\nself._billing_accounts = None\nself._projects = None\nsuper(CloudBillingRepositoryClient, self).__init__(API_NAME, versions=['v1'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limiter=use_rate_limiter)", "if not self._billing_account...
<|body_start_0|> if not quota_max_calls: use_rate_limiter = False self._billing_accounts = None self._projects = None super(CloudBillingRepositoryClient, self).__init__(API_NAME, versions=['v1'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limiter=use...
Cloud Billing API Respository.
CloudBillingRepositoryClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CloudBillingRepositoryClient: """Cloud Billing API Respository.""" def __init__(self, quota_max_calls=None, quota_period=60.0, use_rate_limiter=True): """Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period t...
stack_v2_sparse_classes_36k_train_022618
10,503
permissive
[ { "docstring": "Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests over. use_rate_limiter (bool): Set to false to disable the use of a rate limiter for this service.", "name": "__init__", "signature": "def __...
3
stack_v2_sparse_classes_30k_train_007591
Implement the Python class `CloudBillingRepositoryClient` described below. Class description: Cloud Billing API Respository. Method signatures and docstrings: - def __init__(self, quota_max_calls=None, quota_period=60.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_per...
Implement the Python class `CloudBillingRepositoryClient` described below. Class description: Cloud Billing API Respository. Method signatures and docstrings: - def __init__(self, quota_max_calls=None, quota_period=60.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_per...
d4421afa50a17ed47cbebe942044ebab3720e0f5
<|skeleton|> class CloudBillingRepositoryClient: """Cloud Billing API Respository.""" def __init__(self, quota_max_calls=None, quota_period=60.0, use_rate_limiter=True): """Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CloudBillingRepositoryClient: """Cloud Billing API Respository.""" def __init__(self, quota_max_calls=None, quota_period=60.0, use_rate_limiter=True): """Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track reque...
the_stack_v2_python_sparse
google/cloud/forseti/common/gcp_api/cloudbilling.py
kevensen/forseti-security
train
1
9702d42418b855b14e020ad1874da9f9f89b65d9
[ "self.A = np.mat(A)\nself.B = np.mat(B)\nself.Q = np.mat(Q)\nself.R = np.mat(R)\nF = self.dlqr(A, B, Q, R, **kwargs)\nsuper(LQRController, self).__init__(A, B, F, **kwargs)", "if Q_f == None:\n Q_f = Q\nif T < np.inf:\n K = [None] * T\n P = Q_f\n for t in range(0, T - 1)[::-1]:\n K[t] = (R + B....
<|body_start_0|> self.A = np.mat(A) self.B = np.mat(B) self.Q = np.mat(Q) self.R = np.mat(R) F = self.dlqr(A, B, Q, R, **kwargs) super(LQRController, self).__init__(A, B, F, **kwargs) <|end_body_0|> <|body_start_1|> if Q_f == None: Q_f = Q if ...
Linear feedback controller where control gains are set by optimizing a quadratic cost function
LQRController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LQRController: """Linear feedback controller where control gains are set by optimizing a quadratic cost function""" def __init__(self, A, B, Q, R, **kwargs): """Constructor for LQRController The system should evolve as $$x_{t+1} = Ax_t + Bu_t + w_t; w_t ~ N(0, W)$$ with infinite hori...
stack_v2_sparse_classes_36k_train_022619
12,992
permissive
[ { "docstring": "Constructor for LQRController The system should evolve as $$x_{t+1} = Ax_t + Bu_t + w_t; w_t ~ N(0, W)$$ with infinite horizon cost $$\\\\sum{t=0}^{+\\\\infty} (x_t - x_target)^T * Q * (x_t - x_target) + u_t^T * R * u_t$$ Parameters ---------- A: np.ndarray of shape (n_states, n_states) Model of...
2
null
Implement the Python class `LQRController` described below. Class description: Linear feedback controller where control gains are set by optimizing a quadratic cost function Method signatures and docstrings: - def __init__(self, A, B, Q, R, **kwargs): Constructor for LQRController The system should evolve as $$x_{t+1...
Implement the Python class `LQRController` described below. Class description: Linear feedback controller where control gains are set by optimizing a quadratic cost function Method signatures and docstrings: - def __init__(self, A, B, Q, R, **kwargs): Constructor for LQRController The system should evolve as $$x_{t+1...
a0e296aa663b49e767c9ebb274defb54b301eb12
<|skeleton|> class LQRController: """Linear feedback controller where control gains are set by optimizing a quadratic cost function""" def __init__(self, A, B, Q, R, **kwargs): """Constructor for LQRController The system should evolve as $$x_{t+1} = Ax_t + Bu_t + w_t; w_t ~ N(0, W)$$ with infinite hori...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LQRController: """Linear feedback controller where control gains are set by optimizing a quadratic cost function""" def __init__(self, A, B, Q, R, **kwargs): """Constructor for LQRController The system should evolve as $$x_{t+1} = Ax_t + Bu_t + w_t; w_t ~ N(0, W)$$ with infinite horizon cost $$\\...
the_stack_v2_python_sparse
riglib/bmi/feedback_controllers.py
carmenalab/brain-python-interface
train
9
bb5e6e69e4e827c119ea558e158e008c2a3c1019
[ "subject = smart_text(self.subject)\nmessage = self.message\nhtml_message = self.html_message\nif html_message:\n msg = EmailMultiAlternatives(subject=subject, body=message, from_email=settings.DEFAULT_FROM_EMAIL, to=[self.to], connection=connection)\n msg.attach_alternative(html_message, 'text/html')\nelse:\...
<|body_start_0|> subject = smart_text(self.subject) message = self.message html_message = self.html_message if html_message: msg = EmailMultiAlternatives(subject=subject, body=message, from_email=settings.DEFAULT_FROM_EMAIL, to=[self.to], connection=connection) ms...
EmailNotification
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailNotification: def email_message(self, connection=None): """Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object depending on whether html_message is empty.""" <|body_0|> def send(self): """Caller should catch all exceptions :return:""" ...
stack_v2_sparse_classes_36k_train_022620
3,621
no_license
[ { "docstring": "Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object depending on whether html_message is empty.", "name": "email_message", "signature": "def email_message(self, connection=None)" }, { "docstring": "Caller should catch all exceptions :return:", "name": "send...
2
stack_v2_sparse_classes_30k_train_019862
Implement the Python class `EmailNotification` described below. Class description: Implement the EmailNotification class. Method signatures and docstrings: - def email_message(self, connection=None): Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object depending on whether html_message is empty. - d...
Implement the Python class `EmailNotification` described below. Class description: Implement the EmailNotification class. Method signatures and docstrings: - def email_message(self, connection=None): Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object depending on whether html_message is empty. - d...
f29e802338e5ddcf18beb708c0858eb842a5dbd4
<|skeleton|> class EmailNotification: def email_message(self, connection=None): """Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object depending on whether html_message is empty.""" <|body_0|> def send(self): """Caller should catch all exceptions :return:""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmailNotification: def email_message(self, connection=None): """Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object depending on whether html_message is empty.""" subject = smart_text(self.subject) message = self.message html_message = self.html_message ...
the_stack_v2_python_sparse
pl_notifications/models/emails.py
exister/python_code_sample
train
0
807d1d275f98b609e5f1e6bfbff3b89e97c04066
[ "if temperature < 1 or temperature > 37:\n raise DITTE(DITTE.CELSIUS, temperature)\nreturn str(round((temperature + 273) * 10))", "if temperature < 34 or temperature > 98:\n raise DITTE(DITTE.FAHRENHEIT, temperature)\nreturn str(int((int(temperature) + 459.67) * 5 / 9) * 10)" ]
<|body_start_0|> if temperature < 1 or temperature > 37: raise DITTE(DITTE.CELSIUS, temperature) return str(round((temperature + 273) * 10)) <|end_body_0|> <|body_start_1|> if temperature < 34 or temperature > 98: raise DITTE(DITTE.FAHRENHEIT, temperature) return...
Heat Target for fan. Note dyson uses kelvin as the temperature unit.
HeatTarget
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeatTarget: """Heat Target for fan. Note dyson uses kelvin as the temperature unit.""" def celsius(temperature): """Convert the given int celsius temperature to string in Kelvin. :param temperature temperature in celsius between 1 to 37 inclusive.""" <|body_0|> def fahre...
stack_v2_sparse_classes_36k_train_022621
4,224
permissive
[ { "docstring": "Convert the given int celsius temperature to string in Kelvin. :param temperature temperature in celsius between 1 to 37 inclusive.", "name": "celsius", "signature": "def celsius(temperature)" }, { "docstring": "Convert the given int fahrenheit temperature to string in Kelvin. :p...
2
stack_v2_sparse_classes_30k_train_008500
Implement the Python class `HeatTarget` described below. Class description: Heat Target for fan. Note dyson uses kelvin as the temperature unit. Method signatures and docstrings: - def celsius(temperature): Convert the given int celsius temperature to string in Kelvin. :param temperature temperature in celsius betwee...
Implement the Python class `HeatTarget` described below. Class description: Heat Target for fan. Note dyson uses kelvin as the temperature unit. Method signatures and docstrings: - def celsius(temperature): Convert the given int celsius temperature to string in Kelvin. :param temperature temperature in celsius betwee...
5f0caec1a1678b9c9fc1a99b000bb320ee3f3ae2
<|skeleton|> class HeatTarget: """Heat Target for fan. Note dyson uses kelvin as the temperature unit.""" def celsius(temperature): """Convert the given int celsius temperature to string in Kelvin. :param temperature temperature in celsius between 1 to 37 inclusive.""" <|body_0|> def fahre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HeatTarget: """Heat Target for fan. Note dyson uses kelvin as the temperature unit.""" def celsius(temperature): """Convert the given int celsius temperature to string in Kelvin. :param temperature temperature in celsius between 1 to 37 inclusive.""" if temperature < 1 or temperature > 37...
the_stack_v2_python_sparse
libpurecool/const.py
googanhiem/libpurecool
train
1
9a51169e250a5fea886104e52d439cea4e719744
[ "self.desc_ctx = {'main_filter': _('All pages'), 'title_filter': ''}\nqueryset = self.model.objects.all().order_by('title')\nself.form = self.form_class(self.request.GET)\nif not self.form.is_valid():\n return queryset\ndata = self.form.cleaned_data\nif data['title']:\n queryset = queryset.filter(title__icont...
<|body_start_0|> self.desc_ctx = {'main_filter': _('All pages'), 'title_filter': ''} queryset = self.model.objects.all().order_by('title') self.form = self.form_class(self.request.GET) if not self.form.is_valid(): return queryset data = self.form.cleaned_data ...
View for listing all existing flatpages.
PageListView
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PageListView: """View for listing all existing flatpages.""" def get_queryset(self): """Get queryset of all flatpages to be displayed. If a search term is specified in the search form, it will be used to filter the queryset.""" <|body_0|> def get_context_data(self, **kwa...
stack_v2_sparse_classes_36k_train_022622
4,524
permissive
[ { "docstring": "Get queryset of all flatpages to be displayed. If a search term is specified in the search form, it will be used to filter the queryset.", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Get context data with *form* and *queryset_description* data...
2
null
Implement the Python class `PageListView` described below. Class description: View for listing all existing flatpages. Method signatures and docstrings: - def get_queryset(self): Get queryset of all flatpages to be displayed. If a search term is specified in the search form, it will be used to filter the queryset. - ...
Implement the Python class `PageListView` described below. Class description: View for listing all existing flatpages. Method signatures and docstrings: - def get_queryset(self): Get queryset of all flatpages to be displayed. If a search term is specified in the search form, it will be used to filter the queryset. - ...
5edac196f41f8cc97f8a07f7579f1041db2a02af
<|skeleton|> class PageListView: """View for listing all existing flatpages.""" def get_queryset(self): """Get queryset of all flatpages to be displayed. If a search term is specified in the search form, it will be used to filter the queryset.""" <|body_0|> def get_context_data(self, **kwa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PageListView: """View for listing all existing flatpages.""" def get_queryset(self): """Get queryset of all flatpages to be displayed. If a search term is specified in the search form, it will be used to filter the queryset.""" self.desc_ctx = {'main_filter': _('All pages'), 'title_filter...
the_stack_v2_python_sparse
src/oscar/apps/dashboard/pages/views.py
django-oscar/django-oscar
train
5,320
695cee99cf12c7c750bdd02cbb215e58afb2e2f2
[ "super().__init__()\nself.conv1 = conv3x3(inplanes, planes, stride, n_dim=n_dim)\nself.bn1 = NormNdTorch(norm_layer, n_dim, planes)\nself.relu = torch.nn.ReLU(inplace=True)\nself.conv2 = conv3x3(planes, planes, n_dim=n_dim)\nself.bn2 = NormNdTorch(norm_layer, n_dim, planes)\nself.downsample = downsample\nself.strid...
<|body_start_0|> super().__init__() self.conv1 = conv3x3(inplanes, planes, stride, n_dim=n_dim) self.bn1 = NormNdTorch(norm_layer, n_dim, planes) self.relu = torch.nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes, n_dim=n_dim) self.bn2 = NormNdTorch(norm_layer, n...
SEBasicBlockTorch
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SEBasicBlockTorch: def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): """Squeeze and Excitation Basic ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stride : ...
stack_v2_sparse_classes_36k_train_022623
8,979
permissive
[ { "docstring": "Squeeze and Excitation Basic ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stride : int or tuple stride of first convolution downsample : nn.Module downsampling in residual path norm_layer : str type of normalisation layer...
2
stack_v2_sparse_classes_30k_train_005548
Implement the Python class `SEBasicBlockTorch` described below. Class description: Implement the SEBasicBlockTorch class. Method signatures and docstrings: - def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): Squeeze and Excitation Basic ResNet block Parameters...
Implement the Python class `SEBasicBlockTorch` described below. Class description: Implement the SEBasicBlockTorch class. Method signatures and docstrings: - def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): Squeeze and Excitation Basic ResNet block Parameters...
d944aa67d319bd63a2add5cb89e8308413943de6
<|skeleton|> class SEBasicBlockTorch: def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): """Squeeze and Excitation Basic ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stride : ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SEBasicBlockTorch: def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): """Squeeze and Excitation Basic ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stride : int or tuple s...
the_stack_v2_python_sparse
deliravision/torch/models/backbones/seblocks.py
delira-dev/vision_torch
train
5
a974eccb8e1e0d44c9cfa0b1cb7e0525cab54c81
[ "if 'L' not in problem_params:\n problem_params['L'] = 1.0\nif 'init_type' not in problem_params:\n problem_params['init_type'] = 'circle'\nessential_keys = ['nvars', 'a', 'kappa', 'rest', 'thresh', 'depol', 'init_type', 'eps']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'nee...
<|body_start_0|> if 'L' not in problem_params: problem_params['L'] = 1.0 if 'init_type' not in problem_params: problem_params['init_type'] = 'circle' essential_keys = ['nvars', 'a', 'kappa', 'rest', 'thresh', 'depol', 'init_type', 'eps'] for key in essential_keys:...
Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Attributes: xvalues: grid points in space dx: mesh width lap: spectral operator for Laplacian rfft_object: planned real FFT for forward transformation irfft_object: planned IFFT for backward transformation
monodomain2d_imex
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class monodomain2d_imex: """Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Attributes: xvalues: grid points in space dx: mesh width lap: spectral operator for Laplacian rfft_object: planned real FFT for forward transformation irfft_object: planned...
stack_v2_sparse_classes_36k_train_022624
5,966
permissive
[ { "docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed to parent class) dtype_f: mesh data type wuth implicit and explicit parts (will be passed to parent class)", "name": "__init__", "signature": "def __init__(self, ...
4
stack_v2_sparse_classes_30k_train_007328
Implement the Python class `monodomain2d_imex` described below. Class description: Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Attributes: xvalues: grid points in space dx: mesh width lap: spectral operator for Laplacian rfft_object: planned real FFT for forwa...
Implement the Python class `monodomain2d_imex` described below. Class description: Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Attributes: xvalues: grid points in space dx: mesh width lap: spectral operator for Laplacian rfft_object: planned real FFT for forwa...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class monodomain2d_imex: """Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Attributes: xvalues: grid points in space dx: mesh width lap: spectral operator for Laplacian rfft_object: planned real FFT for forward transformation irfft_object: planned...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class monodomain2d_imex: """Example implementing Allen-Cahn equation in 2D using FFTs for solving linear parts, IMEX time-stepping Attributes: xvalues: grid points in space dx: mesh width lap: spectral operator for Laplacian rfft_object: planned real FFT for forward transformation irfft_object: planned IFFT for bac...
the_stack_v2_python_sparse
pySDC/playgrounds/monodomain/Monodomain.py
Parallel-in-Time/pySDC
train
30
436b7c2130f15da4555e56fce24609074419f27d
[ "self.env.cr.execute(\"\\n SELECT PRODUCT_ID, \\n SUM(SQ.QTY * SQ.WEIGHT_OBSERVED) / SUM(SQ.qty)\\n FROM STOCK_QUANT SQ\\n INNER JOIN STOCK_LOCATION SL ON SQ.LOCATION_ID = SL.ID\\n WHERE SQ.PRODUCT_ID IN %s\\n AND ...
<|body_start_0|> self.env.cr.execute("\n SELECT PRODUCT_ID, \n SUM(SQ.QTY * SQ.WEIGHT_OBSERVED) / SUM(SQ.qty)\n FROM STOCK_QUANT SQ\n INNER JOIN STOCK_LOCATION SL ON SQ.LOCATION_ID = SL.ID\n WHERE SQ.PRODUCT_ID IN %s\n ...
ProductProduct
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProductProduct: def _get_weight_observed(self): """Get the average weight of the lots in stock""" <|body_0|> def _search_weight_observed(self, operator, value): """Search for a product by average weight""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_022625
3,483
no_license
[ { "docstring": "Get the average weight of the lots in stock", "name": "_get_weight_observed", "signature": "def _get_weight_observed(self)" }, { "docstring": "Search for a product by average weight", "name": "_search_weight_observed", "signature": "def _search_weight_observed(self, opera...
2
stack_v2_sparse_classes_30k_train_014382
Implement the Python class `ProductProduct` described below. Class description: Implement the ProductProduct class. Method signatures and docstrings: - def _get_weight_observed(self): Get the average weight of the lots in stock - def _search_weight_observed(self, operator, value): Search for a product by average weig...
Implement the Python class `ProductProduct` described below. Class description: Implement the ProductProduct class. Method signatures and docstrings: - def _get_weight_observed(self): Get the average weight of the lots in stock - def _search_weight_observed(self, operator, value): Search for a product by average weig...
7e6da5d7633ec585b0869d7e6aa8c95f32e540f5
<|skeleton|> class ProductProduct: def _get_weight_observed(self): """Get the average weight of the lots in stock""" <|body_0|> def _search_weight_observed(self, operator, value): """Search for a product by average weight""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProductProduct: def _get_weight_observed(self): """Get the average weight of the lots in stock""" self.env.cr.execute("\n SELECT PRODUCT_ID, \n SUM(SQ.QTY * SQ.WEIGHT_OBSERVED) / SUM(SQ.qty)\n FROM STOCK_QUANT SQ\n INNER JOIN ...
the_stack_v2_python_sparse
stock_prodlot_weight/stock.py
numerigraphe/numerigraphe-addons
train
0
88fe0b93d6fead5379ca0b748f24e3e7ca767162
[ "if 'pix' in string_rep:\n return u.Quantity(string_rep[:-3], u.dimensionless_unscaled)\nif 'h' in string_rep or 'rad' in string_rep:\n return Angle(string_rep)\nunit = u.deg\nif len(string_rep.split('.')) >= 3:\n string_rep = string_rep.replace('.', ':', 2)\nelif string_rep.count(':') == 2:\n unit = u....
<|body_start_0|> if 'pix' in string_rep: return u.Quantity(string_rep[:-3], u.dimensionless_unscaled) if 'h' in string_rep or 'rad' in string_rep: return Angle(string_rep) unit = u.deg if len(string_rep.split('.')) >= 3: string_rep = string_rep.replace...
Helper class to structure coordinate parser.
_CRTFCoordinateParser
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _CRTFCoordinateParser: """Helper class to structure coordinate parser.""" def parse_coordinate(string_rep): """Parse a single coordinate.""" <|body_0|> def parse_angular_length_quantity(string_rep): """Parse a string into a Quantity object. Given a string that is...
stack_v2_sparse_classes_36k_train_022626
19,388
permissive
[ { "docstring": "Parse a single coordinate.", "name": "parse_coordinate", "signature": "def parse_coordinate(string_rep)" }, { "docstring": "Parse a string into a Quantity object. Given a string that is a number and a unit, return a Quantity of that string. An error is raised if there is no unit,...
2
stack_v2_sparse_classes_30k_train_015946
Implement the Python class `_CRTFCoordinateParser` described below. Class description: Helper class to structure coordinate parser. Method signatures and docstrings: - def parse_coordinate(string_rep): Parse a single coordinate. - def parse_angular_length_quantity(string_rep): Parse a string into a Quantity object. G...
Implement the Python class `_CRTFCoordinateParser` described below. Class description: Helper class to structure coordinate parser. Method signatures and docstrings: - def parse_coordinate(string_rep): Parse a single coordinate. - def parse_angular_length_quantity(string_rep): Parse a string into a Quantity object. G...
501d12d5f5879c49413e20bed90a2d3eb725d5b7
<|skeleton|> class _CRTFCoordinateParser: """Helper class to structure coordinate parser.""" def parse_coordinate(string_rep): """Parse a single coordinate.""" <|body_0|> def parse_angular_length_quantity(string_rep): """Parse a string into a Quantity object. Given a string that is...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _CRTFCoordinateParser: """Helper class to structure coordinate parser.""" def parse_coordinate(string_rep): """Parse a single coordinate.""" if 'pix' in string_rep: return u.Quantity(string_rep[:-3], u.dimensionless_unscaled) if 'h' in string_rep or 'rad' in string_rep...
the_stack_v2_python_sparse
regions/io/crtf/read.py
e-koch/regions
train
0
246312b70c575409e7e1cc458bda5ce450bb26a2
[ "self.first_idx = {}\nself.last_idx = {}\nself.key_map = {}\nself.arr = []", "if key not in self.key_map:\n self.arr.append([1, key])\n if 1 not in self.last_idx:\n self.first_idx[1] = len(self.arr) - 1\n self.last_idx[1] = len(self.arr) - 1\n self.key_map[key] = len(self.arr) - 1\nelse:\n j...
<|body_start_0|> self.first_idx = {} self.last_idx = {} self.key_map = {} self.arr = [] <|end_body_0|> <|body_start_1|> if key not in self.key_map: self.arr.append([1, key]) if 1 not in self.last_idx: self.first_idx[1] = len(self.arr) - 1 ...
AllOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void""" <|body_1|> def dec(self, key): """De...
stack_v2_sparse_classes_36k_train_022627
3,586
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void", "name": "inc", "signature": "def inc(self, key)" }, ...
5
null
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void -...
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void -...
2722c0deafcd094ce64140a9a837b4027d29ed6f
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void""" <|body_1|> def dec(self, key): """De...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllOne: def __init__(self): """Initialize your data structure here.""" self.first_idx = {} self.last_idx = {} self.key_map = {} self.arr = [] def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rt...
the_stack_v2_python_sparse
432_all_one_ds_h/main.py
chao-shi/lclc
train
0
1bbb11067df0cc8bbc821fc2c314494b163dbe65
[ "super(ProgressScene, self).__init__()\nself._page = 0\nself._num_pages = math.ceil(len(get_prize_names()) / (self.ROWS * self.COLUMNS))\nself._key_press_time = 0", "super().update(dt)\nkeys = pygame.key.get_pressed()\nif keys[pygame.K_a] and time.time() - self._key_press_time > 0.25:\n self._key_press_time = ...
<|body_start_0|> super(ProgressScene, self).__init__() self._page = 0 self._num_pages = math.ceil(len(get_prize_names()) / (self.ROWS * self.COLUMNS)) self._key_press_time = 0 <|end_body_0|> <|body_start_1|> super().update(dt) keys = pygame.key.get_pressed() if k...
ProgressScene
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProgressScene: def __init__(self): """A scene containing images of all the pokemon and their names/win count.""" <|body_0|> def update(self, dt: float): """Updates which page is currently being shown based on key presses. Args: dt (float): the time in seconds since t...
stack_v2_sparse_classes_36k_train_022628
2,910
no_license
[ { "docstring": "A scene containing images of all the pokemon and their names/win count.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Updates which page is currently being shown based on key presses. Args: dt (float): the time in seconds since the last update", "...
3
stack_v2_sparse_classes_30k_train_009432
Implement the Python class `ProgressScene` described below. Class description: Implement the ProgressScene class. Method signatures and docstrings: - def __init__(self): A scene containing images of all the pokemon and their names/win count. - def update(self, dt: float): Updates which page is currently being shown b...
Implement the Python class `ProgressScene` described below. Class description: Implement the ProgressScene class. Method signatures and docstrings: - def __init__(self): A scene containing images of all the pokemon and their names/win count. - def update(self, dt: float): Updates which page is currently being shown b...
115e2ea23e0b7aba41a90ef07d0a239314f1d6cf
<|skeleton|> class ProgressScene: def __init__(self): """A scene containing images of all the pokemon and their names/win count.""" <|body_0|> def update(self, dt: float): """Updates which page is currently being shown based on key presses. Args: dt (float): the time in seconds since t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProgressScene: def __init__(self): """A scene containing images of all the pokemon and their names/win count.""" super(ProgressScene, self).__init__() self._page = 0 self._num_pages = math.ceil(len(get_prize_names()) / (self.ROWS * self.COLUMNS)) self._key_press_time = ...
the_stack_v2_python_sparse
crane/game/scene/progress_scene/progress_scene.py
mtmk-ee/crane-game
train
0
307a1b9a0df5573e6251c96fb23efcd429de09c4
[ "def run(r):\n ld = 0\n rd = 0\n llm = 0\n rlm = 0\n lmax = 0\n if r.left:\n ld += 1\n d, llm = run(r.left)\n ld = ld + d\n if r.right:\n rd += 1\n d, rlm = run(r.right)\n rd = rd + d\n lmax = max(llm, rlm, rd + ld)\n return (rd if rd > ld else ld...
<|body_start_0|> def run(r): ld = 0 rd = 0 llm = 0 rlm = 0 lmax = 0 if r.left: ld += 1 d, llm = run(r.left) ld = ld + d if r.right: rd += 1 d, rlm =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def diameterOfBinaryTree(self, root): """:type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.""" <|body_0|> def rewrite(self, root): """:type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/r...
stack_v2_sparse_classes_36k_train_022629
2,572
no_license
[ { "docstring": ":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.", "name": "diameterOfBinaryTree", "signature": "def diameterOfBinaryTree(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/ri...
2
stack_v2_sparse_classes_30k_train_003884
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right. - def rewrite(self, root): :type root: TreeNode :r...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right. - def rewrite(self, root): :type root: TreeNode :r...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def diameterOfBinaryTree(self, root): """:type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.""" <|body_0|> def rewrite(self, root): """:type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def diameterOfBinaryTree(self, root): """:type root: TreeNode :rtype: int 1. save deepest length 2. save max diff from left/right.""" def run(r): ld = 0 rd = 0 llm = 0 rlm = 0 lmax = 0 if r.left: ...
the_stack_v2_python_sparse
tree/543_Diameter_of_Binary_Tree.py
vsdrun/lc_public
train
6
d77eeadc24dfe1ab373c5e07b7276aaa0f6dd099
[ "import sys\nself.id = sys.maxsize\nself.stack = []", "from heapq import heappush\nheappush(self.stack, (self.id, value))\nself.id -= 1", "from heapq import heappop\nif not self.stack:\n return None\n_, value = heappop(self.stack)\nreturn value" ]
<|body_start_0|> import sys self.id = sys.maxsize self.stack = [] <|end_body_0|> <|body_start_1|> from heapq import heappush heappush(self.stack, (self.id, value)) self.id -= 1 <|end_body_1|> <|body_start_2|> from heapq import heappop if not self.stack: ...
A Stack class which uses only heap.
HeapStack
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeapStack: """A Stack class which uses only heap.""" def __init__(self): """Initialize the stack.""" <|body_0|> def push(self, value): """Push the new value into the stack.""" <|body_1|> def pop(self): """Pop and return the latest value.""" ...
stack_v2_sparse_classes_36k_train_022630
1,443
no_license
[ { "docstring": "Initialize the stack.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Push the new value into the stack.", "name": "push", "signature": "def push(self, value)" }, { "docstring": "Pop and return the latest value.", "name": "pop", ...
3
null
Implement the Python class `HeapStack` described below. Class description: A Stack class which uses only heap. Method signatures and docstrings: - def __init__(self): Initialize the stack. - def push(self, value): Push the new value into the stack. - def pop(self): Pop and return the latest value.
Implement the Python class `HeapStack` described below. Class description: A Stack class which uses only heap. Method signatures and docstrings: - def __init__(self): Initialize the stack. - def push(self, value): Push the new value into the stack. - def pop(self): Pop and return the latest value. <|skeleton|> class...
97eae3ee806756f4d646d600f434b1e68164ad34
<|skeleton|> class HeapStack: """A Stack class which uses only heap.""" def __init__(self): """Initialize the stack.""" <|body_0|> def push(self, value): """Push the new value into the stack.""" <|body_1|> def pop(self): """Pop and return the latest value.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HeapStack: """A Stack class which uses only heap.""" def __init__(self): """Initialize the stack.""" import sys self.id = sys.maxsize self.stack = [] def push(self, value): """Push the new value into the stack.""" from heapq import heappush hea...
the_stack_v2_python_sparse
Python/2019_06_18_Problem_154_Heap_Stack.py
BaoCaiH/Daily_Coding_Problem
train
0
e695309e3f9cae0742a156d2e5db31988f7cb7df
[ "super(LambertSampler, self).__init__()\nself.parent = parent\nself.origin = origin\nself.radius = np.float32(radius)\nself.local_work_size = local_work_size\nself.no_points_required = np.ceil(tau * radius / required_resolution)\nself.density = 2 * root_2 / self.no_points_required\nself.N = len(np.arange(-1, 1, sel...
<|body_start_0|> super(LambertSampler, self).__init__() self.parent = parent self.origin = origin self.radius = np.float32(radius) self.local_work_size = local_work_size self.no_points_required = np.ceil(tau * radius / required_resolution) self.density = 2 * root_...
This is the lambert sampling grid class. It takes the specification for a lambert sampling array and then samples the acoustic field at these points.
LambertSampler
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LambertSampler: """This is the lambert sampling grid class. It takes the specification for a lambert sampling array and then samples the acoustic field at these points.""" def __init__(self, parent=None, origin=np.array((0, 0, 0)), required_resolution=0.012, radius=0.05, local_work_size=(1, ...
stack_v2_sparse_classes_36k_train_022631
3,772
permissive
[ { "docstring": "This method intialises an instance of the LambertSampler class. Parameters ---------- parent : handybeam.world.World This is an instance of the handybeam world class. origin : numpy array This is a vector specifying the origin of the sampling grid. required_resolution : float This specifies the ...
2
stack_v2_sparse_classes_30k_train_009332
Implement the Python class `LambertSampler` described below. Class description: This is the lambert sampling grid class. It takes the specification for a lambert sampling array and then samples the acoustic field at these points. Method signatures and docstrings: - def __init__(self, parent=None, origin=np.array((0, ...
Implement the Python class `LambertSampler` described below. Class description: This is the lambert sampling grid class. It takes the specification for a lambert sampling array and then samples the acoustic field at these points. Method signatures and docstrings: - def __init__(self, parent=None, origin=np.array((0, ...
9f80b97742cde4b75d3478d554dc9bc2cd9dfd96
<|skeleton|> class LambertSampler: """This is the lambert sampling grid class. It takes the specification for a lambert sampling array and then samples the acoustic field at these points.""" def __init__(self, parent=None, origin=np.array((0, 0, 0)), required_resolution=0.012, radius=0.05, local_work_size=(1, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LambertSampler: """This is the lambert sampling grid class. It takes the specification for a lambert sampling array and then samples the acoustic field at these points.""" def __init__(self, parent=None, origin=np.array((0, 0, 0)), required_resolution=0.012, radius=0.05, local_work_size=(1, 1, 1)): ...
the_stack_v2_python_sparse
handybeam/samplers/lambert_sampler.py
hewhocannotbetamed/HandyBeam
train
0
b52c46bfc3dbf639cc3487464d824ed88b70efb2
[ "w = WindowTitle(None, new_title='some title')\nyield w\nw.close()", "widget.show()\nassert isinstance(widget, QtWidgets.QDialog)\nassert widget.windowTitle() == 'Modify Window Title'", "widget.show()\nQtWidgets.qApp.processEvents()\nassert widget.txtTitle.text() == 'some title'\nwidget.txtTitle.clear()\nwidget...
<|body_start_0|> w = WindowTitle(None, new_title='some title') yield w w.close() <|end_body_0|> <|body_start_1|> widget.show() assert isinstance(widget, QtWidgets.QDialog) assert widget.windowTitle() == 'Modify Window Title' <|end_body_1|> <|body_start_2|> widge...
Test the WindowTitle
WindowTitleTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowTitleTest: """Test the WindowTitle""" def widget(self, qapp): """Create/Destroy the WindowTitle""" <|body_0|> def testDefaults(self, widget): """Test the GUI in its default state""" <|body_1|> def testTitle(self, widget): """Modify the ...
stack_v2_sparse_classes_36k_train_022632
1,130
permissive
[ { "docstring": "Create/Destroy the WindowTitle", "name": "widget", "signature": "def widget(self, qapp)" }, { "docstring": "Test the GUI in its default state", "name": "testDefaults", "signature": "def testDefaults(self, widget)" }, { "docstring": "Modify the title", "name": ...
3
null
Implement the Python class `WindowTitleTest` described below. Class description: Test the WindowTitle Method signatures and docstrings: - def widget(self, qapp): Create/Destroy the WindowTitle - def testDefaults(self, widget): Test the GUI in its default state - def testTitle(self, widget): Modify the title
Implement the Python class `WindowTitleTest` described below. Class description: Test the WindowTitle Method signatures and docstrings: - def widget(self, qapp): Create/Destroy the WindowTitle - def testDefaults(self, widget): Test the GUI in its default state - def testTitle(self, widget): Modify the title <|skelet...
55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7
<|skeleton|> class WindowTitleTest: """Test the WindowTitle""" def widget(self, qapp): """Create/Destroy the WindowTitle""" <|body_0|> def testDefaults(self, widget): """Test the GUI in its default state""" <|body_1|> def testTitle(self, widget): """Modify the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WindowTitleTest: """Test the WindowTitle""" def widget(self, qapp): """Create/Destroy the WindowTitle""" w = WindowTitle(None, new_title='some title') yield w w.close() def testDefaults(self, widget): """Test the GUI in its default state""" widget.show...
the_stack_v2_python_sparse
src/sas/qtgui/Plotting/UnitTesting/WindowTitleTest.py
SasView/sasview
train
48
4700e916244e8e5a02d52cb74f76c2969f2b2dac
[ "self.indexType = indexType\nself.requirementsModelLoader = requirementsModelLoader\nself.dictionary = self.__buildIndex(self.requirementsModelLoader)", "for modelKey in modelKeys:\n if not dictionary.has_key(modelKey):\n l = list()\n l.append(modelInfo)\n dictionary[modelKey] = l\n els...
<|body_start_0|> self.indexType = indexType self.requirementsModelLoader = requirementsModelLoader self.dictionary = self.__buildIndex(self.requirementsModelLoader) <|end_body_0|> <|body_start_1|> for modelKey in modelKeys: if not dictionary.has_key(modelKey): ...
This class is an inverted index for RequiremensModels. Given a keyword, returns all the RequirementsModels that contain the keyword. Currently, the index stores all the models
ModelIndex
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelIndex: """This class is an inverted index for RequiremensModels. Given a keyword, returns all the RequirementsModels that contain the keyword. Currently, the index stores all the models""" def __init__(self, requirementsModelLoader, indexType=STEM_STRING): """Constructor. @param...
stack_v2_sparse_classes_36k_train_022633
2,434
no_license
[ { "docstring": "Constructor. @param requirementsModelLoader: classes that stores all the models in memory", "name": "__init__", "signature": "def __init__(self, requirementsModelLoader, indexType=STEM_STRING)" }, { "docstring": "This function adds a model to a dictionary @param modelInfo: object...
4
stack_v2_sparse_classes_30k_train_003259
Implement the Python class `ModelIndex` described below. Class description: This class is an inverted index for RequiremensModels. Given a keyword, returns all the RequirementsModels that contain the keyword. Currently, the index stores all the models Method signatures and docstrings: - def __init__(self, requirement...
Implement the Python class `ModelIndex` described below. Class description: This class is an inverted index for RequiremensModels. Given a keyword, returns all the RequirementsModels that contain the keyword. Currently, the index stores all the models Method signatures and docstrings: - def __init__(self, requirement...
7e6a6adced8e3d1b237f52159afbd16a13cd6aad
<|skeleton|> class ModelIndex: """This class is an inverted index for RequiremensModels. Given a keyword, returns all the RequirementsModels that contain the keyword. Currently, the index stores all the models""" def __init__(self, requirementsModelLoader, indexType=STEM_STRING): """Constructor. @param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelIndex: """This class is an inverted index for RequiremensModels. Given a keyword, returns all the RequirementsModels that contain the keyword. Currently, the index stores all the models""" def __init__(self, requirementsModelLoader, indexType=STEM_STRING): """Constructor. @param requirements...
the_stack_v2_python_sparse
tram/ModelIndex.py
alessioferrari/tram
train
0
ed814db88ac74f0fee1cfefd424227482c925f97
[ "self.n_samples = 1000\nself.n_features = 4\nself.forest = []", "for _ in range(self.n_samples):\n k_indices = np.random.choice(len(col_names) - 1, self.n_features, replace=False)\n tree = DecisionTree(feat_indices=k_indices)\n tree.fit(col_names, rows)\n self.forest.append(tree)", "label_vote = dic...
<|body_start_0|> self.n_samples = 1000 self.n_features = 4 self.forest = [] <|end_body_0|> <|body_start_1|> for _ in range(self.n_samples): k_indices = np.random.choice(len(col_names) - 1, self.n_features, replace=False) tree = DecisionTree(feat_indices=k_indices...
RandomForest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomForest: def __init__(self, n_samples=1000, n_features=4): """Construct a random forest using decision tree There are couple missing features for this implementation. - Minimum sample split - Minimum sample leaf - Minimum purity increase - Maximum leaf nodes - Maximum depth Args: n_...
stack_v2_sparse_classes_36k_train_022634
1,740
no_license
[ { "docstring": "Construct a random forest using decision tree There are couple missing features for this implementation. - Minimum sample split - Minimum sample leaf - Minimum purity increase - Maximum leaf nodes - Maximum depth Args: n_samples (int): Number of decision tree in the forest n_features (int): Numb...
3
stack_v2_sparse_classes_30k_train_010301
Implement the Python class `RandomForest` described below. Class description: Implement the RandomForest class. Method signatures and docstrings: - def __init__(self, n_samples=1000, n_features=4): Construct a random forest using decision tree There are couple missing features for this implementation. - Minimum sampl...
Implement the Python class `RandomForest` described below. Class description: Implement the RandomForest class. Method signatures and docstrings: - def __init__(self, n_samples=1000, n_features=4): Construct a random forest using decision tree There are couple missing features for this implementation. - Minimum sampl...
7da789ef34d5e5bcf9033cfbe0ff5df607b2437a
<|skeleton|> class RandomForest: def __init__(self, n_samples=1000, n_features=4): """Construct a random forest using decision tree There are couple missing features for this implementation. - Minimum sample split - Minimum sample leaf - Minimum purity increase - Maximum leaf nodes - Maximum depth Args: n_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomForest: def __init__(self, n_samples=1000, n_features=4): """Construct a random forest using decision tree There are couple missing features for this implementation. - Minimum sample split - Minimum sample leaf - Minimum purity increase - Maximum leaf nodes - Maximum depth Args: n_samples (int):...
the_stack_v2_python_sparse
random_forest/forest/random_forest.py
calvinfeng/machine-learning-notebook
train
38
e586d4fa8b815942078d576ab2fc68423d8082c3
[ "if safe:\n endpoint = SAFE_BOORU_ENDPOINT\n provider = SAFE_BOORU_PROVIDER\n banned_tags = SAFE_TAGS_BANNED\nelse:\n endpoint = NSFW_BOORU_ENDPOINT\n provider = NSFW_BOORU_PROVIDER\n banned_tags = NSFW_TAGS_BANNED\nhandler = ImageHandlerBooru(provider, endpoint, None, banned_tags, requested_tags,...
<|body_start_0|> if safe: endpoint = SAFE_BOORU_ENDPOINT provider = SAFE_BOORU_PROVIDER banned_tags = SAFE_TAGS_BANNED else: endpoint = NSFW_BOORU_ENDPOINT provider = NSFW_BOORU_PROVIDER banned_tags = NSFW_TAGS_BANNED handle...
Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.
ImageCache
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageCache: """Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.""" def __new_...
stack_v2_sparse_classes_36k_train_022635
9,784
no_license
[ { "docstring": "Creates a new image cache for booru commands. Parameters ---------- requested_tags : `set` of `str` The requested tags. safe : `bool` Whether we want safe images.", "name": "__new__", "signature": "def __new__(cls, requested_tags, safe)" }, { "docstring": "Invokes the booru cache...
4
stack_v2_sparse_classes_30k_train_020167
Implement the Python class `ImageCache` described below. Class description: Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the ...
Implement the Python class `ImageCache` described below. Class description: Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the ...
74f92b598e86606ea3a269311316cddd84a5215f
<|skeleton|> class ImageCache: """Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.""" def __new_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageCache: """Booru image cache. Attributes ---------- cache_id : `int` The identifier of the cache. handler : ``ImageHandlerBooru`` Handler used to request images. last : `None`, ``ImageDetail`` The last show image detail. last_call : `float` When was the handler last called.""" def __new__(cls, reques...
the_stack_v2_python_sparse
koishi/plugins/image_handling_commands/booru/booru.py
HuyaneMatsu/Koishi
train
17
7b4903ac31d8027239fcd817bfbe38c55c2da475
[ "self.configeditor = configeditor\nself.store = gtk.ListStore(str, int)\ngtk.TreeView.__init__(self, self.store)\nrenderer = gtk.CellRendererText()\ncolumn = gtk.TreeViewColumn('Name', renderer, markup=0)\nself.append_column(column)\nself.set_headers_visible(False)\nself.connect('cursor-changed', self.cb_select)", ...
<|body_start_0|> self.configeditor = configeditor self.store = gtk.ListStore(str, int) gtk.TreeView.__init__(self, self.store) renderer = gtk.CellRendererText() column = gtk.TreeViewColumn('Name', renderer, markup=0) self.append_column(column) self.set_headers_vis...
A treeview control for switching a notebook's tabs.
listtree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class listtree: """A treeview control for switching a notebook's tabs.""" def __init__(self, configeditor): """Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type config...
stack_v2_sparse_classes_36k_train_022636
15,303
no_license
[ { "docstring": "Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type configeditor: pida.config.ConfigEditor", "name": "__init__", "signature": "def __init__(self, configeditor)" }, ...
3
null
Implement the Python class `listtree` described below. Class description: A treeview control for switching a notebook's tabs. Method signatures and docstrings: - def __init__(self, configeditor): Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The con...
Implement the Python class `listtree` described below. Class description: A treeview control for switching a notebook's tabs. Method signatures and docstrings: - def __init__(self, configeditor): Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The con...
739147ed21a23cab23c2bba98f1c54108f8c2516
<|skeleton|> class listtree: """A treeview control for switching a notebook's tabs.""" def __init__(self, configeditor): """Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type config...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class listtree: """A treeview control for switching a notebook's tabs.""" def __init__(self, configeditor): """Constructor. @param cb: An instance of the application class. @type cb: pida.main.Application @param configeditor: The configuration editor that the list is used for. @type configeditor: pida....
the_stack_v2_python_sparse
branches/model-config/pida/pidagtk/registrywidgets.py
BackupTheBerlios/pida-svn
train
1
bf41c967b967706fb6036d15e571318c69bd34ae
[ "if 'QI' not in params:\n params['QI'] = 'IE'\nif 'QE' not in params:\n params['QE'] = 'EE'\nsuper(verlet, self).__init__(params)\n[self.QT, self.Qx, self.QQ] = self.__get_Qd()\nself.qQ = np.dot(self.coll.weights, self.coll.Qmat[1:, 1:])", "QI = self.get_Qdelta_implicit(self.coll, self.params.QI)\nQE = self...
<|body_start_0|> if 'QI' not in params: params['QI'] = 'IE' if 'QE' not in params: params['QE'] = 'EE' super(verlet, self).__init__(params) [self.QT, self.Qx, self.QQ] = self.__get_Qd() self.qQ = np.dot(self.coll.weights, self.coll.Qmat[1:, 1:]) <|end_body...
Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ: 0-to-node collocation matrix (second order) QT: 0-to-node trapezoidal matrix Qx: 0-to-node Euler half-step for position update qQ: update rule for final value (if needed)
verlet
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class verlet: """Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ: 0-to-node collocation matrix (second order) QT: 0-to-node trapezoidal matrix Qx: 0-to-node Euler half-step for position update qQ: update rule for final value (if n...
stack_v2_sparse_classes_36k_train_022637
7,247
permissive
[ { "docstring": "Initialization routine for the custom sweeper Args: params: parameters for the sweeper", "name": "__init__", "signature": "def __init__(self, params)" }, { "docstring": "Get integration matrices for 2nd-order SDC Returns: S: node-to-node collocation matrix (first order) SQ: node-...
5
stack_v2_sparse_classes_30k_train_009117
Implement the Python class `verlet` described below. Class description: Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ: 0-to-node collocation matrix (second order) QT: 0-to-node trapezoidal matrix Qx: 0-to-node Euler half-step for position updat...
Implement the Python class `verlet` described below. Class description: Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ: 0-to-node collocation matrix (second order) QT: 0-to-node trapezoidal matrix Qx: 0-to-node Euler half-step for position updat...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class verlet: """Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ: 0-to-node collocation matrix (second order) QT: 0-to-node trapezoidal matrix Qx: 0-to-node Euler half-step for position update qQ: update rule for final value (if n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class verlet: """Custom sweeper class, implements Sweeper.py Second-order sweeper using velocity-Verlet as base integrator Attributes: QQ: 0-to-node collocation matrix (second order) QT: 0-to-node trapezoidal matrix Qx: 0-to-node Euler half-step for position update qQ: update rule for final value (if needed)""" ...
the_stack_v2_python_sparse
pySDC/implementations/sweeper_classes/verlet.py
Parallel-in-Time/pySDC
train
30
57fe1ef3247ddcbbd3274545bc56ae87e89f04fd
[ "super().validate(data)\nhandle_invalid_fields(self, data)\nreturn data", "dh = DateHelper()\nif value >= materialized_view_month_start(dh).date() and value <= dh.today.date():\n return value\nerror = 'Parameter start_date must be from {} to {}'.format(dh.last_month_start.date(), dh.today.date())\nraise serial...
<|body_start_0|> super().validate(data) handle_invalid_fields(self, data) return data <|end_body_0|> <|body_start_1|> dh = DateHelper() if value >= materialized_view_month_start(dh).date() and value <= dh.today.date(): return value error = 'Parameter start_da...
Serializer for handling query parameters.
TagsQueryParamSerializer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagsQueryParamSerializer: """Serializer for handling query parameters.""" def validate(self, data): """Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_022638
11,000
permissive
[ { "docstring": "Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid", "name": "validate", "signature": "def validate(self, data)" }, { "docstring": "Validate that the start_date is within the expec...
3
stack_v2_sparse_classes_30k_train_017011
Implement the Python class `TagsQueryParamSerializer` described below. Class description: Serializer for handling query parameters. Method signatures and docstrings: - def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): i...
Implement the Python class `TagsQueryParamSerializer` described below. Class description: Serializer for handling query parameters. Method signatures and docstrings: - def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): i...
2979f03fbdd1c20c3abc365a963a1282b426f321
<|skeleton|> class TagsQueryParamSerializer: """Serializer for handling query parameters.""" def validate(self, data): """Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TagsQueryParamSerializer: """Serializer for handling query parameters.""" def validate(self, data): """Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid""" super().validate(data) h...
the_stack_v2_python_sparse
koku/api/tags/serializers.py
luisfdez/koku
train
0
29a1184fa0a47b1bf31e810232f41e76866cfb1d
[ "if not root:\n return 0\nreturn self.subroutine(root, 0)", "if not node:\n return depth\nreturn max(self.subroutine(node.left, depth + 1), self.subroutine(node.right, depth + 1))" ]
<|body_start_0|> if not root: return 0 return self.subroutine(root, 0) <|end_body_0|> <|body_start_1|> if not node: return depth return max(self.subroutine(node.left, depth + 1), self.subroutine(node.right, depth + 1)) <|end_body_1|>
Leet104
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Leet104: def max_depth(self, root): """Finds the max depth of a binary tree. Args: root -- TreeNode Returns: The max depth of a binary tree.""" <|body_0|> def subroutine(self, node, depth): """Find the max depth of two subtrees of a node. Args: node -- TreeNode max_d...
stack_v2_sparse_classes_36k_train_022639
1,033
no_license
[ { "docstring": "Finds the max depth of a binary tree. Args: root -- TreeNode Returns: The max depth of a binary tree.", "name": "max_depth", "signature": "def max_depth(self, root)" }, { "docstring": "Find the max depth of two subtrees of a node. Args: node -- TreeNode max_depth -- keeps track o...
2
stack_v2_sparse_classes_30k_train_014107
Implement the Python class `Leet104` described below. Class description: Implement the Leet104 class. Method signatures and docstrings: - def max_depth(self, root): Finds the max depth of a binary tree. Args: root -- TreeNode Returns: The max depth of a binary tree. - def subroutine(self, node, depth): Find the max d...
Implement the Python class `Leet104` described below. Class description: Implement the Leet104 class. Method signatures and docstrings: - def max_depth(self, root): Finds the max depth of a binary tree. Args: root -- TreeNode Returns: The max depth of a binary tree. - def subroutine(self, node, depth): Find the max d...
b0cfcfa1eff0101cf8e0e3fb9db55fb83f566f6f
<|skeleton|> class Leet104: def max_depth(self, root): """Finds the max depth of a binary tree. Args: root -- TreeNode Returns: The max depth of a binary tree.""" <|body_0|> def subroutine(self, node, depth): """Find the max depth of two subtrees of a node. Args: node -- TreeNode max_d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Leet104: def max_depth(self, root): """Finds the max depth of a binary tree. Args: root -- TreeNode Returns: The max depth of a binary tree.""" if not root: return 0 return self.subroutine(root, 0) def subroutine(self, node, depth): """Find the max depth of two...
the_stack_v2_python_sparse
archive/algorithms-leetcode/leet104.py
riehseun/software-engineering
train
0
2227e9440eb907bf5c3d030f5dea08c7e806051c
[ "pre = None\nresult = 0\nfor cur in prices:\n if pre is None:\n pre = cur\n continue\n if cur > pre:\n result += cur - pre\n pre = cur\nreturn result", "res = 0\nfor i in range(1, len(prices)):\n res += max(prices[i] - prices[i - 1], 0)\nreturn res" ]
<|body_start_0|> pre = None result = 0 for cur in prices: if pre is None: pre = cur continue if cur > pre: result += cur - pre pre = cur return result <|end_body_0|> <|body_start_1|> res = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit1(self, prices): """贪心算法: 方法1""" <|body_0|> def maxProfit(self, prices): """贪心算法: 方法2""" <|body_1|> <|end_skeleton|> <|body_start_0|> pre = None result = 0 for cur in prices: if pre is None: ...
stack_v2_sparse_classes_36k_train_022640
701
no_license
[ { "docstring": "贪心算法: 方法1", "name": "maxProfit1", "signature": "def maxProfit1(self, prices)" }, { "docstring": "贪心算法: 方法2", "name": "maxProfit", "signature": "def maxProfit(self, prices)" } ]
2
stack_v2_sparse_classes_30k_train_006903
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices): 贪心算法: 方法1 - def maxProfit(self, prices): 贪心算法: 方法2
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices): 贪心算法: 方法1 - def maxProfit(self, prices): 贪心算法: 方法2 <|skeleton|> class Solution: def maxProfit1(self, prices): """贪心算法: 方法1""" ...
2acf8468c2e3454b9685b214e25617c98d55b3bc
<|skeleton|> class Solution: def maxProfit1(self, prices): """贪心算法: 方法1""" <|body_0|> def maxProfit(self, prices): """贪心算法: 方法2""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit1(self, prices): """贪心算法: 方法1""" pre = None result = 0 for cur in prices: if pre is None: pre = cur continue if cur > pre: result += cur - pre pre = cur return res...
the_stack_v2_python_sparse
122_best-time-to-buy-and-sell-stock-ii.py
linxuedong/leetcode
train
0
c8139875b737aa6b776a36d2c056ddf6f4ea052a
[ "self.v1 = v1\nself.v2 = v2\nself.lenv1 = len(v1)\nself.lenv2 = len(v2)\nself.min2len = 2 * min(len(v1), len(v2))\nself.alllen = len(v1) + len(v2)\nself.cnt = 0\nself.pos = 0\nif len(v1) > len(v2):\n self.remainlist = v1[len(v2):len(v1)]\nelse:\n self.remainlist = v2[len(v1):len(v2)]\nself.remaincnt = 0", "...
<|body_start_0|> self.v1 = v1 self.v2 = v2 self.lenv1 = len(v1) self.lenv2 = len(v2) self.min2len = 2 * min(len(v1), len(v2)) self.alllen = len(v1) + len(v2) self.cnt = 0 self.pos = 0 if len(v1) > len(v2): self.remainlist = v1[len(v2):l...
ZigzagIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end...
stack_v2_sparse_classes_36k_train_022641
1,340
no_license
[ { "docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]", "name": "__init__", "signature": "def __init__(self, v1, v2)" }, { "docstring": ":rtype: int", "name": "next", "signature": "def next(self)" }, { "docstring": ":rtype: bool", "name"...
3
stack_v2_sparse_classes_30k_val_001177
Implement the Python class `ZigzagIterator` described below. Class description: Implement the ZigzagIterator class. Method signatures and docstrings: - def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int] - def next(self): :rtype: int - def hasNext(self): :rtype: bo...
Implement the Python class `ZigzagIterator` described below. Class description: Implement the ZigzagIterator class. Method signatures and docstrings: - def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int] - def next(self): :rtype: int - def hasNext(self): :rtype: bo...
cd0341341a0216ac39850727804411e4cf5e4a67
<|skeleton|> class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" <|body_0|> def next(self): """:rtype: int""" <|body_1|> def hasNext(self): """:rtype: bool""" <|body_2|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ZigzagIterator: def __init__(self, v1, v2): """Initialize your data structure here. :type v1: List[int] :type v2: List[int]""" self.v1 = v1 self.v2 = v2 self.lenv1 = len(v1) self.lenv2 = len(v2) self.min2len = 2 * min(len(v1), len(v2)) self.alllen = len(...
the_stack_v2_python_sparse
281. Zigzag Iterator_google.py
cclain/LeetCode-Problem-Solution
train
0
b974f0025d7f1568013cc02a97d1d167c365b19d
[ "super().setUp()\nguild = Guild(12345)\nself.db.session.add(guild)\nself.db.session.add(Event(guild, 'One', datetime(2020, 10, 10, 10, 0, tzinfo=utc)))\nself.db.session.add(Event(guild, 'Two', datetime(2020, 10, 10, 11, 0, tzinfo=utc), repetition=EventRepetitionFrequency.weekly))\nself.db.session.commit()", "with...
<|body_start_0|> super().setUp() guild = Guild(12345) self.db.session.add(guild) self.db.session.add(Event(guild, 'One', datetime(2020, 10, 10, 10, 0, tzinfo=utc))) self.db.session.add(Event(guild, 'Two', datetime(2020, 10, 10, 11, 0, tzinfo=utc), repetition=EventRepetitionFreque...
TestEventControllers
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestEventControllers: def setUp(self): """Add some stuff in the database.""" <|body_0|> def test_get_all_events(self): """Ensure we return all events in the database.""" <|body_1|> def test_get_event(self): """Ensure we can retrieve a single even...
stack_v2_sparse_classes_36k_train_022642
3,578
permissive
[ { "docstring": "Add some stuff in the database.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Ensure we return all events in the database.", "name": "test_get_all_events", "signature": "def test_get_all_events(self)" }, { "docstring": "Ensure we can retriev...
6
stack_v2_sparse_classes_30k_train_004692
Implement the Python class `TestEventControllers` described below. Class description: Implement the TestEventControllers class. Method signatures and docstrings: - def setUp(self): Add some stuff in the database. - def test_get_all_events(self): Ensure we return all events in the database. - def test_get_event(self):...
Implement the Python class `TestEventControllers` described below. Class description: Implement the TestEventControllers class. Method signatures and docstrings: - def setUp(self): Add some stuff in the database. - def test_get_all_events(self): Ensure we return all events in the database. - def test_get_event(self):...
709dd307b046158ddf9e49a559852d486168a94f
<|skeleton|> class TestEventControllers: def setUp(self): """Add some stuff in the database.""" <|body_0|> def test_get_all_events(self): """Ensure we return all events in the database.""" <|body_1|> def test_get_event(self): """Ensure we can retrieve a single even...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestEventControllers: def setUp(self): """Add some stuff in the database.""" super().setUp() guild = Guild(12345) self.db.session.add(guild) self.db.session.add(Event(guild, 'One', datetime(2020, 10, 10, 10, 0, tzinfo=utc))) self.db.session.add(Event(guild, 'Two...
the_stack_v2_python_sparse
api/mod_event/controllers_test.py
FunkySayu/discord-event-manager
train
6
b81375fe3db43aa96fbfda9dabd194cb53df4a26
[ "self.level_vectors = level_vectors\nself.labels = labels\nself.pairs_df = pairs_df", "scores = []\nfor left in range(251):\n if left in self.labels:\n for right in range(left, 251):\n if right in self.labels:\n scores.append(self.compare_vectors(left, right, weights))\nscores_...
<|body_start_0|> self.level_vectors = level_vectors self.labels = labels self.pairs_df = pairs_df <|end_body_0|> <|body_start_1|> scores = [] for left in range(251): if left in self.labels: for right in range(left, 251): if right i...
Comparator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Comparator: def __init__(self, level_vectors, labels, pairs_df): """Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed ...
stack_v2_sparse_classes_36k_train_022643
4,868
permissive
[ { "docstring": "Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed vectors pairs_df: dataframe containing pair indices and respective mean scor...
5
stack_v2_sparse_classes_30k_train_005846
Implement the Python class `Comparator` described below. Class description: Implement the Comparator class. Method signatures and docstrings: - def __init__(self, level_vectors, labels, pairs_df): Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing den...
Implement the Python class `Comparator` described below. Class description: Implement the Comparator class. Method signatures and docstrings: - def __init__(self, level_vectors, labels, pairs_df): Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing den...
cc9b28b8741b41bea1273c8bc9b4d265d79a1dca
<|skeleton|> class Comparator: def __init__(self, level_vectors, labels, pairs_df): """Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Comparator: def __init__(self, level_vectors, labels, pairs_df): """Class for comparing all the vectors and generating similarity scores for them Args: level_vectors: ndarray containing dense vector representations of all levels labels: ndarray containing labels for respectively indexed vectors pairs_...
the_stack_v2_python_sparse
autoencoder/comparator.py
xingchen1106/match3-level-similarity
train
0
2ecd069a7b89a039219c0bb12bf8ebe2f8609a00
[ "if not prices:\n return 0\nprofit = [[[0 for _ in range(2)] for _ in range(3)] for _ in range(len(prices))]\nprofit[0][0][0], profit[0][0][1] = (0, -prices[0])\nprofit[0][1][0], profit[0][1][1] = (float('-inf'), float('-inf'))\nprofit[0][2][0], profit[0][2][1] = (float('-inf'), float('-inf'))\nn = len(prices)\n...
<|body_start_0|> if not prices: return 0 profit = [[[0 for _ in range(2)] for _ in range(3)] for _ in range(len(prices))] profit[0][0][0], profit[0][0][1] = (0, -prices[0]) profit[0][1][0], profit[0][1][1] = (float('-inf'), float('-inf')) profit[0][2][0], profit[0][2]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit2(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not prices: return 0 ...
stack_v2_sparse_classes_36k_train_022644
2,024
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" }, { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit2", "signature": "def maxProfit2(self, prices)" } ]
2
stack_v2_sparse_classes_30k_test_001119
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit2(self, prices): :type prices: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit2(self, prices): :type prices: List[int] :rtype: int <|skeleton|> class Solution: def maxPro...
5450beff0115e74bd7ecaa5edb076e942fe4f046
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit2(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" if not prices: return 0 profit = [[[0 for _ in range(2)] for _ in range(3)] for _ in range(len(prices))] profit[0][0][0], profit[0][0][1] = (0, -prices[0]) profit[0][1][0], prof...
the_stack_v2_python_sparse
src/best_time_to_buy_and_sell_stock_III_123.py
reflectc/leetcode_program
train
2
5d086bdd865702d2cceaee5b021e15d31c8104fb
[ "self.initLen = 1000000\nself.dic = [-1] * self.initLen\nself.used = 0", "i = hash(key) % self.initLen\nif self.dic[i] == -1:\n self.dic[i] = key\nelse:\n while self.dic[i] != key and self.dic[i] != -1:\n i = hash(i) % self.initLen\n self.dic[i] = key\nself.used += 1\nif self.used >= self.initLen ...
<|body_start_0|> self.initLen = 1000000 self.dic = [-1] * self.initLen self.used = 0 <|end_body_0|> <|body_start_1|> i = hash(key) % self.initLen if self.dic[i] == -1: self.dic[i] = key else: while self.dic[i] != key and self.dic[i] != -1: ...
MyHashSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyHashSet: def __init__(self): """Initialize your data structure here.""" <|body_0|> def add(self, key): """:type key: int :rtype: void""" <|body_1|> def remove(self, key): """:type key: int :rtype: void""" <|body_2|> def contains(se...
stack_v2_sparse_classes_36k_train_022645
1,770
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ":type key: int :rtype: void", "name": "add", "signature": "def add(self, key)" }, { "docstring": ":type key: int :rtype: void", "name": "remove", ...
4
stack_v2_sparse_classes_30k_test_000375
Implement the Python class `MyHashSet` described below. Class description: Implement the MyHashSet class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def add(self, key): :type key: int :rtype: void - def remove(self, key): :type key: int :rtype: void - def contains(s...
Implement the Python class `MyHashSet` described below. Class description: Implement the MyHashSet class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def add(self, key): :type key: int :rtype: void - def remove(self, key): :type key: int :rtype: void - def contains(s...
e16702d2b3ec4e5054baad56f4320bc3b31676ad
<|skeleton|> class MyHashSet: def __init__(self): """Initialize your data structure here.""" <|body_0|> def add(self, key): """:type key: int :rtype: void""" <|body_1|> def remove(self, key): """:type key: int :rtype: void""" <|body_2|> def contains(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyHashSet: def __init__(self): """Initialize your data structure here.""" self.initLen = 1000000 self.dic = [-1] * self.initLen self.used = 0 def add(self, key): """:type key: int :rtype: void""" i = hash(key) % self.initLen if self.dic[i] == -1: ...
the_stack_v2_python_sparse
leetcode/medium/Design_a_hashset.py
SuperMartinYang/learning_algorithm
train
0
26f1b91faa9f85f22214419e9e526798dee252e7
[ "cache = {}\n\ndef dfs(n, rpl):\n if n in cache:\n return cache[n]\n if n == 1:\n return rpl\n if n & 1:\n temp = 1 + min(dfs(n + 1, rpl), dfs(n - 1, rpl))\n else:\n temp = 1 + dfs(n // 2, rpl)\n cache[n] = temp\n return temp\nreturn dfs(n, 0)", "res = 0\nwhile n > 1:...
<|body_start_0|> cache = {} def dfs(n, rpl): if n in cache: return cache[n] if n == 1: return rpl if n & 1: temp = 1 + min(dfs(n + 1, rpl), dfs(n - 1, rpl)) else: temp = 1 + dfs(n // 2, rpl) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def integerReplacement(self, n): """:type n: int :rtype: int""" <|body_0|> def integerReplacement2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> cache = {} def dfs(n, rpl): if n ...
stack_v2_sparse_classes_36k_train_022646
899
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "integerReplacement", "signature": "def integerReplacement(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "integerReplacement2", "signature": "def integerReplacement2(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_010577
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerReplacement(self, n): :type n: int :rtype: int - def integerReplacement2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def integerReplacement(self, n): :type n: int :rtype: int - def integerReplacement2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def integerReplacement(s...
dbdb227e12f329e4ca064b338f1fbdca42f3a848
<|skeleton|> class Solution: def integerReplacement(self, n): """:type n: int :rtype: int""" <|body_0|> def integerReplacement2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def integerReplacement(self, n): """:type n: int :rtype: int""" cache = {} def dfs(n, rpl): if n in cache: return cache[n] if n == 1: return rpl if n & 1: temp = 1 + min(dfs(n + 1, rpl), dfs(...
the_stack_v2_python_sparse
LC397.py
Qiao-Liang/LeetCode
train
0
2e9e3da49d7f45b6f3afcb6cf5d89e354bd19553
[ "response = self.client.get('/')\nself.assertEqual(response.status_code, 200)\nocsp = OCSPResponse.load(response.content)\nself.assertEqual(ocsp.native['response_status'], 'malformed_request')", "response = self.client.get('/something')\nself.assertEqual(response.status_code, 200)\nocsp = OCSPResponse.load(respon...
<|body_start_0|> response = self.client.get('/') self.assertEqual(response.status_code, 200) ocsp = OCSPResponse.load(response.content) self.assertEqual(ocsp.native['response_status'], 'malformed_request') <|end_body_0|> <|body_start_1|> response = self.client.get('/something') ...
Test the OCSP responder.
OCSP
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OCSP: """Test the OCSP responder.""" def test_get_empty(self): """Empty GET.""" <|body_0|> def test_get_slug_invalid(self): """Invalid GET request.""" <|body_1|> def test_get(self): """Valid GET request.""" <|body_2|> def test_po...
stack_v2_sparse_classes_36k_train_022647
3,537
permissive
[ { "docstring": "Empty GET.", "name": "test_get_empty", "signature": "def test_get_empty(self)" }, { "docstring": "Invalid GET request.", "name": "test_get_slug_invalid", "signature": "def test_get_slug_invalid(self)" }, { "docstring": "Valid GET request.", "name": "test_get",...
5
stack_v2_sparse_classes_30k_train_009347
Implement the Python class `OCSP` described below. Class description: Test the OCSP responder. Method signatures and docstrings: - def test_get_empty(self): Empty GET. - def test_get_slug_invalid(self): Invalid GET request. - def test_get(self): Valid GET request. - def test_post_revoked(self): Valid POST request. - ...
Implement the Python class `OCSP` described below. Class description: Test the OCSP responder. Method signatures and docstrings: - def test_get_empty(self): Empty GET. - def test_get_slug_invalid(self): Invalid GET request. - def test_get(self): Valid GET request. - def test_post_revoked(self): Valid POST request. - ...
1c3608e0a02aaba9bd8594d80a247d692cbd04ad
<|skeleton|> class OCSP: """Test the OCSP responder.""" def test_get_empty(self): """Empty GET.""" <|body_0|> def test_get_slug_invalid(self): """Invalid GET request.""" <|body_1|> def test_get(self): """Valid GET request.""" <|body_2|> def test_po...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OCSP: """Test the OCSP responder.""" def test_get_empty(self): """Empty GET.""" response = self.client.get('/') self.assertEqual(response.status_code, 200) ocsp = OCSPResponse.load(response.content) self.assertEqual(ocsp.native['response_status'], 'malformed_reques...
the_stack_v2_python_sparse
webca/webca/ca_ocsp/tests.py
jesusfer/webca
train
0
bdd16bb6870ea5a9ded39bef95448c15cdc1223b
[ "super(GraphVisualizerConnectedcolumn, self).__init__(grid, column_id, column_span)\nfor i in range(column_span):\n self._grid.setColumnStretch(self._column_id + i, 1)", "painter = QPainter(surface)\nfor connection in self._connected_items:\n start = surface.mapFromGlobal(connection.from_item.get_attach_poi...
<|body_start_0|> super(GraphVisualizerConnectedcolumn, self).__init__(grid, column_id, column_span) for i in range(column_span): self._grid.setColumnStretch(self._column_id + i, 1) <|end_body_0|> <|body_start_1|> painter = QPainter(surface) for connection in self._connected_...
Simple visual column with arrow between connected widget.
GraphVisualizerConnectedcolumn
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphVisualizerConnectedcolumn: """Simple visual column with arrow between connected widget.""" def __init__(self, grid, column_id, column_span=1): """Initialize a GraphVisualizerConnectedcolumn instance.""" <|body_0|> def draw(self, surface): """Draw the surface...
stack_v2_sparse_classes_36k_train_022648
24,840
permissive
[ { "docstring": "Initialize a GraphVisualizerConnectedcolumn instance.", "name": "__init__", "signature": "def __init__(self, grid, column_id, column_span=1)" }, { "docstring": "Draw the surface.", "name": "draw", "signature": "def draw(self, surface)" } ]
2
stack_v2_sparse_classes_30k_train_013981
Implement the Python class `GraphVisualizerConnectedcolumn` described below. Class description: Simple visual column with arrow between connected widget. Method signatures and docstrings: - def __init__(self, grid, column_id, column_span=1): Initialize a GraphVisualizerConnectedcolumn instance. - def draw(self, surfa...
Implement the Python class `GraphVisualizerConnectedcolumn` described below. Class description: Simple visual column with arrow between connected widget. Method signatures and docstrings: - def __init__(self, grid, column_id, column_span=1): Initialize a GraphVisualizerConnectedcolumn instance. - def draw(self, surfa...
bbcf475a4b4e85836123452053bbbf34cc44063a
<|skeleton|> class GraphVisualizerConnectedcolumn: """Simple visual column with arrow between connected widget.""" def __init__(self, grid, column_id, column_span=1): """Initialize a GraphVisualizerConnectedcolumn instance.""" <|body_0|> def draw(self, surface): """Draw the surface...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraphVisualizerConnectedcolumn: """Simple visual column with arrow between connected widget.""" def __init__(self, grid, column_id, column_span=1): """Initialize a GraphVisualizerConnectedcolumn instance.""" super(GraphVisualizerConnectedcolumn, self).__init__(grid, column_id, column_span...
the_stack_v2_python_sparse
posydon/visualization/VH_diagram/GraphVisualizer.py
POSYDON-code/POSYDON
train
11
5a866f7ed3243b014c36d9fffeec10b9cd2b94f3
[ "try:\n profile = Profile.objects.get(user=request.user)\nexcept Profile.DoesNotExist:\n if request.user.is_superuser:\n return Rating.objects.all()\nif profile.access == 'teacher':\n return Rating.objects.filter(subject__teacher__profile_id=profile.id)\nif profile.access == 'student':\n return R...
<|body_start_0|> try: profile = Profile.objects.get(user=request.user) except Profile.DoesNotExist: if request.user.is_superuser: return Rating.objects.all() if profile.access == 'teacher': return Rating.objects.filter(subject__teacher__profile...
RatingAdmin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RatingAdmin: def get_queryset(self, request): """Get all marks for current profile""" <|body_0|> def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: ...
stack_v2_sparse_classes_36k_train_022649
2,628
no_license
[ { "docstring": "Get all marks for current profile", "name": "get_queryset", "signature": "def get_queryset(self, request)" }, { "docstring": "Set default teacher", "name": "formfield_for_foreignkey", "signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_016653
Implement the Python class `RatingAdmin` described below. Class description: Implement the RatingAdmin class. Method signatures and docstrings: - def get_queryset(self, request): Get all marks for current profile - def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher
Implement the Python class `RatingAdmin` described below. Class description: Implement the RatingAdmin class. Method signatures and docstrings: - def get_queryset(self, request): Get all marks for current profile - def formfield_for_foreignkey(self, db_field, request, **kwargs): Set default teacher <|skeleton|> clas...
76c0df6f07f41f4baf7346acdbbf316b4dd13ee5
<|skeleton|> class RatingAdmin: def get_queryset(self, request): """Get all marks for current profile""" <|body_0|> def formfield_for_foreignkey(self, db_field, request, **kwargs): """Set default teacher""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RatingAdmin: def get_queryset(self, request): """Get all marks for current profile""" try: profile = Profile.objects.get(user=request.user) except Profile.DoesNotExist: if request.user.is_superuser: return Rating.objects.all() if profile....
the_stack_v2_python_sparse
journal/admin.py
HallrizonX/api_chpk
train
3
7d8eb92601283deda10ca6263e7b8b7aefad5cbe
[ "Validate.required(raw_costs, 'raw_costs')\nValidate.required(demand, 'demand')\nif raw_costs.holding_cost == 0.0:\n return demand.quantity\nelse:\n numerator = 2 * raw_costs.ordering_cost * demand.quantity\n denominator = raw_costs.holding_cost\n return math.sqrt(numerator / denominator)", "Validate....
<|body_start_0|> Validate.required(raw_costs, 'raw_costs') Validate.required(demand, 'demand') if raw_costs.holding_cost == 0.0: return demand.quantity else: numerator = 2 * raw_costs.ordering_cost * demand.quantity denominator = raw_costs.holding_cost...
EOQ
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EOQ: def optimal_order_quantity(raw_costs, demand): """Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quant...
stack_v2_sparse_classes_36k_train_022650
3,268
no_license
[ { "docstring": "Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quantity and time frame Returns ------- optimal_order_quantity: floa...
4
stack_v2_sparse_classes_30k_train_018999
Implement the Python class `EOQ` described below. Class description: Implement the EOQ class. Method signatures and docstrings: - def optimal_order_quantity(raw_costs, demand): Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, co...
Implement the Python class `EOQ` described below. Class description: Implement the EOQ class. Method signatures and docstrings: - def optimal_order_quantity(raw_costs, demand): Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, co...
230b7bead81265dfee2e0e5c5819ae7a9c46acbc
<|skeleton|> class EOQ: def optimal_order_quantity(raw_costs, demand): """Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quant...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EOQ: def optimal_order_quantity(raw_costs, demand): """Calculate economic order quantity (optimal Q*) given raw costs and demand. Parameters ---------- raw_costs : RawCosts A `RawCosts` object, containing a set of raw cost values demand : Demand A `Demand` object, containing demand quantity and time f...
the_stack_v2_python_sparse
eoq.py
rickhaffey/supply-chain-python
train
2
2423a4a09b4d46627bc082085c7e8a27cdadd5ed
[ "super().__init__()\nif activation_type == 'tanh':\n self.activation = nn.Tanh()\nelif activation_type == 'relu':\n self.activation = nn.ReLU()\nelse:\n raise InvalidActivationError\nself.dropout = nn.Dropout(dropout)\nself.layers = []\nself.params = nn.ParameterList([])\nself.layers.append(nn.Linear(n_fea...
<|body_start_0|> super().__init__() if activation_type == 'tanh': self.activation = nn.Tanh() elif activation_type == 'relu': self.activation = nn.ReLU() else: raise InvalidActivationError self.dropout = nn.Dropout(dropout) self.layers ...
FeedforwardNetwork
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeedforwardNetwork: def __init__(self, n_classes, n_features, hidden_size, layers, activation_type, dropout, **kwargs): """n_classes (int) n_features (int) hidden_size (int) layers (int) activation_type (str) dropout (float): dropout probability As in logistic regression, the __init__ he...
stack_v2_sparse_classes_36k_train_022651
8,770
no_license
[ { "docstring": "n_classes (int) n_features (int) hidden_size (int) layers (int) activation_type (str) dropout (float): dropout probability As in logistic regression, the __init__ here defines a bunch of attributes that each FeedforwardNetwork instance has. Note that nn includes modules for several activation fu...
2
stack_v2_sparse_classes_30k_train_017209
Implement the Python class `FeedforwardNetwork` described below. Class description: Implement the FeedforwardNetwork class. Method signatures and docstrings: - def __init__(self, n_classes, n_features, hidden_size, layers, activation_type, dropout, **kwargs): n_classes (int) n_features (int) hidden_size (int) layers ...
Implement the Python class `FeedforwardNetwork` described below. Class description: Implement the FeedforwardNetwork class. Method signatures and docstrings: - def __init__(self, n_classes, n_features, hidden_size, layers, activation_type, dropout, **kwargs): n_classes (int) n_features (int) hidden_size (int) layers ...
ae6782f00c0eb8380b2fe417eef8772e2d7abef5
<|skeleton|> class FeedforwardNetwork: def __init__(self, n_classes, n_features, hidden_size, layers, activation_type, dropout, **kwargs): """n_classes (int) n_features (int) hidden_size (int) layers (int) activation_type (str) dropout (float): dropout probability As in logistic regression, the __init__ he...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeedforwardNetwork: def __init__(self, n_classes, n_features, hidden_size, layers, activation_type, dropout, **kwargs): """n_classes (int) n_features (int) hidden_size (int) layers (int) activation_type (str) dropout (float): dropout probability As in logistic regression, the __init__ here defines a b...
the_stack_v2_python_sparse
deepLearning/hw1/hw1-q4.py
afonsocrg/portfolio
train
2
1f6f4b9fdbc4758ecf8b23b43f45dfea993ffcb1
[ "if '_details' not in self.__dict__:\n self.__dict__['_details'] = self.IntermediateMassExtract(self.directory)\nreturn self._details", "if self.success:\n return self\n\ndef cmp(a):\n return int(a[0].split('/')[-1])\nreturn max(self.details.items(), key=cmp)[1]", "from itertools import chain\nfor file...
<|body_start_0|> if '_details' not in self.__dict__: self.__dict__['_details'] = self.IntermediateMassExtract(self.directory) return self._details <|end_body_0|> <|body_start_1|> if self.success: return self def cmp(a): return int(a[0].split('/')[-1]...
Extractor class for vasp relaxations.
RelaxExtract
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelaxExtract: """Extractor class for vasp relaxations.""" def details(self): """Intermediate steps.""" <|body_0|> def last_step(self): """Extraction object for current step.""" <|body_1|> def iterfiles(self, **kwargs): """Iterates over input/...
stack_v2_sparse_classes_36k_train_022652
6,637
no_license
[ { "docstring": "Intermediate steps.", "name": "details", "signature": "def details(self)" }, { "docstring": "Extraction object for current step.", "name": "last_step", "signature": "def last_step(self)" }, { "docstring": "Iterates over input/output files.", "name": "iterfiles...
5
null
Implement the Python class `RelaxExtract` described below. Class description: Extractor class for vasp relaxations. Method signatures and docstrings: - def details(self): Intermediate steps. - def last_step(self): Extraction object for current step. - def iterfiles(self, **kwargs): Iterates over input/output files. -...
Implement the Python class `RelaxExtract` described below. Class description: Extractor class for vasp relaxations. Method signatures and docstrings: - def details(self): Intermediate steps. - def last_step(self): Extraction object for current step. - def iterfiles(self, **kwargs): Iterates over input/output files. -...
9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3
<|skeleton|> class RelaxExtract: """Extractor class for vasp relaxations.""" def details(self): """Intermediate steps.""" <|body_0|> def last_step(self): """Extraction object for current step.""" <|body_1|> def iterfiles(self, **kwargs): """Iterates over input/...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelaxExtract: """Extractor class for vasp relaxations.""" def details(self): """Intermediate steps.""" if '_details' not in self.__dict__: self.__dict__['_details'] = self.IntermediateMassExtract(self.directory) return self._details def last_step(self): ""...
the_stack_v2_python_sparse
dftcrystal/relax.py
Shibu778/LaDa
train
0
30d363e37ac5d60d8851ce5fa025e3941fda4f84
[ "min_start = min((v.start for v in overlapping_variants))\nself.variant_indices = [(v.start - min_start, v.end - min_start) for v in overlapping_variants]\nself.size = max((v.end - min_start for v in overlapping_variants))", "if len(nonref_genotype_counts) != len(self.variant_indices):\n raise ValueError('Vari...
<|body_start_0|> min_start = min((v.start for v in overlapping_variants)) self.variant_indices = [(v.start - min_start, v.end - min_start) for v in overlapping_variants] self.size = max((v.end - min_start for v in overlapping_variants)) <|end_body_0|> <|body_start_1|> if len(nonref_geno...
Represents the reference genome spanned by overlapping Variants. Each Variant affects a portion of the reference genome that is determined by its start and end coordinates. For a given set of Variants, they are deemed compatible if the total area along the reference genome that is called as non-reference genotypes neve...
_VariantCompatibilityCalculator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _VariantCompatibilityCalculator: """Represents the reference genome spanned by overlapping Variants. Each Variant affects a portion of the reference genome that is determined by its start and end coordinates. For a given set of Variants, they are deemed compatible if the total area along the refe...
stack_v2_sparse_classes_36k_train_022653
20,898
permissive
[ { "docstring": "Constructor. Args: overlapping_variants: list(Variant). The Variant protos of interest.", "name": "__init__", "signature": "def __init__(self, overlapping_variants)" }, { "docstring": "Returns True if and only if all variants are compatible. Args: nonref_genotype_counts: list of ...
2
stack_v2_sparse_classes_30k_train_018485
Implement the Python class `_VariantCompatibilityCalculator` described below. Class description: Represents the reference genome spanned by overlapping Variants. Each Variant affects a portion of the reference genome that is determined by its start and end coordinates. For a given set of Variants, they are deemed comp...
Implement the Python class `_VariantCompatibilityCalculator` described below. Class description: Represents the reference genome spanned by overlapping Variants. Each Variant affects a portion of the reference genome that is determined by its start and end coordinates. For a given set of Variants, they are deemed comp...
ab068c4588a02e2167051bd9e74c0c9579462b51
<|skeleton|> class _VariantCompatibilityCalculator: """Represents the reference genome spanned by overlapping Variants. Each Variant affects a portion of the reference genome that is determined by its start and end coordinates. For a given set of Variants, they are deemed compatible if the total area along the refe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _VariantCompatibilityCalculator: """Represents the reference genome spanned by overlapping Variants. Each Variant affects a portion of the reference genome that is determined by its start and end coordinates. For a given set of Variants, they are deemed compatible if the total area along the reference genome ...
the_stack_v2_python_sparse
deepvariant/haplotypes.py
google/deepvariant
train
3,002
7abc4731091617b9599e022bb64e4f8ffccd522d
[ "Data = ''\ntry:\n with open(FileName, 'r') as fp:\n Data = json.load(fp)\n return Data\nexcept ValueError or IOError:\n data = {}\n with open(FileName, 'w+') as fp:\n json.dump(data, fp)\n return Data", "Teams = SystemToolKit.readFile(Config.TeamFile)\nfor i in Teams:\n if Tea...
<|body_start_0|> Data = '' try: with open(FileName, 'r') as fp: Data = json.load(fp) return Data except ValueError or IOError: data = {} with open(FileName, 'w+') as fp: json.dump(data, fp) return Dat...
SystemToolKit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SystemToolKit: def readFile(FileName): """Takes a json File and returns its data If no file exisits one will be created and populated with a blank dictionary""" <|body_0|> def getTeamId(TeamNumber): """Takes a Team Number and returns a Team ID(String) If a Team of Nu...
stack_v2_sparse_classes_36k_train_022654
1,327
no_license
[ { "docstring": "Takes a json File and returns its data If no file exisits one will be created and populated with a blank dictionary", "name": "readFile", "signature": "def readFile(FileName)" }, { "docstring": "Takes a Team Number and returns a Team ID(String) If a Team of Number parsed does not...
3
stack_v2_sparse_classes_30k_train_001582
Implement the Python class `SystemToolKit` described below. Class description: Implement the SystemToolKit class. Method signatures and docstrings: - def readFile(FileName): Takes a json File and returns its data If no file exisits one will be created and populated with a blank dictionary - def getTeamId(TeamNumber):...
Implement the Python class `SystemToolKit` described below. Class description: Implement the SystemToolKit class. Method signatures and docstrings: - def readFile(FileName): Takes a json File and returns its data If no file exisits one will be created and populated with a blank dictionary - def getTeamId(TeamNumber):...
6420f365540d935906178691fbb5e46b6a31c6b5
<|skeleton|> class SystemToolKit: def readFile(FileName): """Takes a json File and returns its data If no file exisits one will be created and populated with a blank dictionary""" <|body_0|> def getTeamId(TeamNumber): """Takes a Team Number and returns a Team ID(String) If a Team of Nu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SystemToolKit: def readFile(FileName): """Takes a json File and returns its data If no file exisits one will be created and populated with a blank dictionary""" Data = '' try: with open(FileName, 'r') as fp: Data = json.load(fp) return Data ...
the_stack_v2_python_sparse
SystemToolKit.py
Lamppost122/Controlled-assessment-Final
train
0
93583167fdea3c7155e6c18cf54a098d6e2b3518
[ "a = self.to_bin(a)\nb = self.to_bin(b)\ndiff = len(a) - len(b)\nret = 0\nif diff < 0:\n a, b = (b, a)\n diff *= -1\nb = '0' * diff + b\nfor i in xrange(len(b)):\n if a[i] != b[i]:\n ret += 1\nreturn ret", "\"\"\"\n :param n:\n :return:\n \"\"\"\na = abs(n)\nlst = []\nwhile a ...
<|body_start_0|> a = self.to_bin(a) b = self.to_bin(b) diff = len(a) - len(b) ret = 0 if diff < 0: a, b = (b, a) diff *= -1 b = '0' * diff + b for i in xrange(len(b)): if a[i] != b[i]: ret += 1 return ret...
Solution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def bitSwapRequired(self, a, b): """:param a: :param b: :return: int""" <|body_0|> def to_bin(self, n): """2's complement 32-bit :param n: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> a = self.to_bin(a) b = self.to_bin(...
stack_v2_sparse_classes_36k_train_022655
1,433
permissive
[ { "docstring": ":param a: :param b: :return: int", "name": "bitSwapRequired", "signature": "def bitSwapRequired(self, a, b)" }, { "docstring": "2's complement 32-bit :param n: :return:", "name": "to_bin", "signature": "def to_bin(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_011177
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bitSwapRequired(self, a, b): :param a: :param b: :return: int - def to_bin(self, n): 2's complement 32-bit :param n: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def bitSwapRequired(self, a, b): :param a: :param b: :return: int - def to_bin(self, n): 2's complement 32-bit :param n: :return: <|skeleton|> class Solution: def bitSwapRe...
4629a3857b2c57418b86a3b3a7180ecb15e763e3
<|skeleton|> class Solution: def bitSwapRequired(self, a, b): """:param a: :param b: :return: int""" <|body_0|> def to_bin(self, n): """2's complement 32-bit :param n: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def bitSwapRequired(self, a, b): """:param a: :param b: :return: int""" a = self.to_bin(a) b = self.to_bin(b) diff = len(a) - len(b) ret = 0 if diff < 0: a, b = (b, a) diff *= -1 b = '0' * diff + b for i in xrang...
the_stack_v2_python_sparse
Convert Integer A to Integer B.py
RijuDasgupta9116/LintCode
train
0
d7cb2dd14579ed3c6053c651cddc02117792083c
[ "print('\\n------Ejecutando test para crear usuario-------\\n')\nu = User.objects.create_user('testuser', 'test1', 'test1')\nself.assertTrue(u.has_usable_password())\nself.assertFalse(u.check_password('bad'))\nself.assertTrue(u.check_password('test1'))\nprint('\\n------Test para crear usuario correcto-------\\n')\n...
<|body_start_0|> print('\n------Ejecutando test para crear usuario-------\n') u = User.objects.create_user('testuser', 'test1', 'test1') self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password('bad')) self.assertTrue(u.check_password('test1')) print('\n...
GTGTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GTGTestCase: def test_crear_usuario(self): """Test para la creacion de un usuario con contrasenha""" <|body_0|> def test_eliminar_usuario(self): """Test para la eliminacion de un usuario""" <|body_1|> <|end_skeleton|> <|body_start_0|> print('\n-----...
stack_v2_sparse_classes_36k_train_022656
1,916
no_license
[ { "docstring": "Test para la creacion de un usuario con contrasenha", "name": "test_crear_usuario", "signature": "def test_crear_usuario(self)" }, { "docstring": "Test para la eliminacion de un usuario", "name": "test_eliminar_usuario", "signature": "def test_eliminar_usuario(self)" } ...
2
stack_v2_sparse_classes_30k_train_016164
Implement the Python class `GTGTestCase` described below. Class description: Implement the GTGTestCase class. Method signatures and docstrings: - def test_crear_usuario(self): Test para la creacion de un usuario con contrasenha - def test_eliminar_usuario(self): Test para la eliminacion de un usuario
Implement the Python class `GTGTestCase` described below. Class description: Implement the GTGTestCase class. Method signatures and docstrings: - def test_crear_usuario(self): Test para la creacion de un usuario con contrasenha - def test_eliminar_usuario(self): Test para la eliminacion de un usuario <|skeleton|> cl...
4ffe359fd884754725355017e1c3cffe5a4ce13f
<|skeleton|> class GTGTestCase: def test_crear_usuario(self): """Test para la creacion de un usuario con contrasenha""" <|body_0|> def test_eliminar_usuario(self): """Test para la eliminacion de un usuario""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GTGTestCase: def test_crear_usuario(self): """Test para la creacion de un usuario con contrasenha""" print('\n------Ejecutando test para crear usuario-------\n') u = User.objects.create_user('testuser', 'test1', 'test1') self.assertTrue(u.has_usable_password()) self.ass...
the_stack_v2_python_sparse
sistema/tests.py
mocomauricio/sigestrec
train
0
122a88d597095b1ec328c2f67925de2182365551
[ "self.env.revert_snapshot('deploy_ha_influxdb_grafana')\nmanipulated_node = {'slave-03': ['controller']}\nself.helpers.remove_nodes_from_cluster(manipulated_node)\nself.check_plugin_online()\nself.helpers.run_ostf(should_fail=1)\nself.helpers.add_nodes_to_cluster(manipulated_node)\nself.check_plugin_online()\nself....
<|body_start_0|> self.env.revert_snapshot('deploy_ha_influxdb_grafana') manipulated_node = {'slave-03': ['controller']} self.helpers.remove_nodes_from_cluster(manipulated_node) self.check_plugin_online() self.helpers.run_ostf(should_fail=1) self.helpers.add_nodes_to_clust...
Class for system tests for InfluxDB-Grafana plugin.
TestNodesInfluxdbPlugin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestNodesInfluxdbPlugin: """Class for system tests for InfluxDB-Grafana plugin.""" def add_remove_controller_influxdb_grafana(self): """Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one con...
stack_v2_sparse_classes_36k_train_022657
7,472
no_license
[ { "docstring": "Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one controller node and update the cluster 3. Check that plugin is working 4. Run OSTF 5. Add one controller node (return previous state) and update the cl...
5
stack_v2_sparse_classes_30k_test_001177
Implement the Python class `TestNodesInfluxdbPlugin` described below. Class description: Class for system tests for InfluxDB-Grafana plugin. Method signatures and docstrings: - def add_remove_controller_influxdb_grafana(self): Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot wi...
Implement the Python class `TestNodesInfluxdbPlugin` described below. Class description: Class for system tests for InfluxDB-Grafana plugin. Method signatures and docstrings: - def add_remove_controller_influxdb_grafana(self): Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot wi...
179249df2d206eeabb3955c9dc8cb78cac3c36c6
<|skeleton|> class TestNodesInfluxdbPlugin: """Class for system tests for InfluxDB-Grafana plugin.""" def add_remove_controller_influxdb_grafana(self): """Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestNodesInfluxdbPlugin: """Class for system tests for InfluxDB-Grafana plugin.""" def add_remove_controller_influxdb_grafana(self): """Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one controller node ...
the_stack_v2_python_sparse
stacklight_tests/influxdb_grafana/test_system.py
rkhozinov/stacklight-integration-tests
train
1
0d73e399216c23799494f586be0f29c058bf6a8d
[ "for index, num in enumerate(nums):\n if index == 0:\n continue\n nums[index] += nums[index - 1]\nself.nums = nums", "if i == 0:\n return self.nums[j]\nreturn self.nums[j] - self.nums[i - 1]" ]
<|body_start_0|> for index, num in enumerate(nums): if index == 0: continue nums[index] += nums[index - 1] self.nums = nums <|end_body_0|> <|body_start_1|> if i == 0: return self.nums[j] return self.nums[j] - self.nums[i - 1] <|end_bod...
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> for index, num in enumerate(nums): if index == ...
stack_v2_sparse_classes_36k_train_022658
984
no_license
[ { "docstring": ":type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": ":type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, i, j)" } ]
2
null
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): :type nums: List[int] - def sumRange(self, i, j): :type i: int :type j: int :rtype: int <|skeleton|> class NumArray: def __init__(self, nums): ...
1dec441f1975d402d093031569cfd301eb71d465
<|skeleton|> class NumArray: def __init__(self, nums): """:type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """:type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumArray: def __init__(self, nums): """:type nums: List[int]""" for index, num in enumerate(nums): if index == 0: continue nums[index] += nums[index - 1] self.nums = nums def sumRange(self, i, j): """:type i: int :type j: int :rtype:...
the_stack_v2_python_sparse
303-range-sum-query-immutable.py
franktank/py-practice
train
1
30e5137cf2187e467f5c5c96817ee5633bc973f0
[ "self.height = height\nself.length = length\nself.weight = weight\nself.width = width", "if dictionary is None:\n return None\nheight = awsecommerceservice.models.decimal_with_units.DecimalWithUnits.from_dictionary(dictionary.get('Height')) if dictionary.get('Height') else None\nlength = awsecommerceservice.mo...
<|body_start_0|> self.height = height self.length = length self.weight = weight self.width = width <|end_body_0|> <|body_start_1|> if dictionary is None: return None height = awsecommerceservice.models.decimal_with_units.DecimalWithUnits.from_dictionary(dicti...
Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (DecimalWithUnits): TODO: type description here.
PackageDimensions
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PackageDimensions: """Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (Deci...
stack_v2_sparse_classes_36k_train_022659
2,533
permissive
[ { "docstring": "Constructor for the PackageDimensions class", "name": "__init__", "signature": "def __init__(self, height=None, length=None, weight=None, width=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation...
2
stack_v2_sparse_classes_30k_train_003175
Implement the Python class `PackageDimensions` described below. Class description: Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): T...
Implement the Python class `PackageDimensions` described below. Class description: Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): T...
26ea1019115a1de3b1b37a4b830525e164ac55ce
<|skeleton|> class PackageDimensions: """Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (Deci...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PackageDimensions: """Implementation of the 'PackageDimensions' model. TODO: type model description here. Attributes: height (DecimalWithUnits): TODO: type description here. length (DecimalWithUnits): TODO: type description here. weight (DecimalWithUnits): TODO: type description here. width (DecimalWithUnits)...
the_stack_v2_python_sparse
awsecommerceservice/models/package_dimensions.py
nidaizamir/Test-PY
train
0
ec033c87421054d5accc658daf3d040de2b5106f
[ "self._serv = SimpleXMLRPCServer(address, allow_none=True)\nself._db = pyvanas_db\nself._redis = redis\nfor name in self._rpc_methods_:\n self._serv.register_function(getattr(self, name))", "user_info = self._db['user']\nuser = user_info.find_one({'_id': ObjectId(user_id)})\nstart_utc_time = datetime.datetime....
<|body_start_0|> self._serv = SimpleXMLRPCServer(address, allow_none=True) self._db = pyvanas_db self._redis = redis for name in self._rpc_methods_: self._serv.register_function(getattr(self, name)) <|end_body_0|> <|body_start_1|> user_info = self._db['user'] ...
vanas_data_server
VanasDataServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VanasDataServer: """vanas_data_server""" def __init__(self, address, pyvanas_db, redis): """TODO: to be defined1.""" <|body_0|> def get_data(self, symbol, start_time, end_time, user_id): """docstring for get_data""" <|body_1|> def send_status(self, d...
stack_v2_sparse_classes_36k_train_022660
2,259
no_license
[ { "docstring": "TODO: to be defined1.", "name": "__init__", "signature": "def __init__(self, address, pyvanas_db, redis)" }, { "docstring": "docstring for get_data", "name": "get_data", "signature": "def get_data(self, symbol, start_time, end_time, user_id)" }, { "docstring": "发送...
3
stack_v2_sparse_classes_30k_train_009152
Implement the Python class `VanasDataServer` described below. Class description: vanas_data_server Method signatures and docstrings: - def __init__(self, address, pyvanas_db, redis): TODO: to be defined1. - def get_data(self, symbol, start_time, end_time, user_id): docstring for get_data - def send_status(self, data,...
Implement the Python class `VanasDataServer` described below. Class description: vanas_data_server Method signatures and docstrings: - def __init__(self, address, pyvanas_db, redis): TODO: to be defined1. - def get_data(self, symbol, start_time, end_time, user_id): docstring for get_data - def send_status(self, data,...
80c33304d25f01b321f3351d934190dc927e13dc
<|skeleton|> class VanasDataServer: """vanas_data_server""" def __init__(self, address, pyvanas_db, redis): """TODO: to be defined1.""" <|body_0|> def get_data(self, symbol, start_time, end_time, user_id): """docstring for get_data""" <|body_1|> def send_status(self, d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VanasDataServer: """vanas_data_server""" def __init__(self, address, pyvanas_db, redis): """TODO: to be defined1.""" self._serv = SimpleXMLRPCServer(address, allow_none=True) self._db = pyvanas_db self._redis = redis for name in self._rpc_methods_: self...
the_stack_v2_python_sparse
vanas_server/vanas_rpc_server.py
tianhm/pyvanas-halfway
train
0
827c723650dbe5c1f7316ceeb75ec8bc7f6f75ca
[ "turbulenceProperties = turbulenceProperties or TurbulenceProperties.RAS()\nfvSolution = fvSolution or FvSolution.fromRecipe(1)\nfvSchemes = fvSchemes or FvSchemes.fromRecipe(1)\nself.temperature = TRef or 300\nquantities = self.__quantities\n_SingleCommandRecipe.__init__(self, self.__command, turbulenceProperties,...
<|body_start_0|> turbulenceProperties = turbulenceProperties or TurbulenceProperties.RAS() fvSolution = fvSolution or FvSolution.fromRecipe(1) fvSchemes = fvSchemes or FvSchemes.fromRecipe(1) self.temperature = TRef or 300 quantities = self.__quantities _SingleCommandReci...
Recipe for heat transfer. This recipe excutes buoyantBoussinesqSimpleFoam for the input case. Attributes: turbulenceProperties: Turbulence properties. fvSolution: Optional input for fvSolution to overwrite default fvSolution. fvSchemes: Optional input for fvSchemes to overwrite default fvSchemes. residualControl: A dic...
HeatTransfer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeatTransfer: """Recipe for heat transfer. This recipe excutes buoyantBoussinesqSimpleFoam for the input case. Attributes: turbulenceProperties: Turbulence properties. fvSolution: Optional input for fvSolution to overwrite default fvSolution. fvSchemes: Optional input for fvSchemes to overwrite d...
stack_v2_sparse_classes_36k_train_022661
16,103
no_license
[ { "docstring": "Initiate recipe.", "name": "__init__", "signature": "def __init__(self, turbulenceProperties=None, fvSolution=None, fvSchemes=None, residualControl=None, relaxationFactors=None, TRef=None)" }, { "docstring": "Prepare a case for this recipe. This method sets up the application in ...
2
null
Implement the Python class `HeatTransfer` described below. Class description: Recipe for heat transfer. This recipe excutes buoyantBoussinesqSimpleFoam for the input case. Attributes: turbulenceProperties: Turbulence properties. fvSolution: Optional input for fvSolution to overwrite default fvSolution. fvSchemes: Opti...
Implement the Python class `HeatTransfer` described below. Class description: Recipe for heat transfer. This recipe excutes buoyantBoussinesqSimpleFoam for the input case. Attributes: turbulenceProperties: Turbulence properties. fvSolution: Optional input for fvSolution to overwrite default fvSolution. fvSchemes: Opti...
330e96867fc3df530ad21c11de01c54562745e65
<|skeleton|> class HeatTransfer: """Recipe for heat transfer. This recipe excutes buoyantBoussinesqSimpleFoam for the input case. Attributes: turbulenceProperties: Turbulence properties. fvSolution: Optional input for fvSolution to overwrite default fvSolution. fvSchemes: Optional input for fvSchemes to overwrite d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HeatTransfer: """Recipe for heat transfer. This recipe excutes buoyantBoussinesqSimpleFoam for the input case. Attributes: turbulenceProperties: Turbulence properties. fvSolution: Optional input for fvSolution to overwrite default fvSolution. fvSchemes: Optional input for fvSchemes to overwrite default fvSche...
the_stack_v2_python_sparse
samples/recipe.py
aKarm1905/PythonMSC
train
0
8635ae9392b824f818c844357aa27a509f2fcc13
[ "singlePaths = []\nfor togo in self.graph[node]:\n if togo != parent:\n singlePaths.append(self.postorder(togo, node))\nif not singlePaths:\n return 1\nif len(singlePaths) == 1:\n r = 1 + singlePaths[0]\n self.maxNodeCount = max(self.maxNodeCount, r)\n return r\nsinglePaths.sort()\ntop1, top2 ...
<|body_start_0|> singlePaths = [] for togo in self.graph[node]: if togo != parent: singlePaths.append(self.postorder(togo, node)) if not singlePaths: return 1 if len(singlePaths) == 1: r = 1 + singlePaths[0] self.maxNodeCoun...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def postorder(self, node: int, parent: int) -> int: """@return: max node count from node to 1 of its child branch.""" <|body_0|> def treeDiameter(self, edges: List[List[int]]) -> int: """Similar to 124. Binary Tree Maximum Path Sum""" <|body_1|> <|...
stack_v2_sparse_classes_36k_train_022662
2,126
no_license
[ { "docstring": "@return: max node count from node to 1 of its child branch.", "name": "postorder", "signature": "def postorder(self, node: int, parent: int) -> int" }, { "docstring": "Similar to 124. Binary Tree Maximum Path Sum", "name": "treeDiameter", "signature": "def treeDiameter(se...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorder(self, node: int, parent: int) -> int: @return: max node count from node to 1 of its child branch. - def treeDiameter(self, edges: List[List[int]]) -> int: Similar t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorder(self, node: int, parent: int) -> int: @return: max node count from node to 1 of its child branch. - def treeDiameter(self, edges: List[List[int]]) -> int: Similar t...
ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653
<|skeleton|> class Solution: def postorder(self, node: int, parent: int) -> int: """@return: max node count from node to 1 of its child branch.""" <|body_0|> def treeDiameter(self, edges: List[List[int]]) -> int: """Similar to 124. Binary Tree Maximum Path Sum""" <|body_1|> <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def postorder(self, node: int, parent: int) -> int: """@return: max node count from node to 1 of its child branch.""" singlePaths = [] for togo in self.graph[node]: if togo != parent: singlePaths.append(self.postorder(togo, node)) if not si...
the_stack_v2_python_sparse
T-1245 Tree Diameter.py
jz33/LeetCodeSolutions
train
8
c7000b4edcbecceba4e91d16265d0be58f716c89
[ "self.map = {}\nself.patches = {}\nhandler = DefinitionHandler()\nsax.make_parser()\nfor def_file in [aa_file, na_file]:\n sax.parseString(def_file.read(), handler)\n self.map.update(handler.map)\nhandler.map = {}\nsax.parseString(patch_file.read(), handler)\nfor patch in handler.patches:\n if patch.newnam...
<|body_start_0|> self.map = {} self.patches = {} handler = DefinitionHandler() sax.make_parser() for def_file in [aa_file, na_file]: sax.parseString(def_file.read(), handler) self.map.update(handler.map) handler.map = {} sax.parseString(pat...
Force field topology definitions. The Definition class contains the structured definitions found in the files and several mappings for easy access to the information.
Definition
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Definition: """Force field topology definitions. The Definition class contains the structured definitions found in the files and several mappings for easy access to the information.""" def __init__(self, aa_file, na_file, patch_file): """Initialize object. :param aa_file: file-like o...
stack_v2_sparse_classes_36k_train_022663
10,906
no_license
[ { "docstring": "Initialize object. :param aa_file: file-like object with amino acid definitions :type aa_file: file :param na_file: file-like object with nucleic acid definitions :type na_file: file :param patch_file: file-like object with patch definitions :type patch_file: file", "name": "__init__", "...
2
stack_v2_sparse_classes_30k_train_005790
Implement the Python class `Definition` described below. Class description: Force field topology definitions. The Definition class contains the structured definitions found in the files and several mappings for easy access to the information. Method signatures and docstrings: - def __init__(self, aa_file, na_file, pa...
Implement the Python class `Definition` described below. Class description: Force field topology definitions. The Definition class contains the structured definitions found in the files and several mappings for easy access to the information. Method signatures and docstrings: - def __init__(self, aa_file, na_file, pa...
53cbe6d320048508710b3bad8581b69d3a358ab9
<|skeleton|> class Definition: """Force field topology definitions. The Definition class contains the structured definitions found in the files and several mappings for easy access to the information.""" def __init__(self, aa_file, na_file, patch_file): """Initialize object. :param aa_file: file-like o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Definition: """Force field topology definitions. The Definition class contains the structured definitions found in the files and several mappings for easy access to the information.""" def __init__(self, aa_file, na_file, patch_file): """Initialize object. :param aa_file: file-like object with am...
the_stack_v2_python_sparse
pdb2pqr/definitions.py
rkretsch/pdb2pqr
train
0
46fb77b09fb501b6f04eed94d5da04e77c042dd9
[ "edges = defaultdict(list)\nvisited = [0] * num_courses\nresult = list()\ninvalid = False\nfor info in prerequisites:\n edges[info[1]].append(info[0])\n\ndef dfs(u: int):\n nonlocal invalid\n visited[u] = 1\n for v in edges[u]:\n if visited[v] == 0:\n dfs(v)\n if invalid:\n ...
<|body_start_0|> edges = defaultdict(list) visited = [0] * num_courses result = list() invalid = False for info in prerequisites: edges[info[1]].append(info[0]) def dfs(u: int): nonlocal invalid visited[u] = 1 for v in edge...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def find_order(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: """BFS""" <|body_0|> def find_order_v2(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: """DFS""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_022664
3,658
no_license
[ { "docstring": "BFS", "name": "find_order", "signature": "def find_order(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]" }, { "docstring": "DFS", "name": "find_order_v2", "signature": "def find_order_v2(cls, num_courses: int, prerequisites: List[List[int]]) -> List[i...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_order(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: BFS - def find_order_v2(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: D...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_order(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: BFS - def find_order_v2(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: D...
1d1876620a55ff88af7bc390cf1a4fd4350d8d16
<|skeleton|> class Solution: def find_order(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: """BFS""" <|body_0|> def find_order_v2(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: """DFS""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def find_order(cls, num_courses: int, prerequisites: List[List[int]]) -> List[int]: """BFS""" edges = defaultdict(list) visited = [0] * num_courses result = list() invalid = False for info in prerequisites: edges[info[1]].append(info[0]) ...
the_stack_v2_python_sparse
01-数据结构/图/210.课程表II(M).py
jh-lau/leetcode_in_python
train
0
46f3766c8d9dfc196e8bc12f4beda75ccde47c95
[ "if not root:\n return 'null'\nmessage = []\n\ndef build_message(root):\n if root is None:\n message.append('null')\n else:\n message.append(str(root.val))\n build_message(root.left)\n build_message(root.right)\nbuild_message(root)\nreturn ','.join(message)", "queue = collecti...
<|body_start_0|> if not root: return 'null' message = [] def build_message(root): if root is None: message.append('null') else: message.append(str(root.val)) build_message(root.left) build_messag...
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_022665
1,635
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:...
9d0ff0f8705451947a6605ab5ef92bb3e27a7147
<|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""" if not root: return 'null' message = [] def build_message(root): if root is None: message.append('null') else: ...
the_stack_v2_python_sparse
premium/amazon/design/serialize_and_deserialize_bst.py
rayt579/leetcode
train
0
d0a6c5eb21c980df5aa239509751bf000e36b774
[ "response = super(RetrieveUpdateDestroyAPIView, self).get(request, *args, **kwargs)\nname = model_name_urlize(self.model)\nlinks = [('base', ApiRoot.REGISTRY_REL_PREFIX + 'base'), ('base_controller', ApiRoot.CONTROLLER_REL_PREFIX + 'base')]\nif not is_singleton(self.model) and getattr(self, 'list', True):\n reso...
<|body_start_0|> response = super(RetrieveUpdateDestroyAPIView, self).get(request, *args, **kwargs) name = model_name_urlize(self.model) links = [('base', ApiRoot.REGISTRY_REL_PREFIX + 'base'), ('base_controller', ApiRoot.CONTROLLER_REL_PREFIX + 'base')] if not is_singleton(self.model) a...
Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Adds links to the API base and controller API endpoints. `fields_superuser` allows defining fields that only can be updated by a superuser (mark they as readonly otherwise). NOTE: Serializer s...
RetrieveUpdateDestroyAPIView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RetrieveUpdateDestroyAPIView: """Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Adds links to the API base and controller API endpoints. `fields_superuser` allows defining fields that only can be updated by a superus...
stack_v2_sparse_classes_36k_train_022666
7,128
no_license
[ { "docstring": "Add link header", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Mark as readonly fields that only can be updated by superusers", "name": "get_serializer", "signature": "def get_serializer(self, instance=None, data=None, files=Non...
2
null
Implement the Python class `RetrieveUpdateDestroyAPIView` described below. Class description: Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Adds links to the API base and controller API endpoints. `fields_superuser` allows defining field...
Implement the Python class `RetrieveUpdateDestroyAPIView` described below. Class description: Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Adds links to the API base and controller API endpoints. `fields_superuser` allows defining field...
dd798dc9bd3321b17007ff131e7b1288a2cd3c36
<|skeleton|> class RetrieveUpdateDestroyAPIView: """Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Adds links to the API base and controller API endpoints. `fields_superuser` allows defining fields that only can be updated by a superus...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RetrieveUpdateDestroyAPIView: """Used for read-write-delete endpoints to represent a single model instance. Provides get, put, patch and delete method handlers. Adds links to the API base and controller API endpoints. `fields_superuser` allows defining fields that only can be updated by a superuser (mark they...
the_stack_v2_python_sparse
controller/apps/api/generics.py
m00dy/vct-controller
train
2
2a4c63f2e0c71e2f1f553ccef9f23123a0578e61
[ "if not hasattr(self, 'nextFrame'):\n raise RuntimeError('SimpleTour instance has no specified nextFrame method.')\nif not hasattr(self, 'X'):\n raise RuntimeError('SimpleTour instance has no specified X property.')\nself.pauseSteps = pause\nself.moveFlag = True\nself.Fz, self.moveSteps = self.nextFrame(None)...
<|body_start_0|> if not hasattr(self, 'nextFrame'): raise RuntimeError('SimpleTour instance has no specified nextFrame method.') if not hasattr(self, 'X'): raise RuntimeError('SimpleTour instance has no specified X property.') self.pauseSteps = pause self.moveFlag...
A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils.
SimpleTour
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleTour: """A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils.""" def __init__(self, pause=0): """Constructs a SimpleTour object given a generator function that specifie...
stack_v2_sparse_classes_36k_train_022667
3,652
permissive
[ { "docstring": "Constructs a SimpleTour object given a generator function that specifies the next frame to travel to and the number of steps to take. Should not be called explicitly.", "name": "__init__", "signature": "def __init__(self, pause=0)" }, { "docstring": "Checks to make sure that the ...
6
stack_v2_sparse_classes_30k_train_014861
Implement the Python class `SimpleTour` described below. Class description: A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils. Method signatures and docstrings: - def __init__(self, pause=0): Constructs a S...
Implement the Python class `SimpleTour` described below. Class description: A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils. Method signatures and docstrings: - def __init__(self, pause=0): Constructs a S...
435676abe6a1ad07aa9227325c7a35d3c6e146d7
<|skeleton|> class SimpleTour: """A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils.""" def __init__(self, pause=0): """Constructs a SimpleTour object given a generator function that specifie...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimpleTour: """A class for enacting simple tours, where a simple tour is simply a tour that moves from frame to frame using the frame interpolation algorithm specified in utils.""" def __init__(self, pause=0): """Constructs a SimpleTour object given a generator function that specifies the next fr...
the_stack_v2_python_sparse
pytour/simpleTour/simpleTour.py
crhoyt/pytour
train
0
218b1351e4058fee2cb91eff1bd0534136acc9a3
[ "n = len(nums)\nmax_window = []\nfor i in range(0, n - k + 1):\n curr_max = float('-inf')\n for j in range(i, i + k):\n curr_max = max(curr_max, nums[j])\n max_window.append(curr_max)\nreturn max_window", "if not nums:\n return []\nif k > len(nums):\n return [max(nums)]\nmax_window = []\ndeq...
<|body_start_0|> n = len(nums) max_window = [] for i in range(0, n - k + 1): curr_max = float('-inf') for j in range(i, i + k): curr_max = max(curr_max, nums[j]) max_window.append(curr_max) return max_window <|end_body_0|> <|body_start...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def max_window_brute(self, nums, k): """Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).""" <|body_0|> def max_window_deque(self, nums, k): """Algorithm based on using dequeue. Assumes k <= len(nums). Time complexity...
stack_v2_sparse_classes_36k_train_022668
2,969
no_license
[ { "docstring": "Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).", "name": "max_window_brute", "signature": "def max_window_brute(self, nums, k)" }, { "docstring": "Algorithm based on using dequeue. Assumes k <= len(nums). Time complexity: O(n). Space com...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_window_brute(self, nums, k): Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums). - def max_window_deque(self, nums, k): Algorithm ba...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_window_brute(self, nums, k): Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums). - def max_window_deque(self, nums, k): Algorithm ba...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def max_window_brute(self, nums, k): """Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).""" <|body_0|> def max_window_deque(self, nums, k): """Algorithm based on using dequeue. Assumes k <= len(nums). Time complexity...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def max_window_brute(self, nums, k): """Brute force algorithm. Time complexity: O(n * k). Space complexity: O(1), n is len(nums).""" n = len(nums) max_window = [] for i in range(0, n - k + 1): curr_max = float('-inf') for j in range(i, i + k): ...
the_stack_v2_python_sparse
Stack/sliding_window_maximum.py
vladn90/Algorithms
train
0
2341fe14b0c9367f2eec943e95293609e4ac66bb
[ "if not name:\n raise ValueError('Users must have an name')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email, password=password, name=name)\nuser.is_superuser = True\nuser.save(using=self._db)\...
<|body_start_0|> if not name: raise ValueError('Users must have an name') user = self.model(email=self.normalize_email(email), name=name) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user = self.create_user...
BackendUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BackendUserManager: def create_user(self, email, name, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, email, name, password): """Creates and saves a superuser with the given email...
stack_v2_sparse_classes_36k_train_022669
8,553
no_license
[ { "docstring": "Creates and saves a User with the given email, date of birth and password.", "name": "create_user", "signature": "def create_user(self, email, name, password=None)" }, { "docstring": "Creates and saves a superuser with the given email, date of birth and password.", "name": "c...
2
stack_v2_sparse_classes_30k_val_000393
Implement the Python class `BackendUserManager` described below. Class description: Implement the BackendUserManager class. Method signatures and docstrings: - def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superuser(self, ema...
Implement the Python class `BackendUserManager` described below. Class description: Implement the BackendUserManager class. Method signatures and docstrings: - def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password. - def create_superuser(self, ema...
2e8bd27ed244ce4f385c365ae2b1c9f5dbbb4d58
<|skeleton|> class BackendUserManager: def create_user(self, email, name, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, email, name, password): """Creates and saves a superuser with the given email...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BackendUserManager: def create_user(self, email, name, password=None): """Creates and saves a User with the given email, date of birth and password.""" if not name: raise ValueError('Users must have an name') user = self.model(email=self.normalize_email(email), name=name) ...
the_stack_v2_python_sparse
backend/models.py
JIAWea/WeChat_demo
train
0
2283b88a918d63730ab37f2bfb086374cd614d32
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ProvisioningErrorInfo()", "from .provisioning_status_error_category import ProvisioningStatusErrorCategory\nfrom .provisioning_status_error_category import ProvisioningStatusErrorCategory\nfields: Dict[str, Callable[[Any], None]] = {'a...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return ProvisioningErrorInfo() <|end_body_0|> <|body_start_1|> from .provisioning_status_error_category import ProvisioningStatusErrorCategory from .provisioning_status_error_category import Pr...
ProvisioningErrorInfo
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProvisioningErrorInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: """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 th...
stack_v2_sparse_classes_36k_train_022670
3,926
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: ProvisioningErrorInfo", "name": "create_from_discriminator_value", "signature": "def create_from_discriminat...
3
stack_v2_sparse_classes_30k_train_012120
Implement the Python class `ProvisioningErrorInfo` described below. Class description: Implement the ProvisioningErrorInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: Creates a new instance of the appropriate class base...
Implement the Python class `ProvisioningErrorInfo` described below. Class description: Implement the ProvisioningErrorInfo class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: Creates a new instance of the appropriate class base...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class ProvisioningErrorInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: """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 th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProvisioningErrorInfo: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ProvisioningErrorInfo: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur...
the_stack_v2_python_sparse
msgraph/generated/models/provisioning_error_info.py
microsoftgraph/msgraph-sdk-python
train
135
bd0554a0e4db39f52e818b7cc5460fa65d687ef2
[ "for x, y in (('gid', portage_gid), ('perms', 436)):\n if x in config:\n setattr(self, f'_{x}', config[x])\n del config[x]\n else:\n setattr(self, f'_{x}', y)\nsuper().__init__(**config)\nif label is not None:\n location = pjoin(location, label.lstrip(os.path.sep))\nself.location = loc...
<|body_start_0|> for x, y in (('gid', portage_gid), ('perms', 436)): if x in config: setattr(self, f'_{x}', config[x]) del config[x] else: setattr(self, f'_{x}', y) super().__init__(**config) if label is not None: ...
Template wrapping fs needed options. Provides _ensure_access as a way to attempt to ensure files have the specified owners/perms.
FsBased
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FsBased: """Template wrapping fs needed options. Provides _ensure_access as a way to attempt to ensure files have the specified owners/perms.""" def __init__(self, location, label=None, **config): """throws InitializationError if needs args aren't specified :keyword gid: defaults to ...
stack_v2_sparse_classes_36k_train_022671
2,222
permissive
[ { "docstring": "throws InitializationError if needs args aren't specified :keyword gid: defaults to :obj:`pkgcore.os_data.portage_gid`, gid to force all entries to :keyword perms: defaults to 0665, mode to force all entries to", "name": "__init__", "signature": "def __init__(self, location, label=None, ...
3
stack_v2_sparse_classes_30k_test_000673
Implement the Python class `FsBased` described below. Class description: Template wrapping fs needed options. Provides _ensure_access as a way to attempt to ensure files have the specified owners/perms. Method signatures and docstrings: - def __init__(self, location, label=None, **config): throws InitializationError ...
Implement the Python class `FsBased` described below. Class description: Template wrapping fs needed options. Provides _ensure_access as a way to attempt to ensure files have the specified owners/perms. Method signatures and docstrings: - def __init__(self, location, label=None, **config): throws InitializationError ...
ad4c3d51a2aff49ed898382c58baa852f47e17b9
<|skeleton|> class FsBased: """Template wrapping fs needed options. Provides _ensure_access as a way to attempt to ensure files have the specified owners/perms.""" def __init__(self, location, label=None, **config): """throws InitializationError if needs args aren't specified :keyword gid: defaults to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FsBased: """Template wrapping fs needed options. Provides _ensure_access as a way to attempt to ensure files have the specified owners/perms.""" def __init__(self, location, label=None, **config): """throws InitializationError if needs args aren't specified :keyword gid: defaults to :obj:`pkgcore...
the_stack_v2_python_sparse
src/pkgcore/cache/fs_template.py
pkgcore/pkgcore
train
107
7c1b06d06a9ef11b9b96e68adad7366c8c280132
[ "config = BaseModel.default_config()\nconfig['input_block'] = {'layout': 'cnap', 'c': dict(kernel_size=7, stride=2, filters=32), 'p': dict(kernel_size=3, stride=2)}\nconfig['body_block/dense'] = {'num_layers': (6, 12, 24, 16), 'layout': 'nac', 'kernel_size': 3, 'use_bottleneck': True, 'bottleneck_factor': 4, 'growt...
<|body_start_0|> config = BaseModel.default_config() config['input_block'] = {'layout': 'cnap', 'c': dict(kernel_size=7, stride=2, filters=32), 'p': dict(kernel_size=3, stride=2)} config['body_block/dense'] = {'num_layers': (6, 12, 24, 16), 'layout': 'nac', 'kernel_size': 3, 'use_bottleneck': Tr...
DenseNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DenseNet: def default_config(cls): """Get default config for DenseNet model.""" <|body_0|> def body_block(cls, input_shape, block, config): """Body block of densenet model.""" <|body_1|> <|end_skeleton|> <|body_start_0|> config = BaseModel.default_c...
stack_v2_sparse_classes_36k_train_022672
3,674
no_license
[ { "docstring": "Get default config for DenseNet model.", "name": "default_config", "signature": "def default_config(cls)" }, { "docstring": "Body block of densenet model.", "name": "body_block", "signature": "def body_block(cls, input_shape, block, config)" } ]
2
stack_v2_sparse_classes_30k_train_019449
Implement the Python class `DenseNet` described below. Class description: Implement the DenseNet class. Method signatures and docstrings: - def default_config(cls): Get default config for DenseNet model. - def body_block(cls, input_shape, block, config): Body block of densenet model.
Implement the Python class `DenseNet` described below. Class description: Implement the DenseNet class. Method signatures and docstrings: - def default_config(cls): Get default config for DenseNet model. - def body_block(cls, input_shape, block, config): Body block of densenet model. <|skeleton|> class DenseNet: ...
9554e0f96703a37a9a41fc70dc8e70e45c6181a2
<|skeleton|> class DenseNet: def default_config(cls): """Get default config for DenseNet model.""" <|body_0|> def body_block(cls, input_shape, block, config): """Body block of densenet model.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DenseNet: def default_config(cls): """Get default config for DenseNet model.""" config = BaseModel.default_config() config['input_block'] = {'layout': 'cnap', 'c': dict(kernel_size=7, stride=2, filters=32), 'p': dict(kernel_size=3, stride=2)} config['body_block/dense'] = {'num_...
the_stack_v2_python_sparse
dnn_backend/radio_dep/models/models/pytorch/models/densenet.py
theVmagnificient/radiology_web
train
0
066dc967932d8f126c6047804eef3ee16af627e7
[ "input_cube = self.precip_cube.copy()\ninput_cube.rename('air_temperature')\ninput_cube.units = 'K'\nplugin = CreateExtrapolationForecast(input_cube, self.vel_x, self.vel_y)\nresult = plugin.extrapolate(10)\nexpected_result = np.array([[np.nan, np.nan, np.nan], [np.nan, 1, 2], [np.nan, 1, 1], [np.nan, 0, 2]], dtype...
<|body_start_0|> input_cube = self.precip_cube.copy() input_cube.rename('air_temperature') input_cube.units = 'K' plugin = CreateExtrapolationForecast(input_cube, self.vel_x, self.vel_y) result = plugin.extrapolate(10) expected_result = np.array([[np.nan, np.nan, np.nan],...
Test the extrapolate method.
Test_extrapolate
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_extrapolate: """Test the extrapolate method.""" def test_without_orographic_enhancement(self): """Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minu...
stack_v2_sparse_classes_36k_train_022673
11,800
permissive
[ { "docstring": "Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minutes, our precipitation will have moved exactly one grid square along each axis.", "name": "test_without_orograp...
2
stack_v2_sparse_classes_30k_train_000255
Implement the Python class `Test_extrapolate` described below. Class description: Test the extrapolate method. Method signatures and docstrings: - def test_without_orographic_enhancement(self): Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advect...
Implement the Python class `Test_extrapolate` described below. Class description: Test the extrapolate method. Method signatures and docstrings: - def test_without_orographic_enhancement(self): Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advect...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test_extrapolate: """Test the extrapolate method.""" def test_without_orographic_enhancement(self): """Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_extrapolate: """Test the extrapolate method.""" def test_without_orographic_enhancement(self): """Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minutes, our prec...
the_stack_v2_python_sparse
improver_tests/nowcasting/forecasting/test_CreateExtrapolationForecast.py
metoppv/improver
train
101
461d2b085873b53b5c1f77c7940545d48e33d464
[ "dt_now = datetime.now()\ndt_future = dt_now + timedelta(days=30)\ninvoice_obj = Invoices()\ninvoice_obj.nr = None\ninvoice_obj.customer_id = customer_id\ninvoice_obj.price_sum_brutto = 0\ninvoice_obj.price_sum_netto = 0\ninvoice_obj.paid_sum_brutto = 0\ninvoice_obj.pay_form_id = None\ninvoice_obj.dt_created = dt_n...
<|body_start_0|> dt_now = datetime.now() dt_future = dt_now + timedelta(days=30) invoice_obj = Invoices() invoice_obj.nr = None invoice_obj.customer_id = customer_id invoice_obj.price_sum_brutto = 0 invoice_obj.price_sum_netto = 0 invoice_obj.paid_sum_brut...
InvoicesCommon
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InvoicesCommon: def create_empty_invoice(self, customer_id): """:param customer_id: :return:""" <|body_0|> def common_invoice_middle_show(self, web_context, invoice_obj): """:param web_context: :param invoice_obj: :return:""" <|body_1|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_36k_train_022674
6,738
no_license
[ { "docstring": ":param customer_id: :return:", "name": "create_empty_invoice", "signature": "def create_empty_invoice(self, customer_id)" }, { "docstring": ":param web_context: :param invoice_obj: :return:", "name": "common_invoice_middle_show", "signature": "def common_invoice_middle_sh...
2
stack_v2_sparse_classes_30k_train_004989
Implement the Python class `InvoicesCommon` described below. Class description: Implement the InvoicesCommon class. Method signatures and docstrings: - def create_empty_invoice(self, customer_id): :param customer_id: :return: - def common_invoice_middle_show(self, web_context, invoice_obj): :param web_context: :param...
Implement the Python class `InvoicesCommon` described below. Class description: Implement the InvoicesCommon class. Method signatures and docstrings: - def create_empty_invoice(self, customer_id): :param customer_id: :return: - def common_invoice_middle_show(self, web_context, invoice_obj): :param web_context: :param...
b1c72571da01c5d6f5e3bee27140931527132ef4
<|skeleton|> class InvoicesCommon: def create_empty_invoice(self, customer_id): """:param customer_id: :return:""" <|body_0|> def common_invoice_middle_show(self, web_context, invoice_obj): """:param web_context: :param invoice_obj: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InvoicesCommon: def create_empty_invoice(self, customer_id): """:param customer_id: :return:""" dt_now = datetime.now() dt_future = dt_now + timedelta(days=30) invoice_obj = Invoices() invoice_obj.nr = None invoice_obj.customer_id = customer_id invoice_o...
the_stack_v2_python_sparse
py/iai_invoice/invoices/utils/invoices_common.py
wiks/fakturkowo_DjangoSymfony5
train
0
ac12dd8b96fac67829490d7df53bb2f78005a3e0
[ "if DbContext.__instance is None:\n client = MongoClient('mongodb+srv://niobrara:niobrara123@adaptiveblinddateapp-hdqaj.mongodb.net/test')\n DbContext.__instance = client.timble\nreturn DbContext.__instance", "if DbContext.__instance is None:\n raise Exception('This class is a singleton!')\nelse:\n Db...
<|body_start_0|> if DbContext.__instance is None: client = MongoClient('mongodb+srv://niobrara:niobrara123@adaptiveblinddateapp-hdqaj.mongodb.net/test') DbContext.__instance = client.timble return DbContext.__instance <|end_body_0|> <|body_start_1|> if DbContext.__instan...
DbContext
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DbContext: def get_instance(): """Static access method.""" <|body_0|> def __init__(self): """Virtually private constructor.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if DbContext.__instance is None: client = MongoClient('mongodb+sr...
stack_v2_sparse_classes_36k_train_022675
620
no_license
[ { "docstring": "Static access method.", "name": "get_instance", "signature": "def get_instance()" }, { "docstring": "Virtually private constructor.", "name": "__init__", "signature": "def __init__(self)" } ]
2
stack_v2_sparse_classes_30k_train_002745
Implement the Python class `DbContext` described below. Class description: Implement the DbContext class. Method signatures and docstrings: - def get_instance(): Static access method. - def __init__(self): Virtually private constructor.
Implement the Python class `DbContext` described below. Class description: Implement the DbContext class. Method signatures and docstrings: - def get_instance(): Static access method. - def __init__(self): Virtually private constructor. <|skeleton|> class DbContext: def get_instance(): """Static access ...
17162732956f33e17619f26d1ff5b280a8f40856
<|skeleton|> class DbContext: def get_instance(): """Static access method.""" <|body_0|> def __init__(self): """Virtually private constructor.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DbContext: def get_instance(): """Static access method.""" if DbContext.__instance is None: client = MongoClient('mongodb+srv://niobrara:niobrara123@adaptiveblinddateapp-hdqaj.mongodb.net/test') DbContext.__instance = client.timble return DbContext.__instance ...
the_stack_v2_python_sparse
repository/db_context.py
soumenghosh2205/AdaptiveBlindDateApp
train
0
665a779dd1c850dd312112f8a3e637683717033d
[ "low = 1\nhigh = n\nwhile low <= high:\n mid = low + (high - low) // 2\n ans = guess(mid)\n if ans == 0:\n return mid\n elif ans == 1:\n high = mid - 1\n else:\n low = mid + 1", "low = 1\nhigh = n\nwhile low <= high:\n mid = low + (high - low) // 2\n ans = guess(mid)\n ...
<|body_start_0|> low = 1 high = n while low <= high: mid = low + (high - low) // 2 ans = guess(mid) if ans == 0: return mid elif ans == 1: high = mid - 1 else: low = mid + 1 <|end_body_0|>...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def guessNumber(self, n): """:type n: int :rtype: int""" <|body_0|> def guessNumber(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> low = 1 high = n while low <= high: mid =...
stack_v2_sparse_classes_36k_train_022676
1,047
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "guessNumber", "signature": "def guessNumber(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "guessNumber", "signature": "def guessNumber(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_016691
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def guessNumber(self, n): :type n: int :rtype: int - def guessNumber(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def guessNumber(self, n): :type n: int :rtype: int - def guessNumber(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def guessNumber(self, n): """:t...
4add324fb1cc41fee21fcb7c84083facbf18997e
<|skeleton|> class Solution: def guessNumber(self, n): """:type n: int :rtype: int""" <|body_0|> def guessNumber(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def guessNumber(self, n): """:type n: int :rtype: int""" low = 1 high = n while low <= high: mid = low + (high - low) // 2 ans = guess(mid) if ans == 0: return mid elif ans == 1: high = mi...
the_stack_v2_python_sparse
guess_number_higher_or_lower_374.py
taibaili/Pylc
train
0
82171a6c0a78b947813eab1a9dd5b4b71882e704
[ "tailA = headA\nwhile tailA.next:\n tailA = tailA.next\ntailA.next = headB\nfast, slow = (headA.next.next, headA.next)\nwhile fast and fast.next and (fast != slow):\n fast = fast.next.next\n slow = slow.next\nif not fast or not fast.next:\n tailA.next = None\n return None\nfast = headA\nwhile fast !=...
<|body_start_0|> tailA = headA while tailA.next: tailA = tailA.next tailA.next = headB fast, slow = (headA.next.next, headA.next) while fast and fast.next and (fast != slow): fast = fast.next.next slow = slow.next if not fast or not fas...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: """AC: 06/06/2022 Runtime: 213 ms, faster than 48.04% Memory Usage: 29.5 MB, less than 69.35% :param headA: :param headB: The number of nodes of listA is in the m. The number of nodes of lis...
stack_v2_sparse_classes_36k_train_022677
2,970
permissive
[ { "docstring": "AC: 06/06/2022 Runtime: 213 ms, faster than 48.04% Memory Usage: 29.5 MB, less than 69.35% :param headA: :param headB: The number of nodes of listA is in the m. The number of nodes of listB is in the n. 1 <= m, n <= 3 * 10^4 1 <= Node.val <= 10^5 0 <= skipA < m 0 <= skipB < n intersectVal is 0 i...
2
stack_v2_sparse_classes_30k_train_019318
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: AC: 06/06/2022 Runtime: 213 ms, faster than 48.04% Memory Usage: 29.5 MB, less than 69.35%...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: AC: 06/06/2022 Runtime: 213 ms, faster than 48.04% Memory Usage: 29.5 MB, less than 69.35%...
4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5
<|skeleton|> class Solution: def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: """AC: 06/06/2022 Runtime: 213 ms, faster than 48.04% Memory Usage: 29.5 MB, less than 69.35% :param headA: :param headB: The number of nodes of listA is in the m. The number of nodes of lis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getIntersectionNode2(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: """AC: 06/06/2022 Runtime: 213 ms, faster than 48.04% Memory Usage: 29.5 MB, less than 69.35% :param headA: :param headB: The number of nodes of listA is in the m. The number of nodes of listB is in the n...
the_stack_v2_python_sparse
src/160-IntersectionofTwoLinkedLists.py
Jiezhi/myleetcode
train
1
da2c3febebe42f269d2b0802d4378863d8d970ee
[ "this_user = self.context['request'].user\nworkflow = validated_data['workflow']\nif workflow.user != this_user:\n raise APIException(_('Incorrect permission to manipulate workflow.'))\naction = validated_data['action']\nif action is not None and action.workflow != workflow:\n raise APIException(_('Incorrect ...
<|body_start_0|> this_user = self.context['request'].user workflow = validated_data['workflow'] if workflow.user != this_user: raise APIException(_('Incorrect permission to manipulate workflow.')) action = validated_data['action'] if action is not None and action.work...
Serializer to take care of a few fields and the item column.
ScheduledOperationSerializer
[ "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "Apache-2.0", "LGPL-2.1-only", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScheduledOperationSerializer: """Serializer to take care of a few fields and the item column.""" def extra_validation(self, validated_data: Dict): """Check for extra properties. Checking for extra properties in the information contained in the validated data. Namely: - The action nam...
stack_v2_sparse_classes_36k_train_022678
8,568
permissive
[ { "docstring": "Check for extra properties. Checking for extra properties in the information contained in the validated data. Namely: - The action name corresponds with a valid action for the user. - The execution time must be in the future - The received object has a payload - The item_column, if present, must...
3
null
Implement the Python class `ScheduledOperationSerializer` described below. Class description: Serializer to take care of a few fields and the item column. Method signatures and docstrings: - def extra_validation(self, validated_data: Dict): Check for extra properties. Checking for extra properties in the information ...
Implement the Python class `ScheduledOperationSerializer` described below. Class description: Serializer to take care of a few fields and the item column. Method signatures and docstrings: - def extra_validation(self, validated_data: Dict): Check for extra properties. Checking for extra properties in the information ...
c432745dfff932cbe7397100422d49df78f0a882
<|skeleton|> class ScheduledOperationSerializer: """Serializer to take care of a few fields and the item column.""" def extra_validation(self, validated_data: Dict): """Check for extra properties. Checking for extra properties in the information contained in the validated data. Namely: - The action nam...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScheduledOperationSerializer: """Serializer to take care of a few fields and the item column.""" def extra_validation(self, validated_data: Dict): """Check for extra properties. Checking for extra properties in the information contained in the validated data. Namely: - The action name corresponds...
the_stack_v2_python_sparse
ontask/scheduler/serializers.py
abelardopardo/ontask_b
train
43
17a37e96b9caf44c6518a5e843566ef4ae767f43
[ "self._requirements: Dict[str, Dict] = requirements\nself.__sha_algorithm: str = sha_algorithm\nself.__download: Callable = download_func\nself.__download_args: Dict = download_func_args or {}\nself.__check_connection: Callable = check_connection or (lambda addr: True)", "if requirement[self.__sha_algorithm] != S...
<|body_start_0|> self._requirements: Dict[str, Dict] = requirements self.__sha_algorithm: str = sha_algorithm self.__download: Callable = download_func self.__download_args: Dict = download_func_args or {} self.__check_connection: Callable = check_connection or (lambda addr: True...
Wrapper for downloading requirements with checksum validation.
BaseDownloader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseDownloader: """Wrapper for downloading requirements with checksum validation.""" def __init__(self, requirements: Dict[str, Dict], sha_algorithm: str, download_func: Callable, download_func_args: Dict=None, check_connection: Callable=None): """:param requirements: data from parse...
stack_v2_sparse_classes_36k_train_022679
4,097
permissive
[ { "docstring": ":param requirements: data from parsed requirements file :param sha_algorithm: which algorithm will be used in validating the requirements :param download_func: back end function used for downloading the requirements :param download_func_args: optional args passed to the `download_func` :param ch...
3
null
Implement the Python class `BaseDownloader` described below. Class description: Wrapper for downloading requirements with checksum validation. Method signatures and docstrings: - def __init__(self, requirements: Dict[str, Dict], sha_algorithm: str, download_func: Callable, download_func_args: Dict=None, check_connect...
Implement the Python class `BaseDownloader` described below. Class description: Wrapper for downloading requirements with checksum validation. Method signatures and docstrings: - def __init__(self, requirements: Dict[str, Dict], sha_algorithm: str, download_func: Callable, download_func_args: Dict=None, check_connect...
6c917422dfa831ffb3eb7f8f5a616bc074734b66
<|skeleton|> class BaseDownloader: """Wrapper for downloading requirements with checksum validation.""" def __init__(self, requirements: Dict[str, Dict], sha_algorithm: str, download_func: Callable, download_func_args: Dict=None, check_connection: Callable=None): """:param requirements: data from parse...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseDownloader: """Wrapper for downloading requirements with checksum validation.""" def __init__(self, requirements: Dict[str, Dict], sha_algorithm: str, download_func: Callable, download_func_args: Dict=None, check_connection: Callable=None): """:param requirements: data from parsed requirement...
the_stack_v2_python_sparse
ansible/playbooks/roles/repository/files/download-requirements/src/downloader/base_downloader.py
seriva/epiphany
train
1
99c58e84b8f4739ae6f1c44654c687c14c7c0057
[ "if data['status'] == JSendStatus.SUCCESS or data['status'] == JSendStatus.FAIL:\n if 'data' not in data:\n raise ValidationError(f\"When status is {data['status']}, the data field must be populated.\")\nif data['status'] == JSendStatus.FAIL:\n if 'message' not in data['data']:\n raise Validatio...
<|body_start_0|> if data['status'] == JSendStatus.SUCCESS or data['status'] == JSendStatus.FAIL: if 'data' not in data: raise ValidationError(f"When status is {data['status']}, the data field must be populated.") if data['status'] == JSendStatus.FAIL: if 'message'...
A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend
JSendSchema
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSendSchema: """A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend""" def assert_fields(self, data, **kwargs): """Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`...
stack_v2_sparse_classes_36k_train_022680
2,641
permissive
[ { "docstring": "Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`~JSendStatus.SUCCESS` or :attr:`~JSendStatus.FAIL` - the ``message`` field is included when the status is :attr:`~JSendStatus.ERROR`", "name": "assert_fields", "signature": "def asser...
2
null
Implement the Python class `JSendSchema` described below. Class description: A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend Method signatures and docstrings: - def assert_fields(self, data, **kwargs): Asserts that, according to the specification: - ...
Implement the Python class `JSendSchema` described below. Class description: A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend Method signatures and docstrings: - def assert_fields(self, data, **kwargs): Asserts that, according to the specification: - ...
fc6f9230e4701cbddcb16d7257fddb9ff08bddb9
<|skeleton|> class JSendSchema: """A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend""" def assert_fields(self, data, **kwargs): """Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JSendSchema: """A Schema that encapsulates the logic of the `JSend Format`_. .. _`JSend Format`: https://labs.omniti.com/labs/jsend""" def assert_fields(self, data, **kwargs): """Asserts that, according to the specification: - the ``data`` field is included when the status is :attr:`~JSendStatus....
the_stack_v2_python_sparse
server/serializer/jsend.py
dragorhast/server
train
6
5da0dd8aae32f282d4a2182b7aa81dc4343397b1
[ "try:\n server = smtplib.SMTP(host, port)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login(username, password)\n return server\nexcept smtplib.SMTPException as e:\n logger.error('Could not establish SMTP connection: {}'.format(e))\n raise e", "bcc = to\nmessage = MIMEMult...
<|body_start_0|> try: server = smtplib.SMTP(host, port) server.ehlo() server.starttls() server.ehlo() server.login(username, password) return server except smtplib.SMTPException as e: logger.error('Could not establish SM...
Creates connection and mail message body.
Emailer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Emailer: """Creates connection and mail message body.""" def run_server(self, host, port, username, password): """This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the ho...
stack_v2_sparse_classes_36k_train_022681
1,797
no_license
[ { "docstring": "This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the host server", "name": "run_server", "signature": "def run_server(self, host, port, username, password)" }, { "do...
2
null
Implement the Python class `Emailer` described below. Class description: Creates connection and mail message body. Method signatures and docstrings: - def run_server(self, host, port, username, password): This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: u...
Implement the Python class `Emailer` described below. Class description: Creates connection and mail message body. Method signatures and docstrings: - def run_server(self, host, port, username, password): This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: u...
e4bf166f3ffe226668396c8beba3d369b3b4428f
<|skeleton|> class Emailer: """Creates connection and mail message body.""" def run_server(self, host, port, username, password): """This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the ho...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Emailer: """Creates connection and mail message body.""" def run_server(self, host, port, username, password): """This function manages connection to SMTP or ESMTP server. Args: - host: host name - port: host port - username: username on the host server - password: password on the host server""" ...
the_stack_v2_python_sparse
notification_service/notification/handlers/emailer.py
timegenconsulting/tp-django-site
train
0
deb205ba7e0ebde9727ba76a8ae2e43aa8068d9d
[ "user = get_user_from_username(request.user, username)\nis_self = user == request.user\nif is_self:\n shelves = user.shelf_set.all()\nelse:\n shelves = models.Shelf.privacy_filter(request.user).filter(user=user).all()\nif shelf_identifier:\n shelf = get_object_or_404(user.shelf_set, identifier=shelf_identi...
<|body_start_0|> user = get_user_from_username(request.user, username) is_self = user == request.user if is_self: shelves = user.shelf_set.all() else: shelves = models.Shelf.privacy_filter(request.user).filter(user=user).all() if shelf_identifier: ...
shelf page
Shelf
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Shelf: """shelf page""" def get(self, request, username, shelf_identifier=None): """display a shelf""" <|body_0|> def post(self, request, username, shelf_identifier): """edit a shelf""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = get_use...
stack_v2_sparse_classes_36k_train_022682
5,096
no_license
[ { "docstring": "display a shelf", "name": "get", "signature": "def get(self, request, username, shelf_identifier=None)" }, { "docstring": "edit a shelf", "name": "post", "signature": "def post(self, request, username, shelf_identifier)" } ]
2
null
Implement the Python class `Shelf` described below. Class description: shelf page Method signatures and docstrings: - def get(self, request, username, shelf_identifier=None): display a shelf - def post(self, request, username, shelf_identifier): edit a shelf
Implement the Python class `Shelf` described below. Class description: shelf page Method signatures and docstrings: - def get(self, request, username, shelf_identifier=None): display a shelf - def post(self, request, username, shelf_identifier): edit a shelf <|skeleton|> class Shelf: """shelf page""" def ge...
0f8da5b738047f3c34d60d93f59bdedd8f797224
<|skeleton|> class Shelf: """shelf page""" def get(self, request, username, shelf_identifier=None): """display a shelf""" <|body_0|> def post(self, request, username, shelf_identifier): """edit a shelf""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Shelf: """shelf page""" def get(self, request, username, shelf_identifier=None): """display a shelf""" user = get_user_from_username(request.user, username) is_self = user == request.user if is_self: shelves = user.shelf_set.all() else: shel...
the_stack_v2_python_sparse
bookwyrm/views/shelf/shelf.py
bookwyrm-social/bookwyrm
train
1,398
a705c1dc4d518cdf234b011a27d35a60ed3cb0a9
[ "super().__init__(experiment)\nfrom dials.algorithms.shoebox import MaskEmpirical\nself.mask_empirical = MaskEmpirical(reference)\nself._reference = reference", "reflections = super().__call__(reflections, adjacency_list)\nif self.mask_empirical:\n self.mask_empirical(reflections)\nreturn reflections" ]
<|body_start_0|> super().__init__(experiment) from dials.algorithms.shoebox import MaskEmpirical self.mask_empirical = MaskEmpirical(reference) self._reference = reference <|end_body_0|> <|body_start_1|> reflections = super().__call__(reflections, adjacency_list) if self...
A class to perform empirical masking
MaskerEmpirical
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaskerEmpirical: """A class to perform empirical masking""" def __init__(self, experiment, reference): """Initialise the masking algorithms Params: experiment The experiment data""" <|body_0|> def __call__(self, reflections, adjacency_list=None): """Mask the give...
stack_v2_sparse_classes_36k_train_022683
3,387
permissive
[ { "docstring": "Initialise the masking algorithms Params: experiment The experiment data", "name": "__init__", "signature": "def __init__(self, experiment, reference)" }, { "docstring": "Mask the given reflections. Params: reflections The reflection list adjacency_list The adjacency_list (option...
2
stack_v2_sparse_classes_30k_train_014737
Implement the Python class `MaskerEmpirical` described below. Class description: A class to perform empirical masking Method signatures and docstrings: - def __init__(self, experiment, reference): Initialise the masking algorithms Params: experiment The experiment data - def __call__(self, reflections, adjacency_list...
Implement the Python class `MaskerEmpirical` described below. Class description: A class to perform empirical masking Method signatures and docstrings: - def __init__(self, experiment, reference): Initialise the masking algorithms Params: experiment The experiment data - def __call__(self, reflections, adjacency_list...
88bf7f7c5ac44defc046ebf0719cde748092cfff
<|skeleton|> class MaskerEmpirical: """A class to perform empirical masking""" def __init__(self, experiment, reference): """Initialise the masking algorithms Params: experiment The experiment data""" <|body_0|> def __call__(self, reflections, adjacency_list=None): """Mask the give...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaskerEmpirical: """A class to perform empirical masking""" def __init__(self, experiment, reference): """Initialise the masking algorithms Params: experiment The experiment data""" super().__init__(experiment) from dials.algorithms.shoebox import MaskEmpirical self.mask_e...
the_stack_v2_python_sparse
src/dials/algorithms/shoebox/masker.py
dials/dials
train
71
e6fddc928ef5d0c98d399ded2897d080c5bc3fd0
[ "jwt_value = self.get_jwt_value(request)\nif jwt_value is None:\n return None\ntry:\n payload = jwt_decode_handler(jwt_value)\nexcept jwt.ExpiredSignature:\n msg = _('Signature has expired.')\n raise exceptions.AuthenticationFailed(msg)\nexcept jwt.DecodeError:\n msg = _('Error decoding signature.')\...
<|body_start_0|> jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg...
Token based authentication using the JSON Web Token standard. 重写jwt 单点登录token问题 用redis做状态
MyBaseJSONWebTokenAuthentication
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyBaseJSONWebTokenAuthentication: """Token based authentication using the JSON Web Token standard. 重写jwt 单点登录token问题 用redis做状态""" def authenticate(self, request): """Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwi...
stack_v2_sparse_classes_36k_train_022684
16,023
permissive
[ { "docstring": "Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`.", "name": "authenticate", "signature": "def authenticate(self, request)" }, { "docstring": "Returns an active user that matches the payload's u...
2
null
Implement the Python class `MyBaseJSONWebTokenAuthentication` described below. Class description: Token based authentication using the JSON Web Token standard. 重写jwt 单点登录token问题 用redis做状态 Method signatures and docstrings: - def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature ...
Implement the Python class `MyBaseJSONWebTokenAuthentication` described below. Class description: Token based authentication using the JSON Web Token standard. 重写jwt 单点登录token问题 用redis做状态 Method signatures and docstrings: - def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature ...
c9c143eaba6c06e3cee866669ec286e4d3cdbba8
<|skeleton|> class MyBaseJSONWebTokenAuthentication: """Token based authentication using the JSON Web Token standard. 重写jwt 单点登录token问题 用redis做状态""" def authenticate(self, request): """Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyBaseJSONWebTokenAuthentication: """Token based authentication using the JSON Web Token standard. 重写jwt 单点登录token问题 用redis做状态""" def authenticate(self, request): """Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `N...
the_stack_v2_python_sparse
Python3/Tornado/apps/pg/PG_Client/clientadmin/serializers.py
youngqqcn/QBlockChainNotes
train
37
c8b27eee8b5c9b83117c4c30bedf601980475f03
[ "fig_legend = self.get_legend()\nif self.show_legend is not False and fig_legend is not None:\n fig_legend.set_visible(True)\nself.grid(grid_on=True)", "de = CDensityEstimation(**params)\nxm, malicious_pdf = de.estimate_density(scores[ts.Y == 1])\nxb, benign_pdf = de.estimate_density(scores[ts.Y == 0])\nself.p...
<|body_start_0|> fig_legend = self.get_legend() if self.show_legend is not False and fig_legend is not None: fig_legend.set_visible(True) self.grid(grid_on=True) <|end_body_0|> <|body_start_1|> de = CDensityEstimation(**params) xm, malicious_pdf = de.estimate_density...
Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures.
CPlotStats
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CPlotStats: """Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures.""" def apply_params_stats(self): ""...
stack_v2_sparse_classes_36k_train_022685
1,328
permissive
[ { "docstring": "Apply defined parameters to active subplot.", "name": "apply_params_stats", "signature": "def apply_params_stats(self)" }, { "docstring": "Plot density estimation of benign and malicious class.", "name": "plot_prob_density", "signature": "def plot_prob_density(self, score...
2
stack_v2_sparse_classes_30k_train_013398
Implement the Python class `CPlotStats` described below. Class description: Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures. Method s...
Implement the Python class `CPlotStats` described below. Class description: Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures. Method s...
431373e65d8cfe2cb7cf042ce1a6c9519ea5a14a
<|skeleton|> class CPlotStats: """Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures.""" def apply_params_stats(self): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CPlotStats: """Plots for statistical functions. Custom plotting parameters can be specified. Currently parameters default: - `show_legend`: True. - grid: True. See Also -------- CPlot : basic subplot functions. CFigure : creates and handle figures.""" def apply_params_stats(self): """Apply define...
the_stack_v2_python_sparse
src/secml/figure/_plots/c_plot_stats.py
Cinofix/secml
train
0
a3cfd76931aa64d1a046a0d593bf94836548521a
[ "def preorder(root):\n if root:\n res.append(str(root.val))\n preorder(root.left)\n preorder(root.right)\nres = list()\npreorder(root)\nreturn ' '.join(res)", "left = float('-inf')\nright = float('inf')\ndata = [int(val) for val in data.strip('[]{}').split(',')]\nlength = len(data)\nindex ...
<|body_start_0|> def preorder(root): if root: res.append(str(root.val)) preorder(root.left) preorder(root.right) res = list() preorder(root) return ' '.join(res) <|end_body_0|> <|body_start_1|> left = float('-inf') ...
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_022686
3,101
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:...
6b24724da055a08510c83c645455eaa4ed201298
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" def preorder(root): if root: res.append(str(root.val)) preorder(root.left) preorder(root.right) res = list() p...
the_stack_v2_python_sparse
Tree/python/leetcode/serialize_and_deserialize_bst.py
sankeerth/Algorithms
train
0
da4151eeaac8516893d2ed4a718c5a7076952036
[ "with open('sat.json', 'r') as infile:\n self._sat = json.load(infile)['data']\nself._headers = ['DBN', 'School Name', 'Number of Test Takers', 'Critical Reading Mean', 'Mathematics Mean', 'Writing Mean']", "with open('output.csv', 'w') as outfile:\n for i in range(0, 5):\n outfile.write(self._header...
<|body_start_0|> with open('sat.json', 'r') as infile: self._sat = json.load(infile)['data'] self._headers = ['DBN', 'School Name', 'Number of Test Takers', 'Critical Reading Mean', 'Mathematics Mean', 'Writing Mean'] <|end_body_0|> <|body_start_1|> with open('output.csv', 'w') as o...
SatData
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SatData: def __init__(self): """Initializes the SatData object and reads in the .json file""" <|body_0|> def save_as_csv(self, DBNs): """This method takes a list of district bureau numbers and saves a CSV file""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_022687
1,403
no_license
[ { "docstring": "Initializes the SatData object and reads in the .json file", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This method takes a list of district bureau numbers and saves a CSV file", "name": "save_as_csv", "signature": "def save_as_csv(self, DBNs...
2
stack_v2_sparse_classes_30k_train_011631
Implement the Python class `SatData` described below. Class description: Implement the SatData class. Method signatures and docstrings: - def __init__(self): Initializes the SatData object and reads in the .json file - def save_as_csv(self, DBNs): This method takes a list of district bureau numbers and saves a CSV fi...
Implement the Python class `SatData` described below. Class description: Implement the SatData class. Method signatures and docstrings: - def __init__(self): Initializes the SatData object and reads in the .json file - def save_as_csv(self, DBNs): This method takes a list of district bureau numbers and saves a CSV fi...
281749a4ac6961f146ebd9abaf79ccf641262619
<|skeleton|> class SatData: def __init__(self): """Initializes the SatData object and reads in the .json file""" <|body_0|> def save_as_csv(self, DBNs): """This method takes a list of district bureau numbers and saves a CSV file""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SatData: def __init__(self): """Initializes the SatData object and reads in the .json file""" with open('sat.json', 'r') as infile: self._sat = json.load(infile)['data'] self._headers = ['DBN', 'School Name', 'Number of Test Takers', 'Critical Reading Mean', 'Mathematics Me...
the_stack_v2_python_sparse
project 5/5c/SatData.py
huynmela/CS162
train
0
6017b71578f433731fe772948cebaa8db7445fd0
[ "self.subtrie = dict()\nself.isWord = False\nself.val = ''", "if not word:\n self.isWord = True\n return\nif word[0] not in self.subtrie:\n t = Trie()\n t.val = word[0]\n self.subtrie[word[0]] = t\nself.subtrie[word[0]].insert(word[1:])", "t = self\nfor v in word:\n if v in t.subtrie:\n ...
<|body_start_0|> self.subtrie = dict() self.isWord = False self.val = '' <|end_body_0|> <|body_start_1|> if not word: self.isWord = True return if word[0] not in self.subtrie: t = Trie() t.val = word[0] self.subtrie[wor...
Trie
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trie: def __init__(self): """Initialize your data structure here.""" <|body_0|> def insert(self, word): """Inserts a word into the trie. :type word: str :rtype: void""" <|body_1|> def search(self, word): """Returns if the word is in the trie. :ty...
stack_v2_sparse_classes_36k_train_022688
1,460
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a word into the trie. :type word: str :rtype: void", "name": "insert", "signature": "def insert(self, word)" }, { "docstring": "Returns if the w...
4
null
Implement the Python class `Trie` described below. Class description: Implement the Trie class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def insert(self, word): Inserts a word into the trie. :type word: str :rtype: void - def search(self, word): Returns if the wor...
Implement the Python class `Trie` described below. Class description: Implement the Trie class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def insert(self, word): Inserts a word into the trie. :type word: str :rtype: void - def search(self, word): Returns if the wor...
9eb44afa4233fdedc2e5c72be0fdf54b25d1c45c
<|skeleton|> class Trie: def __init__(self): """Initialize your data structure here.""" <|body_0|> def insert(self, word): """Inserts a word into the trie. :type word: str :rtype: void""" <|body_1|> def search(self, word): """Returns if the word is in the trie. :ty...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trie: def __init__(self): """Initialize your data structure here.""" self.subtrie = dict() self.isWord = False self.val = '' def insert(self, word): """Inserts a word into the trie. :type word: str :rtype: void""" if not word: self.isWord = True...
the_stack_v2_python_sparse
Facebook/Pro208. Implement Trie (Prefix Tree).py
YoyinZyc/Leetcode_Python
train
0
44d6acc5c4a549324a4cfab6cd6e3ae09c0f0967
[ "self.topic = cfg['topic']\nself.host = cfg['host']\nself.port = cfg['port']\nself.username = cfg['username']\nself.password = cfg['password']", "LOGGER.debug('Sending message of triggered event | event: {0}'.format(msg))\nif self.username is not None and self.password is not None:\n publish.single(self.topic,...
<|body_start_0|> self.topic = cfg['topic'] self.host = cfg['host'] self.port = cfg['port'] self.username = cfg['username'] self.password = cfg['password'] <|end_body_0|> <|body_start_1|> LOGGER.debug('Sending message of triggered event | event: {0}'.format(msg)) ...
An MQTT implementation of a sender to dispatch the application's events. Methods: send
MqttSender
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MqttSender: """An MQTT implementation of a sender to dispatch the application's events. Methods: send""" def __init__(self, cfg: dict): """MqttSender's constructor. Params ------ cfg: dict -- the MQTT sender adapter's configuration""" <|body_0|> def send(self, msg): ...
stack_v2_sparse_classes_36k_train_022689
4,940
permissive
[ { "docstring": "MqttSender's constructor. Params ------ cfg: dict -- the MQTT sender adapter's configuration", "name": "__init__", "signature": "def __init__(self, cfg: dict)" }, { "docstring": "View @app.domain.ports.QueueSender.", "name": "send", "signature": "def send(self, msg)" } ...
2
stack_v2_sparse_classes_30k_train_001482
Implement the Python class `MqttSender` described below. Class description: An MQTT implementation of a sender to dispatch the application's events. Methods: send Method signatures and docstrings: - def __init__(self, cfg: dict): MqttSender's constructor. Params ------ cfg: dict -- the MQTT sender adapter's configura...
Implement the Python class `MqttSender` described below. Class description: An MQTT implementation of a sender to dispatch the application's events. Methods: send Method signatures and docstrings: - def __init__(self, cfg: dict): MqttSender's constructor. Params ------ cfg: dict -- the MQTT sender adapter's configura...
7192ef724ceed9aa60c03ee3bda2a97a8b532298
<|skeleton|> class MqttSender: """An MQTT implementation of a sender to dispatch the application's events. Methods: send""" def __init__(self, cfg: dict): """MqttSender's constructor. Params ------ cfg: dict -- the MQTT sender adapter's configuration""" <|body_0|> def send(self, msg): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MqttSender: """An MQTT implementation of a sender to dispatch the application's events. Methods: send""" def __init__(self, cfg: dict): """MqttSender's constructor. Params ------ cfg: dict -- the MQTT sender adapter's configuration""" self.topic = cfg['topic'] self.host = cfg['hos...
the_stack_v2_python_sparse
app/adapters/mqtt.py
LucasRGoes/ports-adapters-sample
train
43
689a23e578063f29e15e85e0fe6572fb5a382aa8
[ "Figure.__init__(self, name=name)\nself.xvar, self.yvar = (xvar, yvar)\nself.render(data, **kwargs)", "self.fig = self.create_figure(figsize)\nself.add_axes()\nself._add_markers(data[self.xvar], data[self.yvar], c='k', s=1)\nself.format()", "_ = ax.spines['top'].set_visible(False)\n_ = ax.spines['right'].set_vi...
<|body_start_0|> Figure.__init__(self, name=name) self.xvar, self.yvar = (xvar, yvar) self.render(data, **kwargs) <|end_body_0|> <|body_start_1|> self.fig = self.create_figure(figsize) self.add_axes() self._add_markers(data[self.xvar], data[self.yvar], c='k', s=1) ...
Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)
Scatterplot
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Scatterplot: """Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)""" def __ini...
stack_v2_sparse_classes_36k_train_022690
8,479
permissive
[ { "docstring": "Instantiate scatter plot. Args: data (pd.DataFrame) - selected cell measurement data xvar, yvar (str) - cell measurement features to be scattered name (str) - figure name kwargs: keyword arguments for", "name": "__init__", "signature": "def __init__(self, data, xvar, yvar, name, **kwargs...
3
stack_v2_sparse_classes_30k_train_003531
Implement the Python class `Scatterplot` described below. Class description: Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotl...
Implement the Python class `Scatterplot` described below. Class description: Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotl...
4a622c3f5fed4456c3b9240f5a96428789fde9bd
<|skeleton|> class Scatterplot: """Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)""" def __ini...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Scatterplot: """Scatter points in XY plane. Attributes: xvar, yvar (str) - cell measurement features to be scattered Inherited attributes: name (str) - figure name directory (str) - default path for saving figure fig (matplotlib.figure.Figure) axes (matplotlib.axes.AxesSubplots)""" def __init__(self, dat...
the_stack_v2_python_sparse
flyqma/visualization/figures.py
sbernasek/flyqma
train
1
7e766aacfad92a5527b3fcebb8cd70b350e09244
[ "self._base_item = None\nif description is None:\n description = name\nif description in translations:\n self._base_item = description + ':'\n description = translations[description].get_string(**tokens)\nsuper().__init__(cvar_prefix + name, default, description, flags, min_value, max_value)\nself.translat...
<|body_start_0|> self._base_item = None if description is None: description = name if description in translations: self._base_item = description + ':' description = translations[description].get_string(**tokens) super().__init__(cvar_prefix + name, def...
Class used to more easily add translations for cvars in config files.
_GunGameCvarManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _GunGameCvarManager: """Class used to more easily add translations for cvars in config files.""" def __init__(self, name, default, description, flags, min_value, max_value, cvar_prefix, translations, **tokens): """Get the true description and store the translations.""" <|body...
stack_v2_sparse_classes_36k_train_022691
4,371
no_license
[ { "docstring": "Get the true description and store the translations.", "name": "__init__", "signature": "def __init__(self, name, default, description, flags, min_value, max_value, cvar_prefix, translations, **tokens)" }, { "docstring": "Add all other text for the ConVar.", "name": "add_text...
2
null
Implement the Python class `_GunGameCvarManager` described below. Class description: Class used to more easily add translations for cvars in config files. Method signatures and docstrings: - def __init__(self, name, default, description, flags, min_value, max_value, cvar_prefix, translations, **tokens): Get the true ...
Implement the Python class `_GunGameCvarManager` described below. Class description: Class used to more easily add translations for cvars in config files. Method signatures and docstrings: - def __init__(self, name, default, description, flags, min_value, max_value, cvar_prefix, translations, **tokens): Get the true ...
dd76d1f581a1a8aff18c2194834665fa66a82aab
<|skeleton|> class _GunGameCvarManager: """Class used to more easily add translations for cvars in config files.""" def __init__(self, name, default, description, flags, min_value, max_value, cvar_prefix, translations, **tokens): """Get the true description and store the translations.""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _GunGameCvarManager: """Class used to more easily add translations for cvars in config files.""" def __init__(self, name, default, description, flags, min_value, max_value, cvar_prefix, translations, **tokens): """Get the true description and store the translations.""" self._base_item = N...
the_stack_v2_python_sparse
addons/source-python/plugins/gungame/core/config/manager.py
Hackmastr/GunGame-SP
train
0
4509f180ef7bf4824c3b1b75f3778c87553dce86
[ "super(AdaptiveLossFunction, self).__init__(name=name)\n_check_scale(scale_lo, scale_init)\nif not np.isscalar(alpha_lo):\n raise ValueError('`alpha_lo` must be a scalar, but is of type {}'.format(type(alpha_lo)))\nif not np.isscalar(alpha_hi):\n raise ValueError('`alpha_hi` must be a scalar, but is of type {...
<|body_start_0|> super(AdaptiveLossFunction, self).__init__(name=name) _check_scale(scale_lo, scale_init) if not np.isscalar(alpha_lo): raise ValueError('`alpha_lo` must be a scalar, but is of type {}'.format(type(alpha_lo))) if not np.isscalar(alpha_hi): raise Va...
Implements the adaptive form of the general loss for matrix inputs. This loss behaves differently from general.lossfun() and distribution.nllfun(), which are "stateless", allow the caller to specify the shape and scale of the loss, and allow for arbitrary sized inputs. This loss only allows for rank-2 inputs, and expec...
AdaptiveLossFunction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdaptiveLossFunction: """Implements the adaptive form of the general loss for matrix inputs. This loss behaves differently from general.lossfun() and distribution.nllfun(), which are "stateless", allow the caller to specify the shape and scale of the loss, and allow for arbitrary sized inputs. Th...
stack_v2_sparse_classes_36k_train_022692
23,679
permissive
[ { "docstring": "Constructs the loss function. Args: num_channels: the number of different \"channels\" for the adaptive loss function, where each channel will be assigned its own shape (alpha) and scale parameters that are constructed as variables and can be optimized over. float_dtype: The expected numerical p...
4
stack_v2_sparse_classes_30k_test_000073
Implement the Python class `AdaptiveLossFunction` described below. Class description: Implements the adaptive form of the general loss for matrix inputs. This loss behaves differently from general.lossfun() and distribution.nllfun(), which are "stateless", allow the caller to specify the shape and scale of the loss, a...
Implement the Python class `AdaptiveLossFunction` described below. Class description: Implements the adaptive form of the general loss for matrix inputs. This loss behaves differently from general.lossfun() and distribution.nllfun(), which are "stateless", allow the caller to specify the shape and scale of the loss, a...
727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7
<|skeleton|> class AdaptiveLossFunction: """Implements the adaptive form of the general loss for matrix inputs. This loss behaves differently from general.lossfun() and distribution.nllfun(), which are "stateless", allow the caller to specify the shape and scale of the loss, and allow for arbitrary sized inputs. Th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdaptiveLossFunction: """Implements the adaptive form of the general loss for matrix inputs. This loss behaves differently from general.lossfun() and distribution.nllfun(), which are "stateless", allow the caller to specify the shape and scale of the loss, and allow for arbitrary sized inputs. This loss only ...
the_stack_v2_python_sparse
robust_loss/adaptive.py
Ayoob7/google-research
train
2
1c6b3eb5a901c2524b83e570236be272a60cdbed
[ "if user not in connector:\n uuid = str(uuid4())\n connector.setdefault(uuid, user)\n logger.debug('用户:%s,加入连接' % connector.get(uuid))\n return uuid", "logger.debug('用户:%s,断开连接' % uuid)\ntry:\n del connector[uuid]\nexcept Exception as e:\n logger.error(e)\nelse:\n logger.success('成功清理用户:%s连接信...
<|body_start_0|> if user not in connector: uuid = str(uuid4()) connector.setdefault(uuid, user) logger.debug('用户:%s,加入连接' % connector.get(uuid)) return uuid <|end_body_0|> <|body_start_1|> logger.debug('用户:%s,断开连接' % uuid) try: del con...
用户控制及推送
PushCore
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PushCore: """用户控制及推送""" def user_connect(user): """pass :param user: :return:""" <|body_0|> def user_remove(uuid): """pass :param uuid: :return:""" <|body_1|> def trigger(message, uuid=None): """向已被记录的客户端推送最新内容 :param uuid: :param message: :r...
stack_v2_sparse_classes_36k_train_022693
2,077
no_license
[ { "docstring": "pass :param user: :return:", "name": "user_connect", "signature": "def user_connect(user)" }, { "docstring": "pass :param uuid: :return:", "name": "user_remove", "signature": "def user_remove(uuid)" }, { "docstring": "向已被记录的客户端推送最新内容 :param uuid: :param message: :...
3
stack_v2_sparse_classes_30k_train_019381
Implement the Python class `PushCore` described below. Class description: 用户控制及推送 Method signatures and docstrings: - def user_connect(user): pass :param user: :return: - def user_remove(uuid): pass :param uuid: :return: - def trigger(message, uuid=None): 向已被记录的客户端推送最新内容 :param uuid: :param message: :return:
Implement the Python class `PushCore` described below. Class description: 用户控制及推送 Method signatures and docstrings: - def user_connect(user): pass :param user: :return: - def user_remove(uuid): pass :param uuid: :return: - def trigger(message, uuid=None): 向已被记录的客户端推送最新内容 :param uuid: :param message: :return: <|skele...
00ca5023d500a0f08389fb1b961776808cd260ab
<|skeleton|> class PushCore: """用户控制及推送""" def user_connect(user): """pass :param user: :return:""" <|body_0|> def user_remove(uuid): """pass :param uuid: :return:""" <|body_1|> def trigger(message, uuid=None): """向已被记录的客户端推送最新内容 :param uuid: :param message: :r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PushCore: """用户控制及推送""" def user_connect(user): """pass :param user: :return:""" if user not in connector: uuid = str(uuid4()) connector.setdefault(uuid, user) logger.debug('用户:%s,加入连接' % connector.get(uuid)) return uuid def user_remove...
the_stack_v2_python_sparse
Core/ConnectCore.py
Clare-York/tornado_demo
train
1
c09dd5c06160b9e5c00ea28e0610d0f0268def4d
[ "if level is None:\n self.logLevel = logging.INFO\nelse:\n pass", "logger = logging.getLogger(_name)\nlogger.setLevel(self.logLevel)\nhandler = logging.FileHandler('output_files/log_examp.log')\nhandler.setLevel(self.logLevel)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(messag...
<|body_start_0|> if level is None: self.logLevel = logging.INFO else: pass <|end_body_0|> <|body_start_1|> logger = logging.getLogger(_name) logger.setLevel(self.logLevel) handler = logging.FileHandler('output_files/log_examp.log') handler.setLeve...
DOCSTRING.
CfgLogger
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CfgLogger: """DOCSTRING.""" def __init__(self, level=None): """DOCSTRING.""" <|body_0|> def create_logger(self, _name): """DOCSTRING.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if level is None: self.logLevel = logging.INFO ...
stack_v2_sparse_classes_36k_train_022694
836
no_license
[ { "docstring": "DOCSTRING.", "name": "__init__", "signature": "def __init__(self, level=None)" }, { "docstring": "DOCSTRING.", "name": "create_logger", "signature": "def create_logger(self, _name)" } ]
2
stack_v2_sparse_classes_30k_train_011031
Implement the Python class `CfgLogger` described below. Class description: DOCSTRING. Method signatures and docstrings: - def __init__(self, level=None): DOCSTRING. - def create_logger(self, _name): DOCSTRING.
Implement the Python class `CfgLogger` described below. Class description: DOCSTRING. Method signatures and docstrings: - def __init__(self, level=None): DOCSTRING. - def create_logger(self, _name): DOCSTRING. <|skeleton|> class CfgLogger: """DOCSTRING.""" def __init__(self, level=None): """DOCSTRIN...
4c4b8fb381c8d98980e119f7f73f393034393468
<|skeleton|> class CfgLogger: """DOCSTRING.""" def __init__(self, level=None): """DOCSTRING.""" <|body_0|> def create_logger(self, _name): """DOCSTRING.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CfgLogger: """DOCSTRING.""" def __init__(self, level=None): """DOCSTRING.""" if level is None: self.logLevel = logging.INFO else: pass def create_logger(self, _name): """DOCSTRING.""" logger = logging.getLogger(_name) logger.set...
the_stack_v2_python_sparse
Python_Scripts/config/log.py
jommysmoth/ECE_Music
train
0
2bc999e8f14c573c2c3b44bfaec1a05889999048
[ "if not lists:\n return\nelif len(lists) == 1:\n return lists[0]\nmid = len(lists) // 2\nleft = self.mergeKLists(lists[:mid])\nright = self.mergeKLists(lists[mid:])\nreturn self.mergeTwoLists(left, right)", "pre = ListNode(-1)\ncur = pre\nwhile l1 and l2:\n if l1.val <= l2.val:\n cur.next = l1\n ...
<|body_start_0|> if not lists: return elif len(lists) == 1: return lists[0] mid = len(lists) // 2 left = self.mergeKLists(lists[:mid]) right = self.mergeKLists(lists[mid:]) return self.mergeTwoLists(left, right) <|end_body_0|> <|body_start_1|> ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" <|body_0|> def mergeTwoLists(self, l1, l2): """:type l1: ListNode :type l2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not l...
stack_v2_sparse_classes_36k_train_022695
1,125
permissive
[ { "docstring": ":type lists: List[ListNode] :rtype: ListNode", "name": "mergeKLists", "signature": "def mergeKLists(self, lists)" }, { "docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode", "name": "mergeTwoLists", "signature": "def mergeTwoLists(self, l1, l2)" } ]
2
stack_v2_sparse_classes_30k_train_011036
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode - def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode - def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode <|skeleton|>...
eb58cd4f01d9b8006b7d1a725fc48910aad7f192
<|skeleton|> class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" <|body_0|> def mergeTwoLists(self, l1, l2): """:type l1: ListNode :type l2: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mergeKLists(self, lists): """:type lists: List[ListNode] :rtype: ListNode""" if not lists: return elif len(lists) == 1: return lists[0] mid = len(lists) // 2 left = self.mergeKLists(lists[:mid]) right = self.mergeKLists(list...
the_stack_v2_python_sparse
1stRound/Hard/23-Merge K Sorted Lists/Merge2ListRecursion.py
ericchen12377/Leetcode-Algorithm-Python
train
2
b8173d8f3c95d53202e04eb9aeac4ea64e95ce78
[ "ws = cls.get_source_values(index_chunk, f'windspeed_{height}m', source_files)\nwd = cls.get_source_values(index_chunk, f'winddirection_{height}m', source_files)\nu = ws * np.sin(np.radians(wd))\nv = ws * np.cos(np.radians(wd))\nreturn (u, v)", "ws = np.hypot(u, v)\nwd = np.rad2deg(np.arctan2(u, v))\nwd = (wd + 3...
<|body_start_0|> ws = cls.get_source_values(index_chunk, f'windspeed_{height}m', source_files) wd = cls.get_source_values(index_chunk, f'winddirection_{height}m', source_files) u = ws * np.sin(np.radians(wd)) v = ws * np.cos(np.radians(wd)) return (u, v) <|end_body_0|> <|body_st...
Class to regrid windspeed and winddirection. Includes methods for converting windspeed and winddirection to U and V and inverting after interpolation
WindRegridder
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindRegridder: """Class to regrid windspeed and winddirection. Includes methods for converting windspeed and winddirection to U and V and inverting after interpolation""" def get_source_uv(cls, index_chunk, height, source_files): """Get u/v wind components from windspeed and winddire...
stack_v2_sparse_classes_36k_train_022696
29,957
permissive
[ { "docstring": "Get u/v wind components from windspeed and winddirection Parameters ---------- index_chunk : ndarray Chunk of the full array of indices where indices[i] gives the list of coordinate indices in the source data to be used for interpolation for the i-th coordinate in the target data. (temporal, n_p...
3
stack_v2_sparse_classes_30k_train_003900
Implement the Python class `WindRegridder` described below. Class description: Class to regrid windspeed and winddirection. Includes methods for converting windspeed and winddirection to U and V and inverting after interpolation Method signatures and docstrings: - def get_source_uv(cls, index_chunk, height, source_fi...
Implement the Python class `WindRegridder` described below. Class description: Class to regrid windspeed and winddirection. Includes methods for converting windspeed and winddirection to U and V and inverting after interpolation Method signatures and docstrings: - def get_source_uv(cls, index_chunk, height, source_fi...
f3803a823c7bb0afd7ab6064625908dca0be3476
<|skeleton|> class WindRegridder: """Class to regrid windspeed and winddirection. Includes methods for converting windspeed and winddirection to U and V and inverting after interpolation""" def get_source_uv(cls, index_chunk, height, source_files): """Get u/v wind components from windspeed and winddire...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WindRegridder: """Class to regrid windspeed and winddirection. Includes methods for converting windspeed and winddirection to U and V and inverting after interpolation""" def get_source_uv(cls, index_chunk, height, source_files): """Get u/v wind components from windspeed and winddirection Paramet...
the_stack_v2_python_sparse
sup3r/utilities/regridder.py
NREL/sup3r
train
20
24f3a2d167a29d0f1bfa2f45095074a7f7c3d507
[ "super(MySprite, self).__init__()\nself.images = [pygame.image.load(dir_images + f'walk_{i + 1:02d}.png') for i in range(10)]\nself.index = 0\nself.image = pygame.transform.smoothscale(self.images[self.index], WINDOW_SIZE)\nself.rect = self.image.get_rect()\nself.rect.topleft = START_POS", "self.index += 1\nif se...
<|body_start_0|> super(MySprite, self).__init__() self.images = [pygame.image.load(dir_images + f'walk_{i + 1:02d}.png') for i in range(10)] self.index = 0 self.image = pygame.transform.smoothscale(self.images[self.index], WINDOW_SIZE) self.rect = self.image.get_rect() se...
# pygame Sprite 속성을 상속 받는다
MySprite
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MySprite: """# pygame Sprite 속성을 상속 받는다""" def __init__(self): """make image array & make rect""" <|body_0|> def update(self): """image update when it is called""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(MySprite, self).__init__() ...
stack_v2_sparse_classes_36k_train_022697
1,203
no_license
[ { "docstring": "make image array & make rect", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "image update when it is called", "name": "update", "signature": "def update(self)" } ]
2
null
Implement the Python class `MySprite` described below. Class description: # pygame Sprite 속성을 상속 받는다 Method signatures and docstrings: - def __init__(self): make image array & make rect - def update(self): image update when it is called
Implement the Python class `MySprite` described below. Class description: # pygame Sprite 속성을 상속 받는다 Method signatures and docstrings: - def __init__(self): make image array & make rect - def update(self): image update when it is called <|skeleton|> class MySprite: """# pygame Sprite 속성을 상속 받는다""" def __ini...
68c8c6a94adc99005fb0fc8c38c416f902d37888
<|skeleton|> class MySprite: """# pygame Sprite 속성을 상속 받는다""" def __init__(self): """make image array & make rect""" <|body_0|> def update(self): """image update when it is called""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MySprite: """# pygame Sprite 속성을 상속 받는다""" def __init__(self): """make image array & make rect""" super(MySprite, self).__init__() self.images = [pygame.image.load(dir_images + f'walk_{i + 1:02d}.png') for i in range(10)] self.index = 0 self.image = pygame.transfor...
the_stack_v2_python_sparse
module_pygame/pumpkin_walking/assets/sprite.py
onitonitonito/k_mooc_reboot
train
0
649143f88d61d04528c416f1c4aa7e2166f94f4b
[ "self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.cat_first = Category.objects.create(name='first', caffe=self...
<|body_start_0|> self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100') self.cat_first = Category.objec...
ProductForm tests.
ProductFormTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProductFormTest: """ProductForm tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_product_form(self): """Check validation.""" <|body_1|> def test_product_same_name(self): """Check if product with same name is properly hand...
stack_v2_sparse_classes_36k_train_022698
12,667
permissive
[ { "docstring": "Test data setup.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Check validation.", "name": "test_product_form", "signature": "def test_product_form(self)" }, { "docstring": "Check if product with same name is properly handled.", "name": ...
3
stack_v2_sparse_classes_30k_train_007911
Implement the Python class `ProductFormTest` described below. Class description: ProductForm tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_product_form(self): Check validation. - def test_product_same_name(self): Check if product with same name is properly handled.
Implement the Python class `ProductFormTest` described below. Class description: ProductForm tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_product_form(self): Check validation. - def test_product_same_name(self): Check if product with same name is properly handled. <|skeleto...
cdb7f5edb29255c7e874eaa6231621063210a8b0
<|skeleton|> class ProductFormTest: """ProductForm tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_product_form(self): """Check validation.""" <|body_1|> def test_product_same_name(self): """Check if product with same name is properly hand...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProductFormTest: """ProductForm tests.""" def setUp(self): """Test data setup.""" self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='...
the_stack_v2_python_sparse
caffe/reports/test_forms.py
VirrageS/io-kawiarnie
train
3
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115
[ "if db_field.name == 'user':\n kwargs['queryset'] = User.objects.filter(id=request.user.id)\n kwargs['initial'] = request.user.id\nelif db_field.name == 'topic' and (not request.user.is_superuser):\n kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())\nreturn super(ExamAdmin...
<|body_start_0|> if db_field.name == 'user': kwargs['queryset'] = User.objects.filter(id=request.user.id) kwargs['initial'] = request.user.id elif db_field.name == 'topic' and (not request.user.is_superuser): kwargs['queryset'] = Topic.objects.filter(id__in=request.us...
ExamAdmin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExamAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Assigns default value for User field. limits Topics field to user's topics.""" <|body_0|> def formfield_for_manytomany(self, db_field, request, **kwargs): """Limits the choices of professo...
stack_v2_sparse_classes_36k_train_022699
9,167
permissive
[ { "docstring": "Assigns default value for User field. limits Topics field to user's topics.", "name": "formfield_for_foreignkey", "signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)" }, { "docstring": "Limits the choices of professors for the limit of user.", "name"...
3
stack_v2_sparse_classes_30k_train_018249
Implement the Python class `ExamAdmin` described below. Class description: Implement the ExamAdmin class. Method signatures and docstrings: - def formfield_for_foreignkey(self, db_field, request, **kwargs): Assigns default value for User field. limits Topics field to user's topics. - def formfield_for_manytomany(self...
Implement the Python class `ExamAdmin` described below. Class description: Implement the ExamAdmin class. Method signatures and docstrings: - def formfield_for_foreignkey(self, db_field, request, **kwargs): Assigns default value for User field. limits Topics field to user's topics. - def formfield_for_manytomany(self...
70638c121ea85ff0e6a650c5f2641b0b3b04d6d0
<|skeleton|> class ExamAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Assigns default value for User field. limits Topics field to user's topics.""" <|body_0|> def formfield_for_manytomany(self, db_field, request, **kwargs): """Limits the choices of professo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExamAdmin: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Assigns default value for User field. limits Topics field to user's topics.""" if db_field.name == 'user': kwargs['queryset'] = User.objects.filter(id=request.user.id) kwargs['initial'] = req...
the_stack_v2_python_sparse
cms/admin.py
Ibrahem3amer/bala7
train
0