blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
be318ebe530e734eed8edd9677075437a2022935 | [
"self.fp = fp\nself._line_len = 0\nself.tell = fp.tell",
"try:\n pos = s.index('\\n')\n rpos = s.rindex('\\n')\nexcept ValueError:\n pos = len(s)\n rpos = None\nif self._line_len + pos > self.TARGET_LINE_LEN - 1:\n self.fp.write('\\n ')\n self._line_len = 1\nself.fp.write(s)\nif rpos is not None... | <|body_start_0|>
self.fp = fp
self._line_len = 0
self.tell = fp.tell
<|end_body_0|>
<|body_start_1|>
try:
pos = s.index('\n')
rpos = s.rindex('\n')
except ValueError:
pos = len(s)
rpos = None
if self._line_len + pos > self.... | _WidthLimitedFile | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _WidthLimitedFile:
def __init__(self, fp: typing.TextIO):
"""Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying ... | stack_v2_sparse_classes_75kplus_train_003500 | 12,988 | permissive | [
{
"docstring": "Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying the line length requirement of LP files for all inputs. This design h... | 2 | stack_v2_sparse_classes_30k_train_024194 | Implement the Python class `_WidthLimitedFile` described below.
Class description:
Implement the _WidthLimitedFile class.
Method signatures and docstrings:
- def __init__(self, fp: typing.TextIO): Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done ... | Implement the Python class `_WidthLimitedFile` described below.
Class description:
Implement the _WidthLimitedFile class.
Method signatures and docstrings:
- def __init__(self, fp: typing.TextIO): Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done ... | 8433f221a1e79101e1db0d80968ab5a2f59b865d | <|skeleton|>
class _WidthLimitedFile:
def __init__(self, fp: typing.TextIO):
"""Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _WidthLimitedFile:
def __init__(self, fp: typing.TextIO):
"""Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying the line lengt... | the_stack_v2_python_sparse | dimod/lp.py | dwavesystems/dimod | train | 118 | |
f9b039185d2144964ec097ff51b7c274d23c17d4 | [
"super(VelocityMotor, self).__init__(part_id, motor_id, joint=joint, pid=pid, motor_type=motor_type)\nself.max_velocity = max_velocity\nself.min_velocity = -max_velocity if min_velocity is None else min_velocity",
"attrs = super(VelocityMotor, self).render_attributes()\nattrs.update({'min_velocity': nf(self.min_v... | <|body_start_0|>
super(VelocityMotor, self).__init__(part_id, motor_id, joint=joint, pid=pid, motor_type=motor_type)
self.max_velocity = max_velocity
self.min_velocity = -max_velocity if min_velocity is None else min_velocity
<|end_body_0|>
<|body_start_1|>
attrs = super(VelocityMotor, ... | A velocity based PID motor | VelocityMotor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VelocityMotor:
"""A velocity based PID motor"""
def __init__(self, part_id, motor_id, joint, pid=None, motor_type=None, max_velocity=10, min_velocity=None):
""":param max_velocity: Maximum velocity in radians / second :param min_velocity: Minimum velocity in radians / second. Default... | stack_v2_sparse_classes_75kplus_train_003501 | 5,832 | permissive | [
{
"docstring": ":param max_velocity: Maximum velocity in radians / second :param min_velocity: Minimum velocity in radians / second. Defaults to -max_velocity. :return:",
"name": "__init__",
"signature": "def __init__(self, part_id, motor_id, joint, pid=None, motor_type=None, max_velocity=10, min_veloci... | 2 | stack_v2_sparse_classes_30k_val_000121 | Implement the Python class `VelocityMotor` described below.
Class description:
A velocity based PID motor
Method signatures and docstrings:
- def __init__(self, part_id, motor_id, joint, pid=None, motor_type=None, max_velocity=10, min_velocity=None): :param max_velocity: Maximum velocity in radians / second :param mi... | Implement the Python class `VelocityMotor` described below.
Class description:
A velocity based PID motor
Method signatures and docstrings:
- def __init__(self, part_id, motor_id, joint, pid=None, motor_type=None, max_velocity=10, min_velocity=None): :param max_velocity: Maximum velocity in radians / second :param mi... | 70e65320a28fe04e121145b2cdde289d3052728a | <|skeleton|>
class VelocityMotor:
"""A velocity based PID motor"""
def __init__(self, part_id, motor_id, joint, pid=None, motor_type=None, max_velocity=10, min_velocity=None):
""":param max_velocity: Maximum velocity in radians / second :param min_velocity: Minimum velocity in radians / second. Default... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VelocityMotor:
"""A velocity based PID motor"""
def __init__(self, part_id, motor_id, joint, pid=None, motor_type=None, max_velocity=10, min_velocity=None):
""":param max_velocity: Maximum velocity in radians / second :param min_velocity: Minimum velocity in radians / second. Defaults to -max_vel... | the_stack_v2_python_sparse | revolve/build/sdf/motor.py | ElteHupkes/revolve | train | 0 |
c629b3d05e5188f02e9832af8764596b05f89da3 | [
"if 'username' in request.COOKIES:\n username = request.COOKIES.get('username')\n checked = request.COOKIES.get('checked')\nelse:\n username = ''\n checked = ''\nreturn render(request, 'login.html', {'username': username, 'checked': checked})",
"username = request.POST.get('username')\npassword = requ... | <|body_start_0|>
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked = request.COOKIES.get('checked')
else:
username = ''
checked = ''
return render(request, 'login.html', {'username': username, 'checked': checked})... | LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request):
"""登录校验"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked ... | stack_v2_sparse_classes_75kplus_train_003502 | 10,263 | no_license | [
{
"docstring": "显示登录页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "登录校验",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019952 | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def get(self, request): 显示登录页面
- def post(self, request): 登录校验 | Implement the Python class `LoginView` described below.
Class description:
Implement the LoginView class.
Method signatures and docstrings:
- def get(self, request): 显示登录页面
- def post(self, request): 登录校验
<|skeleton|>
class LoginView:
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post... | d6c6b6155190929a8343ce9080d1329e703d34ed | <|skeleton|>
class LoginView:
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request):
"""登录校验"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginView:
def get(self, request):
"""显示登录页面"""
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked = request.COOKIES.get('checked')
else:
username = ''
checked = ''
return render(request, 'login.h... | the_stack_v2_python_sparse | apps/ugc_home/views.py | bayhax/UGC | train | 0 | |
4999bf31b37b0be7e0073134f2ff4b0ab7c12344 | [
"if isinstance(image_type, ImageType):\n self.image_type = image_type\nelse:\n self.image_type = ImageType(dtype_to_ImageType(image_type))",
"boof_image_class = self.image_type.java_obj.getImageClass()\njava_tracker = pbg.gateway.jvm.boofcv.factory.tracker.FactoryTrackerObjectQuad.circulant(config, boof_ima... | <|body_start_0|>
if isinstance(image_type, ImageType):
self.image_type = image_type
else:
self.image_type = ImageType(dtype_to_ImageType(image_type))
<|end_body_0|>
<|body_start_1|>
boof_image_class = self.image_type.java_obj.getImageClass()
java_tracker = pbg.ga... | FactoryTrackerObjectQuad | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryTrackerObjectQuad:
def __init__(self, image_type):
"""Creates a factory for a specific image type. :param image_type: Specifies the type of image it processes. Can be a dtype or ImageType :type image_type: int | ImageType"""
<|body_0|>
def circulant(self, config=None)... | stack_v2_sparse_classes_75kplus_train_003503 | 44,501 | permissive | [
{
"docstring": "Creates a factory for a specific image type. :param image_type: Specifies the type of image it processes. Can be a dtype or ImageType :type image_type: int | ImageType",
"name": "__init__",
"signature": "def __init__(self, image_type)"
},
{
"docstring": "Creates a Circulant track... | 4 | stack_v2_sparse_classes_30k_train_048723 | Implement the Python class `FactoryTrackerObjectQuad` described below.
Class description:
Implement the FactoryTrackerObjectQuad class.
Method signatures and docstrings:
- def __init__(self, image_type): Creates a factory for a specific image type. :param image_type: Specifies the type of image it processes. Can be a... | Implement the Python class `FactoryTrackerObjectQuad` described below.
Class description:
Implement the FactoryTrackerObjectQuad class.
Method signatures and docstrings:
- def __init__(self, image_type): Creates a factory for a specific image type. :param image_type: Specifies the type of image it processes. Can be a... | d0b60d7c7e0c7f0ebc1e6186317d54b803d3bd7c | <|skeleton|>
class FactoryTrackerObjectQuad:
def __init__(self, image_type):
"""Creates a factory for a specific image type. :param image_type: Specifies the type of image it processes. Can be a dtype or ImageType :type image_type: int | ImageType"""
<|body_0|>
def circulant(self, config=None)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FactoryTrackerObjectQuad:
def __init__(self, image_type):
"""Creates a factory for a specific image type. :param image_type: Specifies the type of image it processes. Can be a dtype or ImageType :type image_type: int | ImageType"""
if isinstance(image_type, ImageType):
self.image_t... | the_stack_v2_python_sparse | pyboof/recognition.py | lessthanoptimal/PyBoof | train | 53 | |
308847a0859e74da63aa27ea10646b3054857f20 | [
"if not root:\n return 0\nret = 0\nstack = [(root, 1)]\nwhile stack:\n node, cnt = stack.pop()\n if node.left:\n stack.append((node.left, cnt + 1 if node.left.val == node.val + 1 else 1))\n if node.right:\n stack.append((node.right, cnt + 1 if node.right.val == node.val + 1 else 1))\n r... | <|body_start_0|>
if not root:
return 0
ret = 0
stack = [(root, 1)]
while stack:
node, cnt = stack.pop()
if node.left:
stack.append((node.left, cnt + 1 if node.left.val == node.val + 1 else 1))
if node.right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def rewrite(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
re... | stack_v2_sparse_classes_75kplus_train_003504 | 2,928 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rewrite",
"signature": "def rewrite(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, root): :type root: TreeNode :rtype: int
- def rewrite(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, root): :type root: TreeNode :rtype: int
- def rewrite(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def longestCon... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def longestConsecutive(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def rewrite(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestConsecutive(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
ret = 0
stack = [(root, 1)]
while stack:
node, cnt = stack.pop()
if node.left:
stack.append((node.left, cnt + 1... | the_stack_v2_python_sparse | co_google/298_Binary_Tree_Longest_Consecutive_Sequence.py | vsdrun/lc_public | train | 6 | |
1990faf5734a55dcc1e7d8a2120f328cce7523e9 | [
"nrow = len(board)\nncol = len(board[0])\nfor i in range(nrow):\n for j in range(ncol):\n e = board[i][j]\n if e == word[0]:\n loc_array = np.zeros((nrow, ncol))\n loc_array[i][j] = 1\n if self.one_start((i, j), loc_array, board, word[1:]):\n return T... | <|body_start_0|>
nrow = len(board)
ncol = len(board[0])
for i in range(nrow):
for j in range(ncol):
e = board[i][j]
if e == word[0]:
loc_array = np.zeros((nrow, ncol))
loc_array[i][j] = 1
if s... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def exist(self, board, word):
""":type board: List[List[str]] :type word: str :rtype: bool"""
<|body_0|>
def one_start(self, start_loc, loc_array, board, word_left):
"""给定了要找的位置 (start_loc),查看loc_array看可以往垂直还是水平方向找, word_left就是剩下要找的"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_003505 | 3,812 | no_license | [
{
"docstring": ":type board: List[List[str]] :type word: str :rtype: bool",
"name": "exist",
"signature": "def exist(self, board, word)"
},
{
"docstring": "给定了要找的位置 (start_loc),查看loc_array看可以往垂直还是水平方向找, word_left就是剩下要找的",
"name": "one_start",
"signature": "def one_start(self, start_loc, ... | 2 | stack_v2_sparse_classes_30k_train_007773 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool
- def one_start(self, start_loc, loc_array, board, word_left): 给定了要找的位置 (start_loc),查看lo... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool
- def one_start(self, start_loc, loc_array, board, word_left): 给定了要找的位置 (start_loc),查看lo... | f1a3930c571a6d062208ee1c1aadfe93a5684c40 | <|skeleton|>
class Solution1:
def exist(self, board, word):
""":type board: List[List[str]] :type word: str :rtype: bool"""
<|body_0|>
def one_start(self, start_loc, loc_array, board, word_left):
"""给定了要找的位置 (start_loc),查看loc_array看可以往垂直还是水平方向找, word_left就是剩下要找的"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
def exist(self, board, word):
""":type board: List[List[str]] :type word: str :rtype: bool"""
nrow = len(board)
ncol = len(board[0])
for i in range(nrow):
for j in range(ncol):
e = board[i][j]
if e == word[0]:
... | the_stack_v2_python_sparse | solution/problem 83.py | Fay321/leetcode-exercise | train | 0 | |
fe3b184b1cad8ddf0b5726b4e121f77e69362c34 | [
"is_reputation_valid = all([super().is_valid_file(validate_rn), self.is_valid_version(), self.is_valid_expiration(), self.is_required_fields_empty(), self.is_valid_indicator_type_id()])\nif not self.old_file:\n is_reputation_valid = all([is_reputation_valid, self.is_id_equals_details()])\nreturn is_reputation_va... | <|body_start_0|>
is_reputation_valid = all([super().is_valid_file(validate_rn), self.is_valid_version(), self.is_valid_expiration(), self.is_required_fields_empty(), self.is_valid_indicator_type_id()])
if not self.old_file:
is_reputation_valid = all([is_reputation_valid, self.is_id_equals_de... | ReputationValidator is designed to validate the correctness of the file structure we enter to content repo. | ReputationValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReputationValidator:
"""ReputationValidator is designed to validate the correctness of the file structure we enter to content repo."""
def is_valid_file(self, validate_rn=True):
"""Check whether the reputation file is valid or not"""
<|body_0|>
def is_valid_version(self)... | stack_v2_sparse_classes_75kplus_train_003506 | 4,381 | permissive | [
{
"docstring": "Check whether the reputation file is valid or not",
"name": "is_valid_file",
"signature": "def is_valid_file(self, validate_rn=True)"
},
{
"docstring": "Validate that the reputations file as version of -1.",
"name": "is_valid_version",
"signature": "def is_valid_version(s... | 6 | stack_v2_sparse_classes_30k_train_039040 | Implement the Python class `ReputationValidator` described below.
Class description:
ReputationValidator is designed to validate the correctness of the file structure we enter to content repo.
Method signatures and docstrings:
- def is_valid_file(self, validate_rn=True): Check whether the reputation file is valid or ... | Implement the Python class `ReputationValidator` described below.
Class description:
ReputationValidator is designed to validate the correctness of the file structure we enter to content repo.
Method signatures and docstrings:
- def is_valid_file(self, validate_rn=True): Check whether the reputation file is valid or ... | 3169757a2f98c8457e46572bf656ec6b69cc3a2e | <|skeleton|>
class ReputationValidator:
"""ReputationValidator is designed to validate the correctness of the file structure we enter to content repo."""
def is_valid_file(self, validate_rn=True):
"""Check whether the reputation file is valid or not"""
<|body_0|>
def is_valid_version(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReputationValidator:
"""ReputationValidator is designed to validate the correctness of the file structure we enter to content repo."""
def is_valid_file(self, validate_rn=True):
"""Check whether the reputation file is valid or not"""
is_reputation_valid = all([super().is_valid_file(valida... | the_stack_v2_python_sparse | demisto_sdk/commands/common/hook_validations/reputation.py | demisto/demisto-sdk | train | 63 |
659b31a69e3df274d9f2ea381978bfaee2b246ce | [
"assert 'newsletter_slug' in kwargs\nsuper(NewsletterMixin, self).process_url_data(*args, **kwargs)\nnewsletter_queryset = kwargs.get('newsletter_queryset', Newsletter.on_site.all())\nnewsletter_slug = kwargs['newsletter_slug']\nself.newsletter = get_object_or_404(newsletter_queryset, slug=newsletter_slug)",
"kwa... | <|body_start_0|>
assert 'newsletter_slug' in kwargs
super(NewsletterMixin, self).process_url_data(*args, **kwargs)
newsletter_queryset = kwargs.get('newsletter_queryset', Newsletter.on_site.all())
newsletter_slug = kwargs['newsletter_slug']
self.newsletter = get_object_or_404(new... | Mixin retrieving newsletter based on newsletter_slug from url and adding it to context and form kwargs. | NewsletterMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsletterMixin:
"""Mixin retrieving newsletter based on newsletter_slug from url and adding it to context and form kwargs."""
def process_url_data(self, *args, **kwargs):
"""Get newsletter based on `newsletter_slug` from url and add it to instance attributes."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_003507 | 19,073 | permissive | [
{
"docstring": "Get newsletter based on `newsletter_slug` from url and add it to instance attributes.",
"name": "process_url_data",
"signature": "def process_url_data(self, *args, **kwargs)"
},
{
"docstring": "Add newsletter to form kwargs.",
"name": "get_form_kwargs",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_test_000553 | Implement the Python class `NewsletterMixin` described below.
Class description:
Mixin retrieving newsletter based on newsletter_slug from url and adding it to context and form kwargs.
Method signatures and docstrings:
- def process_url_data(self, *args, **kwargs): Get newsletter based on `newsletter_slug` from url a... | Implement the Python class `NewsletterMixin` described below.
Class description:
Mixin retrieving newsletter based on newsletter_slug from url and adding it to context and form kwargs.
Method signatures and docstrings:
- def process_url_data(self, *args, **kwargs): Get newsletter based on `newsletter_slug` from url a... | 4bd988575537b37b5cf852b616d3db5666c95e7f | <|skeleton|>
class NewsletterMixin:
"""Mixin retrieving newsletter based on newsletter_slug from url and adding it to context and form kwargs."""
def process_url_data(self, *args, **kwargs):
"""Get newsletter based on `newsletter_slug` from url and add it to instance attributes."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewsletterMixin:
"""Mixin retrieving newsletter based on newsletter_slug from url and adding it to context and form kwargs."""
def process_url_data(self, *args, **kwargs):
"""Get newsletter based on `newsletter_slug` from url and add it to instance attributes."""
assert 'newsletter_slug' ... | the_stack_v2_python_sparse | newsletter/views.py | Williano/Final-Senior-Year-Project- | train | 173 |
84a7d83e66c8250c58472990f995e78d07c51a47 | [
"from consultorio.decorators.consulta_decorator import ConsultaDecorator\ntry:\n associated | should | be_instance_of(ConsultaDecorator)\nexcept ShouldNotSatisfied:\n return False\nelse:\n return True",
"from consultorio.decorators.paciente_decorator import PacienteDecorator\ntry:\n associated | shoul... | <|body_start_0|>
from consultorio.decorators.consulta_decorator import ConsultaDecorator
try:
associated | should | be_instance_of(ConsultaDecorator)
except ShouldNotSatisfied:
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
fro... | DoctorsOfficeRuleBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoctorsOfficeRuleBase:
def should_be_instance_of_consulta(self, associated):
"""Associated object should be instance of Consulta Decorator"""
<|body_0|>
def should_be_instance_of_paciente(self, associated):
"""Associated object should be instance of Paciente Decorato... | stack_v2_sparse_classes_75kplus_train_003508 | 1,319 | no_license | [
{
"docstring": "Associated object should be instance of Consulta Decorator",
"name": "should_be_instance_of_consulta",
"signature": "def should_be_instance_of_consulta(self, associated)"
},
{
"docstring": "Associated object should be instance of Paciente Decorator",
"name": "should_be_instan... | 3 | null | Implement the Python class `DoctorsOfficeRuleBase` described below.
Class description:
Implement the DoctorsOfficeRuleBase class.
Method signatures and docstrings:
- def should_be_instance_of_consulta(self, associated): Associated object should be instance of Consulta Decorator
- def should_be_instance_of_paciente(se... | Implement the Python class `DoctorsOfficeRuleBase` described below.
Class description:
Implement the DoctorsOfficeRuleBase class.
Method signatures and docstrings:
- def should_be_instance_of_consulta(self, associated): Associated object should be instance of Consulta Decorator
- def should_be_instance_of_paciente(se... | 038d530bf2952808cef89e514ba99588469dfc71 | <|skeleton|>
class DoctorsOfficeRuleBase:
def should_be_instance_of_consulta(self, associated):
"""Associated object should be instance of Consulta Decorator"""
<|body_0|>
def should_be_instance_of_paciente(self, associated):
"""Associated object should be instance of Paciente Decorato... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DoctorsOfficeRuleBase:
def should_be_instance_of_consulta(self, associated):
"""Associated object should be instance of Consulta Decorator"""
from consultorio.decorators.consulta_decorator import ConsultaDecorator
try:
associated | should | be_instance_of(ConsultaDecorator)... | the_stack_v2_python_sparse | consultorio/rules/doctors_office_rules_base.py | jainaldo/consultorio_eispatterns | train | 0 | |
b31db16e3ab46aa28fc7692cc69c6557bc1abcf1 | [
"alg = MagicMock()\nalg.asString = MagicMock(return_value='DummyAlgo(\"RoiCreator\")')\ninst = Instantiator()\nself.assertTrue(len(inst.cache) == 0)\nself.assertTrue(inst(alg).__class__.__name__ == 'PESA__DummyUnseededAllTEAlgo')\nself.assertTrue(len(inst.cache) == 1)\ninst(alg)\nself.assertTrue(inst(alg).__class__... | <|body_start_0|>
alg = MagicMock()
alg.asString = MagicMock(return_value='DummyAlgo("RoiCreator")')
inst = Instantiator()
self.assertTrue(len(inst.cache) == 0)
self.assertTrue(inst(alg).__class__.__name__ == 'PESA__DummyUnseededAllTEAlgo')
self.assertTrue(len(inst.cache) ... | Test_jetDefInstantiator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_jetDefInstantiator:
def test_0(self):
"""test instantiation and caching if instatiation is ok"""
<|body_0|>
def test_1(self):
"""test instantiation if instatiation is fails"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
alg = MagicMock()
... | stack_v2_sparse_classes_75kplus_train_003509 | 1,050 | permissive | [
{
"docstring": "test instantiation and caching if instatiation is ok",
"name": "test_0",
"signature": "def test_0(self)"
},
{
"docstring": "test instantiation if instatiation is fails",
"name": "test_1",
"signature": "def test_1(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052563 | Implement the Python class `Test_jetDefInstantiator` described below.
Class description:
Implement the Test_jetDefInstantiator class.
Method signatures and docstrings:
- def test_0(self): test instantiation and caching if instatiation is ok
- def test_1(self): test instantiation if instatiation is fails | Implement the Python class `Test_jetDefInstantiator` described below.
Class description:
Implement the Test_jetDefInstantiator class.
Method signatures and docstrings:
- def test_0(self): test instantiation and caching if instatiation is ok
- def test_1(self): test instantiation if instatiation is fails
<|skeleton|>... | 354f92551294f7be678aebcd7b9d67d2c4448176 | <|skeleton|>
class Test_jetDefInstantiator:
def test_0(self):
"""test instantiation and caching if instatiation is ok"""
<|body_0|>
def test_1(self):
"""test instantiation if instatiation is fails"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_jetDefInstantiator:
def test_0(self):
"""test instantiation and caching if instatiation is ok"""
alg = MagicMock()
alg.asString = MagicMock(return_value='DummyAlgo("RoiCreator")')
inst = Instantiator()
self.assertTrue(len(inst.cache) == 0)
self.assertTrue(i... | the_stack_v2_python_sparse | Trigger/TriggerCommon/TriggerMenu/python/jet/jetDefInstantiator_test.py | strigazi/athena | train | 0 | |
463db3f60eefbe5236d6486c6634e6b8d14a5c2b | [
"self.solution = nan\nself.muhat = full(levels, inf)\nself.sighat = full(levels, inf)\nself.t_eval = zeros(levels)\nself.n = tile(n_init, levels).astype(float)\nself.n_total = 0\nself.confid_int = array([-inf, inf])\nsuper().__init__()",
"for i in range(len(true_measure)):\n t_start = process_time()\n set_x... | <|body_start_0|>
self.solution = nan
self.muhat = full(levels, inf)
self.sighat = full(levels, inf)
self.t_eval = zeros(levels)
self.n = tile(n_init, levels).astype(float)
self.n_total = 0
self.confid_int = array([-inf, inf])
super().__init__()
<|end_body_... | Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values | MeanVarData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanVarData:
"""Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values"""
def __init__(self, levels, n_init):
"""Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples"""
... | stack_v2_sparse_classes_75kplus_train_003510 | 1,918 | no_license | [
{
"docstring": "Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples",
"name": "__init__",
"signature": "def __init__(self, levels, n_init)"
},
{
"docstring": "Update data Args: integrand (Integrand): an instance of Integrand true_measure (Tru... | 2 | stack_v2_sparse_classes_30k_train_026718 | Implement the Python class `MeanVarData` described below.
Class description:
Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values
Method signatures and docstrings:
- def __init__(self, levels, n_init): Initialize data instance Args: levels (int): number of inte... | Implement the Python class `MeanVarData` described below.
Class description:
Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values
Method signatures and docstrings:
- def __init__(self, levels, n_init): Initialize data instance Args: levels (int): number of inte... | 9f37eb67f74c4b1a4ccfb5547a2b284cb5897d37 | <|skeleton|>
class MeanVarData:
"""Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values"""
def __init__(self, levels, n_init):
"""Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeanVarData:
"""Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values"""
def __init__(self, levels, n_init):
"""Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples"""
self.solutio... | the_stack_v2_python_sparse | python_prototype/qmcpy/accum_data/mean_var_data.py | jagadeesr/QMCSoftware | train | 0 |
b38c1664d2502b7ec3625b61ef8f5eed7b87021f | [
"super(BaseC, self).__init__(args.sizes, args.rank, args.dropout, args.gamma, args.dtype, args.bias, args.init_size)\nassert self.rank % 2 == 0, 'Complex models require even embedding dimension'\nself.rank = self.rank // 2\nself.embeddings = nn.ModuleList([nn.Embedding(s, 2 * self.rank, sparse=True) for s in self.s... | <|body_start_0|>
super(BaseC, self).__init__(args.sizes, args.rank, args.dropout, args.gamma, args.dtype, args.bias, args.init_size)
assert self.rank % 2 == 0, 'Complex models require even embedding dimension'
self.rank = self.rank // 2
self.embeddings = nn.ModuleList([nn.Embedding(s, 2 ... | Complex Knowledge Graph Embedding models. Attributes: embeddings: complex embeddings for entities and relations | BaseC | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseC:
"""Complex Knowledge Graph Embedding models. Attributes: embeddings: complex embeddings for entities and relations"""
def __init__(self, args):
"""Initialize a Complex KGModel."""
<|body_0|>
def get_rhs(self, queries, eval_mode):
"""Get embeddings and bias... | stack_v2_sparse_classes_75kplus_train_003511 | 3,740 | permissive | [
{
"docstring": "Initialize a Complex KGModel.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Get embeddings and biases of target entities.",
"name": "get_rhs",
"signature": "def get_rhs(self, queries, eval_mode)"
},
{
"docstring": "Compute simila... | 5 | null | Implement the Python class `BaseC` described below.
Class description:
Complex Knowledge Graph Embedding models. Attributes: embeddings: complex embeddings for entities and relations
Method signatures and docstrings:
- def __init__(self, args): Initialize a Complex KGModel.
- def get_rhs(self, queries, eval_mode): Ge... | Implement the Python class `BaseC` described below.
Class description:
Complex Knowledge Graph Embedding models. Attributes: embeddings: complex embeddings for entities and relations
Method signatures and docstrings:
- def __init__(self, args): Initialize a Complex KGModel.
- def get_rhs(self, queries, eval_mode): Ge... | 3db009285d54df33f1bae6dcc511192d0e317288 | <|skeleton|>
class BaseC:
"""Complex Knowledge Graph Embedding models. Attributes: embeddings: complex embeddings for entities and relations"""
def __init__(self, args):
"""Initialize a Complex KGModel."""
<|body_0|>
def get_rhs(self, queries, eval_mode):
"""Get embeddings and bias... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseC:
"""Complex Knowledge Graph Embedding models. Attributes: embeddings: complex embeddings for entities and relations"""
def __init__(self, args):
"""Initialize a Complex KGModel."""
super(BaseC, self).__init__(args.sizes, args.rank, args.dropout, args.gamma, args.dtype, args.bias, ar... | the_stack_v2_python_sparse | models/complex.py | JThh/HyperGCN | train | 0 |
242179912e1d8753e3765c7faef75c124506dca6 | [
"super(Attention, self).__init__()\nself.linear_h = nn.Linear(input_dim, hidden_size, bias=False)\nself.linear_c = nn.Linear(candidate_dim, hidden_size, bias=False)\nself.softmax = nn.Softmax(dim=1)\nself.linear_out = nn.Linear(hidden_size, 1, bias=False)\nself.tanh = nn.Tanh()\nself.output_logits = output_logits",... | <|body_start_0|>
super(Attention, self).__init__()
self.linear_h = nn.Linear(input_dim, hidden_size, bias=False)
self.linear_c = nn.Linear(candidate_dim, hidden_size, bias=False)
self.softmax = nn.Softmax(dim=1)
self.linear_out = nn.Linear(hidden_size, 1, bias=False)
self... | Generic Attention module | Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Generic Attention module"""
def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False):
"""Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned."... | stack_v2_sparse_classes_75kplus_train_003512 | 14,666 | permissive | [
{
"docstring": "Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned.",
"name": "__init__",
"signature": "def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_042980 | Implement the Python class `Attention` described below.
Class description:
Generic Attention module
Method signatures and docstrings:
- def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False): Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwi... | Implement the Python class `Attention` described below.
Class description:
Generic Attention module
Method signatures and docstrings:
- def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False): Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwi... | f819aea21b94d9d3e23d9b6b9264054ee50c007b | <|skeleton|>
class Attention:
"""Generic Attention module"""
def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False):
"""Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attention:
"""Generic Attention module"""
def __init__(self, input_dim, candidate_dim, hidden_size, output_logits=False):
"""Initialize layer Args: output_logits (bool): If False, returns unnormalized attention weights, otherwise attended features and attention weights are returned."""
su... | the_stack_v2_python_sparse | tracker/modules/components.py | iCodeIN/vln-chasing-ghosts | train | 0 |
af8224846b3a775706c32c803f3355459dde52df | [
"super(GitCheckout, self).__init__(path)\nself.path = path\nself.branch = branch\nself.debug = []\nos.chdir(path)",
"current_branch_results = self._get_current_branch()\nif current_branch_results['results'] == self.branch:\n current_branch_results['checkout_not_needed'] = True\n return current_branch_result... | <|body_start_0|>
super(GitCheckout, self).__init__(path)
self.path = path
self.branch = branch
self.debug = []
os.chdir(path)
<|end_body_0|>
<|body_start_1|>
current_branch_results = self._get_current_branch()
if current_branch_results['results'] == self.branch:
... | Class to wrap the git checkout command line tools | GitCheckout | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitCheckout:
"""Class to wrap the git checkout command line tools"""
def __init__(self, path, branch):
"""Constructor for GitCheckout"""
<|body_0|>
def checkout(self):
"""perform a git checkout"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sup... | stack_v2_sparse_classes_75kplus_train_003513 | 978 | permissive | [
{
"docstring": "Constructor for GitCheckout",
"name": "__init__",
"signature": "def __init__(self, path, branch)"
},
{
"docstring": "perform a git checkout",
"name": "checkout",
"signature": "def checkout(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018913 | Implement the Python class `GitCheckout` described below.
Class description:
Class to wrap the git checkout command line tools
Method signatures and docstrings:
- def __init__(self, path, branch): Constructor for GitCheckout
- def checkout(self): perform a git checkout | Implement the Python class `GitCheckout` described below.
Class description:
Class to wrap the git checkout command line tools
Method signatures and docstrings:
- def __init__(self, path, branch): Constructor for GitCheckout
- def checkout(self): perform a git checkout
<|skeleton|>
class GitCheckout:
"""Class to... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class GitCheckout:
"""Class to wrap the git checkout command line tools"""
def __init__(self, path, branch):
"""Constructor for GitCheckout"""
<|body_0|>
def checkout(self):
"""perform a git checkout"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitCheckout:
"""Class to wrap the git checkout command line tools"""
def __init__(self, path, branch):
"""Constructor for GitCheckout"""
super(GitCheckout, self).__init__(path)
self.path = path
self.branch = branch
self.debug = []
os.chdir(path)
def ch... | the_stack_v2_python_sparse | ansible/roles/lib_git/build/src/git_checkout.py | openshift/openshift-tools | train | 170 |
220e0115941cbe1b0d5c8983dbfb3feef0496eb1 | [
"try:\n echallenge = data[:169]\n challenge = client.ephecc.decrypt(echallenge)\n challenge_bis = hmac_sha256(client.ms, client.session + var)\n if challenge != challenge_bis:\n msg = b'ERROR;application protocol error'\n client.loop.call_soon_threadsafe(client.transport.write, msg)\n ... | <|body_start_0|>
try:
echallenge = data[:169]
challenge = client.ephecc.decrypt(echallenge)
challenge_bis = hmac_sha256(client.ms, client.session + var)
if challenge != challenge_bis:
msg = b'ERROR;application protocol error'
client... | Challenge controller and others useful methods | StateSCC | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateSCC:
"""Challenge controller and others useful methods"""
def control_challenge(self, client, data, var):
"""Action of the state SCC: control the challenge answer"""
<|body_0|>
def compute_client_id(self, ms, login):
"""Compute a client id"""
<|body_... | stack_v2_sparse_classes_75kplus_train_003514 | 3,208 | permissive | [
{
"docstring": "Action of the state SCC: control the challenge answer",
"name": "control_challenge",
"signature": "def control_challenge(self, client, data, var)"
},
{
"docstring": "Compute a client id",
"name": "compute_client_id",
"signature": "def compute_client_id(self, ms, login)"
... | 3 | stack_v2_sparse_classes_30k_train_047304 | Implement the Python class `StateSCC` described below.
Class description:
Challenge controller and others useful methods
Method signatures and docstrings:
- def control_challenge(self, client, data, var): Action of the state SCC: control the challenge answer
- def compute_client_id(self, ms, login): Compute a client ... | Implement the Python class `StateSCC` described below.
Class description:
Challenge controller and others useful methods
Method signatures and docstrings:
- def control_challenge(self, client, data, var): Action of the state SCC: control the challenge answer
- def compute_client_id(self, ms, login): Compute a client ... | e3957e8f5b0ed9908e62badacace7e581761dd96 | <|skeleton|>
class StateSCC:
"""Challenge controller and others useful methods"""
def control_challenge(self, client, data, var):
"""Action of the state SCC: control the challenge answer"""
<|body_0|>
def compute_client_id(self, ms, login):
"""Compute a client id"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StateSCC:
"""Challenge controller and others useful methods"""
def control_challenge(self, client, data, var):
"""Action of the state SCC: control the challenge answer"""
try:
echallenge = data[:169]
challenge = client.ephecc.decrypt(echallenge)
challen... | the_stack_v2_python_sparse | mnemopwd/server/clients/protocol/StateSCC.py | thethythy/Mnemopwd | train | 3 |
9377d4901bc563fee6c99a6caadccba0f29b8907 | [
"self.master = master\nmaster.grid_rowconfigure(0, weight=1)\nmaster.grid_columnconfigure(0, weight=1)\nself.main_frame = tkin.Frame(master, bg='#1e1e1e')\nself.main_frame.grid(row=0, column=0, sticky='nsew')\nself._invis_pic = tkin.PhotoImage(width=1, height=1)",
"self.master.bind('<Tab>', self.toggle_menu)\nsel... | <|body_start_0|>
self.master = master
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)
self.main_frame = tkin.Frame(master, bg='#1e1e1e')
self.main_frame.grid(row=0, column=0, sticky='nsew')
self._invis_pic = tkin.PhotoImage(width=1, height=1... | Class for easily importing a menu system. | MainWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainWindow:
"""Class for easily importing a menu system."""
def __init__(self, master):
"""Set default parameters on initialization."""
<|body_0|>
def initialize_menu(self, title=''):
"""Create menu system."""
<|body_1|>
def toggle_menu(self, event):... | stack_v2_sparse_classes_75kplus_train_003515 | 3,599 | no_license | [
{
"docstring": "Set default parameters on initialization.",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Create menu system.",
"name": "initialize_menu",
"signature": "def initialize_menu(self, title='')"
},
{
"docstring": "Toggle menu displaye... | 3 | stack_v2_sparse_classes_30k_val_002175 | Implement the Python class `MainWindow` described below.
Class description:
Class for easily importing a menu system.
Method signatures and docstrings:
- def __init__(self, master): Set default parameters on initialization.
- def initialize_menu(self, title=''): Create menu system.
- def toggle_menu(self, event): Tog... | Implement the Python class `MainWindow` described below.
Class description:
Class for easily importing a menu system.
Method signatures and docstrings:
- def __init__(self, master): Set default parameters on initialization.
- def initialize_menu(self, title=''): Create menu system.
- def toggle_menu(self, event): Tog... | e452817429195593e9c7cd89fe052bd8ed89943a | <|skeleton|>
class MainWindow:
"""Class for easily importing a menu system."""
def __init__(self, master):
"""Set default parameters on initialization."""
<|body_0|>
def initialize_menu(self, title=''):
"""Create menu system."""
<|body_1|>
def toggle_menu(self, event):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MainWindow:
"""Class for easily importing a menu system."""
def __init__(self, master):
"""Set default parameters on initialization."""
self.master = master
master.grid_rowconfigure(0, weight=1)
master.grid_columnconfigure(0, weight=1)
self.main_frame = tkin.Frame(... | the_stack_v2_python_sparse | project_timeline/assets/menu.py | Keiyrti/python_projects | train | 0 |
f9b176409c00bb8ca3ffbd7bacc04d90a5ffcee8 | [
"super(Powerup, self).__init__()\nself.image = powerup_img\nself.rect = self.image.get_rect()\nself.rect.center = pos\nself.is_targeted = False\nself.boost = 2",
"enemy.max_health *= self.boost\nenemy.health = enemy.max_health\nenemy.speed *= self.boost * 0.7\nenemy.width = int(enemy.width * 1.5)\nenemy.height = ... | <|body_start_0|>
super(Powerup, self).__init__()
self.image = powerup_img
self.rect = self.image.get_rect()
self.rect.center = pos
self.is_targeted = False
self.boost = 2
<|end_body_0|>
<|body_start_1|>
enemy.max_health *= self.boost
enemy.health = enemy.... | Powerup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Powerup:
def __init__(self, pos):
""":param pos: position."""
<|body_0|>
def power_up(self, enemy):
"""Increases attributes :return: none"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Powerup, self).__init__()
self.image = powerup_im... | stack_v2_sparse_classes_75kplus_train_003516 | 1,094 | no_license | [
{
"docstring": ":param pos: position.",
"name": "__init__",
"signature": "def __init__(self, pos)"
},
{
"docstring": "Increases attributes :return: none",
"name": "power_up",
"signature": "def power_up(self, enemy)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016333 | Implement the Python class `Powerup` described below.
Class description:
Implement the Powerup class.
Method signatures and docstrings:
- def __init__(self, pos): :param pos: position.
- def power_up(self, enemy): Increases attributes :return: none | Implement the Python class `Powerup` described below.
Class description:
Implement the Powerup class.
Method signatures and docstrings:
- def __init__(self, pos): :param pos: position.
- def power_up(self, enemy): Increases attributes :return: none
<|skeleton|>
class Powerup:
def __init__(self, pos):
""... | 4f31b24565ac817ae95c5ca4ccb247a9ae18044e | <|skeleton|>
class Powerup:
def __init__(self, pos):
""":param pos: position."""
<|body_0|>
def power_up(self, enemy):
"""Increases attributes :return: none"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Powerup:
def __init__(self, pos):
""":param pos: position."""
super(Powerup, self).__init__()
self.image = powerup_img
self.rect = self.image.get_rect()
self.rect.center = pos
self.is_targeted = False
self.boost = 2
def power_up(self, enemy):
... | the_stack_v2_python_sparse | enemies/powerboost.py | marikb/Tower-Defense | train | 0 | |
041eb7aa4a382077e6c50a739bc2bc81ba311be3 | [
"if teachers is not None:\n targets = []\n for i, t in enumerate(teachers):\n if t is not None:\n targets.append(t(data[0]))\n else:\n targets.append(data[i + 1])\nelse:\n targets = data[1:]\nreturn (data[0], targets)",
"mse_loss = nn.MSELoss()\nce_loss = SoftCELoss(T=... | <|body_start_0|>
if teachers is not None:
targets = []
for i, t in enumerate(teachers):
if t is not None:
targets.append(t(data[0]))
else:
targets.append(data[i + 1])
else:
targets = data[1:]
... | Recombination algorithm for knowledge amalgamation **Parameters:** - **student** (nn.Module): target model. - **teachers** (nn.Module): source models. | Recombination | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Recombination:
"""Recombination algorithm for knowledge amalgamation **Parameters:** - **student** (nn.Module): target model. - **teachers** (nn.Module): source models."""
def prepare_inputs_and_targets(data, teachers):
"""default preparing function"""
<|body_0|>
def fit... | stack_v2_sparse_classes_75kplus_train_003517 | 1,662 | no_license | [
{
"docstring": "default preparing function",
"name": "prepare_inputs_and_targets",
"signature": "def prepare_inputs_and_targets(data, teachers)"
},
{
"docstring": "train on datatsets",
"name": "fit",
"signature": "def fit(self, train_loader, **kargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027622 | Implement the Python class `Recombination` described below.
Class description:
Recombination algorithm for knowledge amalgamation **Parameters:** - **student** (nn.Module): target model. - **teachers** (nn.Module): source models.
Method signatures and docstrings:
- def prepare_inputs_and_targets(data, teachers): defa... | Implement the Python class `Recombination` described below.
Class description:
Recombination algorithm for knowledge amalgamation **Parameters:** - **student** (nn.Module): target model. - **teachers** (nn.Module): source models.
Method signatures and docstrings:
- def prepare_inputs_and_targets(data, teachers): defa... | afd055779c489af38176d16a94a775564d2e6169 | <|skeleton|>
class Recombination:
"""Recombination algorithm for knowledge amalgamation **Parameters:** - **student** (nn.Module): target model. - **teachers** (nn.Module): source models."""
def prepare_inputs_and_targets(data, teachers):
"""default preparing function"""
<|body_0|>
def fit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Recombination:
"""Recombination algorithm for knowledge amalgamation **Parameters:** - **student** (nn.Module): target model. - **teachers** (nn.Module): source models."""
def prepare_inputs_and_targets(data, teachers):
"""default preparing function"""
if teachers is not None:
... | the_stack_v2_python_sparse | kamal/recombination/recombination.py | choppaluv/KamalEngine | train | 0 |
1191a4e12c0df232741e413d99a14aa6c76d22d5 | [
"super().__init__(name)\nself.name = name\nself.storage_uri = storage_uri\nself.ready = False\nself.model: Data = model",
"model_folder = download_model(self.storage_uri)\nself.model: Data = load_detector(model_folder)\nself.ready = True",
"logging.info('PROCESSING EVENT.')\nlogging.info(str(headers))\nlogging.... | <|body_start_0|>
super().__init__(name)
self.name = name
self.storage_uri = storage_uri
self.ready = False
self.model: Data = model
<|end_body_0|>
<|body_start_1|>
model_folder = download_model(self.storage_uri)
self.model: Data = load_detector(model_folder)
... | AlibiDetectAdversarialDetectionModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlibiDetectAdversarialDetectionModel:
def __init__(self, name: str, storage_uri: str, model: Optional[Data]=None):
"""Outlier Detection / Concept Drift Model Parameters ---------- name The name of the model storage_uri The URI location of the model"""
<|body_0|>
def load(sel... | stack_v2_sparse_classes_75kplus_train_003518 | 2,310 | permissive | [
{
"docstring": "Outlier Detection / Concept Drift Model Parameters ---------- name The name of the model storage_uri The URI location of the model",
"name": "__init__",
"signature": "def __init__(self, name: str, storage_uri: str, model: Optional[Data]=None)"
},
{
"docstring": "Load the model fr... | 3 | null | Implement the Python class `AlibiDetectAdversarialDetectionModel` described below.
Class description:
Implement the AlibiDetectAdversarialDetectionModel class.
Method signatures and docstrings:
- def __init__(self, name: str, storage_uri: str, model: Optional[Data]=None): Outlier Detection / Concept Drift Model Param... | Implement the Python class `AlibiDetectAdversarialDetectionModel` described below.
Class description:
Implement the AlibiDetectAdversarialDetectionModel class.
Method signatures and docstrings:
- def __init__(self, name: str, storage_uri: str, model: Optional[Data]=None): Outlier Detection / Concept Drift Model Param... | 6652d080ea10cfca082be7090d12b9e776d96d7a | <|skeleton|>
class AlibiDetectAdversarialDetectionModel:
def __init__(self, name: str, storage_uri: str, model: Optional[Data]=None):
"""Outlier Detection / Concept Drift Model Parameters ---------- name The name of the model storage_uri The URI location of the model"""
<|body_0|>
def load(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlibiDetectAdversarialDetectionModel:
def __init__(self, name: str, storage_uri: str, model: Optional[Data]=None):
"""Outlier Detection / Concept Drift Model Parameters ---------- name The name of the model storage_uri The URI location of the model"""
super().__init__(name)
self.name =... | the_stack_v2_python_sparse | components/alibi-detect-server/adserver/ad_model.py | SeldonIO/seldon-core | train | 3,947 | |
e84844a2c9447f9394944f70c7ff3ab731cbdff8 | [
"self.layers = layers_structure\nself.batch_size = batch_size\nself.layers_num = len(layers_structure)\nself.deep_activation = deep_activation\nself.activation = activation\nself.loss = loss\nself.learning_rate = learning_rate\nself.decay = decay\nself.momentum = momentum\nself.kernel_regularization_params = kernel... | <|body_start_0|>
self.layers = layers_structure
self.batch_size = batch_size
self.layers_num = len(layers_structure)
self.deep_activation = deep_activation
self.activation = activation
self.loss = loss
self.learning_rate = learning_rate
self.decay = decay
... | SequentialMLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialMLP:
def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, optimizer='adam', kernel_regularization_params=('l2', 0.01), dropout=0.3, validation_size=0.2, outfile=None, plot_mod... | stack_v2_sparse_classes_75kplus_train_003519 | 10,575 | no_license | [
{
"docstring": ":param layers_structure: list of int, with the structure of the hidden layers :param loss: str, the name of the loss function :param epochs: int, the number of epochs :param batch_size: int, the size of the batch :param activation: str, the name of the activation function :param deep_activation:... | 2 | stack_v2_sparse_classes_30k_train_010065 | Implement the Python class `SequentialMLP` described below.
Class description:
Implement the SequentialMLP class.
Method signatures and docstrings:
- def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, opti... | Implement the Python class `SequentialMLP` described below.
Class description:
Implement the SequentialMLP class.
Method signatures and docstrings:
- def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, opti... | bb2f1e350140c9d34865ed77f50d4475b515ea7b | <|skeleton|>
class SequentialMLP:
def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, optimizer='adam', kernel_regularization_params=('l2', 0.01), dropout=0.3, validation_size=0.2, outfile=None, plot_mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SequentialMLP:
def __init__(self, layers_structure, loss, epochs=100, batch_size=32, activation='softmax', deep_activation='relu', learning_rate=0.001, decay=1e-06, momentum=0.9, optimizer='adam', kernel_regularization_params=('l2', 0.01), dropout=0.3, validation_size=0.2, outfile=None, plot_model=False, load... | the_stack_v2_python_sparse | app/simple_mlp.py | agromanou/text-classification-with-nn | train | 0 | |
e00e46139216e2c9890d841d536dd43e8ea35680 | [
"data = data or self.fetch_offer_dict(offer_id)\nprint('%s fetch!' % offer_id)\nproduct = dict(offer_id=offer_id, subject=data['subject'], img_url=data['imageList'][0]['originalImageURI'], code=data['productFeatureList'].get('货号'), brand=data['productFeatureList'].get('品牌'), pattern=data['productFeatureList'].get('... | <|body_start_0|>
data = data or self.fetch_offer_dict(offer_id)
print('%s fetch!' % offer_id)
product = dict(offer_id=offer_id, subject=data['subject'], img_url=data['imageList'][0]['originalImageURI'], code=data['productFeatureList'].get('货号'), brand=data['productFeatureList'].get('品牌'), patter... | 抓取外部数据. | FetchDataHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchDataHelper:
"""抓取外部数据."""
def fetch_product(self, offer_id, data=None, raw=False):
"""抓取product数据."""
<|body_0|>
def fetch_skus(self, offer_id=None, data=None, raw=False):
"""抓取sku数据."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = d... | stack_v2_sparse_classes_75kplus_train_003520 | 13,314 | no_license | [
{
"docstring": "抓取product数据.",
"name": "fetch_product",
"signature": "def fetch_product(self, offer_id, data=None, raw=False)"
},
{
"docstring": "抓取sku数据.",
"name": "fetch_skus",
"signature": "def fetch_skus(self, offer_id=None, data=None, raw=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044904 | Implement the Python class `FetchDataHelper` described below.
Class description:
抓取外部数据.
Method signatures and docstrings:
- def fetch_product(self, offer_id, data=None, raw=False): 抓取product数据.
- def fetch_skus(self, offer_id=None, data=None, raw=False): 抓取sku数据. | Implement the Python class `FetchDataHelper` described below.
Class description:
抓取外部数据.
Method signatures and docstrings:
- def fetch_product(self, offer_id, data=None, raw=False): 抓取product数据.
- def fetch_skus(self, offer_id=None, data=None, raw=False): 抓取sku数据.
<|skeleton|>
class FetchDataHelper:
"""抓取外部数据.""... | dafac2566a2994baec837f06bad0344d8455773e | <|skeleton|>
class FetchDataHelper:
"""抓取外部数据."""
def fetch_product(self, offer_id, data=None, raw=False):
"""抓取product数据."""
<|body_0|>
def fetch_skus(self, offer_id=None, data=None, raw=False):
"""抓取sku数据."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetchDataHelper:
"""抓取外部数据."""
def fetch_product(self, offer_id, data=None, raw=False):
"""抓取product数据."""
data = data or self.fetch_offer_dict(offer_id)
print('%s fetch!' % offer_id)
product = dict(offer_id=offer_id, subject=data['subject'], img_url=data['imageList'][0]['... | the_stack_v2_python_sparse | Web/TaobaoShop/app/ledia.py | mrwlwan/workspace | train | 0 |
f00cc3cb8105fcdcd2ef1f89401d31eb221cc577 | [
"Movable.__init__(self, pathToImage)\nself.life = 100\nself.score = 0\nself.shotSound = pygame.mixer.Sound(os.path.join('resources', 'sound', 'shot.ogg'))",
"self.life -= 0.5\nif self.life <= 0:\n self.kill()"
] | <|body_start_0|>
Movable.__init__(self, pathToImage)
self.life = 100
self.score = 0
self.shotSound = pygame.mixer.Sound(os.path.join('resources', 'sound', 'shot.ogg'))
<|end_body_0|>
<|body_start_1|>
self.life -= 0.5
if self.life <= 0:
self.kill()
<|end_body_... | Class representing the player. | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""Class representing the player."""
def __init__(self, pathToImage):
"""Constructor of the player. :param pathToImage: the image of the player"""
<|body_0|>
def hit(self):
"""Called when the player is hit by a enemy. Reduces the players hitpoints."""
... | stack_v2_sparse_classes_75kplus_train_003521 | 741 | no_license | [
{
"docstring": "Constructor of the player. :param pathToImage: the image of the player",
"name": "__init__",
"signature": "def __init__(self, pathToImage)"
},
{
"docstring": "Called when the player is hit by a enemy. Reduces the players hitpoints.",
"name": "hit",
"signature": "def hit(s... | 2 | stack_v2_sparse_classes_30k_train_001239 | Implement the Python class `Player` described below.
Class description:
Class representing the player.
Method signatures and docstrings:
- def __init__(self, pathToImage): Constructor of the player. :param pathToImage: the image of the player
- def hit(self): Called when the player is hit by a enemy. Reduces the play... | Implement the Python class `Player` described below.
Class description:
Class representing the player.
Method signatures and docstrings:
- def __init__(self, pathToImage): Constructor of the player. :param pathToImage: the image of the player
- def hit(self): Called when the player is hit by a enemy. Reduces the play... | 29bde2dd56b259cf65429553432f1166c77f1cd5 | <|skeleton|>
class Player:
"""Class representing the player."""
def __init__(self, pathToImage):
"""Constructor of the player. :param pathToImage: the image of the player"""
<|body_0|>
def hit(self):
"""Called when the player is hit by a enemy. Reduces the players hitpoints."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Player:
"""Class representing the player."""
def __init__(self, pathToImage):
"""Constructor of the player. :param pathToImage: the image of the player"""
Movable.__init__(self, pathToImage)
self.life = 100
self.score = 0
self.shotSound = pygame.mixer.Sound(os.path... | the_stack_v2_python_sparse | source/model/objects/Player.py | divid3byzero/zompy | train | 0 |
1c551eaf6d06a6bfc9172200aef7fcaf94a93a46 | [
"class item:\n\n def __init__(self):\n self.cuda = True\n self.gpu_ids = '0'\nself.Flags = item()\nself.net = Siamese_ResNet([3, 4, 6, 3])\nmodel = torch.load(model_path)\nself.net.load_state_dict(model)\nif len(self.Flags.gpu_ids.split(',')) > 1:\n self.net = torch.nn.DataParallel(self.net)\nif... | <|body_start_0|>
class item:
def __init__(self):
self.cuda = True
self.gpu_ids = '0'
self.Flags = item()
self.net = Siamese_ResNet([3, 4, 6, 3])
model = torch.load(model_path)
self.net.load_state_dict(model)
if len(self.Flags.g... | Worker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
def __init__(self, model_path='./model/Resnet50/models/'):
"""初始化模型 :param model_path: :param gpu_list:gpu列表,逗号字符串包含GPU号,逗号分割"""
<|body_0|>
def get_match_value(self, img_a, img_b):
"""获得匹配值 :param img_a:第一个图像 numpy(H*W*C) :param img_b:第二个图像 numpy(H*W*C :retur... | stack_v2_sparse_classes_75kplus_train_003522 | 1,746 | no_license | [
{
"docstring": "初始化模型 :param model_path: :param gpu_list:gpu列表,逗号字符串包含GPU号,逗号分割",
"name": "__init__",
"signature": "def __init__(self, model_path='./model/Resnet50/models/')"
},
{
"docstring": "获得匹配值 :param img_a:第一个图像 numpy(H*W*C) :param img_b:第二个图像 numpy(H*W*C :return:",
"name": "get_match... | 2 | null | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, model_path='./model/Resnet50/models/'): 初始化模型 :param model_path: :param gpu_list:gpu列表,逗号字符串包含GPU号,逗号分割
- def get_match_value(self, img_a, img_b): 获得匹配值 :param img... | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, model_path='./model/Resnet50/models/'): 初始化模型 :param model_path: :param gpu_list:gpu列表,逗号字符串包含GPU号,逗号分割
- def get_match_value(self, img_a, img_b): 获得匹配值 :param img... | 675cc5a6616f3c321add81781455f63b53e2bd2f | <|skeleton|>
class Worker:
def __init__(self, model_path='./model/Resnet50/models/'):
"""初始化模型 :param model_path: :param gpu_list:gpu列表,逗号字符串包含GPU号,逗号分割"""
<|body_0|>
def get_match_value(self, img_a, img_b):
"""获得匹配值 :param img_a:第一个图像 numpy(H*W*C) :param img_b:第二个图像 numpy(H*W*C :retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Worker:
def __init__(self, model_path='./model/Resnet50/models/'):
"""初始化模型 :param model_path: :param gpu_list:gpu列表,逗号字符串包含GPU号,逗号分割"""
class item:
def __init__(self):
self.cuda = True
self.gpu_ids = '0'
self.Flags = item()
self.net... | the_stack_v2_python_sparse | run.py | XDUNZC/Resnet50 | train | 0 | |
4c0e74e88a3e94548993ced7c581aa0d8b641769 | [
"inp_data = all_inp_data[:BATCH_SIZE]\norig_out_data = all_orig_out_data[:BATCH_SIZE]\nrecons_err_hard, recons_err_soft = AdaroundOptimizer._eval_recons_err_metrics(wrapper, act_func, inp_data, orig_out_data)\nlogger.debug('Before opt, Recons. error metrics using soft rounding=%f and hard rounding=%f', recons_err_s... | <|body_start_0|>
inp_data = all_inp_data[:BATCH_SIZE]
orig_out_data = all_orig_out_data[:BATCH_SIZE]
recons_err_hard, recons_err_soft = AdaroundOptimizer._eval_recons_err_metrics(wrapper, act_func, inp_data, orig_out_data)
logger.debug('Before opt, Recons. error metrics using soft roundi... | Optimizes the weight rounding | AdaroundOptimizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaroundOptimizer:
"""Optimizes the weight rounding"""
def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.ndarray, np.ndarray):
"""Adaround wrapper :param wrapper: Ada... | stack_v2_sparse_classes_75kplus_train_003523 | 10,909 | permissive | [
{
"docstring": "Adaround wrapper :param wrapper: Adaround wrapper :param act_func: Activation function :param all_inp_data: Input activation data :param all_orig_out_data: Original output activation data :param opt_params: Adaround hyper parameters :return: hard_rounded_weight, soft_rounded_weight",
"name":... | 3 | stack_v2_sparse_classes_30k_train_039767 | Implement the Python class `AdaroundOptimizer` described below.
Class description:
Optimizes the weight rounding
Method signatures and docstrings:
- def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.n... | Implement the Python class `AdaroundOptimizer` described below.
Class description:
Optimizes the weight rounding
Method signatures and docstrings:
- def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.n... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class AdaroundOptimizer:
"""Optimizes the weight rounding"""
def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.ndarray, np.ndarray):
"""Adaround wrapper :param wrapper: Ada... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdaroundOptimizer:
"""Optimizes the weight rounding"""
def adaround_wrapper(wrapper: AdaroundWrapper, act_func: Callable, all_inp_data: np.ndarray, all_orig_out_data: np.ndarray, opt_params: AdaroundHyperParameters) -> (np.ndarray, np.ndarray):
"""Adaround wrapper :param wrapper: Adaround wrapper... | the_stack_v2_python_sparse | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/keras/adaround/adaround_optimizer.py | quic/aimet | train | 1,676 |
cdbee95488806eaad3a263331ef1324bb796ed02 | [
"try:\n self.logger_object = logger_object\n self.spreadsheet_key = spreadsheet_key\n scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n self.credentials = ServiceAccountCredentials.from_json_keyfile_name(json, scope)\n self.sheet_name_read = 'アカウント'\n sel... | <|body_start_0|>
try:
self.logger_object = logger_object
self.spreadsheet_key = spreadsheet_key
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
self.credentials = ServiceAccountCredentials.from_json_keyfile_name(json, sco... | スプレッドシート読み書き | SpreadSheet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpreadSheet:
"""スプレッドシート読み書き"""
def __init__(self, logger_object, spreadsheet_key, json):
"""初期化"""
<|body_0|>
def read_sheet(self):
"""スプレッドシート読み込み"""
<|body_1|>
def delete_sheet(self):
"""スプレッドシート内容削除"""
<|body_2|>
def write_sh... | stack_v2_sparse_classes_75kplus_train_003524 | 5,533 | no_license | [
{
"docstring": "初期化",
"name": "__init__",
"signature": "def __init__(self, logger_object, spreadsheet_key, json)"
},
{
"docstring": "スプレッドシート読み込み",
"name": "read_sheet",
"signature": "def read_sheet(self)"
},
{
"docstring": "スプレッドシート内容削除",
"name": "delete_sheet",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_049255 | Implement the Python class `SpreadSheet` described below.
Class description:
スプレッドシート読み書き
Method signatures and docstrings:
- def __init__(self, logger_object, spreadsheet_key, json): 初期化
- def read_sheet(self): スプレッドシート読み込み
- def delete_sheet(self): スプレッドシート内容削除
- def write_sheet(self, info_list, account, now_url): ... | Implement the Python class `SpreadSheet` described below.
Class description:
スプレッドシート読み書き
Method signatures and docstrings:
- def __init__(self, logger_object, spreadsheet_key, json): 初期化
- def read_sheet(self): スプレッドシート読み込み
- def delete_sheet(self): スプレッドシート内容削除
- def write_sheet(self, info_list, account, now_url): ... | 77e937d3b668e10ba613d8f04fd9415491a97402 | <|skeleton|>
class SpreadSheet:
"""スプレッドシート読み書き"""
def __init__(self, logger_object, spreadsheet_key, json):
"""初期化"""
<|body_0|>
def read_sheet(self):
"""スプレッドシート読み込み"""
<|body_1|>
def delete_sheet(self):
"""スプレッドシート内容削除"""
<|body_2|>
def write_sh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpreadSheet:
"""スプレッドシート読み書き"""
def __init__(self, logger_object, spreadsheet_key, json):
"""初期化"""
try:
self.logger_object = logger_object
self.spreadsheet_key = spreadsheet_key
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.... | the_stack_v2_python_sparse | scraping_amazon_and_yahooauc/module/spreadsheet_yahooauc.py | nakatatsu711/Archive | train | 0 |
ff6aed41da05bc04832ff4e91ace116d65d03157 | [
"self.nrows = nrows\nself.ncols = ncols\nself.walls = frozenset(walls)\nagents = []\nfor r, c in locations:\n if (r, c) in self.walls:\n raise ValueError(f'An agent can not be located in a wall {(r, c)}.')\n if r < 0 or r >= self.nrows or c < 0 or (c >= self.ncols):\n raise ValueError(f'Agent lo... | <|body_start_0|>
self.nrows = nrows
self.ncols = ncols
self.walls = frozenset(walls)
agents = []
for r, c in locations:
if (r, c) in self.walls:
raise ValueError(f'An agent can not be located in a wall {(r, c)}.')
if r < 0 or r >= self.nrow... | This is Multi-Agent Path Planning (MAPP) in rectangular grids. The grid consists of rows and columns. Each coordinate location is either empty, or contains a wall, or an agent. Agents are numbered 0 ... N-1. Agents may stay in their location or move N,S,E,W in the grid (but not over the 'edge', in to a wall location, o... | MAPPGridState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MAPPGridState:
"""This is Multi-Agent Path Planning (MAPP) in rectangular grids. The grid consists of rows and columns. Each coordinate location is either empty, or contains a wall, or an agent. Agents are numbered 0 ... N-1. Agents may stay in their location or move N,S,E,W in the grid (but not ... | stack_v2_sparse_classes_75kplus_train_003525 | 10,565 | no_license | [
{
"docstring": "Create new state. Parameters ---------- See class attributes above. Raises ------ ValueError If agent locations are on walls, outside the grid, or not unique.",
"name": "__init__",
"signature": "def __init__(self, locations, nrows=10, ncols=10, walls={})"
},
{
"docstring": "Apply... | 5 | null | Implement the Python class `MAPPGridState` described below.
Class description:
This is Multi-Agent Path Planning (MAPP) in rectangular grids. The grid consists of rows and columns. Each coordinate location is either empty, or contains a wall, or an agent. Agents are numbered 0 ... N-1. Agents may stay in their locatio... | Implement the Python class `MAPPGridState` described below.
Class description:
This is Multi-Agent Path Planning (MAPP) in rectangular grids. The grid consists of rows and columns. Each coordinate location is either empty, or contains a wall, or an agent. Agents are numbered 0 ... N-1. Agents may stay in their locatio... | 1e68e563fa1689dc98c62b7293d2f92064c6bdea | <|skeleton|>
class MAPPGridState:
"""This is Multi-Agent Path Planning (MAPP) in rectangular grids. The grid consists of rows and columns. Each coordinate location is either empty, or contains a wall, or an agent. Agents are numbered 0 ... N-1. Agents may stay in their location or move N,S,E,W in the grid (but not ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MAPPGridState:
"""This is Multi-Agent Path Planning (MAPP) in rectangular grids. The grid consists of rows and columns. Each coordinate location is either empty, or contains a wall, or an agent. Agents are numbered 0 ... N-1. Agents may stay in their location or move N,S,E,W in the grid (but not over the 'edg... | the_stack_v2_python_sparse | astar-exercise/mappgridstate.py | albertonietos/artificial-intelligence | train | 0 |
e1aff39489eef5738a98e40ce069435944d3c477 | [
"self.train_data = train_data\nself.valid_data = valid_data\nself.test_data = test_data\nself._set_params()",
"self.n_user = int(max(np.max(self.train_data[:, 0]), np.max(self.valid_data[:, 0]), np.max(self.test_data[:, 0]))) + 1\nself.n_item = int(max(np.max(self.train_data[:, 1]), np.max(self.valid_data[:, 1]),... | <|body_start_0|>
self.train_data = train_data
self.valid_data = valid_data
self.test_data = test_data
self._set_params()
<|end_body_0|>
<|body_start_1|>
self.n_user = int(max(np.max(self.train_data[:, 0]), np.max(self.valid_data[:, 0]), np.max(self.test_data[:, 0]))) + 1
... | BatchManager Class to manage the train-valid-test datasets Parameters ---------- train_data : Array-like, shape [N_train, 3] Each row is of the form (user_id, item_id, rating) valid_data : Array-like, shape [N_valid, 3] Each row is of the form (user_id, item_id, rating) test_data : Array-like, shape [N_test, 3] Each ro... | BatchManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchManager:
"""BatchManager Class to manage the train-valid-test datasets Parameters ---------- train_data : Array-like, shape [N_train, 3] Each row is of the form (user_id, item_id, rating) valid_data : Array-like, shape [N_valid, 3] Each row is of the form (user_id, item_id, rating) test_data... | stack_v2_sparse_classes_75kplus_train_003526 | 21,118 | permissive | [
{
"docstring": "Instantiate a BatchManager",
"name": "__init__",
"signature": "def __init__(self, train_data, valid_data, test_data)"
},
{
"docstring": "Private method to set the number of users, number of items, mean and standard deviation attributes",
"name": "_set_params",
"signature"... | 3 | null | Implement the Python class `BatchManager` described below.
Class description:
BatchManager Class to manage the train-valid-test datasets Parameters ---------- train_data : Array-like, shape [N_train, 3] Each row is of the form (user_id, item_id, rating) valid_data : Array-like, shape [N_valid, 3] Each row is of the fo... | Implement the Python class `BatchManager` described below.
Class description:
BatchManager Class to manage the train-valid-test datasets Parameters ---------- train_data : Array-like, shape [N_train, 3] Each row is of the form (user_id, item_id, rating) valid_data : Array-like, shape [N_valid, 3] Each row is of the fo... | 09d5b1639e9b7f6cbd230f181130b681e31cf4f0 | <|skeleton|>
class BatchManager:
"""BatchManager Class to manage the train-valid-test datasets Parameters ---------- train_data : Array-like, shape [N_train, 3] Each row is of the form (user_id, item_id, rating) valid_data : Array-like, shape [N_valid, 3] Each row is of the form (user_id, item_id, rating) test_data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchManager:
"""BatchManager Class to manage the train-valid-test datasets Parameters ---------- train_data : Array-like, shape [N_train, 3] Each row is of the form (user_id, item_id, rating) valid_data : Array-like, shape [N_valid, 3] Each row is of the form (user_id, item_id, rating) test_data : Array-like... | the_stack_v2_python_sparse | reclab/recommenders/llorma/llorma_lib/llorma_g.py | nitaifingerhut/RecLab | train | 0 |
a90c7bc9ef903d79cd82af5d14a69dcb9263b38f | [
"self.layer_dim = layer_dim\nself.regularizer = regularizer\nself.random_seed = random_seed\nself.trainable = trainable\nself.scope = scope\nself.device_spec = get_device_spec(default_gpu_id, num_gpus)\nwith tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec):\n gamma_initializer = cr... | <|body_start_0|>
self.layer_dim = layer_dim
self.regularizer = regularizer
self.random_seed = random_seed
self.trainable = trainable
self.scope = scope
self.device_spec = get_device_spec(default_gpu_id, num_gpus)
with tf.variable_scope(self.scope, reuse=tf.AUTO_RE... | layer norm layer | LayerNorm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerNorm:
"""layer norm layer"""
def __init__(self, layer_dim, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='layer_norm'):
"""initialize layer norm layer"""
<|body_0|>
def __call__(self, input_data, input_mask):
"""call la... | stack_v2_sparse_classes_75kplus_train_003527 | 2,850 | permissive | [
{
"docstring": "initialize layer norm layer",
"name": "__init__",
"signature": "def __init__(self, layer_dim, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='layer_norm')"
},
{
"docstring": "call layer norm layer",
"name": "__call__",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_006080 | Implement the Python class `LayerNorm` described below.
Class description:
layer norm layer
Method signatures and docstrings:
- def __init__(self, layer_dim, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='layer_norm'): initialize layer norm layer
- def __call__(self, input_data,... | Implement the Python class `LayerNorm` described below.
Class description:
layer norm layer
Method signatures and docstrings:
- def __init__(self, layer_dim, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='layer_norm'): initialize layer norm layer
- def __call__(self, input_data,... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class LayerNorm:
"""layer norm layer"""
def __init__(self, layer_dim, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='layer_norm'):
"""initialize layer norm layer"""
<|body_0|>
def __call__(self, input_data, input_mask):
"""call la... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayerNorm:
"""layer norm layer"""
def __init__(self, layer_dim, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='layer_norm'):
"""initialize layer norm layer"""
self.layer_dim = layer_dim
self.regularizer = regularizer
self.random_seed ... | the_stack_v2_python_sparse | sequence_labeling/layer/basic.py | stevezheng23/sequence_labeling_tf | train | 18 |
e50008fffb911c481a140b33b3ecc35a5412ebd6 | [
"super().__init__(master, groupe, **kw)\nself.__frameSchedu = Frame(self)\nsuper().add(self.__frameSchedu, text='Tâches')\nself.__listParamTask = []\nself.__varNbTask = IntVar()\nself.__varListTasks = StringVar()\nself.__varComboLT = StringVar()\nself.__varNbTask.set(len(self._getSchedulable().getListTasks()))\nsel... | <|body_start_0|>
super().__init__(master, groupe, **kw)
self.__frameSchedu = Frame(self)
super().add(self.__frameSchedu, text='Tâches')
self.__listParamTask = []
self.__varNbTask = IntVar()
self.__varListTasks = StringVar()
self.__varComboLT = StringVar()
... | Notebook qui contient tous les paramètres du groupe fournis dans le constructeur. Permet aussi de changer ses attributs (au groupe) | GroupeParametre | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupeParametre:
"""Notebook qui contient tous les paramètres du groupe fournis dans le constructeur. Permet aussi de changer ses attributs (au groupe)"""
def __init__(self, master, groupe, **kw):
"""@param master : <tkinter.frame> @param groupe : <Groupe> ceux qui sont à afficher"""... | stack_v2_sparse_classes_75kplus_train_003528 | 6,893 | no_license | [
{
"docstring": "@param master : <tkinter.frame> @param groupe : <Groupe> ceux qui sont à afficher",
"name": "__init__",
"signature": "def __init__(self, master, groupe, **kw)"
},
{
"docstring": "Méthode qui retire la task du groupe @param task : <str> de la tache AVEC son UID",
"name": "__re... | 4 | stack_v2_sparse_classes_30k_train_033815 | Implement the Python class `GroupeParametre` described below.
Class description:
Notebook qui contient tous les paramètres du groupe fournis dans le constructeur. Permet aussi de changer ses attributs (au groupe)
Method signatures and docstrings:
- def __init__(self, master, groupe, **kw): @param master : <tkinter.fr... | Implement the Python class `GroupeParametre` described below.
Class description:
Notebook qui contient tous les paramètres du groupe fournis dans le constructeur. Permet aussi de changer ses attributs (au groupe)
Method signatures and docstrings:
- def __init__(self, master, groupe, **kw): @param master : <tkinter.fr... | f59e9d491fe1d60654fad5357474763e4755f13a | <|skeleton|>
class GroupeParametre:
"""Notebook qui contient tous les paramètres du groupe fournis dans le constructeur. Permet aussi de changer ses attributs (au groupe)"""
def __init__(self, master, groupe, **kw):
"""@param master : <tkinter.frame> @param groupe : <Groupe> ceux qui sont à afficher"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupeParametre:
"""Notebook qui contient tous les paramètres du groupe fournis dans le constructeur. Permet aussi de changer ses attributs (au groupe)"""
def __init__(self, master, groupe, **kw):
"""@param master : <tkinter.frame> @param groupe : <Groupe> ceux qui sont à afficher"""
supe... | the_stack_v2_python_sparse | TaskManager/schedulable/groupe/dialog/GroupeParametre.py | Zetrypio/TaskManager | train | 2 |
bc6ff988058a9c4d6f6c689e809dbfc7f3228ac4 | [
"super(ResBlock2d, self).__init__(name=name)\nself._num_filters = num_filters\nself._kernel_shape = kernel_shape\nself._conv_stride = conv_stride\nself._projection_shortcut = projection_shortcut\nwith self._enter_variable_scope():\n self._output_channels = num_filters\n conv_arguments = {'output_channels': se... | <|body_start_0|>
super(ResBlock2d, self).__init__(name=name)
self._num_filters = num_filters
self._kernel_shape = kernel_shape
self._conv_stride = conv_stride
self._projection_shortcut = projection_shortcut
with self._enter_variable_scope():
self._output_chann... | Residual network block for 2D system with periodic boundary conditions. A building block of ResidualNetworks. It performs 2 convolutions with Selu activations, which are than concatenated together with the input. In this implementations we use convolutions that pad the input to produce periodic effect. We also omit bat... | ResBlock2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock2d:
"""Residual network block for 2D system with periodic boundary conditions. A building block of ResidualNetworks. It performs 2 convolutions with Selu activations, which are than concatenated together with the input. In this implementations we use convolutions that pad the input to pro... | stack_v2_sparse_classes_75kplus_train_003529 | 15,617 | permissive | [
{
"docstring": "Constructs a ResNet block for 1D systems. Args: num_filters: Number of filters for the convolutions. kernel_shape: Shape of the kernel for the convolutions. conv_stride: Stride for the convolutions. projection_shortcut: The module to apply to shortcuts. name: Name of the module.",
"name": "_... | 2 | stack_v2_sparse_classes_30k_train_029556 | Implement the Python class `ResBlock2d` described below.
Class description:
Residual network block for 2D system with periodic boundary conditions. A building block of ResidualNetworks. It performs 2 convolutions with Selu activations, which are than concatenated together with the input. In this implementations we use... | Implement the Python class `ResBlock2d` described below.
Class description:
Residual network block for 2D system with periodic boundary conditions. A building block of ResidualNetworks. It performs 2 convolutions with Selu activations, which are than concatenated together with the input. In this implementations we use... | 3a298ceab53bf6403c1a4037cb22431499891d79 | <|skeleton|>
class ResBlock2d:
"""Residual network block for 2D system with periodic boundary conditions. A building block of ResidualNetworks. It performs 2 convolutions with Selu activations, which are than concatenated together with the input. In this implementations we use convolutions that pad the input to pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResBlock2d:
"""Residual network block for 2D system with periodic boundary conditions. A building block of ResidualNetworks. It performs 2 convolutions with Selu activations, which are than concatenated together with the input. In this implementations we use convolutions that pad the input to produce periodic... | the_stack_v2_python_sparse | cgs_vmc/layers.py | ClarkResearchGroup/cgs-vmc | train | 18 |
fbf7e15f452ff374e2a3ff76c15ef38c1a7b0c18 | [
"def isPrime(num):\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\nif n < 3:\n return 0\ncount = 1\nfor i in range(3, n, 2):\n if isPrime(i):\n count += 1\nreturn count",
"if n < 2:\n return 0\ns = [1] * n\ns[0] = s[1] = 0\nfor i i... | <|body_start_0|>
def isPrime(num):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
if n < 3:
return 0
count = 1
for i in range(3, n, 2):
if isPrime(i):
co... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def isPrime(num):
for i in range(2, int(num ** 0.5) + 1):... | stack_v2_sparse_classes_75kplus_train_003530 | 932 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017013 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def countPrimes(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 countPrimes(self, n): :type n: int :rtype: int
- def countPrimes(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def countPrimes(self, n):
""":t... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
def isPrime(num):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
if n < 3:
return 0
count = 1
fo... | the_stack_v2_python_sparse | code/204#Count Primes.py | EachenKuang/LeetCode | train | 28 | |
9d96ca0dc26d1471997fc723d57709c5abf760d7 | [
"cls.__que_lock.acquire()\nif context in cls.__que:\n condition, count = cls.__que[context]\n with condition:\n cls.__que[context][1] = count + 1\n cls.__que_lock.release()\n condition.wait()\nelse:\n condition = threading.Condition()\n cls.__que[context] = [condition, 0]\n cls._... | <|body_start_0|>
cls.__que_lock.acquire()
if context in cls.__que:
condition, count = cls.__que[context]
with condition:
cls.__que[context][1] = count + 1
cls.__que_lock.release()
condition.wait()
else:
condition... | counter like hotel counter render threads are the visitors and want context as a room counter should only assign a room to a thread threads willing to have the room(context) has to wait in que | ContextCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextCounter:
"""counter like hotel counter render threads are the visitors and want context as a room counter should only assign a room to a thread threads willing to have the room(context) has to wait in que"""
def checkin(cls, context):
"""render thread want to use a context mar... | stack_v2_sparse_classes_75kplus_train_003531 | 3,941 | no_license | [
{
"docstring": "render thread want to use a context mark context in use and wait-mark if the context is already in use :param context: requested :return:",
"name": "checkin",
"signature": "def checkin(cls, context)"
},
{
"docstring": "render thread return the context :param context: :return:",
... | 2 | stack_v2_sparse_classes_30k_test_000842 | Implement the Python class `ContextCounter` described below.
Class description:
counter like hotel counter render threads are the visitors and want context as a room counter should only assign a room to a thread threads willing to have the room(context) has to wait in que
Method signatures and docstrings:
- def check... | Implement the Python class `ContextCounter` described below.
Class description:
counter like hotel counter render threads are the visitors and want context as a room counter should only assign a room to a thread threads willing to have the room(context) has to wait in que
Method signatures and docstrings:
- def check... | 1dc3987915f16fcbf8a34b1fef51953af56303c5 | <|skeleton|>
class ContextCounter:
"""counter like hotel counter render threads are the visitors and want context as a room counter should only assign a room to a thread threads willing to have the room(context) has to wait in que"""
def checkin(cls, context):
"""render thread want to use a context mar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContextCounter:
"""counter like hotel counter render threads are the visitors and want context as a room counter should only assign a room to a thread threads willing to have the room(context) has to wait in que"""
def checkin(cls, context):
"""render thread want to use a context mark context in ... | the_stack_v2_python_sparse | src/ckernel/render_context/opengl_context/base.py | grasshopperTrainer/CADengine | train | 1 |
1e8363b3f4bafded2833da49a732cce47a07b3d1 | [
"supported_ops = ['shearX', 'shearY', 'translateX', 'translateY', 'rotate', 'color', 'posterize', 'solarize', 'contrast', 'sharpness', 'brightness', 'autocontrast', 'equalize', 'invert']\nassert operation1 in supported_ops and operation2 in supported_ops, 'SubPolicy:one of oper1 or oper2 refers to an unsupported op... | <|body_start_0|>
supported_ops = ['shearX', 'shearY', 'translateX', 'translateY', 'rotate', 'color', 'posterize', 'solarize', 'contrast', 'sharpness', 'brightness', 'autocontrast', 'equalize', 'invert']
assert operation1 in supported_ops and operation2 in supported_ops, 'SubPolicy:one of oper1 or oper2 ... | Definition of a SubPolicy. A SubPolicy consists of two augmentation operations, each of those parametrized as operation, probability, magnitude. The two operations are applied sequentially on the image upon call. | SubPolicy | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubPolicy:
"""Definition of a SubPolicy. A SubPolicy consists of two augmentation operations, each of those parametrized as operation, probability, magnitude. The two operations are applied sequentially on the image upon call."""
def __init__(self, operation1, probability1, magnitude_idx1, o... | stack_v2_sparse_classes_75kplus_train_003532 | 13,416 | permissive | [
{
"docstring": "Initialize a SubPolicy. Args: operation1 (str): Key specifying the first augmentation operation. There are fourteen key values altogether (see supported_ops below listing supported operations). probability1 (float): Probability within [0., 1.] of applying the first augmentation operation. magnit... | 2 | stack_v2_sparse_classes_30k_train_035417 | Implement the Python class `SubPolicy` described below.
Class description:
Definition of a SubPolicy. A SubPolicy consists of two augmentation operations, each of those parametrized as operation, probability, magnitude. The two operations are applied sequentially on the image upon call.
Method signatures and docstrin... | Implement the Python class `SubPolicy` described below.
Class description:
Definition of a SubPolicy. A SubPolicy consists of two augmentation operations, each of those parametrized as operation, probability, magnitude. The two operations are applied sequentially on the image upon call.
Method signatures and docstrin... | 2f4a93fb4888180755a8ef55f4b977ef8f60a89e | <|skeleton|>
class SubPolicy:
"""Definition of a SubPolicy. A SubPolicy consists of two augmentation operations, each of those parametrized as operation, probability, magnitude. The two operations are applied sequentially on the image upon call."""
def __init__(self, operation1, probability1, magnitude_idx1, o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubPolicy:
"""Definition of a SubPolicy. A SubPolicy consists of two augmentation operations, each of those parametrized as operation, probability, magnitude. The two operations are applied sequentially on the image upon call."""
def __init__(self, operation1, probability1, magnitude_idx1, operation2, pr... | the_stack_v2_python_sparse | large_language_model/megatron-lm/megatron/data/autoaugment.py | mlcommons/training | train | 431 |
9bfd3a05b03a827944ce79d18678fcf10fba36c2 | [
"if page_url is None or html_cont is None:\n return\nsoup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')\nnew_urls = self._get_new_urls(page_url, soup)\nnew_data = self._get_new_data(page_url, soup)\nreturn (new_urls, new_data)",
"new_urls = set()\nlinks = soup.find_all('a', href=re.compile('... | <|body_start_0|>
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return (new_urls, new_data)
<|end_body_0... | HtmlParse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParse:
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:"""
<|body_0|>
def _get_new_urls(self, page_url, soup):
"""抽取新的url集合 :param page_url:下载页面的url :param soup: soup :return: 返回新的url集合"""
... | stack_v2_sparse_classes_75kplus_train_003533 | 2,001 | no_license | [
{
"docstring": "用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:",
"name": "parser",
"signature": "def parser(self, page_url, html_cont)"
},
{
"docstring": "抽取新的url集合 :param page_url:下载页面的url :param soup: soup :return: 返回新的url集合",
"name": "_get_new_urls",
"s... | 3 | stack_v2_sparse_classes_30k_test_002574 | Implement the Python class `HtmlParse` described below.
Class description:
Implement the HtmlParse class.
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:
- def _get_new_urls(self, page_url, soup): 抽取新的url集合 :para... | Implement the Python class `HtmlParse` described below.
Class description:
Implement the HtmlParse class.
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:
- def _get_new_urls(self, page_url, soup): 抽取新的url集合 :para... | 82cd7e39c2accb5f123769c16e66d7234e9a4121 | <|skeleton|>
class HtmlParse:
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:"""
<|body_0|>
def _get_new_urls(self, page_url, soup):
"""抽取新的url集合 :param page_url:下载页面的url :param soup: soup :return: 返回新的url集合"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HtmlParse:
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:"""
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
new_urls = s... | the_stack_v2_python_sparse | Internet worm/five_models/HtmlParse.py | Katherinelove/python | train | 0 | |
5ed0602fea493474aaccea06a791ca1d34779c5e | [
"super().__init__(web3_or_provider, contract_address)\nweb3 = None\nif isinstance(web3_or_provider, BaseProvider):\n web3 = Web3(web3_or_provider)\nelif isinstance(web3_or_provider, Web3):\n web3 = web3_or_provider\nif web3 is None:\n raise TypeError(\"Expected parameter 'web3_or_provider' to be an instanc... | <|body_start_0|>
super().__init__(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
if web3 is None:
rai... | Validate inputs to Exchange methods. | ExchangeValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeValidator:
"""Validate inputs to Exchange methods."""
def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str):
"""Initialize the class."""
<|body_0|>
def assert_valid(self, method_name: str, parameter_name: str, argument_value: Any)... | stack_v2_sparse_classes_75kplus_train_003534 | 2,071 | permissive | [
{
"docstring": "Initialize the class.",
"name": "__init__",
"signature": "def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str)"
},
{
"docstring": "Raise an exception if method input is not valid. :param method_name: Name of the method whose input is to be valida... | 2 | stack_v2_sparse_classes_30k_train_020211 | Implement the Python class `ExchangeValidator` described below.
Class description:
Validate inputs to Exchange methods.
Method signatures and docstrings:
- def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str): Initialize the class.
- def assert_valid(self, method_name: str, parameter... | Implement the Python class `ExchangeValidator` described below.
Class description:
Validate inputs to Exchange methods.
Method signatures and docstrings:
- def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str): Initialize the class.
- def assert_valid(self, method_name: str, parameter... | 53b5bb16d8b4c9050a46978b6f347ef7595fe103 | <|skeleton|>
class ExchangeValidator:
"""Validate inputs to Exchange methods."""
def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str):
"""Initialize the class."""
<|body_0|>
def assert_valid(self, method_name: str, parameter_name: str, argument_value: Any)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExchangeValidator:
"""Validate inputs to Exchange methods."""
def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str):
"""Initialize the class."""
super().__init__(web3_or_provider, contract_address)
web3 = None
if isinstance(web3_or_provider... | the_stack_v2_python_sparse | python-packages/contract_wrappers/src/zero_ex/contract_wrappers/exchange/validator.py | 0xProject/0x-monorepo | train | 1,132 |
ddc5dc3873f4fc8eaf02447b26119ab06d54485a | [
"res = []\nfor direction in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n cost = 0\n i, j = (start[0], start[1])\n while True:\n x, y = (i + direction[0], j + direction[1])\n if 0 <= x < len(maze) and 0 <= y < len(maze[0]) and (maze[x][y] != 1):\n cost += 1\n i, j = (x, y)\n ... | <|body_start_0|>
res = []
for direction in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
cost = 0
i, j = (start[0], start[1])
while True:
x, y = (i + direction[0], j + direction[1])
if 0 <= x < len(maze) and 0 <= y < len(maze[0]) and (maze[x][y] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getNexts(self, maze, start):
"""Return list of next reachable nodes and the cost to reach there from start"""
<|body_0|>
def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
"""Dijkstra, time complexity is ... | stack_v2_sparse_classes_75kplus_train_003535 | 3,519 | no_license | [
{
"docstring": "Return list of next reachable nodes and the cost to reach there from start",
"name": "getNexts",
"signature": "def getNexts(self, maze, start)"
},
{
"docstring": "Dijkstra, time complexity is O(ELogV), which is O(mnlog(mn))",
"name": "shortestDistance",
"signature": "def ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getNexts(self, maze, start): Return list of next reachable nodes and the cost to reach there from start
- def shortestDistance(self, maze: List[List[int]], start: List[int], ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getNexts(self, maze, start): Return list of next reachable nodes and the cost to reach there from start
- def shortestDistance(self, maze: List[List[int]], start: List[int], ... | ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653 | <|skeleton|>
class Solution:
def getNexts(self, maze, start):
"""Return list of next reachable nodes and the cost to reach there from start"""
<|body_0|>
def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
"""Dijkstra, time complexity is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getNexts(self, maze, start):
"""Return list of next reachable nodes and the cost to reach there from start"""
res = []
for direction in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
cost = 0
i, j = (start[0], start[1])
while True:
... | the_stack_v2_python_sparse | 505 The Maze II.py | jz33/LeetCodeSolutions | train | 8 | |
f8b8ccda281ad161e3ecfb925c98a2e0f3bf53b1 | [
"self._id = _id\nself.name = name\nself.active_doc = active_doc\nself.context = context\nself.docs = docs",
"active_doc = None\nif self.active_doc is not None:\n active_doc = self.active_doc.to_dict(raw=False, with_details=True)\ndoclist = []\nfor doc in self.docs:\n doclist.append(doc.to_dict(raw=False, wi... | <|body_start_0|>
self._id = _id
self.name = name
self.active_doc = active_doc
self.context = context
self.docs = docs
<|end_body_0|>
<|body_start_1|>
active_doc = None
if self.active_doc is not None:
active_doc = self.active_doc.to_dict(raw=False, wit... | Object that wraps up an Arthur project. This is the server counterpart of js model's Project (and other models contained by it respectively e.g. ActiveDoc for this object's :attr:`active_doc` attribute, which is an instance of ArthurDocument). | ArthurProject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArthurProject:
"""Object that wraps up an Arthur project. This is the server counterpart of js model's Project (and other models contained by it respectively e.g. ActiveDoc for this object's :attr:`active_doc` attribute, which is an instance of ArthurDocument)."""
def __init__(self, name='',... | stack_v2_sparse_classes_75kplus_train_003536 | 3,250 | permissive | [
{
"docstring": "Initializes ArthurProject instance. Args: name: Name of project. active_doc(ArthurDocument): Currently active document. context(str): Context associated with this project. _id(ObjectId): ID of this project (for database keeping). # docs: List of ArthurDocuments.",
"name": "__init__",
"si... | 4 | stack_v2_sparse_classes_30k_train_003169 | Implement the Python class `ArthurProject` described below.
Class description:
Object that wraps up an Arthur project. This is the server counterpart of js model's Project (and other models contained by it respectively e.g. ActiveDoc for this object's :attr:`active_doc` attribute, which is an instance of ArthurDocumen... | Implement the Python class `ArthurProject` described below.
Class description:
Object that wraps up an Arthur project. This is the server counterpart of js model's Project (and other models contained by it respectively e.g. ActiveDoc for this object's :attr:`active_doc` attribute, which is an instance of ArthurDocumen... | 7a581104141ee5f556e058b1276b4087a2921dfc | <|skeleton|>
class ArthurProject:
"""Object that wraps up an Arthur project. This is the server counterpart of js model's Project (and other models contained by it respectively e.g. ActiveDoc for this object's :attr:`active_doc` attribute, which is an instance of ArthurDocument)."""
def __init__(self, name='',... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArthurProject:
"""Object that wraps up an Arthur project. This is the server counterpart of js model's Project (and other models contained by it respectively e.g. ActiveDoc for this object's :attr:`active_doc` attribute, which is an instance of ArthurDocument)."""
def __init__(self, name='', active_doc=N... | the_stack_v2_python_sparse | libs/arthur/project.py | jaycode/Arthur.workspace | train | 0 |
d6caca973b4a6afbcfce6986451f8096d03f83d6 | [
"for row in rows:\n if str(row.product_code) == product and str(row.activity) == state:\n if chart_type == 'order':\n product_data.append(int(row.orders))\n else:\n product_data.append(int(row.units))\n break\nelse:\n product_data.append(0)",
"product_data.append(0... | <|body_start_0|>
for row in rows:
if str(row.product_code) == product and str(row.activity) == state:
if chart_type == 'order':
product_data.append(int(row.orders))
else:
product_data.append(int(row.units))
break... | Gathers data for the various pipeline related charts that show progress through the workflow for all products. | PipelineChartProc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineChartProc:
"""Gathers data for the various pipeline related charts that show progress through the workflow for all products."""
def _appendAggregate(self, rows, product, state, chart_type, product_data):
"""Append the aggregate for the requested product / state combo to the l... | stack_v2_sparse_classes_75kplus_train_003537 | 3,498 | no_license | [
{
"docstring": "Append the aggregate for the requested product / state combo to the list of data for the current product.",
"name": "_appendAggregate",
"signature": "def _appendAggregate(self, rows, product, state, chart_type, product_data)"
},
{
"docstring": "Append sum of the aggregates for th... | 3 | stack_v2_sparse_classes_30k_train_003087 | Implement the Python class `PipelineChartProc` described below.
Class description:
Gathers data for the various pipeline related charts that show progress through the workflow for all products.
Method signatures and docstrings:
- def _appendAggregate(self, rows, product, state, chart_type, product_data): Append the a... | Implement the Python class `PipelineChartProc` described below.
Class description:
Gathers data for the various pipeline related charts that show progress through the workflow for all products.
Method signatures and docstrings:
- def _appendAggregate(self, rows, product, state, chart_type, product_data): Append the a... | a0edcc220f5c950838c0d0a5e42ee06bb7f2c6ad | <|skeleton|>
class PipelineChartProc:
"""Gathers data for the various pipeline related charts that show progress through the workflow for all products."""
def _appendAggregate(self, rows, product, state, chart_type, product_data):
"""Append the aggregate for the requested product / state combo to the l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipelineChartProc:
"""Gathers data for the various pipeline related charts that show progress through the workflow for all products."""
def _appendAggregate(self, rows, product, state, chart_type, product_data):
"""Append the aggregate for the requested product / state combo to the list of data f... | the_stack_v2_python_sparse | pipelinechartproc.py | ryanlowe0/misc-python | train | 0 |
d44b8f881168e3df760a8bad04414e3665fe89fe | [
"def child_serialize(node, index, result):\n if node is None:\n return None\n left_index = index * 2 + 1\n right_index = left_index + 1\n new_spaces = right_index + 1 - len(result)\n if new_spaces > 0:\n result += [None] * new_spaces\n left_val = node.left.val if node.left else None\... | <|body_start_0|>
def child_serialize(node, index, result):
if node is None:
return None
left_index = index * 2 + 1
right_index = left_index + 1
new_spaces = right_index + 1 - len(result)
if new_spaces > 0:
result += [Non... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_003538 | 3,416 | 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:... | 78ab6a2bc802906a3293c3819e78fa5a6131608e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def child_serialize(node, index, result):
if node is None:
return None
left_index = index * 2 + 1
right_index = left_index + 1
... | the_stack_v2_python_sparse | serialize_deserialize.py | thinkSharp/Interviews | train | 1 | |
cf91167ae80ee39a766aa708cf7e50c09b485a1c | [
"wmin = 2.0 * fmin / sr\nwmax = 2.0 * fmax / sr\nite = np.arange(-(win_size // 2), (win_size + 1) // 2)\nself.filter = wmin * np.sinc(wmin * ite) - wmax * np.sinc(wmax * ite)\nself.filter[win_size // 2] += 1.0\nself.filter *= np.hamming(win_size)\nself.status = np.zeros(win_size)\nself.win_size = win_size",
"if i... | <|body_start_0|>
wmin = 2.0 * fmin / sr
wmax = 2.0 * fmax / sr
ite = np.arange(-(win_size // 2), (win_size + 1) // 2)
self.filter = wmin * np.sinc(wmin * ite) - wmax * np.sinc(wmax * ite)
self.filter[win_size // 2] += 1.0
self.filter *= np.hamming(win_size)
self.s... | BSF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSF:
def __init__(self, fmin, fmax, win_size, sr):
"""Args: fmin (int):the lowest frequency of the band stopped fmax (int):the highest frequency of the band stopped win_size(int):sizeof window applied to filter sr (int):sampling rate of the signal"""
<|body_0|>
def __call__(... | stack_v2_sparse_classes_75kplus_train_003539 | 5,321 | no_license | [
{
"docstring": "Args: fmin (int):the lowest frequency of the band stopped fmax (int):the highest frequency of the band stopped win_size(int):sizeof window applied to filter sr (int):sampling rate of the signal",
"name": "__init__",
"signature": "def __init__(self, fmin, fmax, win_size, sr)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_004536 | Implement the Python class `BSF` described below.
Class description:
Implement the BSF class.
Method signatures and docstrings:
- def __init__(self, fmin, fmax, win_size, sr): Args: fmin (int):the lowest frequency of the band stopped fmax (int):the highest frequency of the band stopped win_size(int):sizeof window app... | Implement the Python class `BSF` described below.
Class description:
Implement the BSF class.
Method signatures and docstrings:
- def __init__(self, fmin, fmax, win_size, sr): Args: fmin (int):the lowest frequency of the band stopped fmax (int):the highest frequency of the band stopped win_size(int):sizeof window app... | 11edb5540f57429019ece8ddd60ed439f337b186 | <|skeleton|>
class BSF:
def __init__(self, fmin, fmax, win_size, sr):
"""Args: fmin (int):the lowest frequency of the band stopped fmax (int):the highest frequency of the band stopped win_size(int):sizeof window applied to filter sr (int):sampling rate of the signal"""
<|body_0|>
def __call__(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BSF:
def __init__(self, fmin, fmax, win_size, sr):
"""Args: fmin (int):the lowest frequency of the band stopped fmax (int):the highest frequency of the band stopped win_size(int):sizeof window applied to filter sr (int):sampling rate of the signal"""
wmin = 2.0 * fmin / sr
wmax = 2.0 *... | the_stack_v2_python_sparse | ex_2/a_miyashita/main.py | shin04/B4Lecture-2021 | train | 0 | |
d23cda2268690cfb5c30f109610d5f7d5994bfad | [
"self.custom_group_by = True\nsuper(CustomGroupByQuerySetMixin, self).__init__(*args, **kwargs)\nself.query._custom_group_by = self.custom_group_by",
"new = super(CustomGroupByQuerySetMixin, self)._clone(*args, **kwargs)\nnew.custom_group_by = new.query._custom_group_by = self.custom_group_by\nreturn new"
] | <|body_start_0|>
self.custom_group_by = True
super(CustomGroupByQuerySetMixin, self).__init__(*args, **kwargs)
self.query._custom_group_by = self.custom_group_by
<|end_body_0|>
<|body_start_1|>
new = super(CustomGroupByQuerySetMixin, self)._clone(*args, **kwargs)
new.custom_grou... | Для корректной работы необходимо подключить edw/patches/sql/compiler.py | CustomGroupByQuerySetMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomGroupByQuerySetMixin:
"""Для корректной работы необходимо подключить edw/patches/sql/compiler.py"""
def __init__(self, *args, **kwargs):
"""ENG: init our queryset object member variables RUS: Конструктор класса объекта запроса."""
<|body_0|>
def _clone(self, *args,... | stack_v2_sparse_classes_75kplus_train_003540 | 6,224 | permissive | [
{
"docstring": "ENG: init our queryset object member variables RUS: Конструктор класса объекта запроса.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "RUS: Создает копию, переопределяя значения переменных.",
"name": "_clone",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_050628 | Implement the Python class `CustomGroupByQuerySetMixin` described below.
Class description:
Для корректной работы необходимо подключить edw/patches/sql/compiler.py
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): ENG: init our queryset object member variables RUS: Конструктор класса объекта за... | Implement the Python class `CustomGroupByQuerySetMixin` described below.
Class description:
Для корректной работы необходимо подключить edw/patches/sql/compiler.py
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): ENG: init our queryset object member variables RUS: Конструктор класса объекта за... | 2f7c535cb9f91d6bcb2f1e91b58edebc01255612 | <|skeleton|>
class CustomGroupByQuerySetMixin:
"""Для корректной работы необходимо подключить edw/patches/sql/compiler.py"""
def __init__(self, *args, **kwargs):
"""ENG: init our queryset object member variables RUS: Конструктор класса объекта запроса."""
<|body_0|>
def _clone(self, *args,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomGroupByQuerySetMixin:
"""Для корректной работы необходимо подключить edw/patches/sql/compiler.py"""
def __init__(self, *args, **kwargs):
"""ENG: init our queryset object member variables RUS: Конструктор класса объекта запроса."""
self.custom_group_by = True
super(CustomGrou... | the_stack_v2_python_sparse | backend/edw/models/mixins/query.py | infolabs/django-edw | train | 5 |
3f2c58771047de95642c976bcd07dff68c672bab | [
"self.generator = dictGenerator\nself.site = pywikibot.Site('commons', 'commons')\nself.repo = pywikibot.Site().data_repository()\nself.create = create",
"for metadata in self.generator:\n grave_item = None\n if metadata.get('wikidata'):\n grave_item = pywikibot.ItemPage(self.repo, title=metadata.get... | <|body_start_0|>
self.generator = dictGenerator
self.site = pywikibot.Site('commons', 'commons')
self.repo = pywikibot.Site().data_repository()
self.create = create
<|end_body_0|>
<|body_start_1|>
for metadata in self.generator:
grave_item = None
if metad... | A bot to enrich and create paintings on Wikidata | GraveBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraveBot:
"""A bot to enrich and create paintings on Wikidata"""
def __init__(self, dictGenerator, create=False):
"""Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you... | stack_v2_sparse_classes_75kplus_train_003541 | 13,014 | no_license | [
{
"docstring": "Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you want to create new items or just update existing",
"name": "__init__",
"signature": "def __init__(self, dictGenerator, c... | 5 | stack_v2_sparse_classes_30k_train_007670 | Implement the Python class `GraveBot` described below.
Class description:
A bot to enrich and create paintings on Wikidata
Method signatures and docstrings:
- def __init__(self, dictGenerator, create=False): Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'id... | Implement the Python class `GraveBot` described below.
Class description:
A bot to enrich and create paintings on Wikidata
Method signatures and docstrings:
- def __init__(self, dictGenerator, create=False): Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'id... | 99a96e49cfe6b2d3151da7ad5469792d80171be3 | <|skeleton|>
class GraveBot:
"""A bot to enrich and create paintings on Wikidata"""
def __init__(self, dictGenerator, create=False):
"""Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraveBot:
"""A bot to enrich and create paintings on Wikidata"""
def __init__(self, dictGenerator, create=False):
"""Arguments: * generator - A generator that yields Dict objects. The dict in this generator needs to contain 'idpid' and 'collectionqid' * create - Boolean to say if you want to crea... | the_stack_v2_python_sparse | bot/wikidata/pere-lachaise_import.py | multichill/toollabs | train | 18 |
3c2155833aa1f736c8c6e75abee8b730ee0d1c1e | [
"for dir_to_remove in args:\n logger.info('cleaning %s' % dir_to_remove)\n shutil.rmtree(dir_to_remove, ignore_errors=True)\n os.makedirs(dir_to_remove)",
"pwd = os.getcwd()\nos.chdir(source_dir)\nfor item in Cleaner.TO_CLEAN:\n name = item.get('name')\n pattern = item.get('pattern')\n file_type... | <|body_start_0|>
for dir_to_remove in args:
logger.info('cleaning %s' % dir_to_remove)
shutil.rmtree(dir_to_remove, ignore_errors=True)
os.makedirs(dir_to_remove)
<|end_body_0|>
<|body_start_1|>
pwd = os.getcwd()
os.chdir(source_dir)
for item in Clean... | Encapsulates functions that help clean up the build environment. | Cleaner | [
"BSD-3-Clause",
"Python-2.0",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cleaner:
"""Encapsulates functions that help clean up the build environment."""
def clean_dirs(self, *args):
"""Recursively remove each of its arguments, then recreate the directory"""
<|body_0|>
def cleanup_source(self, source_dir):
"""Uses the `find` command to... | stack_v2_sparse_classes_75kplus_train_003542 | 12,578 | permissive | [
{
"docstring": "Recursively remove each of its arguments, then recreate the directory",
"name": "clean_dirs",
"signature": "def clean_dirs(self, *args)"
},
{
"docstring": "Uses the `find` command to clean up items listed in TO_CLEAN",
"name": "cleanup_source",
"signature": "def cleanup_s... | 2 | null | Implement the Python class `Cleaner` described below.
Class description:
Encapsulates functions that help clean up the build environment.
Method signatures and docstrings:
- def clean_dirs(self, *args): Recursively remove each of its arguments, then recreate the directory
- def cleanup_source(self, source_dir): Uses ... | Implement the Python class `Cleaner` described below.
Class description:
Encapsulates functions that help clean up the build environment.
Method signatures and docstrings:
- def clean_dirs(self, *args): Recursively remove each of its arguments, then recreate the directory
- def cleanup_source(self, source_dir): Uses ... | 2a56cf26181f34609881b5a78c93616f98f39c9e | <|skeleton|>
class Cleaner:
"""Encapsulates functions that help clean up the build environment."""
def clean_dirs(self, *args):
"""Recursively remove each of its arguments, then recreate the directory"""
<|body_0|>
def cleanup_source(self, source_dir):
"""Uses the `find` command to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cleaner:
"""Encapsulates functions that help clean up the build environment."""
def clean_dirs(self, *args):
"""Recursively remove each of its arguments, then recreate the directory"""
for dir_to_remove in args:
logger.info('cleaning %s' % dir_to_remove)
shutil.rmt... | the_stack_v2_python_sparse | deployment/build-s3-cdk-dist.py | ajayarunachalam/improving-forecast-accuracy-with-machine-learning | train | 0 |
48c4f3611ffc55cdc3a205da40acae304b5aa69e | [
"if os.path.isfile(path):\n with open(path, 'rb') as file:\n return (file.read(), True)\nif save:\n return (cls.fetch_and_save(url, path), False)\nreturn (cls.fetch_with_retry(url), False)",
"content = cls.fetch_with_retry(url)\nif not content:\n return False\nwith open(path, 'wb') as file:\n f... | <|body_start_0|>
if os.path.isfile(path):
with open(path, 'rb') as file:
return (file.read(), True)
if save:
return (cls.fetch_and_save(url, path), False)
return (cls.fetch_with_retry(url), False)
<|end_body_0|>
<|body_start_1|>
content = cls.fetc... | Fetcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fetcher:
def fetch_maybe(cls, url, path, save=False):
"""Fetch from url or from file if it has been cached previously"""
<|body_0|>
def fetch_and_save(cls, url, path):
"""Fetch file and save to disk"""
<|body_1|>
def fetch_with_retry(cls, url):
"... | stack_v2_sparse_classes_75kplus_train_003543 | 2,471 | no_license | [
{
"docstring": "Fetch from url or from file if it has been cached previously",
"name": "fetch_maybe",
"signature": "def fetch_maybe(cls, url, path, save=False)"
},
{
"docstring": "Fetch file and save to disk",
"name": "fetch_and_save",
"signature": "def fetch_and_save(cls, url, path)"
... | 4 | stack_v2_sparse_classes_30k_train_020818 | Implement the Python class `Fetcher` described below.
Class description:
Implement the Fetcher class.
Method signatures and docstrings:
- def fetch_maybe(cls, url, path, save=False): Fetch from url or from file if it has been cached previously
- def fetch_and_save(cls, url, path): Fetch file and save to disk
- def fe... | Implement the Python class `Fetcher` described below.
Class description:
Implement the Fetcher class.
Method signatures and docstrings:
- def fetch_maybe(cls, url, path, save=False): Fetch from url or from file if it has been cached previously
- def fetch_and_save(cls, url, path): Fetch file and save to disk
- def fe... | 31f29e374d8668c92f1b1c48b2d38c967f5e145f | <|skeleton|>
class Fetcher:
def fetch_maybe(cls, url, path, save=False):
"""Fetch from url or from file if it has been cached previously"""
<|body_0|>
def fetch_and_save(cls, url, path):
"""Fetch file and save to disk"""
<|body_1|>
def fetch_with_retry(cls, url):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fetcher:
def fetch_maybe(cls, url, path, save=False):
"""Fetch from url or from file if it has been cached previously"""
if os.path.isfile(path):
with open(path, 'rb') as file:
return (file.read(), True)
if save:
return (cls.fetch_and_save(url, p... | the_stack_v2_python_sparse | fetcher.py | mideind/thesis-corpus | train | 0 | |
4ee0d8cb1de38d7b40796148dd3ce34f10a3a890 | [
"self.data = dat\nself.cov = cov\nself.z = z\nself.prior = prior",
"mod = modelo(theta, self.z)\nself.u = -likelihood(mod, self.data, self.cov) - self.prior.get_log_pdf(theta)\nreturn self.u",
"self.value(theta)\nself.gradient = tf.gradients(self.u, theta)\nreturn self.gradient[0]"
] | <|body_start_0|>
self.data = dat
self.cov = cov
self.z = z
self.prior = prior
<|end_body_0|>
<|body_start_1|>
mod = modelo(theta, self.z)
self.u = -likelihood(mod, self.data, self.cov) - self.prior.get_log_pdf(theta)
return self.u
<|end_body_1|>
<|body_start_2|>... | Potential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
<|body_0|>
def value(self, theta):
"""Returns pote... | stack_v2_sparse_classes_75kplus_train_003544 | 11,880 | no_license | [
{
"docstring": "Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior.",
"name": "__init__",
"signature": "def __init__(self, dat, cov, z, prior)"
},
{
"docstring": "Returns potential value i... | 3 | stack_v2_sparse_classes_30k_train_022999 | Implement the Python class `Potential` described below.
Class description:
Implement the Potential class.
Method signatures and docstrings:
- def __init__(self, dat, cov, z, prior): Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift... | Implement the Python class `Potential` described below.
Class description:
Implement the Potential class.
Method signatures and docstrings:
- def __init__(self, dat, cov, z, prior): Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift... | 8789f692d81c5435a5888b6b151ccf6187d5a064 | <|skeleton|>
class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
<|body_0|>
def value(self, theta):
"""Returns pote... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
self.data = dat
self.cov = cov
self.z = z
self.prior ... | the_stack_v2_python_sparse | p18/hmc.py | fluowhy/MCMC-methods | train | 1 | |
e02af291c7ac26f913dcba28c1949fa44d17c552 | [
"self.X = X\nself.y = y\nself.pipeline_map = pipeline_map",
"if any([isinstance(item, CategoricalEncoder) for item in transforms]):\n categories = dict()\n for cat_col in columns:\n cats = X[~X[cat_col].isnull()][cat_col].unique().tolist()\n categories.update({cat_col: cats})\n transforms =... | <|body_start_0|>
self.X = X
self.y = y
self.pipeline_map = pipeline_map
<|end_body_0|>
<|body_start_1|>
if any([isinstance(item, CategoricalEncoder) for item in transforms]):
categories = dict()
for cat_col in columns:
cats = X[~X[cat_col].isnull(... | DataFrameTransformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFrameTransformer:
def __init__(self, X, pipeline_map, y=None):
""":param X: a Pandas DataFrame object. :param pipeline_map: :param y:"""
<|body_0|>
def column_transformer(self, X, columns, transforms):
"""Perform fit-and-transform on `columns` of DataFrame `X` ac... | stack_v2_sparse_classes_75kplus_train_003545 | 4,618 | permissive | [
{
"docstring": ":param X: a Pandas DataFrame object. :param pipeline_map: :param y:",
"name": "__init__",
"signature": "def __init__(self, X, pipeline_map, y=None)"
},
{
"docstring": "Perform fit-and-transform on `columns` of DataFrame `X` according to `transforms`, returns the transformed DataF... | 3 | stack_v2_sparse_classes_30k_train_017653 | Implement the Python class `DataFrameTransformer` described below.
Class description:
Implement the DataFrameTransformer class.
Method signatures and docstrings:
- def __init__(self, X, pipeline_map, y=None): :param X: a Pandas DataFrame object. :param pipeline_map: :param y:
- def column_transformer(self, X, columns... | Implement the Python class `DataFrameTransformer` described below.
Class description:
Implement the DataFrameTransformer class.
Method signatures and docstrings:
- def __init__(self, X, pipeline_map, y=None): :param X: a Pandas DataFrame object. :param pipeline_map: :param y:
- def column_transformer(self, X, columns... | 1121443bef901fc6c9ed9f7d3ac60a0885189753 | <|skeleton|>
class DataFrameTransformer:
def __init__(self, X, pipeline_map, y=None):
""":param X: a Pandas DataFrame object. :param pipeline_map: :param y:"""
<|body_0|>
def column_transformer(self, X, columns, transforms):
"""Perform fit-and-transform on `columns` of DataFrame `X` ac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataFrameTransformer:
def __init__(self, X, pipeline_map, y=None):
""":param X: a Pandas DataFrame object. :param pipeline_map: :param y:"""
self.X = X
self.y = y
self.pipeline_map = pipeline_map
def column_transformer(self, X, columns, transforms):
"""Perform fit-... | the_stack_v2_python_sparse | titanic/sk_util.py | comsaint/Data-Practice | train | 0 | |
f66ce9d081df3a5425dac84b1c01317b95c8d35a | [
"if not skipValidation:\n self.instructionLength = form['length']\n for descriptionElement in form['description']:\n mask = form['description'][descriptionElement]\n extractedBinary = self._extractValueFromBinaryField(mask, binaryInstruction)\n setattr(self, descriptionElement, extractedB... | <|body_start_0|>
if not skipValidation:
self.instructionLength = form['length']
for descriptionElement in form['description']:
mask = form['description'][descriptionElement]
extractedBinary = self._extractValueFromBinaryField(mask, binaryInstruction)
... | This class is only used for instruction encapsulation after they are fetched from memory. An instance of this class is built by the InstructionFetchUnit and is passed to the ExecutionUnit for execution. This class is simply there to help lower the number of binary parsing required in the execution of a given instructio... | Instruction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Instruction:
"""This class is only used for instruction encapsulation after they are fetched from memory. An instance of this class is built by the InstructionFetchUnit and is passed to the ExecutionUnit for execution. This class is simply there to help lower the number of binary parsing required... | stack_v2_sparse_classes_75kplus_train_003546 | 4,224 | no_license | [
{
"docstring": "This allow for initialisation of the instruction by parsing the binary instruction code :param binaryInstruction: A big number representing the instruction :param form: The form representing the instruction as shown in FormDescription.py :return: An instruction! Warning, this instruction could b... | 2 | null | Implement the Python class `Instruction` described below.
Class description:
This class is only used for instruction encapsulation after they are fetched from memory. An instance of this class is built by the InstructionFetchUnit and is passed to the ExecutionUnit for execution. This class is simply there to help lowe... | Implement the Python class `Instruction` described below.
Class description:
This class is only used for instruction encapsulation after they are fetched from memory. An instance of this class is built by the InstructionFetchUnit and is passed to the ExecutionUnit for execution. This class is simply there to help lowe... | 2e3d7cb2567893353591117a2fe3a6994654a055 | <|skeleton|>
class Instruction:
"""This class is only used for instruction encapsulation after they are fetched from memory. An instance of this class is built by the InstructionFetchUnit and is passed to the ExecutionUnit for execution. This class is simply there to help lower the number of binary parsing required... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Instruction:
"""This class is only used for instruction encapsulation after they are fetched from memory. An instance of this class is built by the InstructionFetchUnit and is passed to the ExecutionUnit for execution. This class is simply there to help lower the number of binary parsing required in the execu... | the_stack_v2_python_sparse | Instruction.py | kommisar5150/assembler | train | 0 |
e28391d7c4b82a0a3918dd79eef43426b5a34cf0 | [
"super(NN, self).__init__()\nself.layers = nn.ModuleList([nn.Linear(dim_in, dim_out) for dim_in, dim_out in zip(layers[:-1], layers[1:])])\nself.activations = [Swish()] * (len(layers) - 2)\nfor i in range(len(activations)):\n self.activations[i] = activations[i]\nself.norm = nn.ModuleList([nn.BatchNorm1d(dim) fo... | <|body_start_0|>
super(NN, self).__init__()
self.layers = nn.ModuleList([nn.Linear(dim_in, dim_out) for dim_in, dim_out in zip(layers[:-1], layers[1:])])
self.activations = [Swish()] * (len(layers) - 2)
for i in range(len(activations)):
self.activations[i] = activations[i]
... | A plain neural network. | NN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NN:
"""A plain neural network."""
def __init__(self, layers, activations, batch_norm=True):
"""Creates a neural network. :param layers: layers of the network, including input and output layers :param activations: per layer activation functions. If less then layers, default Swish will... | stack_v2_sparse_classes_75kplus_train_003547 | 21,063 | no_license | [
{
"docstring": "Creates a neural network. :param layers: layers of the network, including input and output layers :param activations: per layer activation functions. If less then layers, default Swish will be used :param batch_norm: whether to batch normalize between layers",
"name": "__init__",
"signat... | 2 | null | Implement the Python class `NN` described below.
Class description:
A plain neural network.
Method signatures and docstrings:
- def __init__(self, layers, activations, batch_norm=True): Creates a neural network. :param layers: layers of the network, including input and output layers :param activations: per layer acti... | Implement the Python class `NN` described below.
Class description:
A plain neural network.
Method signatures and docstrings:
- def __init__(self, layers, activations, batch_norm=True): Creates a neural network. :param layers: layers of the network, including input and output layers :param activations: per layer acti... | ceeb196bde01592f9ec15f9e24d008a9395c65ea | <|skeleton|>
class NN:
"""A plain neural network."""
def __init__(self, layers, activations, batch_norm=True):
"""Creates a neural network. :param layers: layers of the network, including input and output layers :param activations: per layer activation functions. If less then layers, default Swish will... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NN:
"""A plain neural network."""
def __init__(self, layers, activations, batch_norm=True):
"""Creates a neural network. :param layers: layers of the network, including input and output layers :param activations: per layer activation functions. If less then layers, default Swish will be used :par... | the_stack_v2_python_sparse | src/algorithm/MPC/model.py | al91liwo/pytorch-rl-lab | train | 3 |
216b3d527df2a210c14a0878c0031db222c1a898 | [
"self.now = now\nself.out = DNSOutgoing(_FLAGS_QR_QUERY, multicast=multicast)\nself.bytes = 0",
"self.out.add_question(question)\nfor answer in answers:\n self.out.add_answer_at_time(answer, self.now)\nself.bytes += max_compressed_size"
] | <|body_start_0|>
self.now = now
self.out = DNSOutgoing(_FLAGS_QR_QUERY, multicast=multicast)
self.bytes = 0
<|end_body_0|>
<|body_start_1|>
self.out.add_question(question)
for answer in answers:
self.out.add_answer_at_time(answer, self.now)
self.bytes += max_... | A DNSOutgoing bucket. | _DNSPointerOutgoingBucket | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DNSPointerOutgoingBucket:
"""A DNSOutgoing bucket."""
def __init__(self, now: float, multicast: bool) -> None:
"""Create a bucke to wrap a DNSOutgoing."""
<|body_0|>
def add(self, max_compressed_size: int, question: DNSQuestion, answers: Set[DNSPointer]) -> None:
... | stack_v2_sparse_classes_75kplus_train_003548 | 22,336 | permissive | [
{
"docstring": "Create a bucke to wrap a DNSOutgoing.",
"name": "__init__",
"signature": "def __init__(self, now: float, multicast: bool) -> None"
},
{
"docstring": "Add a new set of questions and known answers to the outgoing.",
"name": "add",
"signature": "def add(self, max_compressed_... | 2 | stack_v2_sparse_classes_30k_train_047150 | Implement the Python class `_DNSPointerOutgoingBucket` described below.
Class description:
A DNSOutgoing bucket.
Method signatures and docstrings:
- def __init__(self, now: float, multicast: bool) -> None: Create a bucke to wrap a DNSOutgoing.
- def add(self, max_compressed_size: int, question: DNSQuestion, answers: ... | Implement the Python class `_DNSPointerOutgoingBucket` described below.
Class description:
A DNSOutgoing bucket.
Method signatures and docstrings:
- def __init__(self, now: float, multicast: bool) -> None: Create a bucke to wrap a DNSOutgoing.
- def add(self, max_compressed_size: int, question: DNSQuestion, answers: ... | 6a450ac1769db19cfdb9908a5d04b387a18b2b54 | <|skeleton|>
class _DNSPointerOutgoingBucket:
"""A DNSOutgoing bucket."""
def __init__(self, now: float, multicast: bool) -> None:
"""Create a bucke to wrap a DNSOutgoing."""
<|body_0|>
def add(self, max_compressed_size: int, question: DNSQuestion, answers: Set[DNSPointer]) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _DNSPointerOutgoingBucket:
"""A DNSOutgoing bucket."""
def __init__(self, now: float, multicast: bool) -> None:
"""Create a bucke to wrap a DNSOutgoing."""
self.now = now
self.out = DNSOutgoing(_FLAGS_QR_QUERY, multicast=multicast)
self.bytes = 0
def add(self, max_com... | the_stack_v2_python_sparse | BondHome.indigoPlugin/Contents/Packages/zeroconf/_services/browser.py | FlyingDiver/Indigo-BondHome | train | 0 |
5ab9420c6e0ec6c6e67ce2fc2ce09d830edfb5d3 | [
"amp.AMP.__init__(self)\nself.store = store\nself.directory = directory",
"command = readPlistFromString(command)\noutput = cStringIO.StringIO()\nfrom calendarserver.tools.gateway import Runner\nrunner = Runner(self.store, [command], output=output)\ntry:\n yield runner.run()\n result = output.getvalue()\n ... | <|body_start_0|>
amp.AMP.__init__(self)
self.store = store
self.directory = directory
<|end_body_0|>
<|body_start_1|>
command = readPlistFromString(command)
output = cStringIO.StringIO()
from calendarserver.tools.gateway import Runner
runner = Runner(self.store, ... | Passes commands to gateway.Runner and returns the results | GatewayAMPProtocol | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GatewayAMPProtocol:
"""Passes commands to gateway.Runner and returns the results"""
def __init__(self, store, directory):
"""@param store: an already opened store operations @param directory: a directory service"""
<|body_0|>
def gatewayCommandReceived(self, command):
... | stack_v2_sparse_classes_75kplus_train_003549 | 10,761 | permissive | [
{
"docstring": "@param store: an already opened store operations @param directory: a directory service",
"name": "__init__",
"signature": "def __init__(self, store, directory)"
},
{
"docstring": "Process a command via gateway.Runner @param command: GatewayAMPCommand @returns: a deferred returnin... | 2 | null | Implement the Python class `GatewayAMPProtocol` described below.
Class description:
Passes commands to gateway.Runner and returns the results
Method signatures and docstrings:
- def __init__(self, store, directory): @param store: an already opened store operations @param directory: a directory service
- def gatewayCo... | Implement the Python class `GatewayAMPProtocol` described below.
Class description:
Passes commands to gateway.Runner and returns the results
Method signatures and docstrings:
- def __init__(self, store, directory): @param store: an already opened store operations @param directory: a directory service
- def gatewayCo... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class GatewayAMPProtocol:
"""Passes commands to gateway.Runner and returns the results"""
def __init__(self, store, directory):
"""@param store: an already opened store operations @param directory: a directory service"""
<|body_0|>
def gatewayCommandReceived(self, command):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GatewayAMPProtocol:
"""Passes commands to gateway.Runner and returns the results"""
def __init__(self, store, directory):
"""@param store: an already opened store operations @param directory: a directory service"""
amp.AMP.__init__(self)
self.store = store
self.directory =... | the_stack_v2_python_sparse | calendarserver/tools/agent.py | ass-a2s/ccs-calendarserver | train | 2 |
36d8c24291726a03b25b6d07fc966ad9b2d101b3 | [
"super(AttnRawDecoderWithSrc, self).__init__()\nself.embedding_size = 256\nself.lstm_size = 512\nself.lstm_num_layer = 3\nself.dropout_rate = 0.3\nself.half_window_size = 3\nself.dec_embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=self.embedding_size)\nself.lstm = nn.LSTM(input_size=self.embedding... | <|body_start_0|>
super(AttnRawDecoderWithSrc, self).__init__()
self.embedding_size = 256
self.lstm_size = 512
self.lstm_num_layer = 3
self.dropout_rate = 0.3
self.half_window_size = 3
self.dec_embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=self.... | AttnRawDecoderWithSrc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttnRawDecoderWithSrc:
def __init__(self, vocab_size, enc_output_size, enc_embedding_size):
"""Common use for both Training and Inference :param vocab_size:"""
<|body_0|>
def forward(self, inputs_idx, h_n_c_n, enc_outputs, enc_inputs, step, *args):
"""Implemented by ... | stack_v2_sparse_classes_75kplus_train_003550 | 11,411 | no_license | [
{
"docstring": "Common use for both Training and Inference :param vocab_size:",
"name": "__init__",
"signature": "def __init__(self, vocab_size, enc_output_size, enc_embedding_size)"
},
{
"docstring": "Implemented by running step by step :param inputs_idx: shape == (seq_len, batch_size) :param h... | 2 | null | Implement the Python class `AttnRawDecoderWithSrc` described below.
Class description:
Implement the AttnRawDecoderWithSrc class.
Method signatures and docstrings:
- def __init__(self, vocab_size, enc_output_size, enc_embedding_size): Common use for both Training and Inference :param vocab_size:
- def forward(self, i... | Implement the Python class `AttnRawDecoderWithSrc` described below.
Class description:
Implement the AttnRawDecoderWithSrc class.
Method signatures and docstrings:
- def __init__(self, vocab_size, enc_output_size, enc_embedding_size): Common use for both Training and Inference :param vocab_size:
- def forward(self, i... | 56ca628b847310bc61a0cd796c0b08dc4126ec01 | <|skeleton|>
class AttnRawDecoderWithSrc:
def __init__(self, vocab_size, enc_output_size, enc_embedding_size):
"""Common use for both Training and Inference :param vocab_size:"""
<|body_0|>
def forward(self, inputs_idx, h_n_c_n, enc_outputs, enc_inputs, step, *args):
"""Implemented by ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttnRawDecoderWithSrc:
def __init__(self, vocab_size, enc_output_size, enc_embedding_size):
"""Common use for both Training and Inference :param vocab_size:"""
super(AttnRawDecoderWithSrc, self).__init__()
self.embedding_size = 256
self.lstm_size = 512
self.lstm_num_lay... | the_stack_v2_python_sparse | source/main/model_def/seq2seq_decoder.py | ductri/diacritics_restoration_contest | train | 0 | |
3b4b264a7f4d6ea39f7a1552f954aca03d9013a4 | [
"self.count = 0\nself.char = ''\nself.children = [None] * 26",
"if not word:\n return\nnode = self\nfor c in word:\n index = ord(c) - ord('a')\n if self.children[index] is None:\n t = Trie()\n t.char = c\n node.children[index] = t\n node = node.children[index]\nnode.count += 1",
... | <|body_start_0|>
self.count = 0
self.char = ''
self.children = [None] * 26
<|end_body_0|>
<|body_start_1|>
if not word:
return
node = self
for c in word:
index = ord(c) - ord('a')
if self.children[index] is None:
t = Tr... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_75kplus_train_003551 | 2,044 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | stack_v2_sparse_classes_30k_train_047249 | 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: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 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: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 55f37eb135bbe4a85235bc8e25f90e3dd9edf9e8 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.count = 0
self.char = ''
self.children = [None] * 26
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
if not word:
return
node = self
... | the_stack_v2_python_sparse | 200~300/201~210/208.implement_prefix_tree.py | lianglee123/leetcode | train | 0 | |
5f9afe4853c0b364ae0d35e509857f28cc8659fc | [
"msg = 'Specify a valid before date (-b) or an age (-a).'\nwith self.assertRaisesMessage(CommandError, msg):\n call_command('clean_entries')",
"msg = 'Specify a valid before date (-b) or an age (-a).'\nwith self.assertRaisesMessage(CommandError, msg):\n call_command('clean_entries', '-a=-3')",
"today, now... | <|body_start_0|>
msg = 'Specify a valid before date (-b) or an age (-a).'
with self.assertRaisesMessage(CommandError, msg):
call_command('clean_entries')
<|end_body_0|>
<|body_start_1|>
msg = 'Specify a valid before date (-b) or an age (-a).'
with self.assertRaisesMessage(Co... | Tests of the management command to clear out old entries. | Clean_Entry_Tests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clean_Entry_Tests:
"""Tests of the management command to clear out old entries."""
def test_no_args_gives_error(self):
"""Make sure providing no arguments raises an error."""
<|body_0|>
def test_negative_age_gives_error(self):
"""Make sure negative age raises an ... | stack_v2_sparse_classes_75kplus_train_003552 | 29,880 | permissive | [
{
"docstring": "Make sure providing no arguments raises an error.",
"name": "test_no_args_gives_error",
"signature": "def test_no_args_gives_error(self)"
},
{
"docstring": "Make sure negative age raises an error.",
"name": "test_negative_age_gives_error",
"signature": "def test_negative_... | 6 | stack_v2_sparse_classes_30k_train_041168 | Implement the Python class `Clean_Entry_Tests` described below.
Class description:
Tests of the management command to clear out old entries.
Method signatures and docstrings:
- def test_no_args_gives_error(self): Make sure providing no arguments raises an error.
- def test_negative_age_gives_error(self): Make sure ne... | Implement the Python class `Clean_Entry_Tests` described below.
Class description:
Tests of the management command to clear out old entries.
Method signatures and docstrings:
- def test_no_args_gives_error(self): Make sure providing no arguments raises an error.
- def test_negative_age_gives_error(self): Make sure ne... | 12e1f2d3f6e7da5fbbbeb2af1322117589e218fa | <|skeleton|>
class Clean_Entry_Tests:
"""Tests of the management command to clear out old entries."""
def test_no_args_gives_error(self):
"""Make sure providing no arguments raises an error."""
<|body_0|>
def test_negative_age_gives_error(self):
"""Make sure negative age raises an ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Clean_Entry_Tests:
"""Tests of the management command to clear out old entries."""
def test_no_args_gives_error(self):
"""Make sure providing no arguments raises an error."""
msg = 'Specify a valid before date (-b) or an age (-a).'
with self.assertRaisesMessage(CommandError, msg):... | the_stack_v2_python_sparse | diary/tests.py | BobBowles/django-diary | train | 23 |
f0cc5f6a96e9e7d5a5eabfb7d64af4cb2410ff5c | [
"self.head = head\nnode, i = (head, 0)\nwhile node:\n i += 1\n node = node.next\nself.len = i",
"node = self.head\ni = random.randint(1, self.len)\nwhile i > 1:\n node = node.next\n i -= 1\nreturn node.val"
] | <|body_start_0|>
self.head = head
node, i = (head, 0)
while node:
i += 1
node = node.next
self.len = i
<|end_body_0|>
<|body_start_1|>
node = self.head
i = random.randint(1, self.len)
while i > 1:
node = node.next
i... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_003553 | 1,805 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode",
"name": "__init__",
"signature": "def __init__(self, head)"
},
{
"docstring": "Returns a random node's value. :rtype: int",
"name": "g... | 2 | stack_v2_sparse_classes_30k_train_014216 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getR... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getR... | 4ed2d3d7a05890e1d39621465e57bc429ccde19b | <|skeleton|>
class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
self.head = head
node, i = (head, 0)
while node:
i += 1
node = node.nex... | the_stack_v2_python_sparse | python/leetcode/p382.py | aloklal99/naukari | train | 0 | |
08e328e884ead0778f24f6f56efb5ac20dcbab56 | [
"super(PlotCellTypeStack, self).__init__(experiment, name='PlotCellTypeStack', label=label)\nself.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)\nself.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experiment.config.getint('Experiment', '... | <|body_start_0|>
super(PlotCellTypeStack, self).__init__(experiment, name='PlotCellTypeStack', label=label)
self.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)
self.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experi... | TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at which to execute (default: 1) priority The prio... | PlotCellTypeStack | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotCellTypeStack:
"""TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at wh... | stack_v2_sparse_classes_75kplus_train_003554 | 3,421 | permissive | [
{
"docstring": "Initialize the PlotCellTypeStack Action",
"name": "__init__",
"signature": "def __init__(self, experiment, label=None)"
},
{
"docstring": "Execute the action",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Since we're at the end of the run, ... | 3 | stack_v2_sparse_classes_30k_train_006111 | Implement the Python class `PlotCellTypeStack` described below.
Class description:
TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment)... | Implement the Python class `PlotCellTypeStack` described below.
Class description:
TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment)... | a114ac66e62a960e18127faf52cff9e48831e212 | <|skeleton|>
class PlotCellTypeStack:
"""TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at wh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlotCellTypeStack:
"""TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at which to execut... | the_stack_v2_python_sparse | contrib/actions/PlotCellTypeStack.py | namlehai/seeds | train | 0 |
86ba83744f81d71215b2b1f364b173e0174f51b4 | [
"if not isinstance(ssh_known_hosts_file, str):\n raise TypeError(f'`ssh_config_file` expected str, got {type(ssh_known_hosts_file)}')\nself.ssh_known_hosts_file = os.path.expanduser(ssh_known_hosts_file)\nif self.ssh_known_hosts_file:\n with open(self.ssh_known_hosts_file, 'r') as f:\n self.ssh_known_h... | <|body_start_0|>
if not isinstance(ssh_known_hosts_file, str):
raise TypeError(f'`ssh_config_file` expected str, got {type(ssh_known_hosts_file)}')
self.ssh_known_hosts_file = os.path.expanduser(ssh_known_hosts_file)
if self.ssh_known_hosts_file:
with open(self.ssh_known_... | SSHKnownHosts | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHKnownHosts:
def __init__(self, ssh_known_hosts_file: str) -> None:
"""Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts ... | stack_v2_sparse_classes_75kplus_train_003555 | 13,310 | permissive | [
{
"docstring": "Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts file Returns: N/A # noqa: DAR202 Raises: TypeError: if non-string value provided ... | 2 | stack_v2_sparse_classes_30k_train_001196 | Implement the Python class `SSHKnownHosts` described below.
Class description:
Implement the SSHKnownHosts class.
Method signatures and docstrings:
- def __init__(self, ssh_known_hosts_file: str) -> None: Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in ... | Implement the Python class `SSHKnownHosts` described below.
Class description:
Implement the SSHKnownHosts class.
Method signatures and docstrings:
- def __init__(self, ssh_known_hosts_file: str) -> None: Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in ... | eeaa8f2ff5e54771c02335d7c2099d56d88b8cdc | <|skeleton|>
class SSHKnownHosts:
def __init__(self, ssh_known_hosts_file: str) -> None:
"""Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSHKnownHosts:
def __init__(self, ssh_known_hosts_file: str) -> None:
"""Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts file Returns: ... | the_stack_v2_python_sparse | scrapli/ssh_config.py | Ferhub255/scrapli | train | 1 | |
d36a24720f2fbff6e55ec4c468365202b0f4551e | [
"self.screen = screen\nself.proporcao = 6\nself.images = []\nself.cont_animacao = 0\nself.cont_frames = 0\nself.na_tela = True\nself.destruido = False\nself.x_aux = coord_x\nself.cont_x = 0\nself.direcao = 0\nself.atirar = False\nself.cont_projetil = 0\nself.screen_dimensions = pygame.display.get_surface().get_size... | <|body_start_0|>
self.screen = screen
self.proporcao = 6
self.images = []
self.cont_animacao = 0
self.cont_frames = 0
self.na_tela = True
self.destruido = False
self.x_aux = coord_x
self.cont_x = 0
self.direcao = 0
self.atirar = Fal... | Superclasse para os três tipos de inimgos | Alien | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Alien:
"""Superclasse para os três tipos de inimgos"""
def __init__(self, screen, coord_x, coord_y, diretorio1, diretorio2):
"""Inicializa atributos e carrega sua imagem"""
<|body_0|>
def desenhar(self):
"""Desenha um alien na tela"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_003556 | 3,061 | no_license | [
{
"docstring": "Inicializa atributos e carrega sua imagem",
"name": "__init__",
"signature": "def __init__(self, screen, coord_x, coord_y, diretorio1, diretorio2)"
},
{
"docstring": "Desenha um alien na tela",
"name": "desenhar",
"signature": "def desenhar(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051245 | Implement the Python class `Alien` described below.
Class description:
Superclasse para os três tipos de inimgos
Method signatures and docstrings:
- def __init__(self, screen, coord_x, coord_y, diretorio1, diretorio2): Inicializa atributos e carrega sua imagem
- def desenhar(self): Desenha um alien na tela | Implement the Python class `Alien` described below.
Class description:
Superclasse para os três tipos de inimgos
Method signatures and docstrings:
- def __init__(self, screen, coord_x, coord_y, diretorio1, diretorio2): Inicializa atributos e carrega sua imagem
- def desenhar(self): Desenha um alien na tela
<|skeleto... | 5f305120652ef1e8ecd94504ddb759feba73750d | <|skeleton|>
class Alien:
"""Superclasse para os três tipos de inimgos"""
def __init__(self, screen, coord_x, coord_y, diretorio1, diretorio2):
"""Inicializa atributos e carrega sua imagem"""
<|body_0|>
def desenhar(self):
"""Desenha um alien na tela"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Alien:
"""Superclasse para os três tipos de inimgos"""
def __init__(self, screen, coord_x, coord_y, diretorio1, diretorio2):
"""Inicializa atributos e carrega sua imagem"""
self.screen = screen
self.proporcao = 6
self.images = []
self.cont_animacao = 0
self... | the_stack_v2_python_sparse | alien_invasion/entidades/aliens/alien.py | breno-abreu/AlienInvasionPython | train | 0 |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertOutput, self).__init__()\nself.dense = nn.Dense(config.intermediate_size, config.hidden_size).to_float(mindspore.float16)\nself.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps).to_float(mindspore.float16)\nself.dropout = nn.Dropout(p=config.hidden_dropout_prob)\nself.cast = ... | <|body_start_0|>
super(BertOutput, self).__init__()
self.dense = nn.Dense(config.intermediate_size, config.hidden_size).to_float(mindspore.float16)
self.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps).to_float(mindspore.float16)
self.dropout = nn.Dropout(p=... | bert output | BertOutput | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertOutput:
"""bert output"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, input_tensor):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BertOutput, self).__init__()
sel... | stack_v2_sparse_classes_75kplus_train_003557 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states, input_tensor)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027785 | Implement the Python class `BertOutput` described below.
Class description:
bert output
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, input_tensor): construct fun | Implement the Python class `BertOutput` described below.
Class description:
bert output
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, input_tensor): construct fun
<|skeleton|>
class BertOutput:
"""bert output"""
def __init__(self, config):
... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertOutput:
"""bert output"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, input_tensor):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BertOutput:
"""bert output"""
def __init__(self, config):
"""init fun"""
super(BertOutput, self).__init__()
self.dense = nn.Dense(config.intermediate_size, config.hidden_size).to_float(mindspore.float16)
self.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.l... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
a53e087755e68a914c78f7111832e1ae9f2be1a8 | [
"self.pb_prm = pb_prm\nself.var_fac = self.compute_variables_factors(dvv_low, dvv_upp)\nself.obj_fac = self.compute_objective_factor(grad)\nself.con_fac = self.compute_constraints_factors(jac)",
"var_fac = np.zeros(len(dvv_low))\nfor i, (v_low, v_upp) in enumerate(zip(dvv_low, dvv_upp)):\n fact = max(abs(v_low... | <|body_start_0|>
self.pb_prm = pb_prm
self.var_fac = self.compute_variables_factors(dvv_low, dvv_upp)
self.obj_fac = self.compute_objective_factor(grad)
self.con_fac = self.compute_constraints_factors(jac)
<|end_body_0|>
<|body_start_1|>
var_fac = np.zeros(len(dvv_low))
... | `Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppad_py sparse jacobian object> Sparse... | Scaling | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scaling:
"""`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppa... | stack_v2_sparse_classes_75kplus_train_003558 | 5,077 | no_license | [
{
"docstring": "Initialiation of the `Scaling` class",
"name": "__init__",
"signature": "def __init__(self, dvv_low, dvv_upp, jac, grad, pb_prm)"
},
{
"docstring": "Computation of the variables scale factors array Parameters ---------- dvv_low : array Decision variables lower boundaries vector d... | 5 | stack_v2_sparse_classes_30k_val_002144 | Implement the Python class `Scaling` described below.
Class description:
`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variab... | Implement the Python class `Scaling` described below.
Class description:
`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variab... | 9d4b1809e868aec674d6bf3c48958b23418290e7 | <|skeleton|>
class Scaling:
"""`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scaling:
"""`Scaling` class computes the scaling factors of decision variables, objective function, defects constraints and constraints Jacobian. Parameters ---------- dvv_low : array Decision variables lower boundaries vector dvv_upp : array Decision variables upper boundaries vector jac : <cppad_py sparse j... | the_stack_v2_python_sparse | collocation/scaling.py | TomSemblanet/Asteroid-Retrieval-Mission | train | 1 |
eb99ccc2e8cefce621198e1d43cee86db5ef1454 | [
"queryset = DistanceType.objects.all()\nserializer = DistanceTypeSerializer(queryset, many=True)\nreturn Response(serializer.data)",
"queryset = StreetType.objects.all()\nserializer = StreetTypeSerializer(queryset, many=True)\nreturn Response(serializer.data)",
"queryset = LocationType.objects.all()\nserializer... | <|body_start_0|>
queryset = DistanceType.objects.all()
serializer = DistanceTypeSerializer(queryset, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = StreetType.objects.all()
serializer = StreetTypeSerializer(queryset, many=True)
ret... | API for working with information related to hotels (Hotel) | HotelViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HotelViewSet:
"""API for working with information related to hotels (Hotel)"""
def distance(self, request):
"""Getting a list of "distance types" :param request: :return:"""
<|body_0|>
def streets(self, request):
"""Getting a list of "street types" :param request... | stack_v2_sparse_classes_75kplus_train_003559 | 7,291 | no_license | [
{
"docstring": "Getting a list of \"distance types\" :param request: :return:",
"name": "distance",
"signature": "def distance(self, request)"
},
{
"docstring": "Getting a list of \"street types\" :param request: :return:",
"name": "streets",
"signature": "def streets(self, request)"
}... | 5 | stack_v2_sparse_classes_30k_train_050123 | Implement the Python class `HotelViewSet` described below.
Class description:
API for working with information related to hotels (Hotel)
Method signatures and docstrings:
- def distance(self, request): Getting a list of "distance types" :param request: :return:
- def streets(self, request): Getting a list of "street ... | Implement the Python class `HotelViewSet` described below.
Class description:
API for working with information related to hotels (Hotel)
Method signatures and docstrings:
- def distance(self, request): Getting a list of "distance types" :param request: :return:
- def streets(self, request): Getting a list of "street ... | bead0c1d30e5772377649e852f9d2be6b0cc9e26 | <|skeleton|>
class HotelViewSet:
"""API for working with information related to hotels (Hotel)"""
def distance(self, request):
"""Getting a list of "distance types" :param request: :return:"""
<|body_0|>
def streets(self, request):
"""Getting a list of "street types" :param request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HotelViewSet:
"""API for working with information related to hotels (Hotel)"""
def distance(self, request):
"""Getting a list of "distance types" :param request: :return:"""
queryset = DistanceType.objects.all()
serializer = DistanceTypeSerializer(queryset, many=True)
retu... | the_stack_v2_python_sparse | src/apps/hotels/viewsets.py | oleg-developer/booking-system | train | 0 |
6c43cbf831e645b1c2e343063347a7a3acd62cc4 | [
"if nums == []:\n return False\nif len(nums) == 1:\n return True\na = nums.copy()\nb = nums.copy()\nfor i in range(len(nums) - 1):\n if nums[i] > nums[i + 1]:\n a[i] = nums[i + 1]\n b[i + 1] = nums[i]\n break\nreturn nums == sorted(a) or nums == sorted(b)",
"mod = False\nfor i in ran... | <|body_start_0|>
if nums == []:
return False
if len(nums) == 1:
return True
a = nums.copy()
b = nums.copy()
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
a[i] = nums[i + 1]
b[i + 1] = nums[i]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkPossibility(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def checkPossibility2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if nums == []:
retur... | stack_v2_sparse_classes_75kplus_train_003560 | 2,035 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "checkPossibility",
"signature": "def checkPossibility(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "checkPossibility2",
"signature": "def checkPossibility2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002577 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPossibility(self, nums): :type nums: List[int] :rtype: bool
- def checkPossibility2(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPossibility(self, nums): :type nums: List[int] :rtype: bool
- def checkPossibility2(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
de... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class Solution:
def checkPossibility(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def checkPossibility2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def checkPossibility(self, nums):
""":type nums: List[int] :rtype: bool"""
if nums == []:
return False
if len(nums) == 1:
return True
a = nums.copy()
b = nums.copy()
for i in range(len(nums) - 1):
if nums[i] > nums[i... | the_stack_v2_python_sparse | Arrays/665. Non-decreasing Array.py | beninghton/notGivenUpToG | train | 0 | |
6a3375212fc1b0e5dd95a8cb2952c7fbf9891b81 | [
"Base.__init__(self, target, opts)\nself.host = self._get_ipv4addr(self.target['host'])\nreturn",
"url = f'https://api.shodan.io/shodan/host/{self.host}?key='\nurl += f\"{self.opts['shodan_key']}\"\nheaders = {'User-Agent': self.useragent}\nwith timeout(self.opts['timeout']):\n if not self.target['privip']:\n ... | <|body_start_0|>
Base.__init__(self, target, opts)
self.host = self._get_ipv4addr(self.target['host'])
return
<|end_body_0|>
<|body_start_1|>
url = f'https://api.shodan.io/shodan/host/{self.host}?key='
url += f"{self.opts['shodan_key']}"
headers = {'User-Agent': self.use... | Search-Engines module (host) | Search | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Search:
"""Search-Engines module (host)"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def shodan(self):
"""DESCR: Perform shodan host search to gather information. (int) TOOLS: python3"""
<|body_1|>
def domain_urls(self):
"""DESC... | stack_v2_sparse_classes_75kplus_train_003561 | 3,115 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, target, opts)"
},
{
"docstring": "DESCR: Perform shodan host search to gather information. (int) TOOLS: python3",
"name": "shodan",
"signature": "def shodan(self)"
},
{
"docstring": "DESCR: Play google: F... | 3 | null | Implement the Python class `Search` described below.
Class description:
Search-Engines module (host)
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def shodan(self): DESCR: Perform shodan host search to gather information. (int) TOOLS: python3
- def domain_urls(self): DESCR: Play google:... | Implement the Python class `Search` described below.
Class description:
Search-Engines module (host)
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def shodan(self): DESCR: Perform shodan host search to gather information. (int) TOOLS: python3
- def domain_urls(self): DESCR: Play google:... | ddc052c8d7d43a60fc00ea40d85111d5bd7a282e | <|skeleton|>
class Search:
"""Search-Engines module (host)"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def shodan(self):
"""DESCR: Perform shodan host search to gather information. (int) TOOLS: python3"""
<|body_1|>
def domain_urls(self):
"""DESC... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Search:
"""Search-Engines module (host)"""
def __init__(self, target, opts):
"""init"""
Base.__init__(self, target, opts)
self.host = self._get_ipv4addr(self.target['host'])
return
def shodan(self):
"""DESCR: Perform shodan host search to gather information. (... | the_stack_v2_python_sparse | src/modules/host/search.py | noptrix/nullscan | train | 52 |
b44ccdcceb1696548fb38c2b22c31d8728641474 | [
"main_root = os.environ['MAIN_ROOT']\ndict_path = os.path.join(main_root, 'tools/cppjieba/dict/jieba.dict.utf8')\nhmm_path = os.path.join(main_root, 'tools/cppjieba/dict/hmm_model.utf8')\nuser_dict_path = os.path.join(main_root, 'tools/cppjieba/dict/user.dict.utf8')\nidf_path = os.path.join(main_root, 'tools/cppjie... | <|body_start_0|>
main_root = os.environ['MAIN_ROOT']
dict_path = os.path.join(main_root, 'tools/cppjieba/dict/jieba.dict.utf8')
hmm_path = os.path.join(main_root, 'tools/cppjieba/dict/hmm_model.utf8')
user_dict_path = os.path.join(main_root, 'tools/cppjieba/dict/user.dict.utf8')
... | jieba op test | JiebaOpsTest | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiebaOpsTest:
"""jieba op test"""
def build_op_use_file(self, sentence):
"""build graph"""
<|body_0|>
def build_op_no_file(self, sentence):
"""build graph"""
<|body_1|>
def test_jieba_cut_op_use_file(self):
"""test jieba"""
<|body_2|>... | stack_v2_sparse_classes_75kplus_train_003562 | 5,875 | permissive | [
{
"docstring": "build graph",
"name": "build_op_use_file",
"signature": "def build_op_use_file(self, sentence)"
},
{
"docstring": "build graph",
"name": "build_op_no_file",
"signature": "def build_op_no_file(self, sentence)"
},
{
"docstring": "test jieba",
"name": "test_jieba... | 4 | stack_v2_sparse_classes_30k_train_016405 | Implement the Python class `JiebaOpsTest` described below.
Class description:
jieba op test
Method signatures and docstrings:
- def build_op_use_file(self, sentence): build graph
- def build_op_no_file(self, sentence): build graph
- def test_jieba_cut_op_use_file(self): test jieba
- def test_jieba_cut_op_no_file(self... | Implement the Python class `JiebaOpsTest` described below.
Class description:
jieba op test
Method signatures and docstrings:
- def build_op_use_file(self, sentence): build graph
- def build_op_no_file(self, sentence): build graph
- def test_jieba_cut_op_use_file(self): test jieba
- def test_jieba_cut_op_no_file(self... | 7eb4e3be578a680737616efff6858d280595ff48 | <|skeleton|>
class JiebaOpsTest:
"""jieba op test"""
def build_op_use_file(self, sentence):
"""build graph"""
<|body_0|>
def build_op_no_file(self, sentence):
"""build graph"""
<|body_1|>
def test_jieba_cut_op_use_file(self):
"""test jieba"""
<|body_2|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JiebaOpsTest:
"""jieba op test"""
def build_op_use_file(self, sentence):
"""build graph"""
main_root = os.environ['MAIN_ROOT']
dict_path = os.path.join(main_root, 'tools/cppjieba/dict/jieba.dict.utf8')
hmm_path = os.path.join(main_root, 'tools/cppjieba/dict/hmm_model.utf8'... | the_stack_v2_python_sparse | delta/layers/ops/kernels/jieba_op_test.py | luffywalf/delta | train | 1 |
4a0a6e4afd046e67ea1a2ba83307e87b47e3043d | [
"all_gas = sum(gas)\nall_cost = sum(cost)\nif all_cost > all_gas:\n return -1\nnums = len(gas)\nfor i in range(nums):\n flag = True\n have_gas = gas[i]\n j = i + 1\n while j % nums != i:\n loss_cost = cost[(j - 1) % nums]\n if have_gas >= loss_cost:\n have_gas = have_gas - lo... | <|body_start_0|>
all_gas = sum(gas)
all_cost = sum(cost)
if all_cost > all_gas:
return -1
nums = len(gas)
for i in range(nums):
flag = True
have_gas = gas[i]
j = i + 1
while j % nums != i:
loss_cost = cos... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""思路:暴力。暴力指两层遍历加油站。第一层遍历起点,第二层遍历能达到的最远距离 :param gas: :param cost: :return:"""
<|body_0|>
def can_CompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""思路:好吧,我承认。使用贪心算法,可以达到O(... | stack_v2_sparse_classes_75kplus_train_003563 | 4,696 | no_license | [
{
"docstring": "思路:暴力。暴力指两层遍历加油站。第一层遍历起点,第二层遍历能达到的最远距离 :param gas: :param cost: :return:",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int"
},
{
"docstring": "思路:好吧,我承认。使用贪心算法,可以达到O(n)的时间复杂度,而在看解析之前,我未想清楚。 现在看到有O(n)的解法,让我重新来思考。 如果从... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 思路:暴力。暴力指两层遍历加油站。第一层遍历起点,第二层遍历能达到的最远距离 :param gas: :param cost: :return:
- def can_CompleteCircuit(self, gas... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 思路:暴力。暴力指两层遍历加油站。第一层遍历起点,第二层遍历能达到的最远距离 :param gas: :param cost: :return:
- def can_CompleteCircuit(self, gas... | 46cfe84921a9a3e865edd1f94e7807b320b53778 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""思路:暴力。暴力指两层遍历加油站。第一层遍历起点,第二层遍历能达到的最远距离 :param gas: :param cost: :return:"""
<|body_0|>
def can_CompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""思路:好吧,我承认。使用贪心算法,可以达到O(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
"""思路:暴力。暴力指两层遍历加油站。第一层遍历起点,第二层遍历能达到的最远距离 :param gas: :param cost: :return:"""
all_gas = sum(gas)
all_cost = sum(cost)
if all_cost > all_gas:
return -1
nums = len(gas)
fo... | the_stack_v2_python_sparse | 2020-09/Q134-can-complete-circuit.py | EAGLE50/LearnLeetCode | train | 0 | |
43ad4d1e8c2b29aa8fc1db4f7f1add73fcbd0b9e | [
"catalog = RestaurantCatalog()\ntry:\n res = requests.get(self.ENDPOINT, timeout=4)\n if res.status_code == 200:\n catalog.add_many([Restaurant.from_json(row) for row in res.json()])\nexcept ConnectionError:\n print('Failed to connect to API')\nreturn catalog",
"if len(data) == 0:\n return\nput... | <|body_start_0|>
catalog = RestaurantCatalog()
try:
res = requests.get(self.ENDPOINT, timeout=4)
if res.status_code == 200:
catalog.add_many([Restaurant.from_json(row) for row in res.json()])
except ConnectionError:
print('Failed to connect to ... | DatabaseOutputter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseOutputter:
def get(self) -> RestaurantCatalog:
"""Retrieve all current restaurants from the API"""
<|body_0|>
def insert(self, data: Union[dict, list], token: str) -> None:
"""Send restaurants marked as insert to API :param data: a list of restaurants or a si... | stack_v2_sparse_classes_75kplus_train_003564 | 7,558 | no_license | [
{
"docstring": "Retrieve all current restaurants from the API",
"name": "get",
"signature": "def get(self) -> RestaurantCatalog"
},
{
"docstring": "Send restaurants marked as insert to API :param data: a list of restaurants or a single restaurant :param token: an identifier for the current sessi... | 4 | stack_v2_sparse_classes_30k_train_026045 | Implement the Python class `DatabaseOutputter` described below.
Class description:
Implement the DatabaseOutputter class.
Method signatures and docstrings:
- def get(self) -> RestaurantCatalog: Retrieve all current restaurants from the API
- def insert(self, data: Union[dict, list], token: str) -> None: Send restaura... | Implement the Python class `DatabaseOutputter` described below.
Class description:
Implement the DatabaseOutputter class.
Method signatures and docstrings:
- def get(self) -> RestaurantCatalog: Retrieve all current restaurants from the API
- def insert(self, data: Union[dict, list], token: str) -> None: Send restaura... | b9d4dd32b4d0dfaa287fd138887a616d962227b7 | <|skeleton|>
class DatabaseOutputter:
def get(self) -> RestaurantCatalog:
"""Retrieve all current restaurants from the API"""
<|body_0|>
def insert(self, data: Union[dict, list], token: str) -> None:
"""Send restaurants marked as insert to API :param data: a list of restaurants or a si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseOutputter:
def get(self) -> RestaurantCatalog:
"""Retrieve all current restaurants from the API"""
catalog = RestaurantCatalog()
try:
res = requests.get(self.ENDPOINT, timeout=4)
if res.status_code == 200:
catalog.add_many([Restaurant.fro... | the_stack_v2_python_sparse | filter_xml/data_outputter.py | sw814f21/filter_xml | train | 0 | |
029085c0f2b9bb174b64cda4869d46b29a2dfe2c | [
"try:\n from config_parser import config_parser\n self.conf_file = current_file_path + '/../../conf/appviewx.conf'\n self.conf_data = config_parser(self.conf_file)\n self.hostname = socket.gethostbyname(socket.gethostname())\n self.path = self.conf_data['ENVIRONMENT']['path'][self.conf_data['ENVIRONM... | <|body_start_0|>
try:
from config_parser import config_parser
self.conf_file = current_file_path + '/../../conf/appviewx.conf'
self.conf_data = config_parser(self.conf_file)
self.hostname = socket.gethostbyname(socket.gethostname())
self.path = self.co... | Class to Initialize Java Security. | JavaSecurity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JavaSecurity:
"""Class to Initialize Java Security."""
def __init__(self):
"""The init function."""
<|body_0|>
def change_data(source, destination):
"""Funtion to edit contents of file."""
<|body_1|>
def initialize(self):
"""Function to start... | stack_v2_sparse_classes_75kplus_train_003565 | 3,199 | no_license | [
{
"docstring": "The init function.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Funtion to edit contents of file.",
"name": "change_data",
"signature": "def change_data(source, destination)"
},
{
"docstring": "Function to start java security.",
"... | 3 | stack_v2_sparse_classes_30k_train_023017 | Implement the Python class `JavaSecurity` described below.
Class description:
Class to Initialize Java Security.
Method signatures and docstrings:
- def __init__(self): The init function.
- def change_data(source, destination): Funtion to edit contents of file.
- def initialize(self): Function to start java security. | Implement the Python class `JavaSecurity` described below.
Class description:
Class to Initialize Java Security.
Method signatures and docstrings:
- def __init__(self): The init function.
- def change_data(source, destination): Funtion to edit contents of file.
- def initialize(self): Function to start java security.... | e513224364dce05ea4d17ac25ecfa981238b1311 | <|skeleton|>
class JavaSecurity:
"""Class to Initialize Java Security."""
def __init__(self):
"""The init function."""
<|body_0|>
def change_data(source, destination):
"""Funtion to edit contents of file."""
<|body_1|>
def initialize(self):
"""Function to start... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JavaSecurity:
"""Class to Initialize Java Security."""
def __init__(self):
"""The init function."""
try:
from config_parser import config_parser
self.conf_file = current_file_path + '/../../conf/appviewx.conf'
self.conf_data = config_parser(self.conf_fi... | the_stack_v2_python_sparse | scripts_avx/scripts/scripts/Commons/java_security_python.py | Poonammahunta/Integration | train | 0 |
4192128b4160ba920d92460f4a422acc2555897b | [
"def distance(c1, c2):\n if c1 == 27 or c2 == 27:\n return 0\n distance = abs(c1 // 6 - c2 // 6) + abs(c1 % 6 - c2 % 6)\n return distance\n\ndef dp(i, n, l, r, memo):\n if i == n:\n return 0\n if memo[i][l][r] != -1:\n return memo[i][l][r]\n c = ord(word[i]) - ord('A')\n co... | <|body_start_0|>
def distance(c1, c2):
if c1 == 27 or c2 == 27:
return 0
distance = abs(c1 // 6 - c2 // 6) + abs(c1 % 6 - c2 % 6)
return distance
def dp(i, n, l, r, memo):
if i == n:
return 0
if memo[i][l][r] !=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumDistance(self, word: str) -> int:
"""LC 1320 dp[i][l][r] stands min cost to type word[i: n] given l/r fingers position TC: O(N*26^2) Args: word (str): [description] Returns: int: [description]"""
<|body_0|>
def minimumDistance(self, word: str) -> int:
... | stack_v2_sparse_classes_75kplus_train_003566 | 2,174 | no_license | [
{
"docstring": "LC 1320 dp[i][l][r] stands min cost to type word[i: n] given l/r fingers position TC: O(N*26^2) Args: word (str): [description] Returns: int: [description]",
"name": "minimumDistance",
"signature": "def minimumDistance(self, word: str) -> int"
},
{
"docstring": "Reduce the space ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDistance(self, word: str) -> int: LC 1320 dp[i][l][r] stands min cost to type word[i: n] given l/r fingers position TC: O(N*26^2) Args: word (str): [description] Retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDistance(self, word: str) -> int: LC 1320 dp[i][l][r] stands min cost to type word[i: n] given l/r fingers position TC: O(N*26^2) Args: word (str): [description] Retur... | 89b6c180bb772978b6646131f9734b122e745f9c | <|skeleton|>
class Solution:
def minimumDistance(self, word: str) -> int:
"""LC 1320 dp[i][l][r] stands min cost to type word[i: n] given l/r fingers position TC: O(N*26^2) Args: word (str): [description] Returns: int: [description]"""
<|body_0|>
def minimumDistance(self, word: str) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minimumDistance(self, word: str) -> int:
"""LC 1320 dp[i][l][r] stands min cost to type word[i: n] given l/r fingers position TC: O(N*26^2) Args: word (str): [description] Returns: int: [description]"""
def distance(c1, c2):
if c1 == 27 or c2 == 27:
re... | the_stack_v2_python_sparse | dp/python/minimum-distance-to-type-a-word-using-two-fingers.py | dyf102/LC-daily | train | 2 | |
989a0dc6b75caecf20832cd857a1ac9ccf136893 | [
"self.log_data = {}\nself.log_dir = logdir\nself.writer = tf.summary.FileWriter(logdir)\nself.summary_file_name = 'summary.csv'",
"file_name = os.path.join(self.log_dir, self.summary_file_name)\nsummary_file = open(os.path.join(self.log_dir, self.summary_file_name), 'w')\nlogger.info(f'writing summary file: {file... | <|body_start_0|>
self.log_data = {}
self.log_dir = logdir
self.writer = tf.summary.FileWriter(logdir)
self.summary_file_name = 'summary.csv'
<|end_body_0|>
<|body_start_1|>
file_name = os.path.join(self.log_dir, self.summary_file_name)
summary_file = open(os.path.join(se... | Logger object for tensorboard with the option to produce a summary csv file | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
"""Logger object for tensorboard with the option to produce a summary csv file"""
def __init__(self, logdir: str=None, summary_file: str='summary.csv'):
"""Create a summary writer logging to log_dir."""
<|body_0|>
def flush(self) -> None:
"""Write all int... | stack_v2_sparse_classes_75kplus_train_003567 | 1,738 | permissive | [
{
"docstring": "Create a summary writer logging to log_dir.",
"name": "__init__",
"signature": "def __init__(self, logdir: str=None, summary_file: str='summary.csv')"
},
{
"docstring": "Write all intermediate out in csv form",
"name": "flush",
"signature": "def flush(self) -> None"
},
... | 3 | stack_v2_sparse_classes_30k_train_013435 | Implement the Python class `Logger` described below.
Class description:
Logger object for tensorboard with the option to produce a summary csv file
Method signatures and docstrings:
- def __init__(self, logdir: str=None, summary_file: str='summary.csv'): Create a summary writer logging to log_dir.
- def flush(self) -... | Implement the Python class `Logger` described below.
Class description:
Logger object for tensorboard with the option to produce a summary csv file
Method signatures and docstrings:
- def __init__(self, logdir: str=None, summary_file: str='summary.csv'): Create a summary writer logging to log_dir.
- def flush(self) -... | 5ec8b2105c841b78c33c78815381f45e1196e159 | <|skeleton|>
class Logger:
"""Logger object for tensorboard with the option to produce a summary csv file"""
def __init__(self, logdir: str=None, summary_file: str='summary.csv'):
"""Create a summary writer logging to log_dir."""
<|body_0|>
def flush(self) -> None:
"""Write all int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
"""Logger object for tensorboard with the option to produce a summary csv file"""
def __init__(self, logdir: str=None, summary_file: str='summary.csv'):
"""Create a summary writer logging to log_dir."""
self.log_data = {}
self.log_dir = logdir
self.writer = tf.summ... | the_stack_v2_python_sparse | dpd/utils/logger.py | AkshatSh/DPD | train | 0 |
8c4e1fa06aa6259080cc410a34aae4f94b860a32 | [
"self.inputs: InputManager = inputs\nself.features_df: pd.DataFrame | None = None\nif feature_type not in ['all', 'training']:\n raise ValueError(f\"feature_type {feature_type} not allowable. Must be either 'all' or 'training'\")\nself.feature_type = feature_type\nself.input_dict = {'all': {'ferc1_df': self.inpu... | <|body_start_0|>
self.inputs: InputManager = inputs
self.features_df: pd.DataFrame | None = None
if feature_type not in ['all', 'training']:
raise ValueError(f"feature_type {feature_type} not allowable. Must be either 'all' or 'training'")
self.feature_type = feature_type
... | Generate feature vectors for connecting FERC and EIA. | Features | [
"CC-BY-4.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Features:
"""Generate feature vectors for connecting FERC and EIA."""
def __init__(self, feature_type: Literal['training', 'all'], inputs: InputManager):
"""Initialize feature generator. Args: feature_type: Type of features to compile. Either 'training' or 'all'. inputs: Instance of ... | stack_v2_sparse_classes_75kplus_train_003568 | 42,623 | permissive | [
{
"docstring": "Initialize feature generator. Args: feature_type: Type of features to compile. Either 'training' or 'all'. inputs: Instance of :class:`InputManager`.",
"name": "__init__",
"signature": "def __init__(self, feature_type: Literal['training', 'all'], inputs: InputManager)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_008393 | Implement the Python class `Features` described below.
Class description:
Generate feature vectors for connecting FERC and EIA.
Method signatures and docstrings:
- def __init__(self, feature_type: Literal['training', 'all'], inputs: InputManager): Initialize feature generator. Args: feature_type: Type of features to ... | Implement the Python class `Features` described below.
Class description:
Generate feature vectors for connecting FERC and EIA.
Method signatures and docstrings:
- def __init__(self, feature_type: Literal['training', 'all'], inputs: InputManager): Initialize feature generator. Args: feature_type: Type of features to ... | 6afae8aade053408f23ac4332d5cbb438ab72dc6 | <|skeleton|>
class Features:
"""Generate feature vectors for connecting FERC and EIA."""
def __init__(self, feature_type: Literal['training', 'all'], inputs: InputManager):
"""Initialize feature generator. Args: feature_type: Type of features to compile. Either 'training' or 'all'. inputs: Instance of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Features:
"""Generate feature vectors for connecting FERC and EIA."""
def __init__(self, feature_type: Literal['training', 'all'], inputs: InputManager):
"""Initialize feature generator. Args: feature_type: Type of features to compile. Either 'training' or 'all'. inputs: Instance of :class:`Input... | the_stack_v2_python_sparse | src/pudl/analysis/ferc1_eia.py | catalyst-cooperative/pudl | train | 382 |
3e8201cad357ce1b1cb72cc9c60be3fef88fa4f2 | [
"if self.config is not None:\n cfg = self.config\n for key in LARGE_ARTEFACTS:\n if key in cfg and hasattr(self._nested_detector, key):\n cfg[key] = getattr(self._nested_detector, key)\n preprocess_at_init = getattr(self._nested_detector, 'preprocess_at_init', True)\n cfg['x_ref_prepro... | <|body_start_0|>
if self.config is not None:
cfg = self.config
for key in LARGE_ARTEFACTS:
if key in cfg and hasattr(self._nested_detector, key):
cfg[key] = getattr(self._nested_detector, key)
preprocess_at_init = getattr(self._nested_detec... | A mixin class containing methods related to a drift detector's configuration dictionary. | DriftConfigMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriftConfigMixin:
"""A mixin class containing methods related to a drift detector's configuration dictionary."""
def get_config(self) -> dict:
"""Get the detector's configuration dictionary. Returns ------- The detector's configuration dictionary."""
<|body_0|>
def from_... | stack_v2_sparse_classes_75kplus_train_003569 | 8,321 | permissive | [
{
"docstring": "Get the detector's configuration dictionary. Returns ------- The detector's configuration dictionary.",
"name": "get_config",
"signature": "def get_config(self) -> dict"
},
{
"docstring": "Instantiate a drift detector from a fully resolved (and validated) config dictionary. Param... | 4 | stack_v2_sparse_classes_30k_train_015231 | Implement the Python class `DriftConfigMixin` described below.
Class description:
A mixin class containing methods related to a drift detector's configuration dictionary.
Method signatures and docstrings:
- def get_config(self) -> dict: Get the detector's configuration dictionary. Returns ------- The detector's confi... | Implement the Python class `DriftConfigMixin` described below.
Class description:
A mixin class containing methods related to a drift detector's configuration dictionary.
Method signatures and docstrings:
- def get_config(self) -> dict: Get the detector's configuration dictionary. Returns ------- The detector's confi... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class DriftConfigMixin:
"""A mixin class containing methods related to a drift detector's configuration dictionary."""
def get_config(self) -> dict:
"""Get the detector's configuration dictionary. Returns ------- The detector's configuration dictionary."""
<|body_0|>
def from_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DriftConfigMixin:
"""A mixin class containing methods related to a drift detector's configuration dictionary."""
def get_config(self) -> dict:
"""Get the detector's configuration dictionary. Returns ------- The detector's configuration dictionary."""
if self.config is not None:
... | the_stack_v2_python_sparse | alibi_detect/base.py | SeldonIO/alibi-detect | train | 1,922 |
74e5c00dc399a0e241c416a4322a12f8a3d93523 | [
"ny = Basket.create_from_string('New York')\nnyc = Basket.create_from_string('New York City')\nself.assertEqual(Basket.objects.count(), 2)\nmerged = merge_baskets(ny, nyc)\nself.assertEqual(Basket.objects.count(), 1)\nself.assertEqual(merged.topic_hits.count(), 2)",
"ny = Basket.create_from_string('New York')\nny... | <|body_start_0|>
ny = Basket.create_from_string('New York')
nyc = Basket.create_from_string('New York City')
self.assertEqual(Basket.objects.count(), 2)
merged = merge_baskets(ny, nyc)
self.assertEqual(Basket.objects.count(), 1)
self.assertEqual(merged.topic_hits.count(),... | MergeTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeTests:
def test_basic_merge(self):
"""Creates two separate baskets. Merging should create only one basket"""
<|body_0|>
def test_merge_with_baskets_related_to_each_other(self):
"""If you merge two baskets related to each other, the relation between them should b... | stack_v2_sparse_classes_75kplus_train_003570 | 11,225 | permissive | [
{
"docstring": "Creates two separate baskets. Merging should create only one basket",
"name": "test_basic_merge",
"signature": "def test_basic_merge(self)"
},
{
"docstring": "If you merge two baskets related to each other, the relation between them should be deleted",
"name": "test_merge_wit... | 6 | stack_v2_sparse_classes_30k_test_000417 | Implement the Python class `MergeTests` described below.
Class description:
Implement the MergeTests class.
Method signatures and docstrings:
- def test_basic_merge(self): Creates two separate baskets. Merging should create only one basket
- def test_merge_with_baskets_related_to_each_other(self): If you merge two ba... | Implement the Python class `MergeTests` described below.
Class description:
Implement the MergeTests class.
Method signatures and docstrings:
- def test_basic_merge(self): Creates two separate baskets. Merging should create only one basket
- def test_merge_with_baskets_related_to_each_other(self): If you merge two ba... | 07455a660fb2cb8bc91a54f7f12d150923678157 | <|skeleton|>
class MergeTests:
def test_basic_merge(self):
"""Creates two separate baskets. Merging should create only one basket"""
<|body_0|>
def test_merge_with_baskets_related_to_each_other(self):
"""If you merge two baskets related to each other, the relation between them should b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MergeTests:
def test_basic_merge(self):
"""Creates two separate baskets. Merging should create only one basket"""
ny = Basket.create_from_string('New York')
nyc = Basket.create_from_string('New York City')
self.assertEqual(Basket.objects.count(), 2)
merged = merge_baske... | the_stack_v2_python_sparse | otcore/hit/tests.py | NYULibraries/dlts-enm-tct-backend | train | 0 | |
08635877872385efbd79cba81e702e25886cf1cc | [
"if resampler == None:\n self._resampler = ResamplerLayer(interpolation='LINEAR', boundary='REPLICATE')\n self._interpolation = 'LINEAR'\nelse:\n self._resampler = resampler\n self._interpolation = self._resampler.interpolation\nself._field_transform = field_transform\nsuper(ResampledFieldGridWarperLaye... | <|body_start_0|>
if resampler == None:
self._resampler = ResamplerLayer(interpolation='LINEAR', boundary='REPLICATE')
self._interpolation = 'LINEAR'
else:
self._resampler = resampler
self._interpolation = self._resampler.interpolation
self._field_t... | The resampled field grid warper defines a grid based on sampling coordinate values from a spatially varying displacement field (passed as a tensor input) along an affine grid pattern in the field. This enables grids representing small patches of a larger transform, as well as the composition of multiple transforms befo... | ResampledFieldGridWarperLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResampledFieldGridWarperLayer:
"""The resampled field grid warper defines a grid based on sampling coordinate values from a spatially varying displacement field (passed as a tensor input) along an affine grid pattern in the field. This enables grids representing small patches of a larger transfor... | stack_v2_sparse_classes_75kplus_train_003571 | 11,338 | permissive | [
{
"docstring": "Constructs an ResampledFieldingGridWarperLayer. Args: source_shape: Iterable of integers determining the size of the source signal domain. output_shape: Iterable of integers determining the size of the destination resampled signal domain. coeff_shape: Shape of displacement field. interpolation: ... | 3 | stack_v2_sparse_classes_30k_test_000374 | Implement the Python class `ResampledFieldGridWarperLayer` described below.
Class description:
The resampled field grid warper defines a grid based on sampling coordinate values from a spatially varying displacement field (passed as a tensor input) along an affine grid pattern in the field. This enables grids represen... | Implement the Python class `ResampledFieldGridWarperLayer` described below.
Class description:
The resampled field grid warper defines a grid based on sampling coordinate values from a spatially varying displacement field (passed as a tensor input) along an affine grid pattern in the field. This enables grids represen... | 84dd0f85c9a1ab8a72f4c55fcf073379acf5ae1b | <|skeleton|>
class ResampledFieldGridWarperLayer:
"""The resampled field grid warper defines a grid based on sampling coordinate values from a spatially varying displacement field (passed as a tensor input) along an affine grid pattern in the field. This enables grids representing small patches of a larger transfor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResampledFieldGridWarperLayer:
"""The resampled field grid warper defines a grid based on sampling coordinate values from a spatially varying displacement field (passed as a tensor input) along an affine grid pattern in the field. This enables grids representing small patches of a larger transform, as well as... | the_stack_v2_python_sparse | niftynet/layer/spatial_transformer.py | 12SigmaTechnologies/NiftyNet-1 | train | 2 |
5305d11951ac31954534b73d0d6c756a85fcb1a3 | [
"self.crushStressTable = crushStressTable\nself.temperatureDependency = temperatureDependency\nself.dependencies = dependencies",
"self.crushStressTable = crushStressTable\nself.temperatureDependency = temperatureDependency\nself.dependencies = dependencies"
] | <|body_start_0|>
self.crushStressTable = crushStressTable
self.temperatureDependency = temperatureDependency
self.dependencies = dependencies
<|end_body_0|>
<|body_start_1|>
self.crushStressTable = crushStressTable
self.temperatureDependency = temperatureDependency
self.... | The CrushStress object specifies the crush stress of a material. Attributes ---------- crushStressTable: tuple[tuple[float, ...]] A sequence of sequences of Floats specifying the items described below. temperatureDependency: Boolean A Boolean specifying whether the data depend on temperature. The default value is OFF. ... | CrushStress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrushStress:
"""The CrushStress object specifies the crush stress of a material. Attributes ---------- crushStressTable: tuple[tuple[float, ...]] A sequence of sequences of Floats specifying the items described below. temperatureDependency: Boolean A Boolean specifying whether the data depend on ... | stack_v2_sparse_classes_75kplus_train_003572 | 3,817 | permissive | [
{
"docstring": "This method creates a CrushStress object. Notes ----- This function can be accessed by: .. code-block:: python mdb.models[name].materials[name].CrushStress session.odbs[name].materials[name].CrushStress Parameters ---------- crushStressTable A sequence of sequences of Floats specifying the items... | 2 | stack_v2_sparse_classes_30k_train_051920 | Implement the Python class `CrushStress` described below.
Class description:
The CrushStress object specifies the crush stress of a material. Attributes ---------- crushStressTable: tuple[tuple[float, ...]] A sequence of sequences of Floats specifying the items described below. temperatureDependency: Boolean A Boolean... | Implement the Python class `CrushStress` described below.
Class description:
The CrushStress object specifies the crush stress of a material. Attributes ---------- crushStressTable: tuple[tuple[float, ...]] A sequence of sequences of Floats specifying the items described below. temperatureDependency: Boolean A Boolean... | ac102b854857961d957f35f5a0ac5f305193c5c8 | <|skeleton|>
class CrushStress:
"""The CrushStress object specifies the crush stress of a material. Attributes ---------- crushStressTable: tuple[tuple[float, ...]] A sequence of sequences of Floats specifying the items described below. temperatureDependency: Boolean A Boolean specifying whether the data depend on ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrushStress:
"""The CrushStress object specifies the crush stress of a material. Attributes ---------- crushStressTable: tuple[tuple[float, ...]] A sequence of sequences of Floats specifying the items described below. temperatureDependency: Boolean A Boolean specifying whether the data depend on temperature. ... | the_stack_v2_python_sparse | src/abaqus/Material/Plastic/CrushStress/CrushStress.py | haiiliin/pyabaqus | train | 34 |
8cda23dd5618502792feb639b94515308ee66749 | [
"self.matomo_url = matomo_url\nself.matomo_api_key = matomo_api_key\nself.matomo_api_key = '&token_auth=' + self.matomo_api_key\nself.ssl_verify = ssl_verify\nself.cleanmatomo_url()",
"self.matomo_url = re.sub('/\\\\/$/', '', self.matomo_url)\nif re.match('^http://', self.matomo_url):\n self.matomo_url = re.su... | <|body_start_0|>
self.matomo_url = matomo_url
self.matomo_api_key = matomo_api_key
self.matomo_api_key = '&token_auth=' + self.matomo_api_key
self.ssl_verify = ssl_verify
self.cleanmatomo_url()
<|end_body_0|>
<|body_start_1|>
self.matomo_url = re.sub('/\\/$/', '', self.m... | This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore. | MatomoApiManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl... | stack_v2_sparse_classes_75kplus_train_003573 | 4,420 | permissive | [
{
"docstring": "Constructor initialises matomo_url, matomo_api_key, ssl_verify :param matomo_url: :param matomo_api_key: :param ssl_verify:",
"name": "__init__",
"signature": "def __init__(self, matomo_url, matomo_api_key, ssl_verify)"
},
{
"docstring": "Cleans Matomo-URL for proper requests. Ch... | 4 | stack_v2_sparse_classes_30k_train_025627 | Implement the Python class `MatomoApiManager` described below.
Class description:
This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore.
Method signatures ... | Implement the Python class `MatomoApiManager` described below.
Class description:
This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore.
Method signatures ... | b769510570d5921e30876565263813c0362994e2 | <|skeleton|>
class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatomoApiManager:
"""This class helps to interact with Matomo API There are several functions to retrieve unique visitors for last 30 days, a month, and a year. You are also able to add new regions to your matomo instance and furthermore."""
def __init__(self, matomo_url, matomo_api_key, ssl_verify):
... | the_stack_v2_python_sparse | src/cms/views/statistics/matomo_api_manager.py | digitalfabrik/coldaid-backend | train | 4 |
c05fe822e5fa5d462086dcca868ff740348f571c | [
"self.key: Optional[str] = None\nself.threshold: Optional[float] = None\nself.relation: Optional[str] = None\nkwargs.setdefault('relation', 'lt')\nkwargs.setdefault('key', 'ft_loss')\nkwargs.setdefault('threshold', 0.0)\nself.__dict__.update(kwargs)\nself.trainer = trainer\nlogging.info(f'Scorer-Configuration: {sel... | <|body_start_0|>
self.key: Optional[str] = None
self.threshold: Optional[float] = None
self.relation: Optional[str] = None
kwargs.setdefault('relation', 'lt')
kwargs.setdefault('key', 'ft_loss')
kwargs.setdefault('threshold', 0.0)
self.__dict__.update(kwargs)
... | Scorer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scorer:
def __init__(self, trainer: Engine, **kwargs):
"""Parameters ---------- trainer : Engine The training-engine"""
<|body_0|>
def __call__(self, engine: Engine):
"""Determines an improvement during training."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_003574 | 4,775 | permissive | [
{
"docstring": "Parameters ---------- trainer : Engine The training-engine",
"name": "__init__",
"signature": "def __init__(self, trainer: Engine, **kwargs)"
},
{
"docstring": "Determines an improvement during training.",
"name": "__call__",
"signature": "def __call__(self, engine: Engin... | 2 | stack_v2_sparse_classes_30k_train_018614 | Implement the Python class `Scorer` described below.
Class description:
Implement the Scorer class.
Method signatures and docstrings:
- def __init__(self, trainer: Engine, **kwargs): Parameters ---------- trainer : Engine The training-engine
- def __call__(self, engine: Engine): Determines an improvement during train... | Implement the Python class `Scorer` described below.
Class description:
Implement the Scorer class.
Method signatures and docstrings:
- def __init__(self, trainer: Engine, **kwargs): Parameters ---------- trainer : Engine The training-engine
- def __call__(self, engine: Engine): Determines an improvement during train... | a511b03a2a2577d4ce372aa44e475df8005eb394 | <|skeleton|>
class Scorer:
def __init__(self, trainer: Engine, **kwargs):
"""Parameters ---------- trainer : Engine The training-engine"""
<|body_0|>
def __call__(self, engine: Engine):
"""Determines an improvement during training."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scorer:
def __init__(self, trainer: Engine, **kwargs):
"""Parameters ---------- trainer : Engine The training-engine"""
self.key: Optional[str] = None
self.threshold: Optional[float] = None
self.relation: Optional[str] = None
kwargs.setdefault('relation', 'lt')
... | the_stack_v2_python_sparse | enel_service/modeling/losses.py | dos-group/enel-experiments | train | 2 | |
53a100b06c0ce30b97d81e7edd468f07e830c24e | [
"self._bound_lo = bound_lo\nself._bound_up = bound_up\nself.data_min = None\nself.data_span = None",
"if isinstance(self._bound_lo, (float, int)) and isinstance(data, np.ndarray):\n bound_lo = self._bound_lo * np.ones_like(data, dtype=np.float64)\nelif isinstance(self._bound_lo, (float, int)) and isinstance(da... | <|body_start_0|>
self._bound_lo = bound_lo
self._bound_up = bound_up
self.data_min = None
self.data_span = None
<|end_body_0|>
<|body_start_1|>
if isinstance(self._bound_lo, (float, int)) and isinstance(data, np.ndarray):
bound_lo = self._bound_lo * np.ones_like(data... | A stateful min-max scaler that remembers the lower and upper bound for later un-unscaling | MinMaxScaler | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinMaxScaler:
"""A stateful min-max scaler that remembers the lower and upper bound for later un-unscaling"""
def __init__(self, bound_lo: Union[int, float, np.ndarray, to.Tensor], bound_up: Union[int, float, np.ndarray, to.Tensor]):
"""Constructor :param bound_lo: lower bound for th... | stack_v2_sparse_classes_75kplus_train_003575 | 18,904 | permissive | [
{
"docstring": "Constructor :param bound_lo: lower bound for the transformed data :param bound_up: upper bound for the transformed data",
"name": "__init__",
"signature": "def __init__(self, bound_lo: Union[int, float, np.ndarray, to.Tensor], bound_up: Union[int, float, np.ndarray, to.Tensor])"
},
{... | 4 | null | Implement the Python class `MinMaxScaler` described below.
Class description:
A stateful min-max scaler that remembers the lower and upper bound for later un-unscaling
Method signatures and docstrings:
- def __init__(self, bound_lo: Union[int, float, np.ndarray, to.Tensor], bound_up: Union[int, float, np.ndarray, to.... | Implement the Python class `MinMaxScaler` described below.
Class description:
A stateful min-max scaler that remembers the lower and upper bound for later un-unscaling
Method signatures and docstrings:
- def __init__(self, bound_lo: Union[int, float, np.ndarray, to.Tensor], bound_up: Union[int, float, np.ndarray, to.... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class MinMaxScaler:
"""A stateful min-max scaler that remembers the lower and upper bound for later un-unscaling"""
def __init__(self, bound_lo: Union[int, float, np.ndarray, to.Tensor], bound_up: Union[int, float, np.ndarray, to.Tensor]):
"""Constructor :param bound_lo: lower bound for th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinMaxScaler:
"""A stateful min-max scaler that remembers the lower and upper bound for later un-unscaling"""
def __init__(self, bound_lo: Union[int, float, np.ndarray, to.Tensor], bound_up: Union[int, float, np.ndarray, to.Tensor]):
"""Constructor :param bound_lo: lower bound for the transformed... | the_stack_v2_python_sparse | Pyrado/pyrado/utils/data_processing.py | 1abner1/SimuRLacra | train | 0 |
65cca0aed5cb191bd4c9e2bf89aad5e78bd93b6d | [
"self.__io: BackupPcCloneStyle = io\n'\\n The output style.\\n '\nself.__host: str = ''\n'\\n The host of the backup.\\n '",
"self.__io.writeln(' Removing files')\nhost_dir_clone = Config.instance.host_dir_clone(self.__host)\nif os.path.isdir(host_dir_clone):\n os.system('rm -fr \"%... | <|body_start_0|>
self.__io: BackupPcCloneStyle = io
'\n The output style.\n '
self.__host: str = ''
'\n The host of the backup.\n '
<|end_body_0|>
<|body_start_1|>
self.__io.writeln(' Removing files')
host_dir_clone = Config.instance.host_dir_... | Deletes a host entirely frm the clone. | HostDelete | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostDelete:
"""Deletes a host entirely frm the clone."""
def __init__(self, io: BackupPcCloneStyle):
"""Object constructor. @param BackupPcCloneStyle io: The output style."""
<|body_0|>
def __delete_files(self) -> None:
"""Removes the host from the clone file sys... | stack_v2_sparse_classes_75kplus_train_003576 | 2,018 | permissive | [
{
"docstring": "Object constructor. @param BackupPcCloneStyle io: The output style.",
"name": "__init__",
"signature": "def __init__(self, io: BackupPcCloneStyle)"
},
{
"docstring": "Removes the host from the clone file system.",
"name": "__delete_files",
"signature": "def __delete_files... | 4 | stack_v2_sparse_classes_30k_train_020415 | Implement the Python class `HostDelete` described below.
Class description:
Deletes a host entirely frm the clone.
Method signatures and docstrings:
- def __init__(self, io: BackupPcCloneStyle): Object constructor. @param BackupPcCloneStyle io: The output style.
- def __delete_files(self) -> None: Removes the host fr... | Implement the Python class `HostDelete` described below.
Class description:
Deletes a host entirely frm the clone.
Method signatures and docstrings:
- def __init__(self, io: BackupPcCloneStyle): Object constructor. @param BackupPcCloneStyle io: The output style.
- def __delete_files(self) -> None: Removes the host fr... | a4009868f6cbec42f247f392965077c55f7265c5 | <|skeleton|>
class HostDelete:
"""Deletes a host entirely frm the clone."""
def __init__(self, io: BackupPcCloneStyle):
"""Object constructor. @param BackupPcCloneStyle io: The output style."""
<|body_0|>
def __delete_files(self) -> None:
"""Removes the host from the clone file sys... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostDelete:
"""Deletes a host entirely frm the clone."""
def __init__(self, io: BackupPcCloneStyle):
"""Object constructor. @param BackupPcCloneStyle io: The output style."""
self.__io: BackupPcCloneStyle = io
'\n The output style.\n '
self.__host: str = ''
... | the_stack_v2_python_sparse | backuppc_clone/helper/HostDelete.py | SetBased/BackupPC-Clone | train | 7 |
10dd2420614be14f6eb7efcc136c9511fcb112ac | [
"Parametre.__init__(self, 'déplacer', 'move')\nself.schema = '<nom_familier> <nom_sortie>'\nself.tronquer = True\nself.aide_courte = 'demande au familier de se déplacer'\nself.aide_longue = \"Cette commande permet d'ordonner à un familier, présent dans la salle, de se déplacer vers l'une des sorties disponibles. Vo... | <|body_start_0|>
Parametre.__init__(self, 'déplacer', 'move')
self.schema = '<nom_familier> <nom_sortie>'
self.tronquer = True
self.aide_courte = 'demande au familier de se déplacer'
self.aide_longue = "Cette commande permet d'ordonner à un familier, présent dans la salle, de se ... | Commande 'familier deplacer'. | PrmDeplacer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmDeplacer:
"""Commande 'familier deplacer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parame... | stack_v2_sparse_classes_75kplus_train_003577 | 3,138 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmDeplacer` described below.
Class description:
Commande 'familier deplacer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmDeplacer` described below.
Class description:
Commande 'familier deplacer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmDeplacer:
"""Commande 'f... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmDeplacer:
"""Commande 'familier deplacer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmDeplacer:
"""Commande 'familier deplacer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'déplacer', 'move')
self.schema = '<nom_familier> <nom_sortie>'
self.tronquer = True
self.aide_courte = 'demande au familier de se déplacer... | the_stack_v2_python_sparse | src/secondaires/familier/commandes/familier/deplacer.py | vincent-lg/tsunami | train | 5 |
62f3ee17d2eaf93ceb22cb0f5ff9e4471cbe2acd | [
"group = None\nitem = entry\nif isinstance(entry, collections.Sequence) and (not isinstance(entry, six.string_types)):\n entry_length = len(entry)\n if all((isinstance(el, list) for el in entry)) and entry_length > 1:\n group, item = entry[0:2]\n return ((group, item),)\n elif all((isinstance... | <|body_start_0|>
group = None
item = entry
if isinstance(entry, collections.Sequence) and (not isinstance(entry, six.string_types)):
entry_length = len(entry)
if all((isinstance(el, list) for el in entry)) and entry_length > 1:
group, item = entry[0:2]
... | View mixin for grouped options. | Select2GroupListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Select2GroupListView:
"""View mixin for grouped options."""
def get_item_as_group(self, entry):
"""Return the item with its group."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return option list with children(s) json response."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_003578 | 10,116 | permissive | [
{
"docstring": "Return the item with its group.",
"name": "get_item_as_group",
"signature": "def get_item_as_group(self, entry)"
},
{
"docstring": "Return option list with children(s) json response.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022536 | Implement the Python class `Select2GroupListView` described below.
Class description:
View mixin for grouped options.
Method signatures and docstrings:
- def get_item_as_group(self, entry): Return the item with its group.
- def get(self, request, *args, **kwargs): Return option list with children(s) json response. | Implement the Python class `Select2GroupListView` described below.
Class description:
View mixin for grouped options.
Method signatures and docstrings:
- def get_item_as_group(self, entry): Return the item with its group.
- def get(self, request, *args, **kwargs): Return option list with children(s) json response.
<... | 0ffcc7c52edbab21153de458dbbb7fbcd706c17e | <|skeleton|>
class Select2GroupListView:
"""View mixin for grouped options."""
def get_item_as_group(self, entry):
"""Return the item with its group."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return option list with children(s) json response."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Select2GroupListView:
"""View mixin for grouped options."""
def get_item_as_group(self, entry):
"""Return the item with its group."""
group = None
item = entry
if isinstance(entry, collections.Sequence) and (not isinstance(entry, six.string_types)):
entry_lengt... | the_stack_v2_python_sparse | src/dal_select2/views.py | HelloWatt/django-autocomplete-light | train | 0 |
12f60eeb4605a202b9daa2bbe3dcda18e554a9ad | [
"next = self.partial_match_table(p)\ni, j = (0, 0)\ntL = len(t)\npL = len(p)\nwhile i < tL and j < pL:\n if j == -1 or t[i] == p[j]:\n i += 1\n j += 1\n else:\n j = next[j]\nif j == pL:\n return i - j\nelse:\n return -1",
"m = len(pattern)\nnext = [-1] * m\nk = -1\nj = 0\nwhile j ... | <|body_start_0|>
next = self.partial_match_table(p)
i, j = (0, 0)
tL = len(t)
pL = len(p)
while i < tL and j < pL:
if j == -1 or t[i] == p[j]:
i += 1
j += 1
else:
j = next[j]
if j == pL:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def strStr(self, t, p):
""":type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def partial_match_table(self, pattern):
"""Compute the "next" table corresponding to pattern, for use in the Knuth-Morris-Pratt string search algorithm."""
<|... | stack_v2_sparse_classes_75kplus_train_003579 | 1,257 | no_license | [
{
"docstring": ":type haystack: str :type needle: str :rtype: int",
"name": "strStr",
"signature": "def strStr(self, t, p)"
},
{
"docstring": "Compute the \"next\" table corresponding to pattern, for use in the Knuth-Morris-Pratt string search algorithm.",
"name": "partial_match_table",
... | 2 | stack_v2_sparse_classes_30k_train_043971 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, t, p): :type haystack: str :type needle: str :rtype: int
- def partial_match_table(self, pattern): Compute the "next" table corresponding to pattern, for use in ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, t, p): :type haystack: str :type needle: str :rtype: int
- def partial_match_table(self, pattern): Compute the "next" table corresponding to pattern, for use in ... | 4aa3a3a0da8b911e140446352debb9b567b6d78b | <|skeleton|>
class Solution:
def strStr(self, t, p):
""":type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def partial_match_table(self, pattern):
"""Compute the "next" table corresponding to pattern, for use in the Knuth-Morris-Pratt string search algorithm."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def strStr(self, t, p):
""":type haystack: str :type needle: str :rtype: int"""
next = self.partial_match_table(p)
i, j = (0, 0)
tL = len(t)
pL = len(p)
while i < tL and j < pL:
if j == -1 or t[i] == p[j]:
i += 1
... | the_stack_v2_python_sparse | implement_strStr_28.py | adiggo/leetcode_py | train | 0 | |
c5fdfdf6d8c9b45317d9c74c0943c1ba65913a69 | [
"self.FEATURE_SIZEs = FEATURE_SIZEs\nself.ELEMENT_SIZEs = ELEMENT_SIZEs\nself.N_LAYERS = len(self.FEATURE_SIZEs)\nself.scope = scope",
"W = []\nb = []\nelement_sizes = (FLAGS.N_INVARIANT, k, FLAGS.N_EQUIVARIANT - k)\nfor x in range(self.N_LAYERS - 1):\n layer_name = self.scope\n if trainable:\n layer... | <|body_start_0|>
self.FEATURE_SIZEs = FEATURE_SIZEs
self.ELEMENT_SIZEs = ELEMENT_SIZEs
self.N_LAYERS = len(self.FEATURE_SIZEs)
self.scope = scope
<|end_body_0|>
<|body_start_1|>
W = []
b = []
element_sizes = (FLAGS.N_INVARIANT, k, FLAGS.N_EQUIVARIANT - k)
... | Params | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Params:
def __init__(self, scope, FEATURE_SIZEs, ELEMENT_SIZEs):
"""scope: name of the parameters to be generated. FEATURE_SIZEs = 2-d array (not ndarray) with [[a0,b0,c0], [a1,b1,c1], [a2,b2,c2]] where each entry is a non-negative integer. There are 3 types (a,b,c) of elements for multi... | stack_v2_sparse_classes_75kplus_train_003580 | 3,834 | no_license | [
{
"docstring": "scope: name of the parameters to be generated. FEATURE_SIZEs = 2-d array (not ndarray) with [[a0,b0,c0], [a1,b1,c1], [a2,b2,c2]] where each entry is a non-negative integer. There are 3 types (a,b,c) of elements for multi-type ENN. a0 denotes the number of the features in the layer 0. The created... | 3 | stack_v2_sparse_classes_30k_train_009750 | Implement the Python class `Params` described below.
Class description:
Implement the Params class.
Method signatures and docstrings:
- def __init__(self, scope, FEATURE_SIZEs, ELEMENT_SIZEs): scope: name of the parameters to be generated. FEATURE_SIZEs = 2-d array (not ndarray) with [[a0,b0,c0], [a1,b1,c1], [a2,b2,c... | Implement the Python class `Params` described below.
Class description:
Implement the Params class.
Method signatures and docstrings:
- def __init__(self, scope, FEATURE_SIZEs, ELEMENT_SIZEs): scope: name of the parameters to be generated. FEATURE_SIZEs = 2-d array (not ndarray) with [[a0,b0,c0], [a1,b1,c1], [a2,b2,c... | e645f8bbee6965d3c94cd6e7d2503d2f0a9c5434 | <|skeleton|>
class Params:
def __init__(self, scope, FEATURE_SIZEs, ELEMENT_SIZEs):
"""scope: name of the parameters to be generated. FEATURE_SIZEs = 2-d array (not ndarray) with [[a0,b0,c0], [a1,b1,c1], [a2,b2,c2]] where each entry is a non-negative integer. There are 3 types (a,b,c) of elements for multi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Params:
def __init__(self, scope, FEATURE_SIZEs, ELEMENT_SIZEs):
"""scope: name of the parameters to be generated. FEATURE_SIZEs = 2-d array (not ndarray) with [[a0,b0,c0], [a1,b1,c1], [a2,b2,c2]] where each entry is a non-negative integer. There are 3 types (a,b,c) of elements for multi-type ENN. a0 ... | the_stack_v2_python_sparse | select_mdp_code/agents/q_network/params_vanilla.py | selectmdp/selectmdp | train | 4 | |
a3952716dcd12408461156ad54a15b6a7519bae5 | [
"res = []\n\ndef helper(root):\n if root:\n res.append(str(root.val))\n helper(root.left)\n helper(root.right)\n else:\n res.append('#')\nhelper(root)\nreturn ' '.join(res)",
"data = iter(data.split())\n\ndef helper():\n val = next(data)\n if val == '#':\n return\n ... | <|body_start_0|>
res = []
def helper(root):
if root:
res.append(str(root.val))
helper(root.left)
helper(root.right)
else:
res.append('#')
helper(root)
return ' '.join(res)
<|end_body_0|>
<|body_star... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_003581 | 11,667 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_021477 | 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:... | 817911d4282d2e226518b3533dff28282a91b3d4 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def helper(root):
if root:
res.append(str(root.val))
helper(root.left)
helper(root.right)
else:
... | the_stack_v2_python_sparse | Week02/297. 二叉树的序列化与反序列化.py | hrz123/algorithm010 | train | 1 | |
64c7ba871de892e73dd14a88d737e735e922970b | [
"self.columns = columns\nkernels = [Projection(RBF(), [c]) for c in columns]\nsuper(SimpleFactorKernel, self).__init__(kernels)",
"params = dict(columns=self.columns)\nif deep:\n for i, kernel in enumerate(self.kernels):\n print('--->', '\\ti = ', i, '\\tkernel = ', kernel)\n deep_items = kernel.... | <|body_start_0|>
self.columns = columns
kernels = [Projection(RBF(), [c]) for c in columns]
super(SimpleFactorKernel, self).__init__(kernels)
<|end_body_0|>
<|body_start_1|>
params = dict(columns=self.columns)
if deep:
for i, kernel in enumerate(self.kernels):
... | Alternative implementation of SimpleCategoricalKernel Testing the water with CompoundKernel before attempting Tensor | SimpleFactorKernel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleFactorKernel:
"""Alternative implementation of SimpleCategoricalKernel Testing the water with CompoundKernel before attempting Tensor"""
def __init__(self, columns):
"""Dummy-code the given column, put a RBF kernel on each of the variates, then return the product kernel If all ... | stack_v2_sparse_classes_75kplus_train_003582 | 37,505 | no_license | [
{
"docstring": "Dummy-code the given column, put a RBF kernel on each of the variates, then return the product kernel If all length scales are small, assume little shared information between categories kernel will typically be RBF with a single length parameter (passing in an alternative kernel not currently im... | 2 | null | Implement the Python class `SimpleFactorKernel` described below.
Class description:
Alternative implementation of SimpleCategoricalKernel Testing the water with CompoundKernel before attempting Tensor
Method signatures and docstrings:
- def __init__(self, columns): Dummy-code the given column, put a RBF kernel on eac... | Implement the Python class `SimpleFactorKernel` described below.
Class description:
Alternative implementation of SimpleCategoricalKernel Testing the water with CompoundKernel before attempting Tensor
Method signatures and docstrings:
- def __init__(self, columns): Dummy-code the given column, put a RBF kernel on eac... | eb9ad22297119c76a345c2cfb9a0519e27ec7eaa | <|skeleton|>
class SimpleFactorKernel:
"""Alternative implementation of SimpleCategoricalKernel Testing the water with CompoundKernel before attempting Tensor"""
def __init__(self, columns):
"""Dummy-code the given column, put a RBF kernel on each of the variates, then return the product kernel If all ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleFactorKernel:
"""Alternative implementation of SimpleCategoricalKernel Testing the water with CompoundKernel before attempting Tensor"""
def __init__(self, columns):
"""Dummy-code the given column, put a RBF kernel on each of the variates, then return the product kernel If all length scales... | the_stack_v2_python_sparse | mlskMBO/CategoricalKernel.py | ECP-CANDLE/Scratch | train | 1 |
2adb169b499f1f166dd20aed7bb7bc450114fe95 | [
"super().__init__()\nself.name = name\nself.config = config\nself.got_data_cb = got_data_cb\nself.update_status_cb = update_status_cb\nself.connection_thread = None\nself.running = True",
"connection_thread = self.connection_thread\nif connection_thread is not None:\n connection_thread.add_data_to_send_queue(d... | <|body_start_0|>
super().__init__()
self.name = name
self.config = config
self.got_data_cb = got_data_cb
self.update_status_cb = update_status_cb
self.connection_thread = None
self.running = True
<|end_body_0|>
<|body_start_1|>
connection_thread = self.co... | 从差分源服务器接收数据的线程,差分源为 tcp server, 本地为 tcp client | StationThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationThread:
"""从差分源服务器接收数据的线程,差分源为 tcp server, 本地为 tcp client"""
def __init__(self, name, config, got_data_cb, update_status_cb):
"""构造函数 Args: name (str): rtk 服务名 config (Entry): 配置 got_data_cb (Callable[[bytes], None]): 接收到数据包时调用的回调函数 update_status_cb (Callable[[str], None]): 更新... | stack_v2_sparse_classes_75kplus_train_003583 | 1,504 | no_license | [
{
"docstring": "构造函数 Args: name (str): rtk 服务名 config (Entry): 配置 got_data_cb (Callable[[bytes], None]): 接收到数据包时调用的回调函数 update_status_cb (Callable[[str], None]): 更新差分状态的回调函数",
"name": "__init__",
"signature": "def __init__(self, name, config, got_data_cb, update_status_cb)"
},
{
"docstring": "向差... | 3 | stack_v2_sparse_classes_30k_train_041955 | Implement the Python class `StationThread` described below.
Class description:
从差分源服务器接收数据的线程,差分源为 tcp server, 本地为 tcp client
Method signatures and docstrings:
- def __init__(self, name, config, got_data_cb, update_status_cb): 构造函数 Args: name (str): rtk 服务名 config (Entry): 配置 got_data_cb (Callable[[bytes], None]): 接收... | Implement the Python class `StationThread` described below.
Class description:
从差分源服务器接收数据的线程,差分源为 tcp server, 本地为 tcp client
Method signatures and docstrings:
- def __init__(self, name, config, got_data_cb, update_status_cb): 构造函数 Args: name (str): rtk 服务名 config (Entry): 配置 got_data_cb (Callable[[bytes], None]): 接收... | 752105d0dec5b10c2f4d54324ff99267cc80bbb3 | <|skeleton|>
class StationThread:
"""从差分源服务器接收数据的线程,差分源为 tcp server, 本地为 tcp client"""
def __init__(self, name, config, got_data_cb, update_status_cb):
"""构造函数 Args: name (str): rtk 服务名 config (Entry): 配置 got_data_cb (Callable[[bytes], None]): 接收到数据包时调用的回调函数 update_status_cb (Callable[[str], None]): 更新... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StationThread:
"""从差分源服务器接收数据的线程,差分源为 tcp server, 本地为 tcp client"""
def __init__(self, name, config, got_data_cb, update_status_cb):
"""构造函数 Args: name (str): rtk 服务名 config (Entry): 配置 got_data_cb (Callable[[bytes], None]): 接收到数据包时调用的回调函数 update_status_cb (Callable[[str], None]): 更新差分状态的回调函数"""
... | the_stack_v2_python_sparse | rtk_trans/station_thread.py | bssthu/rtk_trans | train | 0 |
b4001cba7380517627fdb854f4ea2af66ce9e553 | [
"left = right = max_sum = float('-inf')\nfor a in arr:\n left, right = (max(a, left + a), max(left, right + a))\n max_sum = max(max_sum, right, left)\nreturn max_sum",
"n = len(arr)\ndp = [[float('-inf')] * 2 for _ in range(n)]\nres = float('-inf')\nfor i, a in enumerate(arr):\n dp[i][0] = max(a, dp[i - ... | <|body_start_0|>
left = right = max_sum = float('-inf')
for a in arr:
left, right = (max(a, left + a), max(left, right + a))
max_sum = max(max_sum, right, left)
return max_sum
<|end_body_0|>
<|body_start_1|>
n = len(arr)
dp = [[float('-inf')] * 2 for _ in... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def maximum_sum(self, arr: List[int]) -> int:
"""Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:"""
<|body_0|>
def maximum_sum_(self, arr: List[int]) -> int:
"""Approach: DP Formulae: --------- dp(i,0) = max(arr(i... | stack_v2_sparse_classes_75kplus_train_003584 | 2,196 | no_license | [
{
"docstring": "Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:",
"name": "maximum_sum",
"signature": "def maximum_sum(self, arr: List[int]) -> int"
},
{
"docstring": "Approach: DP Formulae: --------- dp(i,0) = max(arr(i), dp(i - 1, 0) + arr(i)) dp(... | 3 | stack_v2_sparse_classes_30k_train_013868 | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def maximum_sum(self, arr: List[int]) -> int: Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:
- def maximum_sum_(self, arr: List[int]) ->... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def maximum_sum(self, arr: List[int]) -> int: Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:
- def maximum_sum_(self, arr: List[int]) ->... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def maximum_sum(self, arr: List[int]) -> int:
"""Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:"""
<|body_0|>
def maximum_sum_(self, arr: List[int]) -> int:
"""Approach: DP Formulae: --------- dp(i,0) = max(arr(i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Array:
def maximum_sum(self, arr: List[int]) -> int:
"""Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:"""
left = right = max_sum = float('-inf')
for a in arr:
left, right = (max(a, left + a), max(left, right + a))
... | the_stack_v2_python_sparse | revisited_2021/arrays/max_sub_sum_with_one_deletion.py | Shiv2157k/leet_code | train | 1 | |
f1d81d0b6b61f0b5b2b9584be6a857792286e76c | [
"super(PositionalEncoding, self).__init__()\nposition_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for pos in range(max_seq_len)])\nposition_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])\nposition_encoding[:, 1::2] = np.cos(position_encoding[:, 1::2])\npad_... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
position_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for pos in range(max_seq_len)])
position_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])
position_encoding[:, 1::2] =... | PositionalEncoding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
<|body_0|>
def forward(self, input_len):
"""神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回... | stack_v2_sparse_classes_75kplus_train_003585 | 15,500 | no_license | [
{
"docstring": "初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度",
"name": "__init__",
"signature": "def __init__(self, d_model, max_seq_len)"
},
{
"docstring": "神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回这一批序列的位置编码,进行了对齐。",
"nam... | 2 | stack_v2_sparse_classes_30k_train_011461 | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model, max_seq_len): 初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度
- def forward(self, input_len): 神经网络的前向传播。 Args:... | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model, max_seq_len): 初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度
- def forward(self, input_len): 神经网络的前向传播。 Args:... | 6dd9eb4b2c65c346debbaa4cfc6b6a3cbdaf8047 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
<|body_0|>
def forward(self, input_len):
"""神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
super(PositionalEncoding, self).__init__()
position_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for... | the_stack_v2_python_sparse | models/transformer.py | wkk-nlp/SGAN | train | 0 | |
5516f104d579041073dde85424c61342ecb70b3e | [
"user = UserProfile.objects.get(user=self.request.user)\nbid = get_object_or_404(Bid, user=user, id=pk, status=Bid.Status.draft)\nif user.bidlist.filter(status=Bid.Status.submitted, bidcycle=bid.bidcycle).count() >= Bid.MAXIMUM_SUBMITTED_BIDS:\n return Response({'detail': 'Submitted bid limit exceeded.'}, status... | <|body_start_0|>
user = UserProfile.objects.get(user=self.request.user)
bid = get_object_or_404(Bid, user=user, id=pk, status=Bid.Status.draft)
if user.bidlist.filter(status=Bid.Status.submitted, bidcycle=bid.bidcycle).count() >= Bid.MAXIMUM_SUBMITTED_BIDS:
return Response({'detail':... | Supports all bidder actions for a bid | BidListBidderActionView | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidListBidderActionView:
"""Supports all bidder actions for a bid"""
def submit(self, request, pk, format=None):
"""Submits a bid Returns 204 if the action is a success"""
<|body_0|>
def accept_handshake(self, request, pk, format=None):
"""Accepts a handshake for... | stack_v2_sparse_classes_75kplus_train_003586 | 5,772 | permissive | [
{
"docstring": "Submits a bid Returns 204 if the action is a success",
"name": "submit",
"signature": "def submit(self, request, pk, format=None)"
},
{
"docstring": "Accepts a handshake for a bid Returns 204 if the action is a success",
"name": "accept_handshake",
"signature": "def accep... | 3 | stack_v2_sparse_classes_30k_train_009896 | Implement the Python class `BidListBidderActionView` described below.
Class description:
Supports all bidder actions for a bid
Method signatures and docstrings:
- def submit(self, request, pk, format=None): Submits a bid Returns 204 if the action is a success
- def accept_handshake(self, request, pk, format=None): Ac... | Implement the Python class `BidListBidderActionView` described below.
Class description:
Supports all bidder actions for a bid
Method signatures and docstrings:
- def submit(self, request, pk, format=None): Submits a bid Returns 204 if the action is a success
- def accept_handshake(self, request, pk, format=None): Ac... | cf71acd2ea0957aa2d599da8e1185d8519d8b013 | <|skeleton|>
class BidListBidderActionView:
"""Supports all bidder actions for a bid"""
def submit(self, request, pk, format=None):
"""Submits a bid Returns 204 if the action is a success"""
<|body_0|>
def accept_handshake(self, request, pk, format=None):
"""Accepts a handshake for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BidListBidderActionView:
"""Supports all bidder actions for a bid"""
def submit(self, request, pk, format=None):
"""Submits a bid Returns 204 if the action is a success"""
user = UserProfile.objects.get(user=self.request.user)
bid = get_object_or_404(Bid, user=user, id=pk, status=... | the_stack_v2_python_sparse | talentmap_api/bidding/views/bid.py | 18F/State-TalentMAP-API | train | 5 |
d1e5cdd2c43b933bf6c45b09e8e92bdd19d417f2 | [
"super(Repoquery, self).__init__(None)\nself.name = name\nself.query_type = query_type\nself.show_duplicates = show_duplicates\nself.match_version = match_version\nself.verbose = verbose\nif self.match_version:\n self.show_duplicates = True\nself.query_format = '%{version}|%{release}|%{arch}|%{repo}|%{version}-%... | <|body_start_0|>
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.verbose = verbose
if self.match_version:
self.show_duplicates = True
... | Class to wrap the repoquery | Repoquery | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
def process_ver... | stack_v2_sparse_classes_75kplus_train_003587 | 4,645 | permissive | [
{
"docstring": "Constructor for YumList",
"name": "__init__",
"signature": "def __init__(self, name, query_type, show_duplicates, match_version, verbose)"
},
{
"docstring": "build the repoquery cmd options",
"name": "build_cmd",
"signature": "def build_cmd(self)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_010284 | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- def process_version... | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- def process_version... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
def process_ver... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show... | the_stack_v2_python_sparse | ansible/roles/lib_repoquery/build/src/repoquery.py | openshift/openshift-tools | train | 170 |
ea966ae74faaabac0604202b3c685ac936c3000f | [
"initial_solution = create_initial_solution(testcase)\noutput_data = divideconquer_optimization(initial_solution, options, CostChecker(), SolutionChecker(wcdtool_path, wcdtool_testcase_subpath, options['wcdanalysis_timeout']))\nif output_data != None:\n self.generate_output(output_data, output_folder, 'Iterative... | <|body_start_0|>
initial_solution = create_initial_solution(testcase)
output_data = divideconquer_optimization(initial_solution, options, CostChecker(), SolutionChecker(wcdtool_path, wcdtool_testcase_subpath, options['wcdanalysis_timeout']))
if output_data != None:
self.generate_outp... | Finds a solution to the testcase by constructivly generating a good initial solution. Then proceeds to make all stream feasible (catch their deadline), by reducing the periods of the ports on their route | IterativeOptimizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterativeOptimizer:
"""Finds a solution to the testcase by constructivly generating a good initial solution. Then proceeds to make all stream feasible (catch their deadline), by reducing the periods of the ports on their route"""
def run(self, testcase: TestCase, wcdtool_path: str, wcdtool_t... | stack_v2_sparse_classes_75kplus_train_003588 | 12,133 | no_license | [
{
"docstring": "Args: testcase (TestCase): Testcase wcdtool_path (str): Path to WCDTool executable wcdtool_testcase_subpath (str): Relative path from WCDTool executable to testcase folder output_folder (str): Path to output folder options (dict): directory of options specified by user Returns: TestCase object f... | 2 | stack_v2_sparse_classes_30k_train_025517 | Implement the Python class `IterativeOptimizer` described below.
Class description:
Finds a solution to the testcase by constructivly generating a good initial solution. Then proceeds to make all stream feasible (catch their deadline), by reducing the periods of the ports on their route
Method signatures and docstrin... | Implement the Python class `IterativeOptimizer` described below.
Class description:
Finds a solution to the testcase by constructivly generating a good initial solution. Then proceeds to make all stream feasible (catch their deadline), by reducing the periods of the ports on their route
Method signatures and docstrin... | 49f3289f05652b8bda0750442f3f0532242f5aee | <|skeleton|>
class IterativeOptimizer:
"""Finds a solution to the testcase by constructivly generating a good initial solution. Then proceeds to make all stream feasible (catch their deadline), by reducing the periods of the ports on their route"""
def run(self, testcase: TestCase, wcdtool_path: str, wcdtool_t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IterativeOptimizer:
"""Finds a solution to the testcase by constructivly generating a good initial solution. Then proceeds to make all stream feasible (catch their deadline), by reducing the periods of the ports on their route"""
def run(self, testcase: TestCase, wcdtool_path: str, wcdtool_testcase_subpa... | the_stack_v2_python_sparse | optimizers/iterative_optimizer.py | nreusch/tsnwindowfinder | train | 0 |
ac5dfff75236146ede375c4ba8757575f4c6a95b | [
"async with database.connection() as connection:\n raw_connection = connection.raw_connection\n raw_connection.row_factory = aiosqlite.Row\n query = 'SELECT * FROM authors LIMIT :limit OFFSET :offset;'\n cursor = await raw_connection.execute(query, request_data)\n return await cursor.fetchall()",
"... | <|body_start_0|>
async with database.connection() as connection:
raw_connection = connection.raw_connection
raw_connection.row_factory = aiosqlite.Row
query = 'SELECT * FROM authors LIMIT :limit OFFSET :offset;'
cursor = await raw_connection.execute(query, request... | AuthorsEndpoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorsEndpoint:
async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]:
"""Retrieves the list of authors. List is limited with `limit` and `offset` fields."""
<|body_0|>
async def post(self, request_data: typing.Dict) -> aiosqlite.Row:
"""Creat... | stack_v2_sparse_classes_75kplus_train_003589 | 3,278 | permissive | [
{
"docstring": "Retrieves the list of authors. List is limited with `limit` and `offset` fields.",
"name": "get",
"signature": "async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]"
},
{
"docstring": "Creates a new author and returns the created record",
"name": "post... | 2 | stack_v2_sparse_classes_30k_train_021721 | Implement the Python class `AuthorsEndpoint` described below.
Class description:
Implement the AuthorsEndpoint class.
Method signatures and docstrings:
- async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]: Retrieves the list of authors. List is limited with `limit` and `offset` fields.
- asy... | Implement the Python class `AuthorsEndpoint` described below.
Class description:
Implement the AuthorsEndpoint class.
Method signatures and docstrings:
- async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]: Retrieves the list of authors. List is limited with `limit` and `offset` fields.
- asy... | 4c18a1cf1cfa088d67a61b89e64217e2e4dac809 | <|skeleton|>
class AuthorsEndpoint:
async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]:
"""Retrieves the list of authors. List is limited with `limit` and `offset` fields."""
<|body_0|>
async def post(self, request_data: typing.Dict) -> aiosqlite.Row:
"""Creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthorsEndpoint:
async def get(self, request_data: typing.Dict) -> typing.List[aiosqlite.Row]:
"""Retrieves the list of authors. List is limited with `limit` and `offset` fields."""
async with database.connection() as connection:
raw_connection = connection.raw_connection
... | the_stack_v2_python_sparse | example_app/base_api/base_common.py | gvbgduh/starlette-cbge | train | 7 | |
e25ef507aad1c18b3728de1c2df6cc155fa4f82a | [
"super().__init__(**kwargs)\nself.net = net\nself.f0_residual = f0_residual\nself.dense_out = tfkl.Dense(2)\nself.norm = nn.Normalize('layer')",
"x = tf.concat([f0_midi, amps, hd, noise], axis=-1)\nx = self.net(x)\nx = self.norm(x)\nx = self.dense_out(x)\nz_pitch = x[..., 0:1]\nz_vel = x[..., 1:2]\nif self.f0_res... | <|body_start_0|>
super().__init__(**kwargs)
self.net = net
self.f0_residual = f0_residual
self.dense_out = tfkl.Dense(2)
self.norm = nn.Normalize('layer')
<|end_body_0|>
<|body_start_1|>
x = tf.concat([f0_midi, amps, hd, noise], axis=-1)
x = self.net(x)
x... | Encodes Harmonic synthesizer parameters to MIDI representation. | HarmonicToMidiEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HarmonicToMidiEncoder:
"""Encodes Harmonic synthesizer parameters to MIDI representation."""
def __init__(self, net=None, f0_residual=True, **kwargs):
"""Constructor."""
<|body_0|>
def call(self, f0_midi, amps, hd, noise) -> ['z_pitch', 'z_vel']:
"""Forward pass ... | stack_v2_sparse_classes_75kplus_train_003590 | 15,113 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, net=None, f0_residual=True, **kwargs)"
},
{
"docstring": "Forward pass for the encoder. Args: f0_midi: Tensor containing an f0 curve in MIDI scale. [batch, time, 1] amps: Tensor with amplitude curve in log scale.... | 2 | stack_v2_sparse_classes_30k_train_016412 | Implement the Python class `HarmonicToMidiEncoder` described below.
Class description:
Encodes Harmonic synthesizer parameters to MIDI representation.
Method signatures and docstrings:
- def __init__(self, net=None, f0_residual=True, **kwargs): Constructor.
- def call(self, f0_midi, amps, hd, noise) -> ['z_pitch', 'z... | Implement the Python class `HarmonicToMidiEncoder` described below.
Class description:
Encodes Harmonic synthesizer parameters to MIDI representation.
Method signatures and docstrings:
- def __init__(self, net=None, f0_residual=True, **kwargs): Constructor.
- def call(self, f0_midi, amps, hd, noise) -> ['z_pitch', 'z... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class HarmonicToMidiEncoder:
"""Encodes Harmonic synthesizer parameters to MIDI representation."""
def __init__(self, net=None, f0_residual=True, **kwargs):
"""Constructor."""
<|body_0|>
def call(self, f0_midi, amps, hd, noise) -> ['z_pitch', 'z_vel']:
"""Forward pass ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HarmonicToMidiEncoder:
"""Encodes Harmonic synthesizer parameters to MIDI representation."""
def __init__(self, net=None, f0_residual=True, **kwargs):
"""Constructor."""
super().__init__(**kwargs)
self.net = net
self.f0_residual = f0_residual
self.dense_out = tfkl.... | the_stack_v2_python_sparse | ddsp/training/encoders.py | magenta/ddsp | train | 2,666 |
62a74f2569b1818cfd05087b5435e12b75e148a1 | [
"terms = re.findall('[^+ ,;]+', str(proposal_id))\nfor term in terms:\n if re.match('[0-9]+[a-z]?', term):\n proposal_id = term\n break\ntry:\n proposal_entry = Proposals.get(Proposals.id == proposal_id)\nexcept DoesNotExist:\n message = 'No Proposal with an ID of {0} was found'.format(propos... | <|body_start_0|>
terms = re.findall('[^+ ,;]+', str(proposal_id))
for term in terms:
if re.match('[0-9]+[a-z]?', term):
proposal_id = term
break
try:
proposal_entry = Proposals.get(Proposals.id == proposal_id)
except DoesNotExist:
... | Retrieves a set of proposals for a given keyword set. | ProposalLookup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProposalLookup:
"""Retrieves a set of proposals for a given keyword set."""
def _get_proposal_details(proposal_id):
"""Return a formatted dictionary containing the details of a given Proposal entry."""
<|body_0|>
def GET(proposal_id=None):
"""CherryPy GET method.... | stack_v2_sparse_classes_75kplus_train_003591 | 2,925 | no_license | [
{
"docstring": "Return a formatted dictionary containing the details of a given Proposal entry.",
"name": "_get_proposal_details",
"signature": "def _get_proposal_details(proposal_id)"
},
{
"docstring": "CherryPy GET method.",
"name": "GET",
"signature": "def GET(proposal_id=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004934 | Implement the Python class `ProposalLookup` described below.
Class description:
Retrieves a set of proposals for a given keyword set.
Method signatures and docstrings:
- def _get_proposal_details(proposal_id): Return a formatted dictionary containing the details of a given Proposal entry.
- def GET(proposal_id=None):... | Implement the Python class `ProposalLookup` described below.
Class description:
Retrieves a set of proposals for a given keyword set.
Method signatures and docstrings:
- def _get_proposal_details(proposal_id): Return a formatted dictionary containing the details of a given Proposal entry.
- def GET(proposal_id=None):... | dd9dbc8ea508e5412b9b9803805a1cb12f8cfc2e | <|skeleton|>
class ProposalLookup:
"""Retrieves a set of proposals for a given keyword set."""
def _get_proposal_details(proposal_id):
"""Return a formatted dictionary containing the details of a given Proposal entry."""
<|body_0|>
def GET(proposal_id=None):
"""CherryPy GET method.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProposalLookup:
"""Retrieves a set of proposals for a given keyword set."""
def _get_proposal_details(proposal_id):
"""Return a formatted dictionary containing the details of a given Proposal entry."""
terms = re.findall('[^+ ,;]+', str(proposal_id))
for term in terms:
... | the_stack_v2_python_sparse | metadata/rest/proposal_queries/proposal_lookup.py | markborkum/pacifica-metadata | train | 0 |
e64d0d4e9e87e5d2df9a2fa7566610d35c0ea8a9 | [
"password = attrs[source]\nif len(password) < PASSWORD_MIN_LENGTH:\n raise serializers.ValidationError(code['E_INVALID_PASSWORD'])\nreturn attrs",
"username = attrs[source].lower()\nif User.objects.filter(username=username).count() > 0:\n raise serializers.ValidationError(code['E_DUPLICATE_USERNAME'])\nretu... | <|body_start_0|>
password = attrs[source]
if len(password) < PASSWORD_MIN_LENGTH:
raise serializers.ValidationError(code['E_INVALID_PASSWORD'])
return attrs
<|end_body_0|>
<|body_start_1|>
username = attrs[source].lower()
if User.objects.filter(username=username).cou... | RegisterSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterSerializer:
def validate_password(attrs, source):
"""Check valid password"""
<|body_0|>
def validate_username(attrs, source):
"""Check duplicated username"""
<|body_1|>
def validate_password_confirmation(attrs, source):
"""Password confir... | stack_v2_sparse_classes_75kplus_train_003592 | 4,776 | no_license | [
{
"docstring": "Check valid password",
"name": "validate_password",
"signature": "def validate_password(attrs, source)"
},
{
"docstring": "Check duplicated username",
"name": "validate_username",
"signature": "def validate_username(attrs, source)"
},
{
"docstring": "Password conf... | 4 | stack_v2_sparse_classes_30k_val_001238 | Implement the Python class `RegisterSerializer` described below.
Class description:
Implement the RegisterSerializer class.
Method signatures and docstrings:
- def validate_password(attrs, source): Check valid password
- def validate_username(attrs, source): Check duplicated username
- def validate_password_confirmat... | Implement the Python class `RegisterSerializer` described below.
Class description:
Implement the RegisterSerializer class.
Method signatures and docstrings:
- def validate_password(attrs, source): Check valid password
- def validate_username(attrs, source): Check duplicated username
- def validate_password_confirmat... | 28d5f3fd0b4deb6909aeda97f17f2994eaffd48a | <|skeleton|>
class RegisterSerializer:
def validate_password(attrs, source):
"""Check valid password"""
<|body_0|>
def validate_username(attrs, source):
"""Check duplicated username"""
<|body_1|>
def validate_password_confirmation(attrs, source):
"""Password confir... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterSerializer:
def validate_password(attrs, source):
"""Check valid password"""
password = attrs[source]
if len(password) < PASSWORD_MIN_LENGTH:
raise serializers.ValidationError(code['E_INVALID_PASSWORD'])
return attrs
def validate_username(attrs, source)... | the_stack_v2_python_sparse | api/authMana/serializers.py | minhdo6487/api-proto | train | 0 | |
1f1ce2c9c565816e0c806c3da2b884d1d71956e7 | [
"if len(nums) < k:\n return False\ntotal = sum(nums)\nif total % k != 0:\n return False\ntarget = total / k\nused = [0] * len(nums)\ns = self.backtrack(k, 0, nums, 0, used, target)\nreturn s",
"if k == 0:\n return True\nif cur_bucket_total == target:\n return self.backtrack(k - 1, 0, nums, 0, used, ta... | <|body_start_0|>
if len(nums) < k:
return False
total = sum(nums)
if total % k != 0:
return False
target = total / k
used = [0] * len(nums)
s = self.backtrack(k, 0, nums, 0, used, target)
return s
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_possible_divide(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def backtrack(self, k, cur_bucket_total, nums, start, used, target):
"""@param k: 待选择的桶编号 @param cur_bucket_total: 当前桶已经装的数字之和 @param nums: 待选择的数字列表 @par... | stack_v2_sparse_classes_75kplus_train_003593 | 2,042 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "is_possible_divide",
"signature": "def is_possible_divide(self, nums, k)"
},
{
"docstring": "@param k: 待选择的桶编号 @param cur_bucket_total: 当前桶已经装的数字之和 @param nums: 待选择的数字列表 @param used: 已经选择过的索引 @param start: 开始遍历的位置 @param ... | 2 | stack_v2_sparse_classes_30k_train_010845 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_possible_divide(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def backtrack(self, k, cur_bucket_total, nums, start, used, target): @param k: 待选择的桶编号 @p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_possible_divide(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def backtrack(self, k, cur_bucket_total, nums, start, used, target): @param k: 待选择的桶编号 @p... | 5ba3465ba9c85955eac188e1e3793a981de712e7 | <|skeleton|>
class Solution:
def is_possible_divide(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def backtrack(self, k, cur_bucket_total, nums, start, used, target):
"""@param k: 待选择的桶编号 @param cur_bucket_total: 当前桶已经装的数字之和 @param nums: 待选择的数字列表 @par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def is_possible_divide(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
if len(nums) < k:
return False
total = sum(nums)
if total % k != 0:
return False
target = total / k
used = [0] * len(nums)
s = ... | the_stack_v2_python_sparse | backtrack/698_划分为k个相等的子集.py | SilvesSun/learn-algorithm-in-python | train | 0 | |
c113a2e38661aed9a75740556c6091f6a23cab40 | [
"super(StyleTask, self).__init__()\nif num_segments < 3:\n raise Exception('num_segments must be >= 3 for StyleTask.')\nif speed <= 0 or speed > 1:\n raise Exception('power must be between (0, 1] for StyleTask.')\nspeed /= 10000\nself.num_segments = num_segments\nself.angle = angle\nself.seg_rads = angle / nu... | <|body_start_0|>
super(StyleTask, self).__init__()
if num_segments < 3:
raise Exception('num_segments must be >= 3 for StyleTask.')
if speed <= 0 or speed > 1:
raise Exception('power must be between (0, 1] for StyleTask.')
speed /= 10000
self.num_segments ... | StyleTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleTask:
def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4):
"""Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (... | stack_v2_sparse_classes_75kplus_train_003594 | 4,891 | no_license | [
{
"docstring": "Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (float): desired angle of turn in radians num_segments (int): number of segments to check p... | 3 | stack_v2_sparse_classes_30k_train_047926 | Implement the Python class `StyleTask` described below.
Class description:
Implement the StyleTask class.
Method signatures and docstrings:
- def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4): Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (s... | Implement the Python class `StyleTask` described below.
Class description:
Implement the StyleTask class.
Method signatures and docstrings:
- def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4): Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (s... | e2fd7ab924d143bf6354806a104f49d982f32fb1 | <|skeleton|>
class StyleTask:
def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4):
"""Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StyleTask:
def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4):
"""Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (float): desire... | the_stack_v2_python_sparse | onboard/catkin_ws/src/task_planning/scripts/old/style_task.py | DukeRobotics/robosub-ros | train | 24 | |
595ac2335a12fea6bebd10d78e7365622c61beb4 | [
"if not value:\n return []\nreturn [v.strip() for v in value.split() if v != '']",
"super().validate(value)\ntry:\n for email in value:\n validate_email(email)\nexcept ValidationError:\n raise ValidationError(self.message, code=self.code)"
] | <|body_start_0|>
if not value:
return []
return [v.strip() for v in value.split() if v != '']
<|end_body_0|>
<|body_start_1|>
super().validate(value)
try:
for email in value:
validate_email(email)
except ValidationError:
raise ... | MultiEmailField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not value:
... | stack_v2_sparse_classes_75kplus_train_003595 | 1,497 | permissive | [
{
"docstring": "Normalize data to a list of strings.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Check if value consists only of valid emails.",
"name": "validate",
"signature": "def validate(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032825 | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails. | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails.
<|skeleton|>
class Mult... | de532aee33b03f9b580404dbf273713b12bd6275 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
if not value:
return []
return [v.strip() for v in value.split() if v != '']
def validate(self, value):
"""Check if value consists only of valid emails."""
super().v... | the_stack_v2_python_sparse | src/easydmp/invitation/forms.py | hmpf/easydmp | train | 8 | |
3a96028f733a6bc03b05d0164cb61c3133b3b295 | [
"post_body = json.dumps({'identity_provider': kwargs})\nresp, body = self.put('OS-FEDERATION/identity_providers/%s' % identity_provider_id, post_body)\nself.expected_success(201, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)",
"url = 'identity_providers'\nif params:\n url +... | <|body_start_0|>
post_body = json.dumps({'identity_provider': kwargs})
resp, body = self.put('OS-FEDERATION/identity_providers/%s' % identity_provider_id, post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
<|end_... | IdentityProvidersClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityProvidersClient:
def register_identity_provider(self, identity_provider_id, **kwargs):
"""Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-... | stack_v2_sparse_classes_75kplus_train_003596 | 3,718 | permissive | [
{
"docstring": "Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-identity-provider",
"name": "register_identity_provider",
"signature": "def register_identity_prov... | 5 | stack_v2_sparse_classes_30k_train_022695 | Implement the Python class `IdentityProvidersClient` described below.
Class description:
Implement the IdentityProvidersClient class.
Method signatures and docstrings:
- def register_identity_provider(self, identity_provider_id, **kwargs): Register an identity provider. For a full list of available parameters, please... | Implement the Python class `IdentityProvidersClient` described below.
Class description:
Implement the IdentityProvidersClient class.
Method signatures and docstrings:
- def register_identity_provider(self, identity_provider_id, **kwargs): Register an identity provider. For a full list of available parameters, please... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class IdentityProvidersClient:
def register_identity_provider(self, identity_provider_id, **kwargs):
"""Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdentityProvidersClient:
def register_identity_provider(self, identity_provider_id, **kwargs):
"""Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-identity-provi... | the_stack_v2_python_sparse | tempest/lib/services/identity/v3/identity_providers_client.py | openstack/tempest | train | 270 | |
5f1dd141c169131cb651e1c644b3feaa73662497 | [
"if not root:\n return []\n\ndef dfs(node):\n stack.append(node)\n if not node.left and (not node.right):\n vals = [i.val for i in stack]\n if sum(vals) == su:\n result.append(vals)\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\n stack.p... | <|body_start_0|>
if not root:
return []
def dfs(node):
stack.append(node)
if not node.left and (not node.right):
vals = [i.val for i in stack]
if sum(vals) == su:
result.append(vals)
if node.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, su):
""":type root: TreeNode :type su: int :rtype: List[List[int]] DFS: Use stack to save path. 用 sum - current value 直到 根node等於剩下的sum 則為答案 這樣比較快 不用每次sum[stack]"""
<|body_0|>
def rewrite(self, root, sum):
""":type root: TreeNode :typ... | stack_v2_sparse_classes_75kplus_train_003597 | 3,396 | no_license | [
{
"docstring": ":type root: TreeNode :type su: int :rtype: List[List[int]] DFS: Use stack to save path. 用 sum - current value 直到 根node等於剩下的sum 則為答案 這樣比較快 不用每次sum[stack]",
"name": "pathSum",
"signature": "def pathSum(self, root, su)"
},
{
"docstring": ":type root: TreeNode :type su: int :rtype: L... | 3 | stack_v2_sparse_classes_30k_train_019732 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, su): :type root: TreeNode :type su: int :rtype: List[List[int]] DFS: Use stack to save path. 用 sum - current value 直到 根node等於剩下的sum 則為答案 這樣比較快 不用每次sum[sta... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, su): :type root: TreeNode :type su: int :rtype: List[List[int]] DFS: Use stack to save path. 用 sum - current value 直到 根node等於剩下的sum 則為答案 這樣比較快 不用每次sum[sta... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def pathSum(self, root, su):
""":type root: TreeNode :type su: int :rtype: List[List[int]] DFS: Use stack to save path. 用 sum - current value 直到 根node等於剩下的sum 則為答案 這樣比較快 不用每次sum[stack]"""
<|body_0|>
def rewrite(self, root, sum):
""":type root: TreeNode :typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pathSum(self, root, su):
""":type root: TreeNode :type su: int :rtype: List[List[int]] DFS: Use stack to save path. 用 sum - current value 直到 根node等於剩下的sum 則為答案 這樣比較快 不用每次sum[stack]"""
if not root:
return []
def dfs(node):
stack.append(node)
... | the_stack_v2_python_sparse | co_fb/113_Path_Sum_II.py | vsdrun/lc_public | train | 6 | |
8c9f11bf8c5da7f13b577e1eb7ace6f51bf87516 | [
"inv.Inventory.__init__(self, item_code, description, market_price, rental_price)\nself.material = material\nself.size = size",
"output_dict = {}\noutput_dict['item_code'] = self.item_code\noutput_dict['description'] = self.description\noutput_dict['market_price'] = self.market_price\noutput_dict['rental_price'] ... | <|body_start_0|>
inv.Inventory.__init__(self, item_code, description, market_price, rental_price)
self.material = material
self.size = size
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['item_code'] = self.item_code
output_dict['description'] = self.descri... | Contains class methods and attributes for furniture items. | Furniture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Furniture:
"""Contains class methods and attributes for furniture items."""
def __init__(self, item_code, description, market_price, rental_price, material, size):
"""Creates furniture item."""
<|body_0|>
def return_as_dictionary(self):
"""Return furniture item i... | stack_v2_sparse_classes_75kplus_train_003598 | 1,070 | no_license | [
{
"docstring": "Creates furniture item.",
"name": "__init__",
"signature": "def __init__(self, item_code, description, market_price, rental_price, material, size)"
},
{
"docstring": "Return furniture item information as a dictionary.",
"name": "return_as_dictionary",
"signature": "def re... | 2 | stack_v2_sparse_classes_30k_train_033719 | Implement the Python class `Furniture` described below.
Class description:
Contains class methods and attributes for furniture items.
Method signatures and docstrings:
- def __init__(self, item_code, description, market_price, rental_price, material, size): Creates furniture item.
- def return_as_dictionary(self): Re... | Implement the Python class `Furniture` described below.
Class description:
Contains class methods and attributes for furniture items.
Method signatures and docstrings:
- def __init__(self, item_code, description, market_price, rental_price, material, size): Creates furniture item.
- def return_as_dictionary(self): Re... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Furniture:
"""Contains class methods and attributes for furniture items."""
def __init__(self, item_code, description, market_price, rental_price, material, size):
"""Creates furniture item."""
<|body_0|>
def return_as_dictionary(self):
"""Return furniture item i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Furniture:
"""Contains class methods and attributes for furniture items."""
def __init__(self, item_code, description, market_price, rental_price, material, size):
"""Creates furniture item."""
inv.Inventory.__init__(self, item_code, description, market_price, rental_price)
self.m... | the_stack_v2_python_sparse | students/alexander_boone/lesson01/assignment/inventory_management/furniture_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
9b2c14712c1b0daad86199c1c15aa0dfbf713b9b | [
"app = Sharing_Types.WNApplicationHeader()\napp.ApplicationId = app.new_ApplicationId(str(self.AppId).upper())\nauth = Sharing_Types.WNAuthHeader()\nauth.TicketToken = client.get_ticket(self.SSO_Domain).token\nreturn (app, auth)",
"msg.EntityHandle = msg.new_entityHandle()\nmsg.EntityHandle.Cid = cid\nmsg.Locales... | <|body_start_0|>
app = Sharing_Types.WNApplicationHeader()
app.ApplicationId = app.new_ApplicationId(str(self.AppId).upper())
auth = Sharing_Types.WNAuthHeader()
auth.TicketToken = client.get_ticket(self.SSO_Domain).token
return (app, auth)
<|end_body_0|>
<|body_start_1|>
... | WhatsUpService | [
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhatsUpService:
def serviceHeaders(self, client, *a, **k):
"""<soap:Header> <WNApplicationHeader> <ApplicationId> 3B119D87-1D76-4474-91AD-0D7267E86D04 </ApplicationId> </WNApplicationHeader> <WNAuthHeader> <TicketToken> t=EwCYAebpAwAUXYHvLVryvkoZZmChP4TpdQV2xi2AAHGTaHqADpfC+4DlHVPURA4KhB... | stack_v2_sparse_classes_75kplus_train_003599 | 43,764 | permissive | [
{
"docstring": "<soap:Header> <WNApplicationHeader> <ApplicationId> 3B119D87-1D76-4474-91AD-0D7267E86D04 </ApplicationId> </WNApplicationHeader> <WNAuthHeader> <TicketToken> t=EwCYAebpAwAUXYHvLVryvkoZZmChP4TpdQV2xi2AAHGTaHqADpfC+4DlHVPURA4KhB0LQXd9qlo80h3pZpjUSZALqMApTC4rrYvvG+14K1LrBSsa5pR5Cp07GxynXRqObdNNa7cz... | 2 | stack_v2_sparse_classes_30k_train_018744 | Implement the Python class `WhatsUpService` described below.
Class description:
Implement the WhatsUpService class.
Method signatures and docstrings:
- def serviceHeaders(self, client, *a, **k): <soap:Header> <WNApplicationHeader> <ApplicationId> 3B119D87-1D76-4474-91AD-0D7267E86D04 </ApplicationId> </WNApplicationHe... | Implement the Python class `WhatsUpService` described below.
Class description:
Implement the WhatsUpService class.
Method signatures and docstrings:
- def serviceHeaders(self, client, *a, **k): <soap:Header> <WNApplicationHeader> <ApplicationId> 3B119D87-1D76-4474-91AD-0D7267E86D04 </ApplicationId> </WNApplicationHe... | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | <|skeleton|>
class WhatsUpService:
def serviceHeaders(self, client, *a, **k):
"""<soap:Header> <WNApplicationHeader> <ApplicationId> 3B119D87-1D76-4474-91AD-0D7267E86D04 </ApplicationId> </WNApplicationHeader> <WNAuthHeader> <TicketToken> t=EwCYAebpAwAUXYHvLVryvkoZZmChP4TpdQV2xi2AAHGTaHqADpfC+4DlHVPURA4KhB... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WhatsUpService:
def serviceHeaders(self, client, *a, **k):
"""<soap:Header> <WNApplicationHeader> <ApplicationId> 3B119D87-1D76-4474-91AD-0D7267E86D04 </ApplicationId> </WNApplicationHeader> <WNAuthHeader> <TicketToken> t=EwCYAebpAwAUXYHvLVryvkoZZmChP4TpdQV2xi2AAHGTaHqADpfC+4DlHVPURA4KhB0LQXd9qlo80h3p... | the_stack_v2_python_sparse | digsby/src/msn/SOAP/services.py | niterain/digsby | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.