blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
47ab5ac4fc8f1707236e4b7c785c21d539943c9c | [
"self.user = kwargs.pop('user', None)\nsuper(BaseCaseForm, self).__init__(*args, **kwargs)\nself.fields['add_tags'].widget.attrs['data-allow-new'] = 'true' if self.user and self.user.has_perm('tags.manage_tags') else 'false'",
"if self.data.get('tag-newtag') and (not (self.user and self.user.has_perm('tags.manage... | <|body_start_0|>
self.user = kwargs.pop('user', None)
super(BaseCaseForm, self).__init__(*args, **kwargs)
self.fields['add_tags'].widget.attrs['data-allow-new'] = 'true' if self.user and self.user.has_perm('tags.manage_tags') else 'false'
<|end_body_0|>
<|body_start_1|>
if self.data.get... | Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin. | BaseCaseForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseCaseForm:
"""Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin."""
def __init__(self, *args, **kwargs):
"""Initialize form; pull out user from kwargs, set up data-allow-new."""
<|body_0|>
def clean... | stack_v2_sparse_classes_36k_train_013100 | 16,711 | permissive | [
{
"docstring": "Initialize form; pull out user from kwargs, set up data-allow-new.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Can't create new tags without appropriate permissions.",
"name": "clean",
"signature": "def clean(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_011342 | Implement the Python class `BaseCaseForm` described below.
Class description:
Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form; pull out user from kwargs, se... | Implement the Python class `BaseCaseForm` described below.
Class description:
Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize form; pull out user from kwargs, se... | ee54db2fe8ffbf2216d359b7a093b51f2574878e | <|skeleton|>
class BaseCaseForm:
"""Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin."""
def __init__(self, *args, **kwargs):
"""Initialize form; pull out user from kwargs, set up data-allow-new."""
<|body_0|>
def clean... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseCaseForm:
"""Base form for all test case/version forms. Provides self.user, tags and status fields, and non-field-errors-class mixin."""
def __init__(self, *args, **kwargs):
"""Initialize form; pull out user from kwargs, set up data-allow-new."""
self.user = kwargs.pop('user', None)
... | the_stack_v2_python_sparse | moztrap/view/manage/cases/forms.py | isakib/moztrap | train | 1 |
0eeb45c24bef621b07ef38cd2951a41ef13c90cf | [
"self.v1 = v1\nself.v2 = v2\nself.flip = False",
"if not self.flip:\n ret, self.v1 = (self.v1[:1], self.v1[1:])\n if not ret:\n ret, self.v2 = (self.v2[:1], self.v2[1:])\nelse:\n ret, self.v2 = (self.v2[:1], self.v2[1:])\n if not ret:\n ret, self.v1 = (self.v1[:1], self.v1[1:])\nself.fli... | <|body_start_0|>
self.v1 = v1
self.v2 = v2
self.flip = False
<|end_body_0|>
<|body_start_1|>
if not self.flip:
ret, self.v1 = (self.v1[:1], self.v1[1:])
if not ret:
ret, self.v2 = (self.v2[:1], self.v2[1:])
else:
ret, self.v2 =... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k_train_013101 | 3,857 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | null | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.v1 = v1
self.v2 = v2
self.flip = False
def next(self):
""":rtype: int"""
if not self.flip:
ret, self.v1 = (self.v... | the_stack_v2_python_sparse | co_fb/281_Zigzag_Iterator.py | vsdrun/lc_public | train | 6 | |
952c47525b3cb8ed2d97ec70f31695ae0a766477 | [
"seed(datetime.now())\nheight = randint(HEIGHT[0], HEIGHT[1])\nhandler = AVLHandler.from_scratch(height, POINT_CAP)\nreturn handler",
"successes = 0\nfailures = 0\niterations = NUM_CALLS\nfor _ in range(iterations):\n handler = self.new_handler()\n ret = check_golden(handler)\n if ret:\n successes... | <|body_start_0|>
seed(datetime.now())
height = randint(HEIGHT[0], HEIGHT[1])
handler = AVLHandler.from_scratch(height, POINT_CAP)
return handler
<|end_body_0|>
<|body_start_1|>
successes = 0
failures = 0
iterations = NUM_CALLS
for _ in range(iterations):
... | Test the state of the AVL tree upon generation from scratch | AVLNewGeneration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AVLNewGeneration:
"""Test the state of the AVL tree upon generation from scratch"""
def new_handler():
"""create new handler to test"""
<|body_0|>
def test_golden_new(self):
"""make sure new avl is generated with correct golden node"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_013102 | 20,558 | permissive | [
{
"docstring": "create new handler to test",
"name": "new_handler",
"signature": "def new_handler()"
},
{
"docstring": "make sure new avl is generated with correct golden node",
"name": "test_golden_new",
"signature": "def test_golden_new(self)"
},
{
"docstring": "make sure nodes... | 4 | stack_v2_sparse_classes_30k_train_017995 | Implement the Python class `AVLNewGeneration` described below.
Class description:
Test the state of the AVL tree upon generation from scratch
Method signatures and docstrings:
- def new_handler(): create new handler to test
- def test_golden_new(self): make sure new avl is generated with correct golden node
- def tes... | Implement the Python class `AVLNewGeneration` described below.
Class description:
Test the state of the AVL tree upon generation from scratch
Method signatures and docstrings:
- def new_handler(): create new handler to test
- def test_golden_new(self): make sure new avl is generated with correct golden node
- def tes... | a47c849ea97763eff1005273a58aa3d8ab663ff2 | <|skeleton|>
class AVLNewGeneration:
"""Test the state of the AVL tree upon generation from scratch"""
def new_handler():
"""create new handler to test"""
<|body_0|>
def test_golden_new(self):
"""make sure new avl is generated with correct golden node"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AVLNewGeneration:
"""Test the state of the AVL tree upon generation from scratch"""
def new_handler():
"""create new handler to test"""
seed(datetime.now())
height = randint(HEIGHT[0], HEIGHT[1])
handler = AVLHandler.from_scratch(height, POINT_CAP)
return handler
... | the_stack_v2_python_sparse | game_board/avl/test_avl.py | Plongesam/data-structures-game | train | 2 |
966ca4d6cc5abbbc3afc3bb3bcd577cc38541683 | [
"for length in self.LENGTHS:\n pendulum = PendulumPlant(length=length)\n for _ in range(self.iterations):\n angle = (np.random.rand() - 0.5) * 2 * self.max_angle\n self.assertIsInstance(angle, float)\n ee_pos = pendulum.forward_kinematics(angle)[0]\n self.assertIsInstance(ee_pos, l... | <|body_start_0|>
for length in self.LENGTHS:
pendulum = PendulumPlant(length=length)
for _ in range(self.iterations):
angle = (np.random.rand() - 0.5) * 2 * self.max_angle
self.assertIsInstance(angle, float)
ee_pos = pendulum.forward_kinema... | Test | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_0_kinematics(self):
"""Unit test for pendulum kinematics"""
<|body_0|>
def test_1_dynamics(self):
"""Unit test for pendulum dynamics"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for length in self.LENGTHS:
pendulum = Pe... | stack_v2_sparse_classes_36k_train_013103 | 4,821 | permissive | [
{
"docstring": "Unit test for pendulum kinematics",
"name": "test_0_kinematics",
"signature": "def test_0_kinematics(self)"
},
{
"docstring": "Unit test for pendulum dynamics",
"name": "test_1_dynamics",
"signature": "def test_1_dynamics(self)"
}
] | 2 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_0_kinematics(self): Unit test for pendulum kinematics
- def test_1_dynamics(self): Unit test for pendulum dynamics | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_0_kinematics(self): Unit test for pendulum kinematics
- def test_1_dynamics(self): Unit test for pendulum dynamics
<|skeleton|>
class Test:
def test_0_kinematics(self):
... | 2dab162a3a7bd33632fd36924b2bfb289249ffa3 | <|skeleton|>
class Test:
def test_0_kinematics(self):
"""Unit test for pendulum kinematics"""
<|body_0|>
def test_1_dynamics(self):
"""Unit test for pendulum dynamics"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test_0_kinematics(self):
"""Unit test for pendulum kinematics"""
for length in self.LENGTHS:
pendulum = PendulumPlant(length=length)
for _ in range(self.iterations):
angle = (np.random.rand() - 0.5) * 2 * self.max_angle
self.ass... | the_stack_v2_python_sparse | software/python/simple_pendulum/model/unit_test.py | dfki-ric-underactuated-lab/torque_limited_simple_pendulum | train | 37 | |
20c547d6fe672eedcb1623a1f21bcae5540bd168 | [
"super(UsedLimitsClient, self).__init__(serialize_format, deserialize_format)\nself.auth_token = auth_token\nself.default_headers['X-Auth-Token'] = auth_token\nct = 'application/{0}'.format(self.serialize_format)\naccept = 'application/{0}'.format(self.serialize_format)\nself.default_headers['Content-Type'] = ct\ns... | <|body_start_0|>
super(UsedLimitsClient, self).__init__(serialize_format, deserialize_format)
self.auth_token = auth_token
self.default_headers['X-Auth-Token'] = auth_token
ct = 'application/{0}'.format(self.serialize_format)
accept = 'application/{0}'.format(self.serialize_forma... | UsedLimitsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsedLimitsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for ... | stack_v2_sparse_classes_36k_train_013104 | 2,382 | permissive | [
{
"docstring": "@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for serializing requests @type serialize_format: String @param deserialize_format: Format for de-serializing responses... | 2 | null | Implement the Python class `UsedLimitsClient` described below.
Class description:
Implement the UsedLimitsClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @param url: Base URL for the compute service @type url: String @param auth_to... | Implement the Python class `UsedLimitsClient` described below.
Class description:
Implement the UsedLimitsClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @param url: Base URL for the compute service @type url: String @param auth_to... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class UsedLimitsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsedLimitsClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for serializing re... | the_stack_v2_python_sparse | cloudcafe/compute/extensions/used_limits/client.py | kurhula/cloudcafe | train | 0 | |
95270ce02581a7b9dfeac28f5b2a49c32632d901 | [
"self.mask_func = mask_func\nself.resolution = resolution\nself.use_seed = use_seed",
"if target is not None:\n target = T.to_tensor(target)\n max_value = attrs['max']\nelse:\n target = torch.tensor(0)\n max_value = 0.0\nkspace = T.to_tensor(kspace)\nseed = None if not self.use_seed else tuple(map(ord... | <|body_start_0|>
self.mask_func = mask_func
self.resolution = resolution
self.use_seed = use_seed
<|end_body_0|>
<|body_start_1|>
if target is not None:
target = T.to_tensor(target)
max_value = attrs['max']
else:
target = torch.tensor(0)
... | Data Transformer for training Var Net models. | DataTransform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataTransform:
"""Data Transformer for training Var Net models."""
def __init__(self, resolution, mask_func=None, use_seed=True):
"""Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the image. use_see... | stack_v2_sparse_classes_36k_train_013105 | 6,605 | no_license | [
{
"docstring": "Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the image. use_seed (bool): If true, this class computes a pseudo random number generator seed from the filename. This ensures that the same mask is used for all t... | 2 | null | Implement the Python class `DataTransform` described below.
Class description:
Data Transformer for training Var Net models.
Method signatures and docstrings:
- def __init__(self, resolution, mask_func=None, use_seed=True): Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate ... | Implement the Python class `DataTransform` described below.
Class description:
Data Transformer for training Var Net models.
Method signatures and docstrings:
- def __init__(self, resolution, mask_func=None, use_seed=True): Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate ... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class DataTransform:
"""Data Transformer for training Var Net models."""
def __init__(self, resolution, mask_func=None, use_seed=True):
"""Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the image. use_see... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataTransform:
"""Data Transformer for training Var Net models."""
def __init__(self, resolution, mask_func=None, use_seed=True):
"""Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the image. use_seed (bool): If ... | the_stack_v2_python_sparse | fastmri_fixed_sensitivity_variationaldc/valid.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
767bc73f75682a9b257ae675be66f58e21ac1fdc | [
"rows_updated = queryset.update(is_active=False)\nif rows_updated == 1:\n message_bit = '1 user was'\nelse:\n message_bit = '{} users were'.format(rows_updated)\nself.message_user(request, '{} successfully deactivated.'.format(message_bit))",
"rows_updated = queryset.update(is_active=True)\nif rows_updated ... | <|body_start_0|>
rows_updated = queryset.update(is_active=False)
if rows_updated == 1:
message_bit = '1 user was'
else:
message_bit = '{} users were'.format(rows_updated)
self.message_user(request, '{} successfully deactivated.'.format(message_bit))
<|end_body_0|>... | Define admin model for custom User model. | AccountsAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountsAdmin:
"""Define admin model for custom User model."""
def deactivate_user(self, request, queryset):
"""Deactivate selected user accounts."""
<|body_0|>
def activate_user(self, request, queryset):
"""Activate selected user accounts."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_013106 | 2,782 | no_license | [
{
"docstring": "Deactivate selected user accounts.",
"name": "deactivate_user",
"signature": "def deactivate_user(self, request, queryset)"
},
{
"docstring": "Activate selected user accounts.",
"name": "activate_user",
"signature": "def activate_user(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006970 | Implement the Python class `AccountsAdmin` described below.
Class description:
Define admin model for custom User model.
Method signatures and docstrings:
- def deactivate_user(self, request, queryset): Deactivate selected user accounts.
- def activate_user(self, request, queryset): Activate selected user accounts. | Implement the Python class `AccountsAdmin` described below.
Class description:
Define admin model for custom User model.
Method signatures and docstrings:
- def deactivate_user(self, request, queryset): Deactivate selected user accounts.
- def activate_user(self, request, queryset): Activate selected user accounts.
... | 321f0150be09f78c6d98516d246aedd168b85be8 | <|skeleton|>
class AccountsAdmin:
"""Define admin model for custom User model."""
def deactivate_user(self, request, queryset):
"""Deactivate selected user accounts."""
<|body_0|>
def activate_user(self, request, queryset):
"""Activate selected user accounts."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountsAdmin:
"""Define admin model for custom User model."""
def deactivate_user(self, request, queryset):
"""Deactivate selected user accounts."""
rows_updated = queryset.update(is_active=False)
if rows_updated == 1:
message_bit = '1 user was'
else:
... | the_stack_v2_python_sparse | accounts/admin.py | BuildForSDGCohort2/team-101-backend | train | 6 |
1705356892801f174182421e5ef5fa815f42b788 | [
"for field in quota_class.fields:\n if field == 'uuid':\n continue\n setattr(quota_class, field, db_quota_class[field])\nquota_class.obj_reset_changes()\nreturn quota_class",
"db_quota_class = dbapi.quota_class_get(context, class_name, resource)\nquota_class = QuotaClass._from_db_method(cls(context),... | <|body_start_0|>
for field in quota_class.fields:
if field == 'uuid':
continue
setattr(quota_class, field, db_quota_class[field])
quota_class.obj_reset_changes()
return quota_class
<|end_body_0|>
<|body_start_1|>
db_quota_class = dbapi.quota_class... | QuotaClass | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuotaClass:
def _from_db_method(quota_class, db_quota_class):
"""Convert a database entity to a format object"""
<|body_0|>
def get(cls, context, class_name, resource):
"""Find a quota class based on class_name and resource name. :param class_name: the name of class.... | stack_v2_sparse_classes_36k_train_013107 | 4,051 | permissive | [
{
"docstring": "Convert a database entity to a format object",
"name": "_from_db_method",
"signature": "def _from_db_method(quota_class, db_quota_class)"
},
{
"docstring": "Find a quota class based on class_name and resource name. :param class_name: the name of class. :param context: security co... | 5 | null | Implement the Python class `QuotaClass` described below.
Class description:
Implement the QuotaClass class.
Method signatures and docstrings:
- def _from_db_method(quota_class, db_quota_class): Convert a database entity to a format object
- def get(cls, context, class_name, resource): Find a quota class based on clas... | Implement the Python class `QuotaClass` described below.
Class description:
Implement the QuotaClass class.
Method signatures and docstrings:
- def _from_db_method(quota_class, db_quota_class): Convert a database entity to a format object
- def get(cls, context, class_name, resource): Find a quota class based on clas... | 4fa358474ee337f27bfaf8b98e886cc8d10ada50 | <|skeleton|>
class QuotaClass:
def _from_db_method(quota_class, db_quota_class):
"""Convert a database entity to a format object"""
<|body_0|>
def get(cls, context, class_name, resource):
"""Find a quota class based on class_name and resource name. :param class_name: the name of class.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuotaClass:
def _from_db_method(quota_class, db_quota_class):
"""Convert a database entity to a format object"""
for field in quota_class.fields:
if field == 'uuid':
continue
setattr(quota_class, field, db_quota_class[field])
quota_class.obj_rese... | the_stack_v2_python_sparse | zun/objects/quota_class.py | openstack/zun | train | 89 | |
080b7c84d692b28fc532f66d7e56980e0e935d09 | [
"if s == '':\n return False\nif len(s) == 1:\n return True\np1 = 0\np2 = len(s) - 1\ns = s.lower()\nwhile p1 < p2:\n if s[p1] not in self.alphanum:\n p1 += 1\n elif s[p2] not in self.alphanum:\n p2 -= 1\n elif s[p1] != s[p2]:\n return False\n else:\n p1 += 1\n p2... | <|body_start_0|>
if s == '':
return False
if len(s) == 1:
return True
p1 = 0
p2 = len(s) - 1
s = s.lower()
while p1 < p2:
if s[p1] not in self.alphanum:
p1 += 1
elif s[p2] not in self.alphanum:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == '':
return False
if len(s) == 1:
... | stack_v2_sparse_classes_36k_train_013108 | 965 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003192 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def countSubstrings(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def countSubstrings(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def isPalindrome(self, s):
... | 528f545e9a262da09d51b908687dc1d416d907a3 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
if s == '':
return False
if len(s) == 1:
return True
p1 = 0
p2 = len(s) - 1
s = s.lower()
while p1 < p2:
if s[p1] not in self.alphanum:
... | the_stack_v2_python_sparse | python/leetcode/palindromic-substrings.py | quetzaluz/codesnippets | train | 1 | |
2ddecd9114f9d28791355050c36172b4f42fbdf5 | [
"self.index = person.get('Index')\nself.bounding_box = person.get('BoundingBox')\nface = person.get('Face')\nself.face = RekognitionFace(face) if face is not None else None\nself.timestamp = timestamp",
"rendering = self.face.to_dict() if self.face is not None else {}\nif self.index is not None:\n rendering['i... | <|body_start_0|>
self.index = person.get('Index')
self.bounding_box = person.get('BoundingBox')
face = person.get('Face')
self.face = RekognitionFace(face) if face is not None else None
self.timestamp = timestamp
<|end_body_0|>
<|body_start_1|>
rendering = self.face.to_d... | Encapsulates an Amazon Rekognition person. | RekognitionPerson | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RekognitionPerson:
"""Encapsulates an Amazon Rekognition person."""
def __init__(self, person, timestamp=None):
"""Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detecte... | stack_v2_sparse_classes_36k_train_013109 | 11,689 | permissive | [
{
"docstring": "Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detected, if the person was detected in a video.",
"name": "__init__",
"signature": "def __init__(self, person, timestamp=None... | 2 | null | Implement the Python class `RekognitionPerson` described below.
Class description:
Encapsulates an Amazon Rekognition person.
Method signatures and docstrings:
- def __init__(self, person, timestamp=None): Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition function... | Implement the Python class `RekognitionPerson` described below.
Class description:
Encapsulates an Amazon Rekognition person.
Method signatures and docstrings:
- def __init__(self, person, timestamp=None): Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition function... | dec41fb589043ac9d8667aac36fb88a53c3abe50 | <|skeleton|>
class RekognitionPerson:
"""Encapsulates an Amazon Rekognition person."""
def __init__(self, person, timestamp=None):
"""Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detecte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RekognitionPerson:
"""Encapsulates an Amazon Rekognition person."""
def __init__(self, person, timestamp=None):
"""Initializes the person object. :param person: Person data, in the format returned by Amazon Rekognition functions. :param timestamp: The time when the person was detected, if the per... | the_stack_v2_python_sparse | python/example_code/rekognition/rekognition_objects.py | awsdocs/aws-doc-sdk-examples | train | 8,240 |
663ff8cdf1daf29d52167de6e71b3022ea5f07f5 | [
"self.sim = sim\nself.cnt_wt = TimeIndependentCounter()\nself.hist_wt = TimeIndependentHistogram(self.sim, 'w')\nself.cnt_ql = TimeDependentCounter(self.sim)\nself.hist_ql = TimeDependentHistogram(self.sim, 'q')\nself.cnt_sys_util = TimeDependentCounter(self.sim)\n'\\n # blocking probability\\n self.c... | <|body_start_0|>
self.sim = sim
self.cnt_wt = TimeIndependentCounter()
self.hist_wt = TimeIndependentHistogram(self.sim, 'w')
self.cnt_ql = TimeDependentCounter(self.sim)
self.hist_ql = TimeDependentHistogram(self.sim, 'q')
self.cnt_sys_util = TimeDependentCounter(self.si... | CounterCollection is a collection of all counters and histograms that are used in the simulations. It contains several counters and histograms, that are used in the different tasks. Reporting is done by calling the report function. This function can be adapted, depending on which counters should report their results an... | CounterCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CounterCollection:
"""CounterCollection is a collection of all counters and histograms that are used in the simulations. It contains several counters and histograms, that are used in the different tasks. Reporting is done by calling the report function. This function can be adapted, depending on ... | stack_v2_sparse_classes_36k_train_013110 | 4,240 | no_license | [
{
"docstring": "Initialize the counter collection. :param sim: the simulation, the CounterCollection belongs to.",
"name": "__init__",
"signature": "def __init__(self, sim)"
},
{
"docstring": "Resets all counters and histograms.",
"name": "reset",
"signature": "def reset(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_007587 | Implement the Python class `CounterCollection` described below.
Class description:
CounterCollection is a collection of all counters and histograms that are used in the simulations. It contains several counters and histograms, that are used in the different tasks. Reporting is done by calling the report function. This... | Implement the Python class `CounterCollection` described below.
Class description:
CounterCollection is a collection of all counters and histograms that are used in the simulations. It contains several counters and histograms, that are used in the different tasks. Reporting is done by calling the report function. This... | 1a5936c8c0fcd0d74b61941504f2c58669154c15 | <|skeleton|>
class CounterCollection:
"""CounterCollection is a collection of all counters and histograms that are used in the simulations. It contains several counters and histograms, that are used in the different tasks. Reporting is done by calling the report function. This function can be adapted, depending on ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CounterCollection:
"""CounterCollection is a collection of all counters and histograms that are used in the simulations. It contains several counters and histograms, that are used in the different tasks. Reporting is done by calling the report function. This function can be adapted, depending on which counter... | the_stack_v2_python_sparse | DES_part5_03694565/DES_part5_03694565/countercollection.py | gundoganalperen/ams-des | train | 4 |
329df12bc008dfad1329e447e32aec4ea1d5cf2e | [
"graph = {'a': ['b', 'c'], 'b': [], 'c': ['d'], 'd': ['b']}\n\ndef GetEdge(node):\n return tuple(graph[node])\nself.assertEqual(gyp.common.TopologicallySorted(graph.keys(), GetEdge), ['a', 'c', 'd', 'b'])",
"graph = {'a': ['b'], 'b': ['c'], 'c': ['d'], 'd': ['a']}\n\ndef GetEdge(node):\n return tuple(graph[... | <|body_start_0|>
graph = {'a': ['b', 'c'], 'b': [], 'c': ['d'], 'd': ['b']}
def GetEdge(node):
return tuple(graph[node])
self.assertEqual(gyp.common.TopologicallySorted(graph.keys(), GetEdge), ['a', 'c', 'd', 'b'])
<|end_body_0|>
<|body_start_1|>
graph = {'a': ['b'], 'b': [... | TestTopologicallySorted | [
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTopologicallySorted:
def test_Valid(self):
"""Test that sorting works on a valid graph with one possible order."""
<|body_0|>
def test_Cycle(self):
"""Test that an exception is thrown on a cyclic graph."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013111 | 2,021 | permissive | [
{
"docstring": "Test that sorting works on a valid graph with one possible order.",
"name": "test_Valid",
"signature": "def test_Valid(self)"
},
{
"docstring": "Test that an exception is thrown on a cyclic graph.",
"name": "test_Cycle",
"signature": "def test_Cycle(self)"
}
] | 2 | null | Implement the Python class `TestTopologicallySorted` described below.
Class description:
Implement the TestTopologicallySorted class.
Method signatures and docstrings:
- def test_Valid(self): Test that sorting works on a valid graph with one possible order.
- def test_Cycle(self): Test that an exception is thrown on ... | Implement the Python class `TestTopologicallySorted` described below.
Class description:
Implement the TestTopologicallySorted class.
Method signatures and docstrings:
- def test_Valid(self): Test that sorting works on a valid graph with one possible order.
- def test_Cycle(self): Test that an exception is thrown on ... | 43c40535cee37fc7349a21793dc33b1833735af5 | <|skeleton|>
class TestTopologicallySorted:
def test_Valid(self):
"""Test that sorting works on a valid graph with one possible order."""
<|body_0|>
def test_Cycle(self):
"""Test that an exception is thrown on a cyclic graph."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTopologicallySorted:
def test_Valid(self):
"""Test that sorting works on a valid graph with one possible order."""
graph = {'a': ['b', 'c'], 'b': [], 'c': ['d'], 'd': ['b']}
def GetEdge(node):
return tuple(graph[node])
self.assertEqual(gyp.common.TopologicallyS... | the_stack_v2_python_sparse | 3rdParty/V8/gyp/unit_tests/common_test.py | arangodb/arangodb | train | 13,385 | |
cc3e214361b80a633d1024dca83fc4ff313dbe6d | [
"super(BatchSoft, self).__init__()\nself.name = 'BatchSoft(m={}, T={})'.format(m, T)\nself.m = m\nself.T = T",
"n = inputs.size(0)\ndist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n)\ndist = dist + dist.t()\ndist.addmm_(1, -2, inputs, inputs.t())\ndist = dist.clamp(min=1e-12).sqrt()\nreturn batch_s... | <|body_start_0|>
super(BatchSoft, self).__init__()
self.name = 'BatchSoft(m={}, T={})'.format(m, T)
self.m = m
self.T = T
<|end_body_0|>
<|body_start_1|>
n = inputs.size(0)
dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(n, n)
dist = dist + dist.t()
... | BatchSoft implementation using softmax. Also by Tristani as Adaptivei Weighted Triplet Loss. | BatchSoft | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchSoft:
"""BatchSoft implementation using softmax. Also by Tristani as Adaptivei Weighted Triplet Loss."""
def __init__(self, m, T=1.0, **kwargs):
"""Args: m: margin T: Softmax temperature"""
<|body_0|>
def forward(self, inputs, targets):
"""Args: inputs: feat... | stack_v2_sparse_classes_36k_train_013112 | 11,471 | permissive | [
{
"docstring": "Args: m: margin T: Softmax temperature",
"name": "__init__",
"signature": "def __init__(self, m, T=1.0, **kwargs)"
},
{
"docstring": "Args: inputs: feature matrix with shape (batch_size, feat_dim) targets: ground truth labels with shape (num_classes)",
"name": "forward",
... | 2 | stack_v2_sparse_classes_30k_train_003052 | Implement the Python class `BatchSoft` described below.
Class description:
BatchSoft implementation using softmax. Also by Tristani as Adaptivei Weighted Triplet Loss.
Method signatures and docstrings:
- def __init__(self, m, T=1.0, **kwargs): Args: m: margin T: Softmax temperature
- def forward(self, inputs, targets... | Implement the Python class `BatchSoft` described below.
Class description:
BatchSoft implementation using softmax. Also by Tristani as Adaptivei Weighted Triplet Loss.
Method signatures and docstrings:
- def __init__(self, m, T=1.0, **kwargs): Args: m: margin T: Softmax temperature
- def forward(self, inputs, targets... | 61ee2c96611e10fe51a52033b1cd0e2804d544ca | <|skeleton|>
class BatchSoft:
"""BatchSoft implementation using softmax. Also by Tristani as Adaptivei Weighted Triplet Loss."""
def __init__(self, m, T=1.0, **kwargs):
"""Args: m: margin T: Softmax temperature"""
<|body_0|>
def forward(self, inputs, targets):
"""Args: inputs: feat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchSoft:
"""BatchSoft implementation using softmax. Also by Tristani as Adaptivei Weighted Triplet Loss."""
def __init__(self, m, T=1.0, **kwargs):
"""Args: m: margin T: Softmax temperature"""
super(BatchSoft, self).__init__()
self.name = 'BatchSoft(m={}, T={})'.format(m, T)
... | the_stack_v2_python_sparse | Video-Person-ReID/losses.py | anurag3/2019-CVPR-AIC-Track-2-UWIPL | train | 0 |
3d1c22737d65bacaaf96994fd73f364e47f1c2a9 | [
"if cls._driver is None:\n if browser_name == 'Chrome':\n cls._driver = webdriver.Chrome(driverPath['Chrome'])\n elif browser_name == 'Firefox':\n cls._driver = webdriver.Firefox(driverPath['Firefox'])\n cls._driver.maximize_window()\n cls._driver.get(URL)\n cls.__login()\nreturn cls._d... | <|body_start_0|>
if cls._driver is None:
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome(driverPath['Chrome'])
elif browser_name == 'Firefox':
cls._driver = webdriver.Firefox(driverPath['Firefox'])
cls._driver.maximize_window()
... | 浏览器驱动工具类 | Driver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
"""浏览器驱动工具类"""
def get_driver(cls, browser_name='Chrome'):
"""获取浏览器驱动对象 :param browser_name: :return:"""
<|body_0|>
def __login(cls):
"""私有方法,只能在类里边使用 类外部无法使用,子类不能继承 只在浏览器刚打开的时候登陆一次 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013113 | 1,598 | no_license | [
{
"docstring": "获取浏览器驱动对象 :param browser_name: :return:",
"name": "get_driver",
"signature": "def get_driver(cls, browser_name='Chrome')"
},
{
"docstring": "私有方法,只能在类里边使用 类外部无法使用,子类不能继承 只在浏览器刚打开的时候登陆一次 :return:",
"name": "__login",
"signature": "def __login(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021110 | Implement the Python class `Driver` described below.
Class description:
浏览器驱动工具类
Method signatures and docstrings:
- def get_driver(cls, browser_name='Chrome'): 获取浏览器驱动对象 :param browser_name: :return:
- def __login(cls): 私有方法,只能在类里边使用 类外部无法使用,子类不能继承 只在浏览器刚打开的时候登陆一次 :return: | Implement the Python class `Driver` described below.
Class description:
浏览器驱动工具类
Method signatures and docstrings:
- def get_driver(cls, browser_name='Chrome'): 获取浏览器驱动对象 :param browser_name: :return:
- def __login(cls): 私有方法,只能在类里边使用 类外部无法使用,子类不能继承 只在浏览器刚打开的时候登陆一次 :return:
<|skeleton|>
class Driver:
"""浏览器驱动工具类... | c777f2f8f532d58577e9f023db38a0d404c3a150 | <|skeleton|>
class Driver:
"""浏览器驱动工具类"""
def get_driver(cls, browser_name='Chrome'):
"""获取浏览器驱动对象 :param browser_name: :return:"""
<|body_0|>
def __login(cls):
"""私有方法,只能在类里边使用 类外部无法使用,子类不能继承 只在浏览器刚打开的时候登陆一次 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Driver:
"""浏览器驱动工具类"""
def get_driver(cls, browser_name='Chrome'):
"""获取浏览器驱动对象 :param browser_name: :return:"""
if cls._driver is None:
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome(driverPath['Chrome'])
elif browser_name == 'Firefox'... | the_stack_v2_python_sparse | day7/utils/myDriver.py | gongzuo666/pycharm.web | train | 0 |
ce1832913c59662bf039239a1c7c2b76d47c14db | [
"self._normalized_X = False\nself._readCommonHeader()\nself.DX = nappy.utils.text_parser.readItemsFromLine(self.file.readline(), self.NIV, float)\nif self.DX == 0:\n raise 'DX found to be zero (0). Not allowed for FFI 1020.'\nself.NVPM = nappy.utils.text_parser.readItemFromLine(self.file.readline(), int)\nself.X... | <|body_start_0|>
self._normalized_X = False
self._readCommonHeader()
self.DX = nappy.utils.text_parser.readItemsFromLine(self.file.readline(), self.NIV, float)
if self.DX == 0:
raise 'DX found to be zero (0). Not allowed for FFI 1020.'
self.NVPM = nappy.utils.text_par... | Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 1020. | NAFile1020 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NAFile1020:
"""Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 1020."""
def readHeader(self):
"""Reads FFI-specifc header section."""
<|body_0|>
def writeHeader(self):
"""Writes FFI-specifc header section."""
... | stack_v2_sparse_classes_36k_train_013114 | 4,367 | permissive | [
{
"docstring": "Reads FFI-specifc header section.",
"name": "readHeader",
"signature": "def readHeader(self)"
},
{
"docstring": "Writes FFI-specifc header section.",
"name": "writeHeader",
"signature": "def writeHeader(self)"
},
{
"docstring": "Reads second line/section (if used)... | 5 | stack_v2_sparse_classes_30k_train_021244 | Implement the Python class `NAFile1020` described below.
Class description:
Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 1020.
Method signatures and docstrings:
- def readHeader(self): Reads FFI-specifc header section.
- def writeHeader(self): Writes FFI-specifc hea... | Implement the Python class `NAFile1020` described below.
Class description:
Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 1020.
Method signatures and docstrings:
- def readHeader(self): Reads FFI-specifc header section.
- def writeHeader(self): Writes FFI-specifc hea... | 71e42a91112f52eef86183e35129b9ee2019e55b | <|skeleton|>
class NAFile1020:
"""Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 1020."""
def readHeader(self):
"""Reads FFI-specifc header section."""
<|body_0|>
def writeHeader(self):
"""Writes FFI-specifc header section."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NAFile1020:
"""Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 1020."""
def readHeader(self):
"""Reads FFI-specifc header section."""
self._normalized_X = False
self._readCommonHeader()
self.DX = nappy.utils.text_parser.read... | the_stack_v2_python_sparse | nappy/na_file/na_file_1020.py | cedadev/nappy | train | 9 |
0c7c692536dc5e58d65661314e16b826ad56779f | [
"self.object = self.get_object()\ncontractor = self.object\nif self.request.user.talenteditorprofile:\n editor = self.request.user.talenteditorprofile\n active_assignments = contractor.get_active_assignments()\n assignments_for_viewer = active_assignments.filter(editor=editor)\nelif self.request.user.contr... | <|body_start_0|>
self.object = self.get_object()
contractor = self.object
if self.request.user.talenteditorprofile:
editor = self.request.user.talenteditorprofile
active_assignments = contractor.get_active_assignments()
assignments_for_viewer = active_assignme... | Display details about a contractor. | ContractorDetailView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContractorDetailView:
"""Display details about a contractor."""
def contractor_assignments(self):
"""Get assignments that are relevant to requesting user."""
<|body_0|>
def contractor_pitches(self):
"""Get pitches that are relevant to requesting user."""
... | stack_v2_sparse_classes_36k_train_013115 | 28,644 | permissive | [
{
"docstring": "Get assignments that are relevant to requesting user.",
"name": "contractor_assignments",
"signature": "def contractor_assignments(self)"
},
{
"docstring": "Get pitches that are relevant to requesting user.",
"name": "contractor_pitches",
"signature": "def contractor_pitc... | 2 | stack_v2_sparse_classes_30k_train_002097 | Implement the Python class `ContractorDetailView` described below.
Class description:
Display details about a contractor.
Method signatures and docstrings:
- def contractor_assignments(self): Get assignments that are relevant to requesting user.
- def contractor_pitches(self): Get pitches that are relevant to request... | Implement the Python class `ContractorDetailView` described below.
Class description:
Display details about a contractor.
Method signatures and docstrings:
- def contractor_assignments(self): Get assignments that are relevant to requesting user.
- def contractor_pitches(self): Get pitches that are relevant to request... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class ContractorDetailView:
"""Display details about a contractor."""
def contractor_assignments(self):
"""Get assignments that are relevant to requesting user."""
<|body_0|>
def contractor_pitches(self):
"""Get pitches that are relevant to requesting user."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContractorDetailView:
"""Display details about a contractor."""
def contractor_assignments(self):
"""Get assignments that are relevant to requesting user."""
self.object = self.get_object()
contractor = self.object
if self.request.user.talenteditorprofile:
edit... | the_stack_v2_python_sparse | project/editorial/views/contractors.py | ProjectFacet/facet | train | 25 |
7eb0b028b8bfef155f0906a7048077cf40ade3f7 | [
"components_tab = self.driver.find_element(*BasePageLocators.COMPONENTS_TAB)\ncomponents_tab.click()\nreturn self",
"monitors = self.driver.find_element(*BasePageLocators.MONITORS)\nwait = WebDriverWait(self.driver, 10)\nwait.until(expected_conditions.element_to_be_clickable(BasePageLocators.MONITORS))\nmonitors.... | <|body_start_0|>
components_tab = self.driver.find_element(*BasePageLocators.COMPONENTS_TAB)
components_tab.click()
return self
<|end_body_0|>
<|body_start_1|>
monitors = self.driver.find_element(*BasePageLocators.MONITORS)
wait = WebDriverWait(self.driver, 10)
wait.unti... | NavBar | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NavBar:
def click_on_components_tab(self: object) -> object:
"""Click on components tab."""
<|body_0|>
def click_on_monitors(self: object) -> object:
"""Click on monitors in components tab dropdown list."""
<|body_1|>
def click_on_phones_tab(self: object... | stack_v2_sparse_classes_36k_train_013116 | 1,092 | permissive | [
{
"docstring": "Click on components tab.",
"name": "click_on_components_tab",
"signature": "def click_on_components_tab(self: object) -> object"
},
{
"docstring": "Click on monitors in components tab dropdown list.",
"name": "click_on_monitors",
"signature": "def click_on_monitors(self: ... | 3 | stack_v2_sparse_classes_30k_train_015438 | Implement the Python class `NavBar` described below.
Class description:
Implement the NavBar class.
Method signatures and docstrings:
- def click_on_components_tab(self: object) -> object: Click on components tab.
- def click_on_monitors(self: object) -> object: Click on monitors in components tab dropdown list.
- de... | Implement the Python class `NavBar` described below.
Class description:
Implement the NavBar class.
Method signatures and docstrings:
- def click_on_components_tab(self: object) -> object: Click on components tab.
- def click_on_monitors(self: object) -> object: Click on monitors in components tab dropdown list.
- de... | bcb10ac460b5acef3eeaee6ad7e72ba9933b6708 | <|skeleton|>
class NavBar:
def click_on_components_tab(self: object) -> object:
"""Click on components tab."""
<|body_0|>
def click_on_monitors(self: object) -> object:
"""Click on monitors in components tab dropdown list."""
<|body_1|>
def click_on_phones_tab(self: object... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NavBar:
def click_on_components_tab(self: object) -> object:
"""Click on components tab."""
components_tab = self.driver.find_element(*BasePageLocators.COMPONENTS_TAB)
components_tab.click()
return self
def click_on_monitors(self: object) -> object:
"""Click on mon... | the_stack_v2_python_sparse | elements/navbar.py | testsibirtsv/opncrt_courses_version | train | 0 | |
1db467157ad239b3c9beb55c344c33985510ecc6 | [
"dp = np.ones((m, n))\nfor i in xrange(1, m):\n for j in xrange(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nreturn int(dp[m - 1][n - 1])",
"dp = [[1 for i in xrange(n)] for j in xrange(m)]\nfor i in xrange(1, m):\n for j in xrange(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nreturn in... | <|body_start_0|>
dp = np.ones((m, n))
for i in xrange(1, m):
for j in xrange(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return int(dp[m - 1][n - 1])
<|end_body_0|>
<|body_start_1|>
dp = [[1 for i in xrange(n)] for j in xrange(m)]
for i in xrange(1,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = np.ones((m, n))
for i in... | stack_v2_sparse_classes_36k_train_013117 | 684 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001190 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
- def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int
<|skeleton|>
class Solution:
def uni... | 131fe3d622aa765a044fede9d38c9b3fbcd26966 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m, n):
""":type m: int :type n: int :rtype: int"""
dp = np.ones((m, n))
for i in xrange(1, m):
for j in xrange(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return int(dp[m - 1][n - 1])
def uniquePaths(self, m, n)... | the_stack_v2_python_sparse | leetcode/unique-paths.py | Vspick/python_interview | train | 0 | |
e8e135c5fd8f60fd73b098ab4af8e9ea58042b3d | [
"if not email:\n raise ValueError('The given email address must be set')\nemail = EmailUserManager.normalize_email(email)\nif not full_name:\n raise ValueError('You must provide a name for your account')\nuser = self.model(email=email, full_name=full_name, is_staff=False, is_active=True, **extra_fields)\nuser... | <|body_start_0|>
if not email:
raise ValueError('The given email address must be set')
email = EmailUserManager.normalize_email(email)
if not full_name:
raise ValueError('You must provide a name for your account')
user = self.model(email=email, full_name=full_name... | The user manager. | EmailUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailUserManager:
"""The user manager."""
def create_user(self, email, full_name, password=None, **extra_fields):
"""Create user override."""
<|body_0|>
def create_superuser(self, email, full_name, password, **extra_fields):
"""Create super user override."""
... | stack_v2_sparse_classes_36k_train_013118 | 1,160 | no_license | [
{
"docstring": "Create user override.",
"name": "create_user",
"signature": "def create_user(self, email, full_name, password=None, **extra_fields)"
},
{
"docstring": "Create super user override.",
"name": "create_superuser",
"signature": "def create_superuser(self, email, full_name, pas... | 2 | null | Implement the Python class `EmailUserManager` described below.
Class description:
The user manager.
Method signatures and docstrings:
- def create_user(self, email, full_name, password=None, **extra_fields): Create user override.
- def create_superuser(self, email, full_name, password, **extra_fields): Create super u... | Implement the Python class `EmailUserManager` described below.
Class description:
The user manager.
Method signatures and docstrings:
- def create_user(self, email, full_name, password=None, **extra_fields): Create user override.
- def create_superuser(self, email, full_name, password, **extra_fields): Create super u... | 5aed32be522142e7a03001800aceb148fd3fb5e8 | <|skeleton|>
class EmailUserManager:
"""The user manager."""
def create_user(self, email, full_name, password=None, **extra_fields):
"""Create user override."""
<|body_0|>
def create_superuser(self, email, full_name, password, **extra_fields):
"""Create super user override."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailUserManager:
"""The user manager."""
def create_user(self, email, full_name, password=None, **extra_fields):
"""Create user override."""
if not email:
raise ValueError('The given email address must be set')
email = EmailUserManager.normalize_email(email)
i... | the_stack_v2_python_sparse | risk/lib/user_manager.py | kdfwow64/django-angular | train | 0 |
5ed1acc307474ea9490bd0ea235a3d568a2c60c4 | [
"if n <= 0:\n return False\nreturn n & n - 1 == 0",
"if n == 1 or n == 2:\n return True\nelif n == 0:\n return False\nleft = n % 2\nif left:\n return False\nn = n / 2\nwhile n:\n if n == 2:\n return True\n left = n % 2\n if left:\n return False\n n = n / 2\nreturn True"
] | <|body_start_0|>
if n <= 0:
return False
return n & n - 1 == 0
<|end_body_0|>
<|body_start_1|>
if n == 1 or n == 2:
return True
elif n == 0:
return False
left = n % 2
if left:
return False
n = n / 2
while n:... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def _isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n <= 0:
return False
return n & n - 1 == ... | stack_v2_sparse_classes_36k_train_013119 | 1,163 | permissive | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo",
"signature": "def isPowerOfTwo(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "_isPowerOfTwo",
"signature": "def _isPowerOfTwo(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def _isPowerOfTwo(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def _isPowerOfTwo(self, n): :type n: int :rtype: bool
<|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def _isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n <= 0:
return False
return n & n - 1 == 0
def _isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n == 1 or n == 2:
return True
elif n == 0:
... | the_stack_v2_python_sparse | 231.power-of-two.py | windard/leeeeee | train | 0 | |
db7b07be21d0ad1b19a0a9acc7e5c95e4cd821cf | [
"tree = etree.parse(file)\nroot = tree.getroot()\nif not etree.iselement(root):\n sys.exit(\"Error while parsing '\" + file + \"' file.\\n\")\nfor node in root.findall('node'):\n self.parse_node(node)\nfor way in root.findall('way'):\n self.parse_way(way)\nfor relation in root.findall('relation'):\n sel... | <|body_start_0|>
tree = etree.parse(file)
root = tree.getroot()
if not etree.iselement(root):
sys.exit("Error while parsing '" + file + "' file.\n")
for node in root.findall('node'):
self.parse_node(node)
for way in root.findall('way'):
self.pa... | Parser of the OSM file. | Parser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser of the OSM file."""
def parse_file(self, file, disableMultipolygonBuildings=False):
"""Parse the OSM file."""
<|body_0|>
def get_tags(self, element):
"""Return a dictionnary of tags belonging to this element."""
<|body_1|>
def parse... | stack_v2_sparse_classes_36k_train_013120 | 6,805 | permissive | [
{
"docstring": "Parse the OSM file.",
"name": "parse_file",
"signature": "def parse_file(self, file, disableMultipolygonBuildings=False)"
},
{
"docstring": "Return a dictionnary of tags belonging to this element.",
"name": "get_tags",
"signature": "def get_tags(self, element)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_002490 | Implement the Python class `Parser` described below.
Class description:
Parser of the OSM file.
Method signatures and docstrings:
- def parse_file(self, file, disableMultipolygonBuildings=False): Parse the OSM file.
- def get_tags(self, element): Return a dictionnary of tags belonging to this element.
- def parse_nod... | Implement the Python class `Parser` described below.
Class description:
Parser of the OSM file.
Method signatures and docstrings:
- def parse_file(self, file, disableMultipolygonBuildings=False): Parse the OSM file.
- def get_tags(self, element): Return a dictionnary of tags belonging to this element.
- def parse_nod... | 8aba6eaae76989facf3442305c8089d3cc366bcf | <|skeleton|>
class Parser:
"""Parser of the OSM file."""
def parse_file(self, file, disableMultipolygonBuildings=False):
"""Parse the OSM file."""
<|body_0|>
def get_tags(self, element):
"""Return a dictionnary of tags belonging to this element."""
<|body_1|>
def parse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser of the OSM file."""
def parse_file(self, file, disableMultipolygonBuildings=False):
"""Parse the OSM file."""
tree = etree.parse(file)
root = tree.getroot()
if not etree.iselement(root):
sys.exit("Error while parsing '" + file + "' file.\n")
... | the_stack_v2_python_sparse | resources/osm_importer/parser_objects.py | cyberbotics/webots | train | 2,495 |
406a695068149c4bc87f611bf748e9c2fcabd7cc | [
"self.cap = capacity\nself.d = dict()\nself.li = list()",
"if key not in self.d:\n return -1\nidx = self.li.index(key)\ndel self.li[idx]\nself.li.insert(0, key)\nreturn self.d[key]",
"if self.cap < 1:\n return\nif key in self.d:\n idx = self.li.index(key)\n del self.li[idx]\nelif len(self.li) == sel... | <|body_start_0|>
self.cap = capacity
self.d = dict()
self.li = list()
<|end_body_0|>
<|body_start_1|>
if key not in self.d:
return -1
idx = self.li.index(key)
del self.li[idx]
self.li.insert(0, key)
return self.d[key]
<|end_body_1|>
<|body_st... | Design. Data Structure. Use a dictionary and a python list. Python list (array internally) is expensive with delete and insert. | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""Design. Data Structure. Use a dictionary and a python list. Python list (array internally) is expensive with delete and insert."""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""... | stack_v2_sparse_classes_36k_train_013121 | 9,208 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_val_000041 | Implement the Python class `LRUCache` described below.
Class description:
Design. Data Structure. Use a dictionary and a python list. Python list (array internally) is expensive with delete and insert.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type ke... | Implement the Python class `LRUCache` described below.
Class description:
Design. Data Structure. Use a dictionary and a python list. Python list (array internally) is expensive with delete and insert.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type ke... | d634941087bc51869f43c0d8044db09b7bdbaf58 | <|skeleton|>
class LRUCache:
"""Design. Data Structure. Use a dictionary and a python list. Python list (array internally) is expensive with delete and insert."""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
"""Design. Data Structure. Use a dictionary and a python list. Python list (array internally) is expensive with delete and insert."""
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.d = dict()
self.li = list()
def get(self, k... | the_stack_v2_python_sparse | 146_LRU_Cache.py | susunini/leetcode | train | 1 |
2cfa9d4c3428b074a35633f6ec0091d10e29f8a9 | [
"self.freqList = []\nself.maxPrecent = maxPercentage\nself.minPrecent = minPercentage\nself.bandwidth = bandwidth\nself.windowSize = windowSize\nfor i in range(int(windowSize)):\n self.freqList.append([])",
"print('Listening for RabbitMQ messages')\nconnection = pika.BlockingConnection(pika.ConnectionParameter... | <|body_start_0|>
self.freqList = []
self.maxPrecent = maxPercentage
self.minPrecent = minPercentage
self.bandwidth = bandwidth
self.windowSize = windowSize
for i in range(int(windowSize)):
self.freqList.append([])
<|end_body_0|>
<|body_start_1|>
print... | Detector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Detector:
def __init__(self, windowSize, maxPercentage, minPercentage, bandwidth):
"""Simple init method Args: windowSize (int): How many cycles to look through maxPercentage (float): min precentage needed to be considered a digital signal minPercentage ([type]): max precentage needed to... | stack_v2_sparse_classes_36k_train_013122 | 6,020 | no_license | [
{
"docstring": "Simple init method Args: windowSize (int): How many cycles to look through maxPercentage (float): min precentage needed to be considered a digital signal minPercentage ([type]): max precentage needed to be considered a digital signal bandwidth (int): How close do detects need to be in MHz to mer... | 5 | stack_v2_sparse_classes_30k_train_000595 | Implement the Python class `Detector` described below.
Class description:
Implement the Detector class.
Method signatures and docstrings:
- def __init__(self, windowSize, maxPercentage, minPercentage, bandwidth): Simple init method Args: windowSize (int): How many cycles to look through maxPercentage (float): min pre... | Implement the Python class `Detector` described below.
Class description:
Implement the Detector class.
Method signatures and docstrings:
- def __init__(self, windowSize, maxPercentage, minPercentage, bandwidth): Simple init method Args: windowSize (int): How many cycles to look through maxPercentage (float): min pre... | 30d4783e1102a6ff1de7ee14862ee40426e099ba | <|skeleton|>
class Detector:
def __init__(self, windowSize, maxPercentage, minPercentage, bandwidth):
"""Simple init method Args: windowSize (int): How many cycles to look through maxPercentage (float): min precentage needed to be considered a digital signal minPercentage ([type]): max precentage needed to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Detector:
def __init__(self, windowSize, maxPercentage, minPercentage, bandwidth):
"""Simple init method Args: windowSize (int): How many cycles to look through maxPercentage (float): min precentage needed to be considered a digital signal minPercentage ([type]): max precentage needed to be considered... | the_stack_v2_python_sparse | dev/digitalDetector/digitalDetector.py | ANARCYPHER/porglet | train | 0 | |
f203f5c2eb416da8d6cf490674520f0563f581b3 | [
"n = len(nums)\ndp = [False] * n\ndp[0] = nums[0] > 0\nfor i in range(1, n):\n for j in range(i):\n dp[i] |= dp[j] and j + nums[j] >= i\nreturn dp[n - 1]",
"n = len(nums)\nif n <= 1:\n return 0\ndp = [n] * n\ndp[0] = 0\nfor i in range(1, n):\n for j in range(i):\n if j + nums[j] >= i:\n ... | <|body_start_0|>
n = len(nums)
dp = [False] * n
dp[0] = nums[0] > 0
for i in range(1, n):
for j in range(i):
dp[i] |= dp[j] and j + nums[j] >= i
return dp[n - 1]
<|end_body_0|>
<|body_start_1|>
n = len(nums)
if n <= 1:
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def canReach(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"... | stack_v2_sparse_classes_36k_train_013123 | 1,988 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump",
"signature": "def canJump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type arr: List[int] :type start: int :rtyp... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def jump(self, nums): :type nums: List[int] :rtype: int
- def canReach(self, arr, start): :type arr: List[int] :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums): :type nums: List[int] :rtype: bool
- def jump(self, nums): :type nums: List[int] :rtype: int
- def canReach(self, arr, start): :type arr: List[int] :type... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def canReach(self, arr, start):
""":type arr: List[int] :type start: int :rtype: bool"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
n = len(nums)
dp = [False] * n
dp[0] = nums[0] > 0
for i in range(1, n):
for j in range(i):
dp[i] |= dp[j] and j + nums[j] >= i
return dp[n - 1]
def jump... | the_stack_v2_python_sparse | 2019/dynamic_programming/jump_game_55.py | yehongyu/acode | train | 0 | |
e7037a91662adf2b34678544f9388d55981cf87b | [
"soup = BeautifulSoup(response.content, 'html.parser')\nmenu_tag = soup.find_all(class_='post post-list-item')\nfor m in menu_tag:\n url = m.find('h2').find('a').get('href')\n if not url.startswith('http'):\n url = ''.join([self.domain, url])\n yield url",
"html = ''\ntry:\n soup = BeautifulSou... | <|body_start_0|>
soup = BeautifulSoup(response.content, 'html.parser')
menu_tag = soup.find_all(class_='post post-list-item')
for m in menu_tag:
url = m.find('h2').find('a').get('href')
if not url.startswith('http'):
url = ''.join([self.domain, url])
... | 虫师 | BugMasterPythonCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BugMasterPythonCrawler:
"""虫师"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response 爬虫返回的response对象 :return: url生成器"""
<|body_0|>
def parse_body(self, response):
"""解析正文 :param response: 爬虫返回的response对象 :return: 返回处理后的html文本"""
<|body_1... | stack_v2_sparse_classes_36k_train_013124 | 4,730 | no_license | [
{
"docstring": "解析目录结构,获取所有URL目录列表 :param response 爬虫返回的response对象 :return: url生成器",
"name": "parse_menu",
"signature": "def parse_menu(self, response)"
},
{
"docstring": "解析正文 :param response: 爬虫返回的response对象 :return: 返回处理后的html文本",
"name": "parse_body",
"signature": "def parse_body(sel... | 2 | stack_v2_sparse_classes_30k_train_010785 | Implement the Python class `BugMasterPythonCrawler` described below.
Class description:
虫师
Method signatures and docstrings:
- def parse_menu(self, response): 解析目录结构,获取所有URL目录列表 :param response 爬虫返回的response对象 :return: url生成器
- def parse_body(self, response): 解析正文 :param response: 爬虫返回的response对象 :return: 返回处理后的html文... | Implement the Python class `BugMasterPythonCrawler` described below.
Class description:
虫师
Method signatures and docstrings:
- def parse_menu(self, response): 解析目录结构,获取所有URL目录列表 :param response 爬虫返回的response对象 :return: url生成器
- def parse_body(self, response): 解析正文 :param response: 爬虫返回的response对象 :return: 返回处理后的html文... | 64cf3199b4740b83f909a54c937be3bbf26d25b8 | <|skeleton|>
class BugMasterPythonCrawler:
"""虫师"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response 爬虫返回的response对象 :return: url生成器"""
<|body_0|>
def parse_body(self, response):
"""解析正文 :param response: 爬虫返回的response对象 :return: 返回处理后的html文本"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BugMasterPythonCrawler:
"""虫师"""
def parse_menu(self, response):
"""解析目录结构,获取所有URL目录列表 :param response 爬虫返回的response对象 :return: url生成器"""
soup = BeautifulSoup(response.content, 'html.parser')
menu_tag = soup.find_all(class_='post post-list-item')
for m in menu_tag:
... | the_stack_v2_python_sparse | BugMaster.py | BruceZhu88/Script | train | 0 |
671967def9b726e5e14f91d1d3d546a7980cca24 | [
"User.objects.create(username='test', password='test', email='test@test.com')\nself.user = User.objects.get(username='test')\ntoken = Token.objects.get(user=self.user)\nself.client = APIClient()\nself.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)",
"url = reverse('me')\nresponse = self.client.get(ur... | <|body_start_0|>
User.objects.create(username='test', password='test', email='test@test.com')
self.user = User.objects.get(username='test')
token = Token.objects.get(user=self.user)
self.client = APIClient()
self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
<|end_b... | testing the account | AccountTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountTests:
"""testing the account"""
def setUp(self):
"""setup the enviroment"""
<|body_0|>
def test_me(self):
"""Ensure that a user can retrive his data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
User.objects.create(username='test', pas... | stack_v2_sparse_classes_36k_train_013125 | 13,107 | no_license | [
{
"docstring": "setup the enviroment",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Ensure that a user can retrive his data",
"name": "test_me",
"signature": "def test_me(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008505 | Implement the Python class `AccountTests` described below.
Class description:
testing the account
Method signatures and docstrings:
- def setUp(self): setup the enviroment
- def test_me(self): Ensure that a user can retrive his data | Implement the Python class `AccountTests` described below.
Class description:
testing the account
Method signatures and docstrings:
- def setUp(self): setup the enviroment
- def test_me(self): Ensure that a user can retrive his data
<|skeleton|>
class AccountTests:
"""testing the account"""
def setUp(self):... | 16f9d648398ed2ee2a42bee700d9fe869a7f7fdd | <|skeleton|>
class AccountTests:
"""testing the account"""
def setUp(self):
"""setup the enviroment"""
<|body_0|>
def test_me(self):
"""Ensure that a user can retrive his data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountTests:
"""testing the account"""
def setUp(self):
"""setup the enviroment"""
User.objects.create(username='test', password='test', email='test@test.com')
self.user = User.objects.get(username='test')
token = Token.objects.get(user=self.user)
self.client = AP... | the_stack_v2_python_sparse | api/tests.py | CrowdCafe/crowdcafe | train | 4 |
b00baeeea21f8769456e03bacbb89fed027f136c | [
"threading.Thread.__init__(self, name='cleaner')\nself.queues = queue\nself.date_time = date_time\nlname = '{}.{}'.format(__name__, 'clean')\nself._logger = logging.getLogger(lname)\nself._logger.debug('Initialized cleaner thread')",
"for t in self.date_time:\n for v in self.queues.keys():\n self.queues... | <|body_start_0|>
threading.Thread.__init__(self, name='cleaner')
self.queues = queue
self.date_time = date_time
lname = '{}.{}'.format(__name__, 'clean')
self._logger = logging.getLogger(lname)
self._logger.debug('Initialized cleaner thread')
<|end_body_0|>
<|body_start_... | QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it's not longer needed | QueueCleaner | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueueCleaner:
"""QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it's not longer needed"""
def __init__(self, date_time, queue):
"""Args: date_time: array of date_ti... | stack_v2_sparse_classes_36k_train_013126 | 9,600 | permissive | [
{
"docstring": "Args: date_time: array of date_time queue: dict of the queue",
"name": "__init__",
"signature": "def __init__(self, date_time, queue)"
},
{
"docstring": "Go through the date times and look for when all the queues have that date_time",
"name": "run",
"signature": "def run(... | 2 | stack_v2_sparse_classes_30k_train_021022 | Implement the Python class `QueueCleaner` described below.
Class description:
QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it's not longer needed
Method signatures and docstrings:
- def __init__(s... | Implement the Python class `QueueCleaner` described below.
Class description:
QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it's not longer needed
Method signatures and docstrings:
- def __init__(s... | 465d42cca85820e76a50bc311d101c7dc506df8c | <|skeleton|>
class QueueCleaner:
"""QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it's not longer needed"""
def __init__(self, date_time, queue):
"""Args: date_time: array of date_ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueueCleaner:
"""QueueCleaner that will go through all the queues and check if they all have a date in common. When this occurs, all the threads will have processed that time step and it's not longer needed"""
def __init__(self, date_time, queue):
"""Args: date_time: array of date_time queue: dic... | the_stack_v2_python_sparse | smrf/utils/queue.py | USDA-ARS-NWRC/smrf | train | 9 |
2dccf0b0872800c0edc25df19f551a9313e869d6 | [
"super(EnsembleHeteroscedasticRegression).__init__()\nself.config = config\nself.device = device\nself.verbose = verbose\nif model_type == 'ensembleheteroscedasticregression':\n self.model_type = model_type\n self.model = _Ensemble(num_models=self.config['num_models'], model_function=HeteroscedasticRegression... | <|body_start_0|>
super(EnsembleHeteroscedasticRegression).__init__()
self.config = config
self.device = device
self.verbose = verbose
if model_type == 'ensembleheteroscedasticregression':
self.model_type = model_type
self.model = _Ensemble(num_models=self.... | Ensemble Regression assumes an ensemble of models of Gaussian form for the predictive distribution and returns the mean and log variance of the ensemble of Gaussians. | EnsembleHeteroscedasticRegression | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnsembleHeteroscedasticRegression:
"""Ensemble Regression assumes an ensemble of models of Gaussian form for the predictive distribution and returns the mean and log variance of the ensemble of Gaussians."""
def __init__(self, model_type=None, config=None, device=None, verbose=True):
... | stack_v2_sparse_classes_36k_train_013127 | 5,698 | permissive | [
{
"docstring": "Initializer for Ensemble of heteroscedastic regression. Args: model_type: The base model used for predicting a quantile. Currently supported values are [heteroscedasticregression]. config: dictionary containing the config parameters for the model. device: device used for pytorch models ignored o... | 3 | stack_v2_sparse_classes_30k_test_000625 | Implement the Python class `EnsembleHeteroscedasticRegression` described below.
Class description:
Ensemble Regression assumes an ensemble of models of Gaussian form for the predictive distribution and returns the mean and log variance of the ensemble of Gaussians.
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `EnsembleHeteroscedasticRegression` described below.
Class description:
Ensemble Regression assumes an ensemble of models of Gaussian form for the predictive distribution and returns the mean and log variance of the ensemble of Gaussians.
Method signatures and docstrings:
- def __init__(sel... | 016f2023303e30f72fff755a1a97eca5d21d8a94 | <|skeleton|>
class EnsembleHeteroscedasticRegression:
"""Ensemble Regression assumes an ensemble of models of Gaussian form for the predictive distribution and returns the mean and log variance of the ensemble of Gaussians."""
def __init__(self, model_type=None, config=None, device=None, verbose=True):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnsembleHeteroscedasticRegression:
"""Ensemble Regression assumes an ensemble of models of Gaussian form for the predictive distribution and returns the mean and log variance of the ensemble of Gaussians."""
def __init__(self, model_type=None, config=None, device=None, verbose=True):
"""Initializ... | the_stack_v2_python_sparse | uq360/algorithms/ensemble_heteroscedastic_regression/ensemble_heteroscedastic_regression.py | anupamamurthi/UQ360 | train | 0 |
d8a06be246e308f5c1ff503bc83a9e40eb19be3b | [
"tdc_Fields_Plotter.__init__(self, (f_e, f_p, f_g, f_pr))\nself.plot_ylabel = '$n_{e,\\\\gamma,p}$'\nself.plot_idlabel = 'N_{e,p,g,p} : ' + self.data[0].calc_id\nif e_density_negative:\n self.e_sign = -1\nelse:\n self.e_sign = 1",
"self.lines[0], = ax.plot(self.data[0].x, self.e_sign * self.data[0].f, 'b', ... | <|body_start_0|>
tdc_Fields_Plotter.__init__(self, (f_e, f_p, f_g, f_pr))
self.plot_ylabel = '$n_{e,\\gamma,p}$'
self.plot_idlabel = 'N_{e,p,g,p} : ' + self.data[0].calc_id
if e_density_negative:
self.e_sign = -1
else:
self.e_sign = 1
<|end_body_0|>
<|bod... | This class is plotter for (e)lectron, (p)ositron, (g)amma-rays, (p)rotons number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label | tdc_EPGP_Density_Plotter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tdc_EPGP_Density_Plotter:
"""This class is plotter for (e)lectron, (p)ositron, (g)amma-rays, (p)rotons number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label"""
def __init__(self, f_e, f_p, f_g, f_pr, e_density_negative=True):
"""f_e --... | stack_v2_sparse_classes_36k_train_013128 | 5,286 | no_license | [
{
"docstring": "f_e -- field with electron number density f_p -- field with positron number density f_g -- field with gamma-ray number density f_pr -- field with protons number density e_density_negative -- <True> if true Electron density is negative",
"name": "__init__",
"signature": "def __init__(self... | 3 | null | Implement the Python class `tdc_EPGP_Density_Plotter` described below.
Class description:
This class is plotter for (e)lectron, (p)ositron, (g)amma-rays, (p)rotons number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `tdc_EPGP_Density_Plotter` described below.
Class description:
This class is plotter for (e)lectron, (p)ositron, (g)amma-rays, (p)rotons number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label
Method signatures and docstrings:
- def __init__(se... | 775dc841b1d8538584c8c68a5f75ae997191e685 | <|skeleton|>
class tdc_EPGP_Density_Plotter:
"""This class is plotter for (e)lectron, (p)ositron, (g)amma-rays, (p)rotons number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label"""
def __init__(self, f_e, f_p, f_g, f_pr, e_density_negative=True):
"""f_e --... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tdc_EPGP_Density_Plotter:
"""This class is plotter for (e)lectron, (p)ositron, (g)amma-rays, (p)rotons number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label"""
def __init__(self, f_e, f_p, f_g, f_pr, e_density_negative=True):
"""f_e -- field with e... | the_stack_v2_python_sparse | Fields/tdc_ep_density_plotter.py | atimokhin/tdc_vis | train | 0 |
22a95d052d6069f5ccb2bd60d93f52e335dbc054 | [
"self.b = big\nself.m = medium\nself.s = small",
"if carType == 1:\n self.b -= 1\n n = self.b\nelif carType == 2:\n self.m -= 1\n n = self.m\nelif carType == 3:\n self.s -= 1\n n = self.s\nreturn n >= 0"
] | <|body_start_0|>
self.b = big
self.m = medium
self.s = small
<|end_body_0|>
<|body_start_1|>
if carType == 1:
self.b -= 1
n = self.b
elif carType == 2:
self.m -= 1
n = self.m
elif carType == 3:
self.s -= 1
... | 感觉只需要三个数就可以满足要求了 每次入车,车辆上限减一即可 因为这个系统完全不成熟,也没有出车的函数,所以我也不考虑得那么完善 210319 | ParkingSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkingSystem:
"""感觉只需要三个数就可以满足要求了 每次入车,车辆上限减一即可 因为这个系统完全不成熟,也没有出车的函数,所以我也不考虑得那么完善 210319"""
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool""... | stack_v2_sparse_classes_36k_train_013129 | 1,001 | no_license | [
{
"docstring": ":type big: int :type medium: int :type small: int",
"name": "__init__",
"signature": "def __init__(self, big, medium, small)"
},
{
"docstring": ":type carType: int :rtype: bool",
"name": "addCar",
"signature": "def addCar(self, carType)"
}
] | 2 | null | Implement the Python class `ParkingSystem` described below.
Class description:
感觉只需要三个数就可以满足要求了 每次入车,车辆上限减一即可 因为这个系统完全不成熟,也没有出车的函数,所以我也不考虑得那么完善 210319
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carTyp... | Implement the Python class `ParkingSystem` described below.
Class description:
感觉只需要三个数就可以满足要求了 每次入车,车辆上限减一即可 因为这个系统完全不成熟,也没有出车的函数,所以我也不考虑得那么完善 210319
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carTyp... | 7167f1a7c6cb16cca63675c80037682752ee2a7d | <|skeleton|>
class ParkingSystem:
"""感觉只需要三个数就可以满足要求了 每次入车,车辆上限减一即可 因为这个系统完全不成熟,也没有出车的函数,所以我也不考虑得那么完善 210319"""
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParkingSystem:
"""感觉只需要三个数就可以满足要求了 每次入车,车辆上限减一即可 因为这个系统完全不成熟,也没有出车的函数,所以我也不考虑得那么完善 210319"""
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
self.b = big
self.m = medium
self.s = small
def addCar(self, carType):
... | the_stack_v2_python_sparse | Everyday/No1603.py | kikihiter/LeetCode2 | train | 4 |
65532ebeb459863d2e74e325a18907c3ed0c4cb6 | [
"super(FusionModule, self).__init__()\nself.fuse_embed_size = fuse_embed_size\nself.num_classes = class_size\nself.input_fc_size = input_fc_size\nself.q_net = qnetwork\nself.im_net = img_network\nself.embed_layer = nn.Linear(self.input_fc_size, self.fuse_embed_size)\nself.class_layer = nn.Linear(self.fuse_embed_siz... | <|body_start_0|>
super(FusionModule, self).__init__()
self.fuse_embed_size = fuse_embed_size
self.num_classes = class_size
self.input_fc_size = input_fc_size
self.q_net = qnetwork
self.im_net = img_network
self.embed_layer = nn.Linear(self.input_fc_size, self.fuse... | FusionModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FusionModule:
def __init__(self, qnetwork, img_network, fuse_embed_size=2048, input_fc_size=1024, class_size=3123, dropout_rate=0.2):
"""Module for fusing the mean pooled image features and lstm hidden states"""
<|body_0|>
def forward(self, sent_batch, image_batch):
... | stack_v2_sparse_classes_36k_train_013130 | 7,785 | no_license | [
{
"docstring": "Module for fusing the mean pooled image features and lstm hidden states",
"name": "__init__",
"signature": "def __init__(self, qnetwork, img_network, fuse_embed_size=2048, input_fc_size=1024, class_size=3123, dropout_rate=0.2)"
},
{
"docstring": "Forward pass of the Fusion module... | 2 | stack_v2_sparse_classes_30k_val_000214 | Implement the Python class `FusionModule` described below.
Class description:
Implement the FusionModule class.
Method signatures and docstrings:
- def __init__(self, qnetwork, img_network, fuse_embed_size=2048, input_fc_size=1024, class_size=3123, dropout_rate=0.2): Module for fusing the mean pooled image features a... | Implement the Python class `FusionModule` described below.
Class description:
Implement the FusionModule class.
Method signatures and docstrings:
- def __init__(self, qnetwork, img_network, fuse_embed_size=2048, input_fc_size=1024, class_size=3123, dropout_rate=0.2): Module for fusing the mean pooled image features a... | 9b8a7695b8919ecf8906f38137df6d52d6985dd4 | <|skeleton|>
class FusionModule:
def __init__(self, qnetwork, img_network, fuse_embed_size=2048, input_fc_size=1024, class_size=3123, dropout_rate=0.2):
"""Module for fusing the mean pooled image features and lstm hidden states"""
<|body_0|>
def forward(self, sent_batch, image_batch):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FusionModule:
def __init__(self, qnetwork, img_network, fuse_embed_size=2048, input_fc_size=1024, class_size=3123, dropout_rate=0.2):
"""Module for fusing the mean pooled image features and lstm hidden states"""
super(FusionModule, self).__init__()
self.fuse_embed_size = fuse_embed_siz... | the_stack_v2_python_sparse | Visual_All/models.py | nitaytech/VisualQuestion_VQA | train | 0 | |
43a91a5f9ccf7006d4cbbc4cf9333c00e92d4cac | [
"self.bands = []\nself.r95 = []\nfor bandlike in roi.selected:\n band = bandlike.band\n if band.emin < emin[band.event_type]:\n continue\n self.r95.append(np.radians(band.psf.inverse_integral(95, on_axis=False)))\n self.bands.append(band)",
"sd = skydir or SkyDir(Hep3Vector(v[0], v[1], v[2]))\n... | <|body_start_0|>
self.bands = []
self.r95 = []
for bandlike in roi.selected:
band = bandlike.band
if band.emin < emin[band.event_type]:
continue
self.r95.append(np.radians(band.psf.inverse_integral(95, on_axis=False)))
self.bands.ap... | Implement a SkyFunction that returns KDE data for a given ROI | KdeMap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KdeMap:
"""Implement a SkyFunction that returns KDE data for a given ROI"""
def __init__(self, roi, emin=[500, 1000], **kwargs):
"""roi: an ROIstat object emin: list of two minimum energies"""
<|body_0|>
def __call__(self, v, skydir=None):
"""copied from roi_tsma... | stack_v2_sparse_classes_36k_train_013131 | 24,274 | permissive | [
{
"docstring": "roi: an ROIstat object emin: list of two minimum energies",
"name": "__init__",
"signature": "def __init__(self, roi, emin=[500, 1000], **kwargs)"
},
{
"docstring": "copied from roi_tsmap.HealpixKDEMap",
"name": "__call__",
"signature": "def __call__(self, v, skydir=None)... | 2 | stack_v2_sparse_classes_30k_train_019687 | Implement the Python class `KdeMap` described below.
Class description:
Implement a SkyFunction that returns KDE data for a given ROI
Method signatures and docstrings:
- def __init__(self, roi, emin=[500, 1000], **kwargs): roi: an ROIstat object emin: list of two minimum energies
- def __call__(self, v, skydir=None):... | Implement the Python class `KdeMap` described below.
Class description:
Implement a SkyFunction that returns KDE data for a given ROI
Method signatures and docstrings:
- def __init__(self, roi, emin=[500, 1000], **kwargs): roi: an ROIstat object emin: list of two minimum energies
- def __call__(self, v, skydir=None):... | edcdc696c3300e2f26ff3efa92a1bd9790074247 | <|skeleton|>
class KdeMap:
"""Implement a SkyFunction that returns KDE data for a given ROI"""
def __init__(self, roi, emin=[500, 1000], **kwargs):
"""roi: an ROIstat object emin: list of two minimum energies"""
<|body_0|>
def __call__(self, v, skydir=None):
"""copied from roi_tsma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KdeMap:
"""Implement a SkyFunction that returns KDE data for a given ROI"""
def __init__(self, roi, emin=[500, 1000], **kwargs):
"""roi: an ROIstat object emin: list of two minimum energies"""
self.bands = []
self.r95 = []
for bandlike in roi.selected:
band = b... | the_stack_v2_python_sparse | python/uw/like2/maps.py | fermi-lat/pointlike | train | 1 |
7c8441d86da1cf129006a3190c237b99dd5a6af8 | [
"super(WeaveModel, self).__init__()\nself.update_pair = update_pair\nlayers = create_weave_layers(weave_args, update_pair)\nif weave_gath_arg:\n if weave_type.lower() == '1d':\n weave_gath = WeaveGather(*weave_gath_arg.args)\n else:\n weave_gath = WeaveGather2D(*weave_gath_arg, batch_first=batch... | <|body_start_0|>
super(WeaveModel, self).__init__()
self.update_pair = update_pair
layers = create_weave_layers(weave_args, update_pair)
if weave_gath_arg:
if weave_type.lower() == '1d':
weave_gath = WeaveGather(*weave_gath_arg.args)
else:
... | WeaveModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeaveModel:
def __init__(self, weave_args, weave_gath_arg, update_pair=False, weave_type='1D', batch_first=False):
"""Creates a weave model :param weave_args: A list of weave arguments. :param weave_gath_arg: A weave gather argument. :param update_pair: Whether to return the pair-wise em... | stack_v2_sparse_classes_36k_train_013132 | 27,873 | permissive | [
{
"docstring": "Creates a weave model :param weave_args: A list of weave arguments. :param weave_gath_arg: A weave gather argument. :param update_pair: Whether to return the pair-wise embeddings.",
"name": "__init__",
"signature": "def __init__(self, weave_args, weave_gath_arg, update_pair=False, weave_... | 2 | stack_v2_sparse_classes_30k_train_007197 | Implement the Python class `WeaveModel` described below.
Class description:
Implement the WeaveModel class.
Method signatures and docstrings:
- def __init__(self, weave_args, weave_gath_arg, update_pair=False, weave_type='1D', batch_first=False): Creates a weave model :param weave_args: A list of weave arguments. :pa... | Implement the Python class `WeaveModel` described below.
Class description:
Implement the WeaveModel class.
Method signatures and docstrings:
- def __init__(self, weave_args, weave_gath_arg, update_pair=False, weave_type='1D', batch_first=False): Creates a weave model :param weave_args: A list of weave arguments. :pa... | f1ddd11fd769c782c354425967c3cc326b9adf69 | <|skeleton|>
class WeaveModel:
def __init__(self, weave_args, weave_gath_arg, update_pair=False, weave_type='1D', batch_first=False):
"""Creates a weave model :param weave_args: A list of weave arguments. :param weave_gath_arg: A weave gather argument. :param update_pair: Whether to return the pair-wise em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeaveModel:
def __init__(self, weave_args, weave_gath_arg, update_pair=False, weave_type='1D', batch_first=False):
"""Creates a weave model :param weave_args: A list of weave arguments. :param weave_gath_arg: A weave gather argument. :param update_pair: Whether to return the pair-wise embeddings."""
... | the_stack_v2_python_sparse | jova/nn/models.py | bbrighttaer/jova_baselines | train | 2 | |
174ef5425da4c050a820da829e8e8bad350e1da7 | [
"CHOICES = ('dark', 'caramel', 'mint', 'surprise', 'stats', 'shutdown')\nchoice = 'dark'\nself.chocolate_machine = ChocolateMachine(CHOICES)\nself.selection = CHOCOLATE_CHOICES[choice]",
"d_raw_materials = {'sugar': 2, 'butter': 2, 'caramel': 15, 'dark chocolate': 30, 'mint chocolate': 30, 'milk chocolate': 30, '... | <|body_start_0|>
CHOICES = ('dark', 'caramel', 'mint', 'surprise', 'stats', 'shutdown')
choice = 'dark'
self.chocolate_machine = ChocolateMachine(CHOICES)
self.selection = CHOCOLATE_CHOICES[choice]
<|end_body_0|>
<|body_start_1|>
d_raw_materials = {'sugar': 2, 'butter': 2, 'cara... | Test class to test chocolate_machine module | TestChocolateMachine | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChocolateMachine:
"""Test class to test chocolate_machine module"""
def setUp(self):
"""setUp class"""
<|body_0|>
def test_stats(self):
"""test stats functionality"""
<|body_1|>
def test_has_raw_materials(self):
"""test has_raw_materials ... | stack_v2_sparse_classes_36k_train_013133 | 4,538 | permissive | [
{
"docstring": "setUp class",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test stats functionality",
"name": "test_stats",
"signature": "def test_stats(self)"
},
{
"docstring": "test has_raw_materials functionality",
"name": "test_has_raw_materials",
... | 5 | stack_v2_sparse_classes_30k_train_017221 | Implement the Python class `TestChocolateMachine` described below.
Class description:
Test class to test chocolate_machine module
Method signatures and docstrings:
- def setUp(self): setUp class
- def test_stats(self): test stats functionality
- def test_has_raw_materials(self): test has_raw_materials functionality
-... | Implement the Python class `TestChocolateMachine` described below.
Class description:
Test class to test chocolate_machine module
Method signatures and docstrings:
- def setUp(self): setUp class
- def test_stats(self): test stats functionality
- def test_has_raw_materials(self): test has_raw_materials functionality
-... | 3ad0990ee100d0dcf7a69a6851ce84ba262a6f5e | <|skeleton|>
class TestChocolateMachine:
"""Test class to test chocolate_machine module"""
def setUp(self):
"""setUp class"""
<|body_0|>
def test_stats(self):
"""test stats functionality"""
<|body_1|>
def test_has_raw_materials(self):
"""test has_raw_materials ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestChocolateMachine:
"""Test class to test chocolate_machine module"""
def setUp(self):
"""setUp class"""
CHOICES = ('dark', 'caramel', 'mint', 'surprise', 'stats', 'shutdown')
choice = 'dark'
self.chocolate_machine = ChocolateMachine(CHOICES)
self.selection = CHO... | the_stack_v2_python_sparse | Part_7_Unittest/p_0006_wonka_chocolate_machine/test_chocolate_machine.py | mytechnotalent/Python-For-Kids | train | 697 |
48f387761f965601f9d2a4bd424c58888e94faa1 | [
"context = responses.getUniversalContext(request)\ncontext['page_name'] = ugettext('Maintenance')\nnotice = context.pop('site_notice')\nif not notice:\n context['body_content'] = DEF_IN_UNEXPECTED_MAINTENANCE_MSG\nelse:\n context['body_content'] = notice\ncontext['header_title'] = DEF_DOWN_FOR_MAINTENANCE_MSG... | <|body_start_0|>
context = responses.getUniversalContext(request)
context['page_name'] = ugettext('Maintenance')
notice = context.pop('site_notice')
if not notice:
context['body_content'] = DEF_IN_UNEXPECTED_MAINTENANCE_MSG
else:
context['body_content'] = ... | Middleware to handle maintenance mode. | MaintenanceMiddleware | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaintenanceMiddleware:
"""Middleware to handle maintenance mode."""
def maintenance(self, request):
"""Returns a 'down for maintenance' view."""
<|body_0|>
def process_request(self, request):
"""Called when a request is made. See the Django middleware documentati... | stack_v2_sparse_classes_36k_train_013134 | 2,684 | permissive | [
{
"docstring": "Returns a 'down for maintenance' view.",
"name": "maintenance",
"signature": "def maintenance(self, request)"
},
{
"docstring": "Called when a request is made. See the Django middleware documentation for an explanation of the method signature.",
"name": "process_request",
... | 3 | null | Implement the Python class `MaintenanceMiddleware` described below.
Class description:
Middleware to handle maintenance mode.
Method signatures and docstrings:
- def maintenance(self, request): Returns a 'down for maintenance' view.
- def process_request(self, request): Called when a request is made. See the Django m... | Implement the Python class `MaintenanceMiddleware` described below.
Class description:
Middleware to handle maintenance mode.
Method signatures and docstrings:
- def maintenance(self, request): Returns a 'down for maintenance' view.
- def process_request(self, request): Called when a request is made. See the Django m... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class MaintenanceMiddleware:
"""Middleware to handle maintenance mode."""
def maintenance(self, request):
"""Returns a 'down for maintenance' view."""
<|body_0|>
def process_request(self, request):
"""Called when a request is made. See the Django middleware documentati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaintenanceMiddleware:
"""Middleware to handle maintenance mode."""
def maintenance(self, request):
"""Returns a 'down for maintenance' view."""
context = responses.getUniversalContext(request)
context['page_name'] = ugettext('Maintenance')
notice = context.pop('site_notic... | the_stack_v2_python_sparse | app/soc/middleware/maintenance.py | pombredanne/Melange-1 | train | 0 |
906a1e3892e0357f2acf7ba211648f4d981fbad0 | [
"print('start of making discretization abstraction')\nself.env = env\nself.space = env.observation_space\nself.finest_mesh = finest_mesh\nself.cell_to_abstract_cell = []\nself.n = self.space.shape\nself.ranges = self.space.high - self.space.low\nself.bucket_sizes = self.ranges / finest_mesh\nself.starting_group_siz... | <|body_start_0|>
print('start of making discretization abstraction')
self.env = env
self.space = env.observation_space
self.finest_mesh = finest_mesh
self.cell_to_abstract_cell = []
self.n = self.space.shape
self.ranges = self.space.high - self.space.low
s... | DiscretizationAbstraction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscretizationAbstraction:
def __init__(self, env, finest_mesh=1000, starting_mesh=10):
""":param env: the OpenAIGym environment :param finest_mesh: resolution of the finest mesh (applied along each dimension)"""
<|body_0|>
def get_abstr_from_ground(self, cell):
"""G... | stack_v2_sparse_classes_36k_train_013135 | 6,479 | no_license | [
{
"docstring": ":param env: the OpenAIGym environment :param finest_mesh: resolution of the finest mesh (applied along each dimension)",
"name": "__init__",
"signature": "def __init__(self, env, finest_mesh=1000, starting_mesh=10)"
},
{
"docstring": "Get the abstract state corresponding to the g... | 6 | null | Implement the Python class `DiscretizationAbstraction` described below.
Class description:
Implement the DiscretizationAbstraction class.
Method signatures and docstrings:
- def __init__(self, env, finest_mesh=1000, starting_mesh=10): :param env: the OpenAIGym environment :param finest_mesh: resolution of the finest ... | Implement the Python class `DiscretizationAbstraction` described below.
Class description:
Implement the DiscretizationAbstraction class.
Method signatures and docstrings:
- def __init__(self, env, finest_mesh=1000, starting_mesh=10): :param env: the OpenAIGym environment :param finest_mesh: resolution of the finest ... | c0adcd52fc90d9805fa2c148ac5f382c26035c05 | <|skeleton|>
class DiscretizationAbstraction:
def __init__(self, env, finest_mesh=1000, starting_mesh=10):
""":param env: the OpenAIGym environment :param finest_mesh: resolution of the finest mesh (applied along each dimension)"""
<|body_0|>
def get_abstr_from_ground(self, cell):
"""G... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscretizationAbstraction:
def __init__(self, env, finest_mesh=1000, starting_mesh=10):
""":param env: the OpenAIGym environment :param finest_mesh: resolution of the finest mesh (applied along each dimension)"""
print('start of making discretization abstraction')
self.env = env
... | the_stack_v2_python_sparse | MDP/DiscretizationAbstraction.py | AstronautCharlie/Real_Simple_RL | train | 1 | |
3529772f5f0d5a938dfb56da9dce974eb1930df3 | [
"globalsettings = sublime.load_settings('Preferences.sublime-settings')\nsettings = sublime.load_settings('AnacondaKite.sublime-settings')\nenabled = settings.get('integrate_with_kite', False)\nnot_ignored = 'Kite' not in globalsettings.get('ignored_packages')\nif enabled and not_ignored:\n try:\n from Ki... | <|body_start_0|>
globalsettings = sublime.load_settings('Preferences.sublime-settings')
settings = sublime.load_settings('AnacondaKite.sublime-settings')
enabled = settings.get('integrate_with_kite', False)
not_ignored = 'Kite' not in globalsettings.get('ignored_packages')
if ena... | Checks if Kite integration is turned on | Integration | [
"MIT",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-or-later",
"LGPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Integration:
"""Checks if Kite integration is turned on"""
def enabled(cls):
"""Returns True if Kite integration is enabled"""
<|body_0|>
def enable(cls):
"""Enable Kite integration"""
<|body_1|>
def disable(cls):
"""Disable Kite integration"... | stack_v2_sparse_classes_36k_train_013136 | 1,521 | permissive | [
{
"docstring": "Returns True if Kite integration is enabled",
"name": "enabled",
"signature": "def enabled(cls)"
},
{
"docstring": "Enable Kite integration",
"name": "enable",
"signature": "def enable(cls)"
},
{
"docstring": "Disable Kite integration",
"name": "disable",
... | 3 | stack_v2_sparse_classes_30k_train_010310 | Implement the Python class `Integration` described below.
Class description:
Checks if Kite integration is turned on
Method signatures and docstrings:
- def enabled(cls): Returns True if Kite integration is enabled
- def enable(cls): Enable Kite integration
- def disable(cls): Disable Kite integration | Implement the Python class `Integration` described below.
Class description:
Checks if Kite integration is turned on
Method signatures and docstrings:
- def enabled(cls): Returns True if Kite integration is enabled
- def enable(cls): Enable Kite integration
- def disable(cls): Disable Kite integration
<|skeleton|>
c... | 9a3808d0d79504b488a407084b489b9d687a528a | <|skeleton|>
class Integration:
"""Checks if Kite integration is turned on"""
def enabled(cls):
"""Returns True if Kite integration is enabled"""
<|body_0|>
def enable(cls):
"""Enable Kite integration"""
<|body_1|>
def disable(cls):
"""Disable Kite integration"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Integration:
"""Checks if Kite integration is turned on"""
def enabled(cls):
"""Returns True if Kite integration is enabled"""
globalsettings = sublime.load_settings('Preferences.sublime-settings')
settings = sublime.load_settings('AnacondaKite.sublime-settings')
enabled =... | the_stack_v2_python_sparse | sublime/Packages/Anaconda/anaconda_lib/kite.py | Kisura/dotfiles | train | 0 |
4f51ba70cd17e7ea066e3b74500aadc79888c259 | [
"form = ServiceForm()\nservice_obj = models.Services.objects.all().order_by('-id')\nowner_obj = models.User.objects.values('id', 'username')\nreturn render(request, 'host/service_line.html', {'form': form, 'service_obj': service_obj, 'owner_obj': owner_obj})",
"username = request.session.get('user_info')['usernam... | <|body_start_0|>
form = ServiceForm()
service_obj = models.Services.objects.all().order_by('-id')
owner_obj = models.User.objects.values('id', 'username')
return render(request, 'host/service_line.html', {'form': form, 'service_obj': service_obj, 'owner_obj': owner_obj})
<|end_body_0|>
... | 业务线视图函数 | ServiceLineView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceLineView:
"""业务线视图函数"""
def get(self, request, *args, **kwargs):
"""展示业务线信息 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""新建业务线 :param request: :param args: :param kwargs: :return:"""
... | stack_v2_sparse_classes_36k_train_013137 | 7,092 | no_license | [
{
"docstring": "展示业务线信息 :param request: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "新建业务线 :param request: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, request, *args... | 2 | stack_v2_sparse_classes_30k_train_012504 | Implement the Python class `ServiceLineView` described below.
Class description:
业务线视图函数
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 展示业务线信息 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 新建业务线 :param request: :param args: :param kwarg... | Implement the Python class `ServiceLineView` described below.
Class description:
业务线视图函数
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 展示业务线信息 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 新建业务线 :param request: :param args: :param kwarg... | 5ead7c54c73fc3a1ba02cd77d675997cf5c36e12 | <|skeleton|>
class ServiceLineView:
"""业务线视图函数"""
def get(self, request, *args, **kwargs):
"""展示业务线信息 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""新建业务线 :param request: :param args: :param kwargs: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceLineView:
"""业务线视图函数"""
def get(self, request, *args, **kwargs):
"""展示业务线信息 :param request: :param args: :param kwargs: :return:"""
form = ServiceForm()
service_obj = models.Services.objects.all().order_by('-id')
owner_obj = models.User.objects.values('id', 'usernam... | the_stack_v2_python_sparse | warship/host/views/service.py | shuke163/learnpy | train | 1 |
af65b2fe17ade874005a0b6044d809c3df058fb2 | [
"if not isinstance(rc, int):\n raise ValueError('rc is not a int')\nif not isinstance(data, dict):\n raise ValueError('data is not a dict')\nself.rc = rc\nself.data = data",
"return_code = -1\ndata = dict()\nlines = string.splitlines()\nfor line in lines:\n keyval = line.split(separator, 1)\n if len(k... | <|body_start_0|>
if not isinstance(rc, int):
raise ValueError('rc is not a int')
if not isinstance(data, dict):
raise ValueError('data is not a dict')
self.rc = rc
self.data = data
<|end_body_0|>
<|body_start_1|>
return_code = -1
data = dict()
... | CommandResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandResult:
def __init__(self, rc, data):
"""rc : (int) cmd return code data : (dict) key = value result"""
<|body_0|>
def parse(string, separator='='):
"""Parse command results with shape 'xxx = yyy' in a dict."""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_013138 | 9,033 | no_license | [
{
"docstring": "rc : (int) cmd return code data : (dict) key = value result",
"name": "__init__",
"signature": "def __init__(self, rc, data)"
},
{
"docstring": "Parse command results with shape 'xxx = yyy' in a dict.",
"name": "parse",
"signature": "def parse(string, separator='=')"
}
... | 2 | stack_v2_sparse_classes_30k_train_000764 | Implement the Python class `CommandResult` described below.
Class description:
Implement the CommandResult class.
Method signatures and docstrings:
- def __init__(self, rc, data): rc : (int) cmd return code data : (dict) key = value result
- def parse(string, separator='='): Parse command results with shape 'xxx = yy... | Implement the Python class `CommandResult` described below.
Class description:
Implement the CommandResult class.
Method signatures and docstrings:
- def __init__(self, rc, data): rc : (int) cmd return code data : (dict) key = value result
- def parse(string, separator='='): Parse command results with shape 'xxx = yy... | 971665b20dcd8d23ed75e09ee90972bde1aad333 | <|skeleton|>
class CommandResult:
def __init__(self, rc, data):
"""rc : (int) cmd return code data : (dict) key = value result"""
<|body_0|>
def parse(string, separator='='):
"""Parse command results with shape 'xxx = yyy' in a dict."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandResult:
def __init__(self, rc, data):
"""rc : (int) cmd return code data : (dict) key = value result"""
if not isinstance(rc, int):
raise ValueError('rc is not a int')
if not isinstance(data, dict):
raise ValueError('data is not a dict')
self.rc =... | the_stack_v2_python_sparse | framework/tools/device/Zoovstation.py | littlebuaa/legendarytest | train | 0 | |
675b60e927436b88eb72de5809c2ee400b92c27d | [
"request = None\nif self.context is not None and 'request' in self.context:\n request = self.context['request']\nif request is not None and (not request.user.is_anonymous):\n obj = mpmodels.Channel.objects.create_for_user(request.user, **validated_data)\nelse:\n obj = mpmodels.Channel.objects.create(**vali... | <|body_start_0|>
request = None
if self.context is not None and 'request' in self.context:
request = self.context['request']
if request is not None and (not request.user.is_anonymous):
obj = mpmodels.Channel.objects.create_for_user(request.user, **validated_data)
... | An individual channel. | ChannelSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelSerializer:
"""An individual channel."""
def create(self, validated_data):
"""Override behaviour when creating a new object using this serializer. If the current request is being passed in the context, give the request user edit and view permissions on the item."""
<|b... | stack_v2_sparse_classes_36k_train_013139 | 15,251 | permissive | [
{
"docstring": "Override behaviour when creating a new object using this serializer. If the current request is being passed in the context, give the request user edit and view permissions on the item.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Override... | 2 | null | Implement the Python class `ChannelSerializer` described below.
Class description:
An individual channel.
Method signatures and docstrings:
- def create(self, validated_data): Override behaviour when creating a new object using this serializer. If the current request is being passed in the context, give the request u... | Implement the Python class `ChannelSerializer` described below.
Class description:
An individual channel.
Method signatures and docstrings:
- def create(self, validated_data): Override behaviour when creating a new object using this serializer. If the current request is being passed in the context, give the request u... | 731bdd524c0a3b618586fea41aecca2a94486385 | <|skeleton|>
class ChannelSerializer:
"""An individual channel."""
def create(self, validated_data):
"""Override behaviour when creating a new object using this serializer. If the current request is being passed in the context, give the request user edit and view permissions on the item."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelSerializer:
"""An individual channel."""
def create(self, validated_data):
"""Override behaviour when creating a new object using this serializer. If the current request is being passed in the context, give the request user edit and view permissions on the item."""
request = None
... | the_stack_v2_python_sparse | api/serializers.py | uisautomation/media-webapp | train | 5 |
67d5253e4444423d987ef74c73fe5f5b1e7f34ae | [
"self.glat = [x.b() for x in b.wsdl]\nt = np.asarray([x.l() for x in b.wsdl])\nself.glon = np.where(t > 180, t - 360, t)\nself.npix = len(b.wsdl)\nself.size = 9000 / self.npix\nself.band = b\nself.roi_dir = roi_dir",
"assert len(val) == self.npix, 'length of array, %d, not same as number of pixels, %d' % (len(val... | <|body_start_0|>
self.glat = [x.b() for x in b.wsdl]
t = np.asarray([x.l() for x in b.wsdl])
self.glon = np.where(t > 180, t - 360, t)
self.npix = len(b.wsdl)
self.size = 9000 / self.npix
self.band = b
self.roi_dir = roi_dir
<|end_body_0|>
<|body_start_1|>
... | generate one or more plots of the pixels in an ROI | ROIplot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROIplot:
"""generate one or more plots of the pixels in an ROI"""
def __init__(self, b, roi_dir):
"""b: an ROIBand object, loaded from the bands property of an ROIAnalysis only need the wsdl array"""
<|body_0|>
def __call__(self, a, val, classname='', dataname='', **kwar... | stack_v2_sparse_classes_36k_train_013140 | 9,947 | permissive | [
{
"docstring": "b: an ROIBand object, loaded from the bands property of an ROIAnalysis only need the wsdl array",
"name": "__init__",
"signature": "def __init__(self, b, roi_dir)"
},
{
"docstring": "generate a color-coded scatter plot in galactic coordinates a: the Axes object to draw in val : a... | 2 | null | Implement the Python class `ROIplot` described below.
Class description:
generate one or more plots of the pixels in an ROI
Method signatures and docstrings:
- def __init__(self, b, roi_dir): b: an ROIBand object, loaded from the bands property of an ROIAnalysis only need the wsdl array
- def __call__(self, a, val, c... | Implement the Python class `ROIplot` described below.
Class description:
generate one or more plots of the pixels in an ROI
Method signatures and docstrings:
- def __init__(self, b, roi_dir): b: an ROIBand object, loaded from the bands property of an ROIAnalysis only need the wsdl array
- def __call__(self, a, val, c... | edcdc696c3300e2f26ff3efa92a1bd9790074247 | <|skeleton|>
class ROIplot:
"""generate one or more plots of the pixels in an ROI"""
def __init__(self, b, roi_dir):
"""b: an ROIBand object, loaded from the bands property of an ROIAnalysis only need the wsdl array"""
<|body_0|>
def __call__(self, a, val, classname='', dataname='', **kwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ROIplot:
"""generate one or more plots of the pixels in an ROI"""
def __init__(self, b, roi_dir):
"""b: an ROIBand object, loaded from the bands property of an ROIAnalysis only need the wsdl array"""
self.glat = [x.b() for x in b.wsdl]
t = np.asarray([x.l() for x in b.wsdl])
... | the_stack_v2_python_sparse | python/uw/like2/plotting/pixels.py | fermi-lat/pointlike | train | 1 |
faec893908b37d6999206cd72ff2761b35910d78 | [
"self.parameters_full = params\nself.parameters = params.running\nself.network = network\nself.data = data\nself.__prepare_to_run()",
"if self.parameters_full.use_horovod:\n if self.parameters_full.use_gpu:\n printout('size=', hvd.size(), 'global_rank=', hvd.rank(), 'local_rank=', hvd.local_rank(), 'dev... | <|body_start_0|>
self.parameters_full = params
self.parameters = params.running
self.network = network
self.data = data
self.__prepare_to_run()
<|end_body_0|>
<|body_start_1|>
if self.parameters_full.use_horovod:
if self.parameters_full.use_gpu:
... | Parent class for all classes that in some sense "run" the network. That can be training, benchmarking, inference, etc. | Runner | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Runner:
"""Parent class for all classes that in some sense "run" the network. That can be training, benchmarking, inference, etc."""
def __init__(self, params, network, data):
"""Create a Runner object to run a Network. Parameters ---------- params : mala.common.parametes.Parameters ... | stack_v2_sparse_classes_36k_train_013141 | 1,600 | permissive | [
{
"docstring": "Create a Runner object to run a Network. Parameters ---------- params : mala.common.parametes.Parameters Parameters used to create this Runner object. network : mala.network.network.Network Network which is being run. data : mala.datahandling.data_handler.DataHandler DataHandler holding the data... | 2 | stack_v2_sparse_classes_30k_train_004565 | Implement the Python class `Runner` described below.
Class description:
Parent class for all classes that in some sense "run" the network. That can be training, benchmarking, inference, etc.
Method signatures and docstrings:
- def __init__(self, params, network, data): Create a Runner object to run a Network. Paramet... | Implement the Python class `Runner` described below.
Class description:
Parent class for all classes that in some sense "run" the network. That can be training, benchmarking, inference, etc.
Method signatures and docstrings:
- def __init__(self, params, network, data): Create a Runner object to run a Network. Paramet... | 9cc771b0cdc4178c7f66fd717684658abbb0d95c | <|skeleton|>
class Runner:
"""Parent class for all classes that in some sense "run" the network. That can be training, benchmarking, inference, etc."""
def __init__(self, params, network, data):
"""Create a Runner object to run a Network. Parameters ---------- params : mala.common.parametes.Parameters ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Runner:
"""Parent class for all classes that in some sense "run" the network. That can be training, benchmarking, inference, etc."""
def __init__(self, params, network, data):
"""Create a Runner object to run a Network. Parameters ---------- params : mala.common.parametes.Parameters Parameters us... | the_stack_v2_python_sparse | mala/network/runner.py | icamps/mala | train | 0 |
0582fe1d0c3100afd8d4baa29f0fbca1dbf47097 | [
"super(GaussianEmbedder, self).__init__(name=name)\nself.embedder_mean = embedding_mean_layer\nself.embedder_logvar = embedding_logvar_layer\nself.sampling = Sampling()",
"z_mean = self.embedder_mean(inputs)\nif training:\n z_logvar = tf.nn.tanh(self.embedder_logvar(inputs)) * 10.0\n z = self.sampling((z_me... | <|body_start_0|>
super(GaussianEmbedder, self).__init__(name=name)
self.embedder_mean = embedding_mean_layer
self.embedder_logvar = embedding_logvar_layer
self.sampling = Sampling()
<|end_body_0|>
<|body_start_1|>
z_mean = self.embedder_mean(inputs)
if training:
... | Implements a Gaussian embedder. | GaussianEmbedder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianEmbedder:
"""Implements a Gaussian embedder."""
def __init__(self, embedding_mean_layer, embedding_logvar_layer, name=None):
"""Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_logvar_layer: A `tf.keras.Layer` object ... | stack_v2_sparse_classes_36k_train_013142 | 30,548 | permissive | [
{
"docstring": "Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_logvar_layer: A `tf.keras.Layer` object for the logvar of the embedding. name: A string for the name of the layer.",
"name": "__init__",
"signature": "def __init__(self, embedding_... | 2 | null | Implement the Python class `GaussianEmbedder` described below.
Class description:
Implements a Gaussian embedder.
Method signatures and docstrings:
- def __init__(self, embedding_mean_layer, embedding_logvar_layer, name=None): Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embe... | Implement the Python class `GaussianEmbedder` described below.
Class description:
Implements a Gaussian embedder.
Method signatures and docstrings:
- def __init__(self, embedding_mean_layer, embedding_logvar_layer, name=None): Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embe... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class GaussianEmbedder:
"""Implements a Gaussian embedder."""
def __init__(self, embedding_mean_layer, embedding_logvar_layer, name=None):
"""Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_logvar_layer: A `tf.keras.Layer` object ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianEmbedder:
"""Implements a Gaussian embedder."""
def __init__(self, embedding_mean_layer, embedding_logvar_layer, name=None):
"""Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_logvar_layer: A `tf.keras.Layer` object for the logva... | the_stack_v2_python_sparse | poem/cv_mim/models.py | Jimmy-INL/google-research | train | 1 |
88578b825407a1cf8d962d9ec6ddbdf1b1722472 | [
"self.node_ip_address = node_ip_address\nself.redis_client = redis.StrictRedis(host=redis_ip_address, port=redis_port)\nself.log_files = {}\nself.log_file_handles = {}",
"num_current_log_files = len(self.log_files)\nnew_log_filenames = self.redis_client.lrange('LOG_FILENAMES:{}'.format(self.node_ip_address), num_... | <|body_start_0|>
self.node_ip_address = node_ip_address
self.redis_client = redis.StrictRedis(host=redis_ip_address, port=redis_port)
self.log_files = {}
self.log_file_handles = {}
<|end_body_0|>
<|body_start_1|>
num_current_log_files = len(self.log_files)
new_log_filena... | A monitor process for monitoring Ray log files. Attributes: node_ip_address: The IP address of the node that the log monitor process is running on. This will be used to determine which log files to track. redis_client: A client used to communicate with the Redis server. log_filenames: A list of the names of the log fil... | LogMonitor | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogMonitor:
"""A monitor process for monitoring Ray log files. Attributes: node_ip_address: The IP address of the node that the log monitor process is running on. This will be used to determine which log files to track. redis_client: A client used to communicate with the Redis server. log_filenam... | stack_v2_sparse_classes_36k_train_013143 | 4,820 | permissive | [
{
"docstring": "Initialize the log monitor object.",
"name": "__init__",
"signature": "def __init__(self, redis_ip_address, redis_port, node_ip_address)"
},
{
"docstring": "Get the most up-to-date list of log files to monitor from Redis.",
"name": "update_log_filenames",
"signature": "de... | 4 | null | Implement the Python class `LogMonitor` described below.
Class description:
A monitor process for monitoring Ray log files. Attributes: node_ip_address: The IP address of the node that the log monitor process is running on. This will be used to determine which log files to track. redis_client: A client used to communi... | Implement the Python class `LogMonitor` described below.
Class description:
A monitor process for monitoring Ray log files. Attributes: node_ip_address: The IP address of the node that the log monitor process is running on. This will be used to determine which log files to track. redis_client: A client used to communi... | 8e333977e0991738558f4c8bb737da5fb29df0c6 | <|skeleton|>
class LogMonitor:
"""A monitor process for monitoring Ray log files. Attributes: node_ip_address: The IP address of the node that the log monitor process is running on. This will be used to determine which log files to track. redis_client: A client used to communicate with the Redis server. log_filenam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogMonitor:
"""A monitor process for monitoring Ray log files. Attributes: node_ip_address: The IP address of the node that the log monitor process is running on. This will be used to determine which log files to track. redis_client: A client used to communicate with the Redis server. log_filenames: A list of... | the_stack_v2_python_sparse | python/ray/log_monitor.py | cathywu/ray | train | 2 |
d399e0bb128610d03b40bebb7217c88931c6c54c | [
"super().__init__(parent)\nself.gui = parent.parent()\nQTimer.singleShot(200, self.style_me)",
"self.horizontalHeader().show()\nself.verticalHeader().hide()\nself.setAutoScroll(False)\nself.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)\nself.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)",
... | <|body_start_0|>
super().__init__(parent)
self.gui = parent.parent()
QTimer.singleShot(200, self.style_me)
<|end_body_0|>
<|body_start_1|>
self.horizontalHeader().show()
self.verticalHeader().hide()
self.setAutoScroll(False)
self.setVerticalScrollMode(QAbstractIt... | Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView | RightClickView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RightClickView:
"""Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView"""
def __init__(self, parent):
"""Provide access to GUI QMain... | stack_v2_sparse_classes_36k_train_013144 | 4,207 | permissive | [
{
"docstring": "Provide access to GUI QMainWindow via parent.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Style this widget.",
"name": "style_me",
"signature": "def style_me(self)"
},
{
"docstring": "Create options for drop-down context menu... | 6 | null | Implement the Python class `RightClickView` described below.
Class description:
Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView
Method signatures and docstrings:
... | Implement the Python class `RightClickView` described below.
Class description:
Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView
Method signatures and docstrings:
... | 24c58d192a576f25acb8d4208a92a317d0ebb2fd | <|skeleton|>
class RightClickView:
"""Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView"""
def __init__(self, parent):
"""Provide access to GUI QMain... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RightClickView:
"""Standard QTableView with drop-down context menu upon right-clicking. Menu allows for row deletion and renaming a cell. This class extends the `QTableView` class. Access: gui.variables_window.ui.tableView"""
def __init__(self, parent):
"""Provide access to GUI QMainWindow via pa... | the_stack_v2_python_sparse | qiskit_metal/_gui/widgets/variable_table/right_click_table_view.py | jessica-angel7/qiskit-metal | train | 1 |
4e04c0d4303024855ca3d8991ee648eb981ef413 | [
"self.BOX = box\nself.indexBOX = [box[ii] for ii in [0, 1, 2, 3]]\nif len(box) == 8:\n self.indexBOX = [box[ii] for ii in [0, 1, 2, 3, 6, 7]]\nself.fs_index = indexstore(self.cache, self.cachedir, os.path.sep.join([self.local_ftp, 'ar_index_global_prof.txt']))",
"if not hasattr(self, '_list_of_argo_files'):\n ... | <|body_start_0|>
self.BOX = box
self.indexBOX = [box[ii] for ii in [0, 1, 2, 3]]
if len(box) == 8:
self.indexBOX = [box[ii] for ii in [0, 1, 2, 3, 6, 7]]
self.fs_index = indexstore(self.cache, self.cachedir, os.path.sep.join([self.local_ftp, 'ar_index_global_prof.txt']))
<|en... | Manage access to local ftp Argo data for: a rectangular space/time domain | Fetch_box | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fetch_box:
"""Manage access to local ftp Argo data for: a rectangular space/time domain"""
def init(self, box: list):
"""Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_ma... | stack_v2_sparse_classes_36k_train_013145 | 21,335 | permissive | [
{
"docstring": "Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_max, lat_min, lat_max, pres_min, pres_max] - box = [lon_min, lon_max, lat_min, lat_max, pres_min, pres_max, datim_min, datim_max]",
... | 2 | stack_v2_sparse_classes_30k_train_014598 | Implement the Python class `Fetch_box` described below.
Class description:
Manage access to local ftp Argo data for: a rectangular space/time domain
Method signatures and docstrings:
- def init(self, box: list): Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with ... | Implement the Python class `Fetch_box` described below.
Class description:
Manage access to local ftp Argo data for: a rectangular space/time domain
Method signatures and docstrings:
- def init(self, box: list): Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with ... | a9e9375fde6d47506f65e8217d473ac03d4ab469 | <|skeleton|>
class Fetch_box:
"""Manage access to local ftp Argo data for: a rectangular space/time domain"""
def init(self, box: list):
"""Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fetch_box:
"""Manage access to local ftp Argo data for: a rectangular space/time domain"""
def init(self, box: list):
"""Create Argo data loader Parameters ---------- box : list() The box domain to load all Argo data for, with one of the following convention: - box = [lon_min, lon_max, lat_min, l... | the_stack_v2_python_sparse | argopy/data_fetchers/localftp_data.py | xeulha/argopy | train | 0 |
f0cd623056a2bb137ff21dcf8f159717f0f1d627 | [
"ans = []\nstart = 0\nfor p, group in itertools.groupby([n - v for n, v in enumerate(nums)]):\n interval = len(list(group))\n end = start + interval\n if interval == 1:\n ans.append(str(nums[start]))\n else:\n ans.append('{}->{}'.format(nums[start], nums[end - 1]))\n start = end\nreturn... | <|body_start_0|>
ans = []
start = 0
for p, group in itertools.groupby([n - v for n, v in enumerate(nums)]):
interval = len(list(group))
end = start + interval
if interval == 1:
ans.append(str(nums[start]))
else:
ans.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def summaryRanges_group(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_0|>
def summaryRanges_onepass(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []
... | stack_v2_sparse_classes_36k_train_013146 | 1,366 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[str]",
"name": "summaryRanges_group",
"signature": "def summaryRanges_group(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[str]",
"name": "summaryRanges_onepass",
"signature": "def summaryRanges_onepass(self, nums)"
... | 2 | stack_v2_sparse_classes_30k_train_020247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def summaryRanges_group(self, nums): :type nums: List[int] :rtype: List[str]
- def summaryRanges_onepass(self, nums): :type nums: List[int] :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def summaryRanges_group(self, nums): :type nums: List[int] :rtype: List[str]
- def summaryRanges_onepass(self, nums): :type nums: List[int] :rtype: List[str]
<|skeleton|>
class ... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def summaryRanges_group(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_0|>
def summaryRanges_onepass(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def summaryRanges_group(self, nums):
""":type nums: List[int] :rtype: List[str]"""
ans = []
start = 0
for p, group in itertools.groupby([n - v for n, v in enumerate(nums)]):
interval = len(list(group))
end = start + interval
if inte... | the_stack_v2_python_sparse | medium/arrayandstring/test_228_Summary_Ranges.py | wuxu1019/leetcode_sophia | train | 1 | |
095be8e95ef0c7d2a6a00e792fceb8794da8b0f0 | [
"k %= len(nums)\nself.reverse(nums, 0, len(nums) - 1)\nself.reverse(nums, 0, k - 1)\nself.reverse(nums, k, len(nums) - 1)",
"while start < end:\n temp = nums[start]\n nums[start] = nums[end]\n nums[end] = temp\n start += 1\n end -= 1"
] | <|body_start_0|>
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) - 1)
<|end_body_0|>
<|body_start_1|>
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = te... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k) -> None:
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space"""
<|body_0|>
def reverse(self, nums, start... | stack_v2_sparse_classes_36k_train_013147 | 2,000 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space",
"name": "rotate",
"signature": "def rotate(self, nums, k) -> None"
},
{
"docstring": ":type nu... | 2 | stack_v2_sparse_classes_30k_train_006663 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k) -> None: :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k) -> None: :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, ... | 237985eea9853a658f811355e8c75d6b141e40b2 | <|skeleton|>
class Solution:
def rotate(self, nums, k) -> None:
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space"""
<|body_0|>
def reverse(self, nums, start... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k) -> None:
""":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. First reverse all, then reverse first k, then reverse others O(n) time O(1) space"""
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)... | the_stack_v2_python_sparse | 189. Rotate Array.py | Eustaceyi/Leetcode | train | 0 | |
856c273390fe210765718ceeef8fb66c7425c810 | [
"currencies = Currency.all_currencies()\nserializer = CurrencySerializer(currencies, many=True, context={'request': request})\nreturn Response(serializer.data)",
"try:\n currency = Currency(code)\n serializer = CurrencySerializer(currency, context={'request': request})\n return Response(serializer.data)\... | <|body_start_0|>
currencies = Currency.all_currencies()
serializer = CurrencySerializer(currencies, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
try:
currency = Currency(code)
serializer = CurrencySeria... | View for currency | CurrencyViewset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrencyViewset:
"""View for currency"""
def list(self, request, *args, **kwargs):
"""List of currencies"""
<|body_0|>
def retrieve(self, request, code, *args, **kwargs) -> Response:
"""Retrieve single record based on iso4217 code"""
<|body_1|>
def g... | stack_v2_sparse_classes_36k_train_013148 | 6,227 | permissive | [
{
"docstring": "List of currencies",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Retrieve single record based on iso4217 code",
"name": "retrieve",
"signature": "def retrieve(self, request, code, *args, **kwargs) -> Response"
},
{
"d... | 5 | stack_v2_sparse_classes_30k_train_014535 | Implement the Python class `CurrencyViewset` described below.
Class description:
View for currency
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): List of currencies
- def retrieve(self, request, code, *args, **kwargs) -> Response: Retrieve single record based on iso4217 code
- def get_c... | Implement the Python class `CurrencyViewset` described below.
Class description:
View for currency
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): List of currencies
- def retrieve(self, request, code, *args, **kwargs) -> Response: Retrieve single record based on iso4217 code
- def get_c... | 00131739555438b6926caea7c5b237bb23b9848d | <|skeleton|>
class CurrencyViewset:
"""View for currency"""
def list(self, request, *args, **kwargs):
"""List of currencies"""
<|body_0|>
def retrieve(self, request, code, *args, **kwargs) -> Response:
"""Retrieve single record based on iso4217 code"""
<|body_1|>
def g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrencyViewset:
"""View for currency"""
def list(self, request, *args, **kwargs):
"""List of currencies"""
currencies = Currency.all_currencies()
serializer = CurrencySerializer(currencies, many=True, context={'request': request})
return Response(serializer.data)
def... | the_stack_v2_python_sparse | src/geocurrency/currencies/viewsets.py | comradekingu/geocurrency | train | 0 |
bc8d555cce6237665f01659f4f63dbbfee9636a2 | [
"if n_bits not in [8, 16, 32, 64]:\n raise ValueError('n_bits: {}: Must be 8, 16, 32 or 64.'.format(n_bits))\nif signed:\n self.max_value = 2 ** (n_bits - 1) - 1\n self.min_value = -self.max_value - 1\nelse:\n self.max_value = 2 ** n_bits - 1\n self.min_value = 0\nself.bytes_per_element = n_bits / 8\... | <|body_start_0|>
if n_bits not in [8, 16, 32, 64]:
raise ValueError('n_bits: {}: Must be 8, 16, 32 or 64.'.format(n_bits))
if signed:
self.max_value = 2 ** (n_bits - 1) - 1
self.min_value = -self.max_value - 1
else:
self.max_value = 2 ** n_bits - 1... | A callable which converts a lazy array of floats to fixed point General usage is to create a new converter and then call this on arrays of values. The `dtype` of the returned array is determined from the parameters passed. For example:: >>> f = LazyArrayFloatToFixConverter(signed=True, n_bits=8, n_frac=4) | LazyArrayFloatToFixConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazyArrayFloatToFixConverter:
"""A callable which converts a lazy array of floats to fixed point General usage is to create a new converter and then call this on arrays of values. The `dtype` of the returned array is determined from the parameters passed. For example:: >>> f = LazyArrayFloatToFix... | stack_v2_sparse_classes_36k_train_013149 | 10,760 | no_license | [
{
"docstring": "Create a new converter from floats into ints. Parameters ---------- signed : bool Indicates that the converted values are to be signed or otherwise. n_bits : int The number of bits each value will use overall (must be 8, 16, 32, or 64). n_frac : int The number of fractional bits. copy : bool Sho... | 2 | null | Implement the Python class `LazyArrayFloatToFixConverter` described below.
Class description:
A callable which converts a lazy array of floats to fixed point General usage is to create a new converter and then call this on arrays of values. The `dtype` of the returned array is determined from the parameters passed. Fo... | Implement the Python class `LazyArrayFloatToFixConverter` described below.
Class description:
A callable which converts a lazy array of floats to fixed point General usage is to create a new converter and then call this on arrays of values. The `dtype` of the returned array is determined from the parameters passed. Fo... | 89e9bdba78157804f491948bd3d630101d7b9cb6 | <|skeleton|>
class LazyArrayFloatToFixConverter:
"""A callable which converts a lazy array of floats to fixed point General usage is to create a new converter and then call this on arrays of values. The `dtype` of the returned array is determined from the parameters passed. For example:: >>> f = LazyArrayFloatToFix... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LazyArrayFloatToFixConverter:
"""A callable which converts a lazy array of floats to fixed point General usage is to create a new converter and then call this on arrays of values. The `dtype` of the returned array is determined from the parameters passed. For example:: >>> f = LazyArrayFloatToFixConverter(sig... | the_stack_v2_python_sparse | pynn_spinnaker/spinnaker/utils.py | project-rig/pynn_spinnaker | train | 0 |
44d160bd335180af752386c8ffa6662bacf81c5c | [
"self._dbg = debug\nself._log = get_logger(self.__class__.__name__, self._dbg)\nself._log.debug('server_host:server_port=%s:%s', server_host, server_port)\nself._log.debug('cmd=%s', cmd)\nself._server_host = server_host\nself._server_port = server_port\nself._cmd = cmd\nself._client = WsClientHostPort(self._server_... | <|body_start_0|>
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._log.debug('server_host:server_port=%s:%s', server_host, server_port)
self._log.debug('cmd=%s', cmd)
self._server_host = server_host
self._server_port = server_port
... | Music Box Websocket Client App for simple command | WsCmdApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WsCmdApp:
"""Music Box Websocket Client App for simple command"""
def __init__(self, server_host, server_port, cmd, debug=False):
"""Constructor Parameters ---------- server_host: str server_port: int cmd: str"""
<|body_0|>
def main(self):
"""main"""
<|bo... | stack_v2_sparse_classes_36k_train_013150 | 25,197 | no_license | [
{
"docstring": "Constructor Parameters ---------- server_host: str server_port: int cmd: str",
"name": "__init__",
"signature": "def __init__(self, server_host, server_port, cmd, debug=False)"
},
{
"docstring": "main",
"name": "main",
"signature": "def main(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021280 | Implement the Python class `WsCmdApp` described below.
Class description:
Music Box Websocket Client App for simple command
Method signatures and docstrings:
- def __init__(self, server_host, server_port, cmd, debug=False): Constructor Parameters ---------- server_host: str server_port: int cmd: str
- def main(self):... | Implement the Python class `WsCmdApp` described below.
Class description:
Music Box Websocket Client App for simple command
Method signatures and docstrings:
- def __init__(self, server_host, server_port, cmd, debug=False): Constructor Parameters ---------- server_host: str server_port: int cmd: str
- def main(self):... | b8264118d19c7f6c6be9b11f18c890c598eb1295 | <|skeleton|>
class WsCmdApp:
"""Music Box Websocket Client App for simple command"""
def __init__(self, server_host, server_port, cmd, debug=False):
"""Constructor Parameters ---------- server_host: str server_port: int cmd: str"""
<|body_0|>
def main(self):
"""main"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WsCmdApp:
"""Music Box Websocket Client App for simple command"""
def __init__(self, server_host, server_port, cmd, debug=False):
"""Constructor Parameters ---------- server_host: str server_port: int cmd: str"""
self._dbg = debug
self._log = get_logger(self.__class__.__name__, se... | the_stack_v2_python_sparse | musicbox/__main__.py | ytani01/MusicBox | train | 1 |
16f9664f34326755cc256a0606a3f32728fae5f3 | [
"input1 = tf.keras.Input(shape=(64, 16, 4), batch_size=1)\ninput2 = tf.keras.Input(shape=(2, 64, 16, 4), batch_size=1)\ninput3 = tf.keras.Input(shape=(None, None, None, 1), batch_size=1)\nlayer1 = preproc_layers.ResizeWithCropOrPad(shape=[32, 32])\nlayer2 = preproc_layers.ResizeWithCropOrPad(shape=[64, 64, 64])\nou... | <|body_start_0|>
input1 = tf.keras.Input(shape=(64, 16, 4), batch_size=1)
input2 = tf.keras.Input(shape=(2, 64, 16, 4), batch_size=1)
input3 = tf.keras.Input(shape=(None, None, None, 1), batch_size=1)
layer1 = preproc_layers.ResizeWithCropOrPad(shape=[32, 32])
layer2 = preproc_la... | Tests for layer `ResizeWithCropOrPad`. | ResizeWithCropOrPadTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResizeWithCropOrPadTest:
"""Tests for layer `ResizeWithCropOrPad`."""
def test_output_shapes(self):
"""Test output shapes."""
<|body_0|>
def test_serialize_deserialize(self):
"""Test de/serialization."""
<|body_1|>
def _assert_static_shape(self, fn, ... | stack_v2_sparse_classes_36k_train_013151 | 6,474 | permissive | [
{
"docstring": "Test output shapes.",
"name": "test_output_shapes",
"signature": "def test_output_shapes(self)"
},
{
"docstring": "Test de/serialization.",
"name": "test_serialize_deserialize",
"signature": "def test_serialize_deserialize(self)"
},
{
"docstring": "Asserts that fu... | 3 | stack_v2_sparse_classes_30k_train_021175 | Implement the Python class `ResizeWithCropOrPadTest` described below.
Class description:
Tests for layer `ResizeWithCropOrPad`.
Method signatures and docstrings:
- def test_output_shapes(self): Test output shapes.
- def test_serialize_deserialize(self): Test de/serialization.
- def _assert_static_shape(self, fn, inpu... | Implement the Python class `ResizeWithCropOrPadTest` described below.
Class description:
Tests for layer `ResizeWithCropOrPad`.
Method signatures and docstrings:
- def test_output_shapes(self): Test output shapes.
- def test_serialize_deserialize(self): Test de/serialization.
- def _assert_static_shape(self, fn, inpu... | cfd8930ee5281e7f6dceb17c4a5acaf625fd3243 | <|skeleton|>
class ResizeWithCropOrPadTest:
"""Tests for layer `ResizeWithCropOrPad`."""
def test_output_shapes(self):
"""Test output shapes."""
<|body_0|>
def test_serialize_deserialize(self):
"""Test de/serialization."""
<|body_1|>
def _assert_static_shape(self, fn, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResizeWithCropOrPadTest:
"""Tests for layer `ResizeWithCropOrPad`."""
def test_output_shapes(self):
"""Test output shapes."""
input1 = tf.keras.Input(shape=(64, 16, 4), batch_size=1)
input2 = tf.keras.Input(shape=(2, 64, 16, 4), batch_size=1)
input3 = tf.keras.Input(shape=... | the_stack_v2_python_sparse | tensorflow_mri/python/layers/preproc_layers_test.py | mrphys/tensorflow-mri | train | 29 |
bf87611ddb9cb181b40e10937d0c7dd9e34a7b42 | [
"self.sheet = Resources().ROCKET_SHEET\nself.sheet.set_clip(Rect(0, 0, 55, 103))\nself.elevation = 0\nself.frames = Constants.ROCKET_FRAMES\nsuper().__init__(position, self.sheet, *groups)",
"if self.rect.right > Constants.WINDOW_WIDTH:\n self.rect.right = Constants.WINDOW_WIDTH\nif self.rect.left < 0:\n se... | <|body_start_0|>
self.sheet = Resources().ROCKET_SHEET
self.sheet.set_clip(Rect(0, 0, 55, 103))
self.elevation = 0
self.frames = Constants.ROCKET_FRAMES
super().__init__(position, self.sheet, *groups)
<|end_body_0|>
<|body_start_1|>
if self.rect.right > Constants.WINDOW_... | The player sprite. | Rocket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rocket:
"""The player sprite."""
def __init__(self, position, *groups):
"""Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Grou... | stack_v2_sparse_classes_36k_train_013152 | 1,332 | no_license | [
{
"docstring": "Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Group or GroupSingle",
"name": "__init__",
"signature": "def __init__(self, positio... | 2 | stack_v2_sparse_classes_30k_train_015389 | Implement the Python class `Rocket` described below.
Class description:
The player sprite.
Method signatures and docstrings:
- def __init__(self, position, *groups): Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param g... | Implement the Python class `Rocket` described below.
Class description:
The player sprite.
Method signatures and docstrings:
- def __init__(self, position, *groups): Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param g... | fd6ceca39b4395daed165753cac7bb6cbfb2b485 | <|skeleton|>
class Rocket:
"""The player sprite."""
def __init__(self, position, *groups):
"""Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Grou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rocket:
"""The player sprite."""
def __init__(self, position, *groups):
"""Set the base variables specific to the Rocket, set up as an animated sprite. :param position: the starting position of the sprite. :type: tuple :param groups: the groups that the sprite belongs to. :type: Group or GroupSin... | the_stack_v2_python_sparse | src/playerSprite.py | logiczsniper/TakeOff-Revisited | train | 3 |
ea7b5e46017a612f3f18889cbd7ab408db080af2 | [
"include_2D_map = self.get_query_argument('include2DMap', False)\nlocalization = Localization.query_records_accessible_by(self.current_user).filter(Localization.dateobs == dateobs, Localization.localization_name == localization_name).first()\nif localization is None:\n return self.error('Localization not found',... | <|body_start_0|>
include_2D_map = self.get_query_argument('include2DMap', False)
localization = Localization.query_records_accessible_by(self.current_user).filter(Localization.dateobs == dateobs, Localization.localization_name == localization_name).first()
if localization is None:
re... | LocalizationHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalizationHandler:
def get(self, dateobs, localization_name):
"""--- description: Retrieve a GCN localization tags: - localizations parameters: - in: path name: dateobs required: true schema: type: dateobs - in: path name: localization_name required: true schema: type: localization_nam... | stack_v2_sparse_classes_36k_train_013153 | 12,885 | permissive | [
{
"docstring": "--- description: Retrieve a GCN localization tags: - localizations parameters: - in: path name: dateobs required: true schema: type: dateobs - in: path name: localization_name required: true schema: type: localization_name - in: query name: include2DMap nullable: true schema: type: boolean descr... | 2 | stack_v2_sparse_classes_30k_train_013526 | Implement the Python class `LocalizationHandler` described below.
Class description:
Implement the LocalizationHandler class.
Method signatures and docstrings:
- def get(self, dateobs, localization_name): --- description: Retrieve a GCN localization tags: - localizations parameters: - in: path name: dateobs required:... | Implement the Python class `LocalizationHandler` described below.
Class description:
Implement the LocalizationHandler class.
Method signatures and docstrings:
- def get(self, dateobs, localization_name): --- description: Retrieve a GCN localization tags: - localizations parameters: - in: path name: dateobs required:... | 2433d5ae0b2f41faac3c76ed4ae8d9a4da5522fb | <|skeleton|>
class LocalizationHandler:
def get(self, dateobs, localization_name):
"""--- description: Retrieve a GCN localization tags: - localizations parameters: - in: path name: dateobs required: true schema: type: dateobs - in: path name: localization_name required: true schema: type: localization_nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalizationHandler:
def get(self, dateobs, localization_name):
"""--- description: Retrieve a GCN localization tags: - localizations parameters: - in: path name: dateobs required: true schema: type: dateobs - in: path name: localization_name required: true schema: type: localization_name - in: query ... | the_stack_v2_python_sparse | skyportal/handlers/api/gcn.py | dmitryduev/skyportal | train | 1 | |
53e1c8f514b7a3240161d79ae86be9a9fdb66f44 | [
"self.conf = VConf()\nurl = self.conf.get_http('okex')\napikey = self.conf.get_apikey('okex', account)\napisecret = self.conf.get_secret('okex', account)\nsuper(ExchangeOkex, self).__init__(url, apikey, apisecret)\nself.exch_account = account\nself.contract_types = ['this_week', 'next_week', 'quarter']\nself.stat_o... | <|body_start_0|>
self.conf = VConf()
url = self.conf.get_http('okex')
apikey = self.conf.get_apikey('okex', account)
apisecret = self.conf.get_secret('okex', account)
super(ExchangeOkex, self).__init__(url, apikey, apisecret)
self.exch_account = account
self.contr... | 获取OKEX账户的持仓和价格 bb0: 币币权益部分 ft1: 合约权益部分 ft2: 合约持仓部分 | ExchangeOkex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeOkex:
"""获取OKEX账户的持仓和价格 bb0: 币币权益部分 ft1: 合约权益部分 ft2: 合约持仓部分"""
def __init__(self, account='Kevin.wang@126.com'):
"""只接受单账户的传入,多账户下需外部进行遍历"""
<|body_0|>
def bb0(self):
"""获取OKEX的币币权益 没有币种不做 持仓量低不做 权益数低不做"""
<|body_1|>
def ft1(self):
""... | stack_v2_sparse_classes_36k_train_013154 | 11,867 | no_license | [
{
"docstring": "只接受单账户的传入,多账户下需外部进行遍历",
"name": "__init__",
"signature": "def __init__(self, account='Kevin.wang@126.com')"
},
{
"docstring": "获取OKEX的币币权益 没有币种不做 持仓量低不做 权益数低不做",
"name": "bb0",
"signature": "def bb0(self)"
},
{
"docstring": "获取OKEX的合约权益",
"name": "ft1",
"s... | 4 | null | Implement the Python class `ExchangeOkex` described below.
Class description:
获取OKEX账户的持仓和价格 bb0: 币币权益部分 ft1: 合约权益部分 ft2: 合约持仓部分
Method signatures and docstrings:
- def __init__(self, account='Kevin.wang@126.com'): 只接受单账户的传入,多账户下需外部进行遍历
- def bb0(self): 获取OKEX的币币权益 没有币种不做 持仓量低不做 权益数低不做
- def ft1(self): 获取OKEX的合约权益
- ... | Implement the Python class `ExchangeOkex` described below.
Class description:
获取OKEX账户的持仓和价格 bb0: 币币权益部分 ft1: 合约权益部分 ft2: 合约持仓部分
Method signatures and docstrings:
- def __init__(self, account='Kevin.wang@126.com'): 只接受单账户的传入,多账户下需外部进行遍历
- def bb0(self): 获取OKEX的币币权益 没有币种不做 持仓量低不做 权益数低不做
- def ft1(self): 获取OKEX的合约权益
- ... | aa340b640fdc280b599974ea0e6af9fd1a4935e3 | <|skeleton|>
class ExchangeOkex:
"""获取OKEX账户的持仓和价格 bb0: 币币权益部分 ft1: 合约权益部分 ft2: 合约持仓部分"""
def __init__(self, account='Kevin.wang@126.com'):
"""只接受单账户的传入,多账户下需外部进行遍历"""
<|body_0|>
def bb0(self):
"""获取OKEX的币币权益 没有币种不做 持仓量低不做 权益数低不做"""
<|body_1|>
def ft1(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExchangeOkex:
"""获取OKEX账户的持仓和价格 bb0: 币币权益部分 ft1: 合约权益部分 ft2: 合约持仓部分"""
def __init__(self, account='Kevin.wang@126.com'):
"""只接受单账户的传入,多账户下需外部进行遍历"""
self.conf = VConf()
url = self.conf.get_http('okex')
apikey = self.conf.get_apikey('okex', account)
apisecret = self... | the_stack_v2_python_sparse | 20180920持仓统计/BW2_BASE_DATA.py | 3123958139/20180920hwjj | train | 0 |
5ba2fe8332f07253dd137918426f1b1a92201894 | [
"self.train_x = train_x\nself.train_class = train_class\nreturn",
"pred_class = np.zeros(x_data.shape[0])\nfor i, x in enumerate(x_data):\n distancesq = ((x - self.train_x) ** 2).sum(axis=1)\n nn_ind = np.argsort(distancesq)[:k_neighbors]\n nn_class, counts = np.unique(self.train_class[nn_ind], return_co... | <|body_start_0|>
self.train_x = train_x
self.train_class = train_class
return
<|end_body_0|>
<|body_start_1|>
pred_class = np.zeros(x_data.shape[0])
for i, x in enumerate(x_data):
distancesq = ((x - self.train_x) ** 2).sum(axis=1)
nn_ind = np.argsort(dist... | KNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNN:
def __init__(self, train_x, train_class):
"""Initialize the data set that classification will be based on."""
<|body_0|>
def predict(self, x_data, k_neighbors):
"""Find the nearest k-neighbors and classify the new set of data points."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_013155 | 925 | no_license | [
{
"docstring": "Initialize the data set that classification will be based on.",
"name": "__init__",
"signature": "def __init__(self, train_x, train_class)"
},
{
"docstring": "Find the nearest k-neighbors and classify the new set of data points.",
"name": "predict",
"signature": "def pred... | 2 | stack_v2_sparse_classes_30k_train_007582 | Implement the Python class `KNN` described below.
Class description:
Implement the KNN class.
Method signatures and docstrings:
- def __init__(self, train_x, train_class): Initialize the data set that classification will be based on.
- def predict(self, x_data, k_neighbors): Find the nearest k-neighbors and classify ... | Implement the Python class `KNN` described below.
Class description:
Implement the KNN class.
Method signatures and docstrings:
- def __init__(self, train_x, train_class): Initialize the data set that classification will be based on.
- def predict(self, x_data, k_neighbors): Find the nearest k-neighbors and classify ... | 6cd204abbc074734fb7e8ca0e693a15e1cbe4ede | <|skeleton|>
class KNN:
def __init__(self, train_x, train_class):
"""Initialize the data set that classification will be based on."""
<|body_0|>
def predict(self, x_data, k_neighbors):
"""Find the nearest k-neighbors and classify the new set of data points."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KNN:
def __init__(self, train_x, train_class):
"""Initialize the data set that classification will be based on."""
self.train_x = train_x
self.train_class = train_class
return
def predict(self, x_data, k_neighbors):
"""Find the nearest k-neighbors and classify the ... | the_stack_v2_python_sparse | EE565/Project1_GarciaJ/codes/requiredFunctions/kNearestNeighbors.py | JorgeAGR/nmsu-course-work | train | 0 | |
fd571fc7ed2ddc7eccb0912c9e5eef2f75887f74 | [
"n = len(envelopes)\nif n == 0 or n == 1:\n return n\nenvelopes = sorted(envelopes, key=lambda x: x[0])\nstack = []\ntmp_y_list = []\ntmp_x = envelopes[0][0]\nfor x, y in envelopes:\n if x > tmp_x:\n stack = _search(stack, tmp_y_list)\n print(stack)\n tmp_y_list = [y]\n tmp_x = x\n... | <|body_start_0|>
n = len(envelopes)
if n == 0 or n == 1:
return n
envelopes = sorted(envelopes, key=lambda x: x[0])
stack = []
tmp_y_list = []
tmp_x = envelopes[0][0]
for x, y in envelopes:
if x > tmp_x:
stack = _search(stac... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes1(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(en... | stack_v2_sparse_classes_36k_train_013156 | 2,326 | no_license | [
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes",
"signature": "def maxEnvelopes(self, envelopes)"
},
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes1",
"signature": "def maxEnvelopes1(self, envelopes)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes1(self, envelopes): :type envelopes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes1(self, envelopes): :type envelopes: List[List[int]] :rtype: int
<|skeleton|>
c... | c9fb0b623501b3746444b05da55405e3a6c42bbf | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes1(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
n = len(envelopes)
if n == 0 or n == 1:
return n
envelopes = sorted(envelopes, key=lambda x: x[0])
stack = []
tmp_y_list = []
tmp_x = envelopes[0]... | the_stack_v2_python_sparse | Archive-1/RussianDollEnvelopes.py | smsxgz/my-leetcode | train | 0 | |
62f2992408e88848645a4542def89fda4af6305f | [
"if isinstance(key, int):\n return HandoverInitiateFlag(key)\nreturn HandoverInitiateFlag[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nreturn cls(value)"
] | <|body_start_0|>
if isinstance(key, int):
return HandoverInitiateFlag(key)
return HandoverInitiateFlag[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
ret... | [HandoverInitiateFlag] Handover Initiate Flags | HandoverInitiateFlag | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandoverInitiateFlag:
"""[HandoverInitiateFlag] Handover Initiate Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<... | stack_v2_sparse_classes_36k_train_013157 | 1,561 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag'"
},
{
"docstring": "Lookup function used when value is n... | 2 | null | Implement the Python class `HandoverInitiateFlag` described below.
Class description:
[HandoverInitiateFlag] Handover Initiate Flags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag': Backport support for original codes. Args: key: Key to get enum item. default... | Implement the Python class `HandoverInitiateFlag` described below.
Class description:
[HandoverInitiateFlag] Handover Initiate Flags
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag': Backport support for original codes. Args: key: Key to get enum item. default... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class HandoverInitiateFlag:
"""[HandoverInitiateFlag] Handover Initiate Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HandoverInitiateFlag:
"""[HandoverInitiateFlag] Handover Initiate Flags"""
def get(key: 'int | str', default: 'int'=-1) -> 'HandoverInitiateFlag':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(... | the_stack_v2_python_sparse | pcapkit/const/mh/handover_initiate_flag.py | JarryShaw/PyPCAPKit | train | 204 |
3c25d4cf11e3e2fb565273d4eb8de9bdce8aed84 | [
"max_area = left = 0\nright = len(heights) - 1\nwhile left < right:\n max_area = max(max_area, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]:\n left += 1\n else:\n right -= 1\nreturn max_area",
"max_area = 0\nfor left in range(len(heights)):\n f... | <|body_start_0|>
max_area = left = 0
right = len(heights) - 1
while left < right:
max_area = max(max_area, min(heights[left], heights[right]) * (right - left))
if heights[left] < heights[right]:
left += 1
else:
right -= 1
... | Container | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
def get_max_area(self, heights: List[int]) -> int:
"""Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def get_max_area_(self, heights: List[int]) -> int:
"""Approach: Brute Force Time Complexity: O(N^2... | stack_v2_sparse_classes_36k_train_013158 | 1,463 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:",
"name": "get_max_area",
"signature": "def get_max_area(self, heights: List[int]) -> int"
},
{
"docstring": "Approach: Brute Force Time Complexity: O(N^2) Space Complexity: O(1) :param heigh... | 2 | stack_v2_sparse_classes_30k_train_002418 | Implement the Python class `Container` described below.
Class description:
Implement the Container class.
Method signatures and docstrings:
- def get_max_area(self, heights: List[int]) -> int: Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def get_max_area_(self, heights: L... | Implement the Python class `Container` described below.
Class description:
Implement the Container class.
Method signatures and docstrings:
- def get_max_area(self, heights: List[int]) -> int: Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def get_max_area_(self, heights: L... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Container:
def get_max_area(self, heights: List[int]) -> int:
"""Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def get_max_area_(self, heights: List[int]) -> int:
"""Approach: Brute Force Time Complexity: O(N^2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Container:
def get_max_area(self, heights: List[int]) -> int:
"""Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
max_area = left = 0
right = len(heights) - 1
while left < right:
max_area = max(max_area, min(heights[left], ... | the_stack_v2_python_sparse | revisited/math_and_strings/math/container_with_most_amount_of_water.py | Shiv2157k/leet_code | train | 1 | |
f73f67be9da74f9feff4ce530cbab2e20fd06dfb | [
"batch = batch.to(self.device)\nwavs, lens = batch.signal\ntargets, lens_targ = batch.target\nself.targets = targets\nif stage == sb.Stage.TRAIN:\n wavs, targets, lens = augment_data(self.noise_datasets, self.speech_datasets, wavs, targets, lens_targ)\n self.lens = lens\n self.targets = targets\nfeats = se... | <|body_start_0|>
batch = batch.to(self.device)
wavs, lens = batch.signal
targets, lens_targ = batch.target
self.targets = targets
if stage == sb.Stage.TRAIN:
wavs, targets, lens = augment_data(self.noise_datasets, self.speech_datasets, wavs, targets, lens_targ)
... | VADBrain | [
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VADBrain:
def compute_forward(self, batch, stage):
"""Given an input batch it computes the binary probability. In training phase, we create on-the-fly augmentation data."""
<|body_0|>
def compute_objectives(self, predictions, batch, stage):
"""Given the network predi... | stack_v2_sparse_classes_36k_train_013159 | 9,125 | permissive | [
{
"docstring": "Given an input batch it computes the binary probability. In training phase, we create on-the-fly augmentation data.",
"name": "compute_forward",
"signature": "def compute_forward(self, batch, stage)"
},
{
"docstring": "Given the network predictions and targets computed the binary... | 4 | stack_v2_sparse_classes_30k_train_012156 | Implement the Python class `VADBrain` described below.
Class description:
Implement the VADBrain class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Given an input batch it computes the binary probability. In training phase, we create on-the-fly augmentation data.
- def compute_objecti... | Implement the Python class `VADBrain` described below.
Class description:
Implement the VADBrain class.
Method signatures and docstrings:
- def compute_forward(self, batch, stage): Given an input batch it computes the binary probability. In training phase, we create on-the-fly augmentation data.
- def compute_objecti... | d4c9a53773f13d5a2843f25bc7f89482936e2f17 | <|skeleton|>
class VADBrain:
def compute_forward(self, batch, stage):
"""Given an input batch it computes the binary probability. In training phase, we create on-the-fly augmentation data."""
<|body_0|>
def compute_objectives(self, predictions, batch, stage):
"""Given the network predi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VADBrain:
def compute_forward(self, batch, stage):
"""Given an input batch it computes the binary probability. In training phase, we create on-the-fly augmentation data."""
batch = batch.to(self.device)
wavs, lens = batch.signal
targets, lens_targ = batch.target
self.ta... | the_stack_v2_python_sparse | recipes/LibriParty/VAD/train.py | zycv/speechbrain | train | 2 | |
0d15a41e684c9ef3b962b106f147bbdf02c38bd6 | [
"prev = None\ncur = head\nwhile cur:\n tmp = cur.next\n cur.next = prev\n prev = cur\n cur = tmp\nreturn prev",
"fast = slow = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\nslow = self.reverseList(slow)\ncur = head\nslow_cur = slow\nwhile slow_cur:\n if slow_cur.... | <|body_start_0|>
prev = None
cur = head
while cur:
tmp = cur.next
cur.next = prev
prev = cur
cur = tmp
return prev
<|end_body_0|>
<|body_start_1|>
fast = slow = head
while fast and fast.next:
slow = slow.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reorderList(self, head):
""":type head: ListNode :rtype: void Do not return anything, modify head in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_013160 | 1,163 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: void Do not return anything, modify head in-place instead.",
"name": "reorderList",
"signature": "def reorderList(self... | 2 | stack_v2_sparse_classes_30k_val_000565 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reorderList(self, head): :type head: ListNode :rtype: void Do not return anything, modify head in-place i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reorderList(self, head): :type head: ListNode :rtype: void Do not return anything, modify head in-place i... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reorderList(self, head):
""":type head: ListNode :rtype: void Do not return anything, modify head in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
prev = None
cur = head
while cur:
tmp = cur.next
cur.next = prev
prev = cur
cur = tmp
return prev
def reorderList(self, head):
... | the_stack_v2_python_sparse | leetcode/reorderList-143.py | pittcat/Algorithm_Practice | train | 0 | |
da814904d40b66b3e6bd2b8a43af2e420a90ad77 | [
"super(Encoder, self).__init__()\nself.d_model = d_model\nself.number_of_layers = number_of_layers\nself.embedding = tf.keras.layers.Embedding(input_vocabulary_size, d_model)\nself.positional_encoding = positional_encoding(maximum_position_encoding, d_model)\nself.encoder_layers = [EncoderLayer(d_model, number_of_h... | <|body_start_0|>
super(Encoder, self).__init__()
self.d_model = d_model
self.number_of_layers = number_of_layers
self.embedding = tf.keras.layers.Embedding(input_vocabulary_size, d_model)
self.positional_encoding = positional_encoding(maximum_position_encoding, d_model)
s... | Encoder class contains of word embedding, positional encoding and several numbers of encoder layers to represent an encoder of transformer model | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class contains of word embedding, positional encoding and several numbers of encoder layers to represent an encoder of transformer model"""
def __init__(self, number_of_layers, d_model, number_of_heads, dff, input_vocabulary_size, maximum_position_encoding, rate=0.1):
... | stack_v2_sparse_classes_36k_train_013161 | 11,425 | no_license | [
{
"docstring": "Constructor for the Encoder :param number_of_layers: number of encoder layers :param d_model: dimension of the word embedding vector :param number_of_heads: number of heads to work in parallel :param dff: inner-layer dimensionality :param input_vocabulary_size: size of the input vocabulary :para... | 2 | stack_v2_sparse_classes_30k_train_013052 | Implement the Python class `Encoder` described below.
Class description:
Encoder class contains of word embedding, positional encoding and several numbers of encoder layers to represent an encoder of transformer model
Method signatures and docstrings:
- def __init__(self, number_of_layers, d_model, number_of_heads, d... | Implement the Python class `Encoder` described below.
Class description:
Encoder class contains of word embedding, positional encoding and several numbers of encoder layers to represent an encoder of transformer model
Method signatures and docstrings:
- def __init__(self, number_of_layers, d_model, number_of_heads, d... | f164c21ed852dfd10a4701f4050d72dc87bd302a | <|skeleton|>
class Encoder:
"""Encoder class contains of word embedding, positional encoding and several numbers of encoder layers to represent an encoder of transformer model"""
def __init__(self, number_of_layers, d_model, number_of_heads, dff, input_vocabulary_size, maximum_position_encoding, rate=0.1):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder class contains of word embedding, positional encoding and several numbers of encoder layers to represent an encoder of transformer model"""
def __init__(self, number_of_layers, d_model, number_of_heads, dff, input_vocabulary_size, maximum_position_encoding, rate=0.1):
"""Const... | the_stack_v2_python_sparse | backend/code/transformer_model.py | sovaso/NewsHeadlineGenerator | train | 3 |
5b5188c27bf3c2734bfc96857d88e8aff192c5f8 | [
"if from_seg == to_seg:\n raise ValueError('from_seg should not be same as to_seg')\nself.symname = symname\nself.from_seg = from_seg\nif len(tgtaxis1) == 2:\n tgtaxis1 += ([0, 0, 0, 1],)\nif len(tgtaxis2) == 2:\n tgtaxis2 += ([0, 0, 0, 1],)\nself.tgtaxis1 = (tgtaxis1[0], hm.hnormalized(tgtaxis1[1]), hm.hp... | <|body_start_0|>
if from_seg == to_seg:
raise ValueError('from_seg should not be same as to_seg')
self.symname = symname
self.from_seg = from_seg
if len(tgtaxis1) == 2:
tgtaxis1 += ([0, 0, 0, 1],)
if len(tgtaxis2) == 2:
tgtaxis2 += ([0, 0, 0, 1... | TODO: Summary Attributes: angle (TYPE): Description distinct_axes (TYPE): Description from_seg (TYPE): Description lever (TYPE): Description rot_tol (TYPE): Description sym_axes (TYPE): Description symname (TYPE): Description tgtaxis1 (TYPE): Description tgtaxis2 (TYPE): Description to_seg (TYPE): Description tol (TYPE... | AxesIntersect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxesIntersect:
"""TODO: Summary Attributes: angle (TYPE): Description distinct_axes (TYPE): Description from_seg (TYPE): Description lever (TYPE): Description rot_tol (TYPE): Description sym_axes (TYPE): Description symname (TYPE): Description tgtaxis1 (TYPE): Description tgtaxis2 (TYPE): Descrip... | stack_v2_sparse_classes_36k_train_013162 | 9,147 | permissive | [
{
"docstring": "TODO: Summary Args: symname (TYPE): Description tgtaxis1 (TYPE): Description tgtaxis2 (TYPE): Description from_seg (TYPE): Description tol (float, optional): Description lever (int, optional): Description to_seg (TYPE, optional): Description distinct_axes (bool, optional): Description Raises: Va... | 3 | stack_v2_sparse_classes_30k_val_000304 | Implement the Python class `AxesIntersect` described below.
Class description:
TODO: Summary Attributes: angle (TYPE): Description distinct_axes (TYPE): Description from_seg (TYPE): Description lever (TYPE): Description rot_tol (TYPE): Description sym_axes (TYPE): Description symname (TYPE): Description tgtaxis1 (TYPE... | Implement the Python class `AxesIntersect` described below.
Class description:
TODO: Summary Attributes: angle (TYPE): Description distinct_axes (TYPE): Description from_seg (TYPE): Description lever (TYPE): Description rot_tol (TYPE): Description sym_axes (TYPE): Description symname (TYPE): Description tgtaxis1 (TYPE... | b4dbb6d18b47e64ed0c235fa559792ab9f0e7532 | <|skeleton|>
class AxesIntersect:
"""TODO: Summary Attributes: angle (TYPE): Description distinct_axes (TYPE): Description from_seg (TYPE): Description lever (TYPE): Description rot_tol (TYPE): Description sym_axes (TYPE): Description symname (TYPE): Description tgtaxis1 (TYPE): Description tgtaxis2 (TYPE): Descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxesIntersect:
"""TODO: Summary Attributes: angle (TYPE): Description distinct_axes (TYPE): Description from_seg (TYPE): Description lever (TYPE): Description rot_tol (TYPE): Description sym_axes (TYPE): Description symname (TYPE): Description tgtaxis1 (TYPE): Description tgtaxis2 (TYPE): Description to_seg (... | the_stack_v2_python_sparse | worms/criteria/bounded.py | Arielbs/worms | train | 0 |
67c6db611ca134242e4686cc96251b47371c1e8f | [
"if not root:\n return []\nself.cts = Counter()\nself.dfs(root)\nmax_val = max(self.cts.values())\nreturn [s for s, ct in self.cts.items() if ct == max_val]",
"if node:\n sum = node.val + self.dfs(node.left) + self.dfs(node.right)\n self.cts[sum] += 1\n return sum\nreturn 0"
] | <|body_start_0|>
if not root:
return []
self.cts = Counter()
self.dfs(root)
max_val = max(self.cts.values())
return [s for s, ct in self.cts.items() if ct == max_val]
<|end_body_0|>
<|body_start_1|>
if node:
sum = node.val + self.dfs(node.left) + ... | More direct solution - July 2018 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""More direct solution - July 2018"""
def findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def dfs(self, node):
"""Recursive DFS - adds subtree sum count to `self.cts` :returns: integer value of `node`'s subtree ... | stack_v2_sparse_classes_36k_train_013163 | 2,119 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findFrequentTreeSum",
"signature": "def findFrequentTreeSum(self, root)"
},
{
"docstring": "Recursive DFS - adds subtree sum count to `self.cts` :returns: integer value of `node`'s subtree sum.",
"name": "dfs",
"signature"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
More direct solution - July 2018
Method signatures and docstrings:
- def findFrequentTreeSum(self, root): :type root: TreeNode :rtype: List[int]
- def dfs(self, node): Recursive DFS - adds subtree sum count to `self.cts` :returns: integer value... | Implement the Python class `Solution` described below.
Class description:
More direct solution - July 2018
Method signatures and docstrings:
- def findFrequentTreeSum(self, root): :type root: TreeNode :rtype: List[int]
- def dfs(self, node): Recursive DFS - adds subtree sum count to `self.cts` :returns: integer value... | f4cd43f082b58d4410008af49325770bc84d3aba | <|skeleton|>
class Solution:
"""More direct solution - July 2018"""
def findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def dfs(self, node):
"""Recursive DFS - adds subtree sum count to `self.cts` :returns: integer value of `node`'s subtree ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""More direct solution - July 2018"""
def findFrequentTreeSum(self, root):
""":type root: TreeNode :rtype: List[int]"""
if not root:
return []
self.cts = Counter()
self.dfs(root)
max_val = max(self.cts.values())
return [s for s, ct in... | the_stack_v2_python_sparse | 508.Most_Frequent_Subtree_Sum.py | welsny/solutions | train | 1 |
ab445f1c4bb51c0597c570d600537670622051cd | [
"print('facilities of %r:' % name)\nfor facility in facilities:\n print(' %s=<component name>: %s' % (facility['name'], facility['doc']))\n value = facility['descriptor'].value\n locator = facility['descriptor'].locator\n print(' current value: %r, from %s' % (value.name, locator))\n print(... | <|body_start_0|>
print('facilities of %r:' % name)
for facility in facilities:
print(' %s=<component name>: %s' % (facility['name'], facility['doc']))
value = facility['descriptor'].value
locator = facility['descriptor'].locator
print(' current v... | Plain ASCII text. | Ascii | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ascii:
"""Plain ASCII text."""
def formatComponents(name, facilities):
"""Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descriptor for facility."""
<|... | stack_v2_sparse_classes_36k_train_013164 | 3,406 | permissive | [
{
"docstring": "Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descriptor for facility.",
"name": "formatComponents",
"signature": "def formatComponents(name, facilities)"
},
... | 2 | null | Implement the Python class `Ascii` described below.
Class description:
Plain ASCII text.
Method signatures and docstrings:
- def formatComponents(name, facilities): Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help str... | Implement the Python class `Ascii` described below.
Class description:
Plain ASCII text.
Method signatures and docstrings:
- def formatComponents(name, facilities): Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help str... | e914bc62ae974b999ce556cb6b34cdbcc17338fc | <|skeleton|>
class Ascii:
"""Plain ASCII text."""
def formatComponents(name, facilities):
"""Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descriptor for facility."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ascii:
"""Plain ASCII text."""
def formatComponents(name, facilities):
"""Format components information. name: Facility name. facilities: Dictionary with facilities information. - name: Name of facility - doc: Facility help string. - descriptor: Descriptor for facility."""
print('faciliti... | the_stack_v2_python_sparse | pythia/pyre/util/help.py | geodynamics/pythia | train | 1 |
1e3194e0a864cda2c8078ec63d4aad500ac45434 | [
"center_point = self.find_center(A=rect[0][0], B=rect[0][2])\nadj_point = (0, center_point[1])\na = self.pythag(A=rect[0][0], B=rect[0][1])\nb = self.pythag(A=rect[0][1], B=rect[0][2])\nif a > b:\n opp_point = self.find_center(A=rect[0][1], B=rect[0][0])\nelse:\n opp_point = self.find_center(A=rect[0][1], B=r... | <|body_start_0|>
center_point = self.find_center(A=rect[0][0], B=rect[0][2])
adj_point = (0, center_point[1])
a = self.pythag(A=rect[0][0], B=rect[0][1])
b = self.pythag(A=rect[0][1], B=rect[0][2])
if a > b:
opp_point = self.find_center(A=rect[0][1], B=rect[0][0])
... | Geometry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Geometry:
def find_orientation(self, rect):
"""Finds the global rotation of the object in relation to the side of the camera."""
<|body_0|>
def find_center(self, A, B):
"""Simple equation to find the mean point of two points"""
<|body_1|>
def pythag(self... | stack_v2_sparse_classes_36k_train_013165 | 10,498 | no_license | [
{
"docstring": "Finds the global rotation of the object in relation to the side of the camera.",
"name": "find_orientation",
"signature": "def find_orientation(self, rect)"
},
{
"docstring": "Simple equation to find the mean point of two points",
"name": "find_center",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_train_000414 | Implement the Python class `Geometry` described below.
Class description:
Implement the Geometry class.
Method signatures and docstrings:
- def find_orientation(self, rect): Finds the global rotation of the object in relation to the side of the camera.
- def find_center(self, A, B): Simple equation to find the mean p... | Implement the Python class `Geometry` described below.
Class description:
Implement the Geometry class.
Method signatures and docstrings:
- def find_orientation(self, rect): Finds the global rotation of the object in relation to the side of the camera.
- def find_center(self, A, B): Simple equation to find the mean p... | 37718d01662dd382b0075436c4d014ab81b3e946 | <|skeleton|>
class Geometry:
def find_orientation(self, rect):
"""Finds the global rotation of the object in relation to the side of the camera."""
<|body_0|>
def find_center(self, A, B):
"""Simple equation to find the mean point of two points"""
<|body_1|>
def pythag(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Geometry:
def find_orientation(self, rect):
"""Finds the global rotation of the object in relation to the side of the camera."""
center_point = self.find_center(A=rect[0][0], B=rect[0][2])
adj_point = (0, center_point[1])
a = self.pythag(A=rect[0][0], B=rect[0][1])
b = ... | the_stack_v2_python_sparse | camera.py | JMLLincoln/Humanoid-Robot-Playing-Memory-Card-Games | train | 0 | |
bae16d6e8cd9be9ea8cc23bda66a0fbf22432ed4 | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_step = self.get_step()\n y_step = self.get_step()\n if x_step == 0 and y_step == 0:\n continue\n next_x = self.x_values[-1] + x_step\n next_y = self.y_values[-1] + y_ste... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
if x_step == 0 and y_step == 0:
... | 一个生成随机漫步数据的类 | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有的点"""
<|body_1|>
def get_step(self):
"""决定前进方向,以及沿着该前进方向前进的距离"""
<|body_2|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_013166 | 1,542 | no_license | [
{
"docstring": "初始化随机漫步的属性",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "计算随机漫步包含的所有的点",
"name": "fill_walk",
"signature": "def fill_walk(self)"
},
{
"docstring": "决定前进方向,以及沿着该前进方向前进的距离",
"name": "get_step",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_021658 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def fill_walk(self): 计算随机漫步包含的所有的点
- def get_step(self): 决定前进方向,以及沿着该前进方向前进的距离 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步数据的类
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def fill_walk(self): 计算随机漫步包含的所有的点
- def get_step(self): 决定前进方向,以及沿着该前进方向前进的距离
<|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def ... | 0971e5f21a3d3ae9c2e22c87cf1f654be779abef | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有的点"""
<|body_1|>
def get_step(self):
"""决定前进方向,以及沿着该前进方向前进的距离"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""计算随机漫步包含的所有的点"""
while len(self.x_values) < self.num_points:
x... | the_stack_v2_python_sparse | chapter_15-17_数据可视化/chapter_15_生成数据/random_walk.py | wenyoufu/Python-Programming | train | 0 |
eb08abec96daac681ede59cf9fcf636442028f63 | [
"data = self.render_page_info(page)\nif page:\n data[alias] = []\n for row in page:\n info = row.list_info\n info['team'] = row.team.mini_info\n info['my_state'] = row.member.mini_info\n data[alias].append(info)\nelse:\n data[alias] = []\ndata.update(kwargs)\nreturn data",
"pa... | <|body_start_0|>
data = self.render_page_info(page)
if page:
data[alias] = []
for row in page:
info = row.list_info
info['team'] = row.team.mini_info
info['my_state'] = row.member.mini_info
data[alias].append(info)
... | UserMatchesHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserMatchesHandler:
def get_paginated_data(self, page: Page, alias, **kwargs) -> dict:
"""获取分页后的数据 Args: page: Page, alias: serializer serializer_kwargs: Returns: dict() num_pages: int, 总页数, previous_page: int, 上一页 current_page: int, 当前页码 next_pate: int, 下一页 total: 总数 per_page: 每页返回数 res... | stack_v2_sparse_classes_36k_train_013167 | 39,331 | no_license | [
{
"docstring": "获取分页后的数据 Args: page: Page, alias: serializer serializer_kwargs: Returns: dict() num_pages: int, 总页数, previous_page: int, 上一页 current_page: int, 当前页码 next_pate: int, 下一页 total: 总数 per_page: 每页返回数 results: list, 查询结果",
"name": "get_paginated_data",
"signature": "def get_paginated_data(self... | 2 | stack_v2_sparse_classes_30k_train_010618 | Implement the Python class `UserMatchesHandler` described below.
Class description:
Implement the UserMatchesHandler class.
Method signatures and docstrings:
- def get_paginated_data(self, page: Page, alias, **kwargs) -> dict: 获取分页后的数据 Args: page: Page, alias: serializer serializer_kwargs: Returns: dict() num_pages: ... | Implement the Python class `UserMatchesHandler` described below.
Class description:
Implement the UserMatchesHandler class.
Method signatures and docstrings:
- def get_paginated_data(self, page: Page, alias, **kwargs) -> dict: 获取分页后的数据 Args: page: Page, alias: serializer serializer_kwargs: Returns: dict() num_pages: ... | 49c31d9cce6ca451ff069697913b33fe55028a46 | <|skeleton|>
class UserMatchesHandler:
def get_paginated_data(self, page: Page, alias, **kwargs) -> dict:
"""获取分页后的数据 Args: page: Page, alias: serializer serializer_kwargs: Returns: dict() num_pages: int, 总页数, previous_page: int, 上一页 current_page: int, 当前页码 next_pate: int, 下一页 total: 总数 per_page: 每页返回数 res... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserMatchesHandler:
def get_paginated_data(self, page: Page, alias, **kwargs) -> dict:
"""获取分页后的数据 Args: page: Page, alias: serializer serializer_kwargs: Returns: dict() num_pages: int, 总页数, previous_page: int, 上一页 current_page: int, 当前页码 next_pate: int, 下一页 total: 总数 per_page: 每页返回数 results: list, 查询... | the_stack_v2_python_sparse | PaiDuiGuanJia/yiyun/handlers/rest/match.py | haoweiking/image_tesseract_private | train | 0 | |
5a5ca430844f293ae223e1cd63888e066d5009b9 | [
"AssessmentResults.__init__(self, controller, **kwargs)\nself._lst_labels.append(u'π<sub>CV</sub>:')\nself._lst_labels.append(u'π<sub>CF</sub>:')\nself._lst_labels.append(u'π<sub>C</sub>:')\nself._lblModel.set_tooltip_markup(_(u'The assessment model used to calculate the capacitor failure rate.'))\nself.txtPiCV = r... | <|body_start_0|>
AssessmentResults.__init__(self, controller, **kwargs)
self._lst_labels.append(u'π<sub>CV</sub>:')
self._lst_labels.append(u'π<sub>CF</sub>:')
self._lst_labels.append(u'π<sub>C</sub>:')
self._lblModel.set_tooltip_markup(_(u'The assessment model used to calculate ... | Display capacitor assessment results attribute data in the RAMSTK Work Book. The capacitor assessment result view displays all the assessment results for the selected capacitor. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 part stress methods. The attributes of a capacitor asses... | CapacitorAssessmentResults | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CapacitorAssessmentResults:
"""Display capacitor assessment results attribute data in the RAMSTK Work Book. The capacitor assessment result view displays all the assessment results for the selected capacitor. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 pa... | stack_v2_sparse_classes_36k_train_013168 | 30,866 | permissive | [
{
"docstring": "Initialize an instance of the Capacitor assessment result view. :param controller: the Hardware data controller instance. :type controller: :class:`ramstk.hardware.Controller.HardwareBoMDataController`",
"name": "__init__",
"signature": "def __init__(self, controller, **kwargs)"
},
{... | 5 | null | Implement the Python class `CapacitorAssessmentResults` described below.
Class description:
Display capacitor assessment results attribute data in the RAMSTK Work Book. The capacitor assessment result view displays all the assessment results for the selected capacitor. This includes, currently, results for MIL-HDBK-21... | Implement the Python class `CapacitorAssessmentResults` described below.
Class description:
Display capacitor assessment results attribute data in the RAMSTK Work Book. The capacitor assessment result view displays all the assessment results for the selected capacitor. This includes, currently, results for MIL-HDBK-21... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class CapacitorAssessmentResults:
"""Display capacitor assessment results attribute data in the RAMSTK Work Book. The capacitor assessment result view displays all the assessment results for the selected capacitor. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CapacitorAssessmentResults:
"""Display capacitor assessment results attribute data in the RAMSTK Work Book. The capacitor assessment result view displays all the assessment results for the selected capacitor. This includes, currently, results for MIL-HDBK-217FN2 parts count and MIL-HDBK-217FN2 part stress met... | the_stack_v2_python_sparse | src/ramstk/gui/gtk/workviews/components/Capacitor.py | JmiXIII/ramstk | train | 0 |
ef930bdd773811b62dc2dea6a51025e8a1972d01 | [
"if not nums:\n return 0\nif len(nums) == 1:\n return 1\ntemp_num = nums[0]\ncount = 0\nfor index, num in enumerate(nums[1:]):\n if temp_num == num:\n del nums[index - count]\n count += 1\n else:\n temp_num = num\nreturn len(nums)",
"i = 0\nj = 1\nwhile j < len(nums):\n if nums... | <|body_start_0|>
if not nums:
return 0
if len(nums) == 1:
return 1
temp_num = nums[0]
count = 0
for index, num in enumerate(nums[1:]):
if temp_num == num:
del nums[index - count]
count += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicatesB(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
... | stack_v2_sparse_classes_36k_train_013169 | 1,187 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicatesB",
"signature": "def removeDuplicatesB(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicatesB(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicatesB(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 128b567a4aa9eecfee3dc2b6599da6823e56b404 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicatesB(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
if len(nums) == 1:
return 1
temp_num = nums[0]
count = 0
for index, num in enumerate(nums[1:]):
if temp_num == num:
... | the_stack_v2_python_sparse | leetCodeLearning/removeDuplicateNum.py | lyqtiffany/learngit | train | 0 | |
825a5440808d1ff011880471b48aa91dabec151a | [
"base = '0123456789ABCDEF'\ni = 0\ns = s.upper()\ns1 = ''\nwhile i < len(s):\n c1 = s[i]\n c2 = s[i + 1]\n i += 2\n b1 = base.find(c1)\n b2 = base.find(c2)\n if b1 == -1 or b2 == -1:\n return None\n s1 += chr((b1 << 4) + b2)\nreturn s1",
"tmp = []\nfor c in s:\n trs = hex(ord(c)).re... | <|body_start_0|>
base = '0123456789ABCDEF'
i = 0
s = s.upper()
s1 = ''
while i < len(s):
c1 = s[i]
c2 = s[i + 1]
i += 2
b1 = base.find(c1)
b2 = base.find(c2)
if b1 == -1 or b2 == -1:
return No... | Utils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utils:
def hex2str(self, s):
"""十六进制转字符串 :param s: :return:"""
<|body_0|>
def str2hex(self, s):
"""字符串转十六进制"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
base = '0123456789ABCDEF'
i = 0
s = s.upper()
s1 = ''
while i... | stack_v2_sparse_classes_36k_train_013170 | 5,570 | no_license | [
{
"docstring": "十六进制转字符串 :param s: :return:",
"name": "hex2str",
"signature": "def hex2str(self, s)"
},
{
"docstring": "字符串转十六进制",
"name": "str2hex",
"signature": "def str2hex(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003178 | Implement the Python class `Utils` described below.
Class description:
Implement the Utils class.
Method signatures and docstrings:
- def hex2str(self, s): 十六进制转字符串 :param s: :return:
- def str2hex(self, s): 字符串转十六进制 | Implement the Python class `Utils` described below.
Class description:
Implement the Utils class.
Method signatures and docstrings:
- def hex2str(self, s): 十六进制转字符串 :param s: :return:
- def str2hex(self, s): 字符串转十六进制
<|skeleton|>
class Utils:
def hex2str(self, s):
"""十六进制转字符串 :param s: :return:"""
... | 6a4042241dccf268ade6ced6623bb186cc6d05a9 | <|skeleton|>
class Utils:
def hex2str(self, s):
"""十六进制转字符串 :param s: :return:"""
<|body_0|>
def str2hex(self, s):
"""字符串转十六进制"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Utils:
def hex2str(self, s):
"""十六进制转字符串 :param s: :return:"""
base = '0123456789ABCDEF'
i = 0
s = s.upper()
s1 = ''
while i < len(s):
c1 = s[i]
c2 = s[i + 1]
i += 2
b1 = base.find(c1)
b2 = base.find(c2... | the_stack_v2_python_sparse | common/utils.py | XEvan/etp_fota | train | 1 | |
740462d93d94264c1f8d97f55cc55c93d0172a6d | [
"self.config = config.setup()\nself.log = logging.getLogger(__name__)\nserver = self.config.get('IMAP', 'server')\nport = int(self.config.get('IMAP', 'port', 143))\nself.user = self.config.get('IMAP', 'user')\npassword = self.config.get('IMAP', 'password')\nself.mailbox_group = self.config.get('IMAP', 'mailbox_grou... | <|body_start_0|>
self.config = config.setup()
self.log = logging.getLogger(__name__)
server = self.config.get('IMAP', 'server')
port = int(self.config.get('IMAP', 'port', 143))
self.user = self.config.get('IMAP', 'user')
password = self.config.get('IMAP', 'password')
... | Provide CRUD methods to Cyrus IMAP mailboxes | SpokeMbx | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpokeMbx:
"""Provide CRUD methods to Cyrus IMAP mailboxes"""
def __init__(self):
"""Get config, setup logging and cyrus connection."""
<|body_0|>
def _validate_mailbox_name(self, mailbox_name):
"""Ensure input is a valid email address format."""
<|body_1|... | stack_v2_sparse_classes_36k_train_013171 | 3,866 | permissive | [
{
"docstring": "Get config, setup logging and cyrus connection.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Ensure input is a valid email address format.",
"name": "_validate_mailbox_name",
"signature": "def _validate_mailbox_name(self, mailbox_name)"
},
... | 5 | stack_v2_sparse_classes_30k_train_008146 | Implement the Python class `SpokeMbx` described below.
Class description:
Provide CRUD methods to Cyrus IMAP mailboxes
Method signatures and docstrings:
- def __init__(self): Get config, setup logging and cyrus connection.
- def _validate_mailbox_name(self, mailbox_name): Ensure input is a valid email address format.... | Implement the Python class `SpokeMbx` described below.
Class description:
Provide CRUD methods to Cyrus IMAP mailboxes
Method signatures and docstrings:
- def __init__(self): Get config, setup logging and cyrus connection.
- def _validate_mailbox_name(self, mailbox_name): Ensure input is a valid email address format.... | 077d45750643a38b1062a9199800de9c9de900ae | <|skeleton|>
class SpokeMbx:
"""Provide CRUD methods to Cyrus IMAP mailboxes"""
def __init__(self):
"""Get config, setup logging and cyrus connection."""
<|body_0|>
def _validate_mailbox_name(self, mailbox_name):
"""Ensure input is a valid email address format."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpokeMbx:
"""Provide CRUD methods to Cyrus IMAP mailboxes"""
def __init__(self):
"""Get config, setup logging and cyrus connection."""
self.config = config.setup()
self.log = logging.getLogger(__name__)
server = self.config.get('IMAP', 'server')
port = int(self.con... | the_stack_v2_python_sparse | spoke/lib/mbx.py | KrisSaxton/spoke | train | 0 |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"try:\n db.show_by_id(show_id, session=session)\nexcept NoResultFound:\n raise NotFoundError('show with ID %s not found' % show_id)\ntry:\n db.season_by_id(season_id, session)\nexcept NoResultFound:\n raise NotFoundError('season with ID %s not found' % season_id)\ntry:\n release = db.season_release_b... | <|body_start_0|>
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id)
try:
db.season_by_id(season_id, session)
except NoResultFound:
raise NotFoundError('season with I... | SeriesSeasonReleaseAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesSeasonReleaseAPI:
def get(self, show_id, season_id, rel_id, session):
"""Get season release by show ID, season ID and release ID"""
<|body_0|>
def delete(self, show_id, season_id, rel_id, session):
"""Delete episode release by show ID, season ID and release ID"... | stack_v2_sparse_classes_36k_train_013172 | 47,001 | permissive | [
{
"docstring": "Get season release by show ID, season ID and release ID",
"name": "get",
"signature": "def get(self, show_id, season_id, rel_id, session)"
},
{
"docstring": "Delete episode release by show ID, season ID and release ID",
"name": "delete",
"signature": "def delete(self, sho... | 3 | stack_v2_sparse_classes_30k_train_001842 | Implement the Python class `SeriesSeasonReleaseAPI` described below.
Class description:
Implement the SeriesSeasonReleaseAPI class.
Method signatures and docstrings:
- def get(self, show_id, season_id, rel_id, session): Get season release by show ID, season ID and release ID
- def delete(self, show_id, season_id, rel... | Implement the Python class `SeriesSeasonReleaseAPI` described below.
Class description:
Implement the SeriesSeasonReleaseAPI class.
Method signatures and docstrings:
- def get(self, show_id, season_id, rel_id, session): Get season release by show ID, season ID and release ID
- def delete(self, show_id, season_id, rel... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesSeasonReleaseAPI:
def get(self, show_id, season_id, rel_id, session):
"""Get season release by show ID, season ID and release ID"""
<|body_0|>
def delete(self, show_id, season_id, rel_id, session):
"""Delete episode release by show ID, season ID and release ID"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeriesSeasonReleaseAPI:
def get(self, show_id, season_id, rel_id, session):
"""Get season release by show ID, season ID and release ID"""
try:
db.show_by_id(show_id, session=session)
except NoResultFound:
raise NotFoundError('show with ID %s not found' % show_id... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
7e211fd2c0414dcfea889002ba45d2d8c6c78b07 | [
"try:\n db = await self.application.objects.get(DBSetting, id=int(db_id))\n await self.application.objects.delete(db)\n return self.json(JsonResponse(code=1, data={'id': db_id}))\nexcept DBSetting.DoesNotExist:\n self.set_status(400)\n return self.json(JsonResponse(code=10009, msg='该数据库配置尚未创建!'))",
... | <|body_start_0|>
try:
db = await self.application.objects.get(DBSetting, id=int(db_id))
await self.application.objects.delete(db)
return self.json(JsonResponse(code=1, data={'id': db_id}))
except DBSetting.DoesNotExist:
self.set_status(400)
ret... | DbSettingChangeHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbSettingChangeHandler:
async def delete(self, db_id, *args, **kwargs):
"""删除数据库配置 :param db_id: 删除的配置数据库id"""
<|body_0|>
async def patch(self, db_id, *args, **kwargs):
"""更新数据配置 :param db_id: 更新的配置数据库id"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013173 | 17,374 | permissive | [
{
"docstring": "删除数据库配置 :param db_id: 删除的配置数据库id",
"name": "delete",
"signature": "async def delete(self, db_id, *args, **kwargs)"
},
{
"docstring": "更新数据配置 :param db_id: 更新的配置数据库id",
"name": "patch",
"signature": "async def patch(self, db_id, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000796 | Implement the Python class `DbSettingChangeHandler` described below.
Class description:
Implement the DbSettingChangeHandler class.
Method signatures and docstrings:
- async def delete(self, db_id, *args, **kwargs): 删除数据库配置 :param db_id: 删除的配置数据库id
- async def patch(self, db_id, *args, **kwargs): 更新数据配置 :param db_id:... | Implement the Python class `DbSettingChangeHandler` described below.
Class description:
Implement the DbSettingChangeHandler class.
Method signatures and docstrings:
- async def delete(self, db_id, *args, **kwargs): 删除数据库配置 :param db_id: 删除的配置数据库id
- async def patch(self, db_id, *args, **kwargs): 更新数据配置 :param db_id:... | dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb | <|skeleton|>
class DbSettingChangeHandler:
async def delete(self, db_id, *args, **kwargs):
"""删除数据库配置 :param db_id: 删除的配置数据库id"""
<|body_0|>
async def patch(self, db_id, *args, **kwargs):
"""更新数据配置 :param db_id: 更新的配置数据库id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DbSettingChangeHandler:
async def delete(self, db_id, *args, **kwargs):
"""删除数据库配置 :param db_id: 删除的配置数据库id"""
try:
db = await self.application.objects.get(DBSetting, id=int(db_id))
await self.application.objects.delete(db)
return self.json(JsonResponse(code... | the_stack_v2_python_sparse | apps/project/handlers.py | xiaoxiaolulu/MagicTestPlatform | train | 5 | |
fc6ce3b5da8592f44271f6622bb653bbe1aba0c9 | [
"super(Envelope, self).__init__()\nself.p = exponent\nself.a = -(self.p + 1) * (self.p + 2) / 2\nself.b = self.p * (self.p + 2)\nself.c = -self.p * (self.p + 1) / 2",
"p, a, b, c = (self.p, self.a, self.b, self.c)\nx_pow_p0 = x.pow(p)\nx_pow_p1 = x_pow_p0 * x\nenv_val = 1.0 / x + a * x_pow_p0 + b * x_pow_p1 + c *... | <|body_start_0|>
super(Envelope, self).__init__()
self.p = exponent
self.a = -(self.p + 1) * (self.p + 2) / 2
self.b = self.p * (self.p + 2)
self.c = -self.p * (self.p + 1) / 2
<|end_body_0|>
<|body_start_1|>
p, a, b, c = (self.p, self.a, self.b, self.c)
x_pow_p0... | Envelope. | Envelope | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Envelope:
"""Envelope."""
def __init__(self, exponent) -> None:
"""Initialize envelope. Args: exponent: exponent of the envelope."""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x: input. Returns: Envelope of x."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_013174 | 34,044 | permissive | [
{
"docstring": "Initialize envelope. Args: exponent: exponent of the envelope.",
"name": "__init__",
"signature": "def __init__(self, exponent) -> None"
},
{
"docstring": "Forward pass. Args: x: input. Returns: Envelope of x.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017812 | Implement the Python class `Envelope` described below.
Class description:
Envelope.
Method signatures and docstrings:
- def __init__(self, exponent) -> None: Initialize envelope. Args: exponent: exponent of the envelope.
- def forward(self, x): Forward pass. Args: x: input. Returns: Envelope of x. | Implement the Python class `Envelope` described below.
Class description:
Envelope.
Method signatures and docstrings:
- def __init__(self, exponent) -> None: Initialize envelope. Args: exponent: exponent of the envelope.
- def forward(self, x): Forward pass. Args: x: input. Returns: Envelope of x.
<|skeleton|>
class... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class Envelope:
"""Envelope."""
def __init__(self, exponent) -> None:
"""Initialize envelope. Args: exponent: exponent of the envelope."""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x: input. Returns: Envelope of x."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Envelope:
"""Envelope."""
def __init__(self, exponent) -> None:
"""Initialize envelope. Args: exponent: exponent of the envelope."""
super(Envelope, self).__init__()
self.p = exponent
self.a = -(self.p + 1) * (self.p + 2) / 2
self.b = self.p * (self.p + 2)
... | the_stack_v2_python_sparse | src/gt4sd/frameworks/gflownet/ml/models/mxmnet.py | GT4SD/gt4sd-core | train | 239 |
e2ec6d150340e21b649ad4809de0016aed15358a | [
"self.HumiditySensor = HumiditySensorAdapterTask.HumiditySensorAdapterTask()\nself.HI2CSensor = HI2CSensorAdapterTask.HI2CSensorAdapterTask()\nself.dataManager = SensorDataManager.SensorDataManager()\nself.loop_limit = loop_param\nself.sleep_time = sleep_param",
"i = 0\ntry:\n while i < self.loop_limit or self... | <|body_start_0|>
self.HumiditySensor = HumiditySensorAdapterTask.HumiditySensorAdapterTask()
self.HI2CSensor = HI2CSensorAdapterTask.HI2CSensorAdapterTask()
self.dataManager = SensorDataManager.SensorDataManager()
self.loop_limit = loop_param
self.sleep_time = sleep_param
<|end_b... | Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with | MultiSensorAdapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiSensorAdapter:
"""Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with"""
def __init__(self, loop_param=10, sleep_param=1):
"""Constructor Initializing both the sensor tasks and a dat... | stack_v2_sparse_classes_36k_train_013175 | 4,517 | no_license | [
{
"docstring": "Constructor Initializing both the sensor tasks and a data manager.",
"name": "__init__",
"signature": "def __init__(self, loop_param=10, sleep_param=1)"
},
{
"docstring": "Initialize threads",
"name": "__init_threads__",
"signature": "def __init_threads__(self)"
},
{
... | 3 | null | Implement the Python class `MultiSensorAdapter` described below.
Class description:
Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with
Method signatures and docstrings:
- def __init__(self, loop_param=10, sleep_param=1):... | Implement the Python class `MultiSensorAdapter` described below.
Class description:
Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with
Method signatures and docstrings:
- def __init__(self, loop_param=10, sleep_param=1):... | dfd5fd8c757cae8b1306ae3e4eb2cfc9bf124fee | <|skeleton|>
class MultiSensorAdapter:
"""Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with"""
def __init__(self, loop_param=10, sleep_param=1):
"""Constructor Initializing both the sensor tasks and a dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiSensorAdapter:
"""Method to run TempSensorAdapterTask takes in sleeptime and looptime in the constructors has a bunch of settings to control the program behavior with"""
def __init__(self, loop_param=10, sleep_param=1):
"""Constructor Initializing both the sensor tasks and a data manager."""... | the_stack_v2_python_sparse | apps/labs/module04/MultiSensorAdapter.py | mnk400/iot-device | train | 0 |
bdde02442a5825b7a207dbde5f7aa11518d34df6 | [
"super().__init__(surepetcare_id, coordinator)\nself._attr_name = f'{self._device_name} Battery Level'\nself._attr_unique_id = f'{self._device_id}-battery'",
"state = surepy_entity.raw_data()['status']\ntry:\n per_battery_voltage = state['battery'] / 4\n voltage_diff = per_battery_voltage - SURE_BATT_VOLTAG... | <|body_start_0|>
super().__init__(surepetcare_id, coordinator)
self._attr_name = f'{self._device_name} Battery Level'
self._attr_unique_id = f'{self._device_id}-battery'
<|end_body_0|>
<|body_start_1|>
state = surepy_entity.raw_data()['status']
try:
per_battery_volta... | A sensor implementation for Sure Petcare batteries. | SureBattery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SureBattery:
"""A sensor implementation for Sure Petcare batteries."""
def __init__(self, surepetcare_id: int, coordinator: SurePetcareDataCoordinator) -> None:
"""Initialize a Sure Petcare battery sensor."""
<|body_0|>
def _update_attr(self, surepy_entity: SurepyEntity)... | stack_v2_sparse_classes_36k_train_013176 | 3,867 | permissive | [
{
"docstring": "Initialize a Sure Petcare battery sensor.",
"name": "__init__",
"signature": "def __init__(self, surepetcare_id: int, coordinator: SurePetcareDataCoordinator) -> None"
},
{
"docstring": "Update the state and attributes.",
"name": "_update_attr",
"signature": "def _update_... | 2 | stack_v2_sparse_classes_30k_train_016641 | Implement the Python class `SureBattery` described below.
Class description:
A sensor implementation for Sure Petcare batteries.
Method signatures and docstrings:
- def __init__(self, surepetcare_id: int, coordinator: SurePetcareDataCoordinator) -> None: Initialize a Sure Petcare battery sensor.
- def _update_attr(se... | Implement the Python class `SureBattery` described below.
Class description:
A sensor implementation for Sure Petcare batteries.
Method signatures and docstrings:
- def __init__(self, surepetcare_id: int, coordinator: SurePetcareDataCoordinator) -> None: Initialize a Sure Petcare battery sensor.
- def _update_attr(se... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SureBattery:
"""A sensor implementation for Sure Petcare batteries."""
def __init__(self, surepetcare_id: int, coordinator: SurePetcareDataCoordinator) -> None:
"""Initialize a Sure Petcare battery sensor."""
<|body_0|>
def _update_attr(self, surepy_entity: SurepyEntity)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SureBattery:
"""A sensor implementation for Sure Petcare batteries."""
def __init__(self, surepetcare_id: int, coordinator: SurePetcareDataCoordinator) -> None:
"""Initialize a Sure Petcare battery sensor."""
super().__init__(surepetcare_id, coordinator)
self._attr_name = f'{self.... | the_stack_v2_python_sparse | homeassistant/components/surepetcare/sensor.py | home-assistant/core | train | 35,501 |
35ebd862f2db95944c1c51cd8d63e4d17570b69e | [
"assert query_batch_cnt.is_contiguous()\nassert key_batch_cnt.is_contiguous()\nassert index_pair_batch.is_contiguous()\nassert index_pair.is_contiguous()\nassert query_features.is_contiguous()\nassert key_features.is_contiguous()\nb = query_batch_cnt.shape[0]\ntotal_query_num, local_size = index_pair.size()\ntotal_... | <|body_start_0|>
assert query_batch_cnt.is_contiguous()
assert key_batch_cnt.is_contiguous()
assert index_pair_batch.is_contiguous()
assert index_pair.is_contiguous()
assert query_features.is_contiguous()
assert key_features.is_contiguous()
b = query_batch_cnt.sha... | Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size) | AttentionWeightComputation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionWeightComputation:
"""Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, l... | stack_v2_sparse_classes_36k_train_013177 | 8,019 | no_license | [
{
"docstring": ":param ctx: :param query_batch_cnt: A integer tensor with shape [bs], indicating the query amount for each batch. :param key_batch_cnt: A integer tensor with shape [bs], indicating the key amount of each batch. :param index_pair_batch: A integer tensor with shape [total_query_num], indicating th... | 2 | stack_v2_sparse_classes_30k_train_016854 | Implement the Python class `AttentionWeightComputation` described below.
Class description:
Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attenti... | Implement the Python class `AttentionWeightComputation` described below.
Class description:
Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attenti... | bbc78ca91e851f0f04459b1a8bbe96ab44bf41bc | <|skeleton|>
class AttentionWeightComputation:
"""Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentionWeightComputation:
"""Generate the attention weight matrix based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size)"""... | the_stack_v2_python_sparse | EQNet/eqnet/ops/attention/attention_utils_v2.py | dvlab-research/DeepVision3D | train | 94 |
30c24fb676cec8aeeef58435c14141f1c5ea1bf6 | [
"creds = self.os_primary.credentials\nuser_id = creds.user_id\nusername = creds.username\npassword = creds.password\nuser_domain_id = creds.user_domain_id\nsubject_token, token_body = self.non_admin_token.get_token(user_id=user_id, username=username, user_domain_id=user_domain_id, password=password, auth_data=True)... | <|body_start_0|>
creds = self.os_primary.credentials
user_id = creds.user_id
username = creds.username
password = creds.password
user_domain_id = creds.user_domain_id
subject_token, token_body = self.non_admin_token.get_token(user_id=user_id, username=username, user_domai... | Test identity tokens | TokensV3Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokensV3Test:
"""Test identity tokens"""
def test_validate_token(self):
"""Test validating token for user"""
<|body_0|>
def test_create_token(self):
"""Test creating token for user"""
<|body_1|>
def test_token_auth_creation_existence_deletion(self):
... | stack_v2_sparse_classes_36k_train_013178 | 6,688 | permissive | [
{
"docstring": "Test validating token for user",
"name": "test_validate_token",
"signature": "def test_validate_token(self)"
},
{
"docstring": "Test creating token for user",
"name": "test_create_token",
"signature": "def test_create_token(self)"
},
{
"docstring": "Test auth/chec... | 3 | stack_v2_sparse_classes_30k_train_013333 | Implement the Python class `TokensV3Test` described below.
Class description:
Test identity tokens
Method signatures and docstrings:
- def test_validate_token(self): Test validating token for user
- def test_create_token(self): Test creating token for user
- def test_token_auth_creation_existence_deletion(self): Test... | Implement the Python class `TokensV3Test` described below.
Class description:
Test identity tokens
Method signatures and docstrings:
- def test_validate_token(self): Test validating token for user
- def test_create_token(self): Test creating token for user
- def test_token_auth_creation_existence_deletion(self): Test... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class TokensV3Test:
"""Test identity tokens"""
def test_validate_token(self):
"""Test validating token for user"""
<|body_0|>
def test_create_token(self):
"""Test creating token for user"""
<|body_1|>
def test_token_auth_creation_existence_deletion(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokensV3Test:
"""Test identity tokens"""
def test_validate_token(self):
"""Test validating token for user"""
creds = self.os_primary.credentials
user_id = creds.user_id
username = creds.username
password = creds.password
user_domain_id = creds.user_domain_i... | the_stack_v2_python_sparse | tempest/api/identity/v3/test_tokens.py | openstack/tempest | train | 270 |
50a42b8ebedb69c94f5cfc3eea66f289d068c7ff | [
"Ioput.function_name(self.__class__.__name__)\ntry:\n self.execute_test(url=url)\n self.get_text_value(kone='subject')\nexcept AssertionError as a:\n self.assertTrue('', '返回结果text非字典 %s' % a)\nelse:\n self.assertTrue(self.datalist1, '键 subject 无内容')",
"Ioput.function_name(self.__class__.__name__)\ntr... | <|body_start_0|>
Ioput.function_name(self.__class__.__name__)
try:
self.execute_test(url=url)
self.get_text_value(kone='subject')
except AssertionError as a:
self.assertTrue('', '返回结果text非字典 %s' % a)
else:
self.assertTrue(self.datalist1, '... | Test_语音搜索服务接口 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_语音搜索服务接口:
def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'):
"""6.1 直播搜索节目列表接口"""
<|body_0|>
def test_2回看搜索节目列表接口(self, url='http://{{snm_idpVoice}}/idpvoice/searchschedule?name={{name}}&channelname=... | stack_v2_sparse_classes_36k_train_013179 | 1,871 | no_license | [
{
"docstring": "6.1 直播搜索节目列表接口",
"name": "test_1直播搜索节目列表接口",
"signature": "def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}')"
},
{
"docstring": "6.2回看搜索节目列表接口",
"name": "test_2回看搜索节目列表接口",
"signature": "def test_2回看搜索... | 3 | stack_v2_sparse_classes_30k_train_018020 | Implement the Python class `Test_语音搜索服务接口` described below.
Class description:
Implement the Test_语音搜索服务接口 class.
Method signatures and docstrings:
- def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'): 6.1 直播搜索节目列表接口
- def test_2回看搜索节目列表接口(self, ur... | Implement the Python class `Test_语音搜索服务接口` described below.
Class description:
Implement the Test_语音搜索服务接口 class.
Method signatures and docstrings:
- def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'): 6.1 直播搜索节目列表接口
- def test_2回看搜索节目列表接口(self, ur... | 8c3a2447e53f1fcf7d418e171a01c8e94fc4c8ae | <|skeleton|>
class Test_语音搜索服务接口:
def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'):
"""6.1 直播搜索节目列表接口"""
<|body_0|>
def test_2回看搜索节目列表接口(self, url='http://{{snm_idpVoice}}/idpvoice/searchschedule?name={{name}}&channelname=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_语音搜索服务接口:
def test_1直播搜索节目列表接口(self, url='http://{{idpURL}}/idpvoice/searchchannel?name={{name}}&start={{start}}&count={{count}}'):
"""6.1 直播搜索节目列表接口"""
Ioput.function_name(self.__class__.__name__)
try:
self.execute_test(url=url)
self.get_text_value(kone='s... | the_stack_v2_python_sparse | BI_6.0.7_WebUI_AUTOTOOLS_003/BI_6.0.7_WebUI_AUTOTOOLS_03/BI_6.0.7_WebUI_AUTOTOOLS_03/test_case/idmp/搜索推荐/语音搜索服务接口_6/case.py | demi52/mandy | train | 0 | |
b9145842440778a3f8f01b37f50387049c066b83 | [
"captures: List[UsageCapture] = []\nstack: List[Any] = []\nexclude = set() if exclude is None else exclude\n\ndef finder(part):\n if isinstance(part, Variable) and part.variable == var:\n use = part\n work = list(stack)\n while True:\n item = work.pop()\n if isinstance(... | <|body_start_0|>
captures: List[UsageCapture] = []
stack: List[Any] = []
exclude = set() if exclude is None else exclude
def finder(part):
if isinstance(part, Variable) and part.variable == var:
use = part
work = list(stack)
wh... | Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter. | Lifter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lifter:
"""Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter."""
def capture_usages(base: Block, var: ChunkVariable, recursive: ... | stack_v2_sparse_classes_36k_train_013180 | 9,836 | no_license | [
{
"docstring": "Find and capture all the usages (and their contexts) of a variable in a block.",
"name": "capture_usages",
"signature": "def capture_usages(base: Block, var: ChunkVariable, recursive: bool=True, exclude: Optional[Set[Block]]=None) -> List['UsageCapture']"
},
{
"docstring": "Retur... | 3 | null | Implement the Python class `Lifter` described below.
Class description:
Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter.
Method signatures and docstring... | Implement the Python class `Lifter` described below.
Class description:
Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter.
Method signatures and docstring... | 4d37cc16f61af70920c36389fae0c6955b5d9551 | <|skeleton|>
class Lifter:
"""Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter."""
def capture_usages(base: Block, var: ChunkVariable, recursive: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lifter:
"""Utility methods for lifting variables to their most common usages. These functions provide primitives for the interpreter to replace function calls, function signatures and variable usages with the lifted paramter."""
def capture_usages(base: Block, var: ChunkVariable, recursive: bool=True, ex... | the_stack_v2_python_sparse | vulnspec/interpret/lifter.py | jedevc/fyp | train | 0 |
02b7572458a23a3ce384e19c4594cf02f7429179 | [
"p = histogram\np /= np.sum(p)\nq = np.power(histogram, gamma)\nq /= np.sum(q)\nc = 1.0 / k\nalpha = np.sum((p - q) * (p - q)) / np.sum((p - c) * (p - c))\nrate = (1 - alpha) / (1 - alpha + c)\nreturn rate",
"n_category = np.max(dataset)\nself.n_category = n_category\nself.dataset = np.array(dataset)\nhistogram =... | <|body_start_0|>
p = histogram
p /= np.sum(p)
q = np.power(histogram, gamma)
q /= np.sum(q)
c = 1.0 / k
alpha = np.sum((p - q) * (p - q)) / np.sum((p - c) * (p - c))
rate = (1 - alpha) / (1 - alpha + c)
return rate
<|end_body_0|>
<|body_start_1|>
... | Categoricl Sampler - the sampler for getting negative samples | CategoricalSampler | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"CC-BY-NC-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoricalSampler:
"""Categoricl Sampler - the sampler for getting negative samples"""
def calc_random_method_selection_rate(self, k, histogram, gamma):
"""Calculate 2 random type selection rate In this example, the sampler combines 2 random method - sample from dataset - sample fro... | stack_v2_sparse_classes_36k_train_013181 | 11,796 | permissive | [
{
"docstring": "Calculate 2 random type selection rate In this example, the sampler combines 2 random method - sample from dataset - sample from uniform random of n_category This operation intends to simulate the distribution of powered histogram. This function calculate the rate of 2 random method minimizing t... | 3 | stack_v2_sparse_classes_30k_train_021384 | Implement the Python class `CategoricalSampler` described below.
Class description:
Categoricl Sampler - the sampler for getting negative samples
Method signatures and docstrings:
- def calc_random_method_selection_rate(self, k, histogram, gamma): Calculate 2 random type selection rate In this example, the sampler co... | Implement the Python class `CategoricalSampler` described below.
Class description:
Categoricl Sampler - the sampler for getting negative samples
Method signatures and docstrings:
- def calc_random_method_selection_rate(self, k, histogram, gamma): Calculate 2 random type selection rate In this example, the sampler co... | 41f71faa6efff7774a76bbd5af3198322a90a6ab | <|skeleton|>
class CategoricalSampler:
"""Categoricl Sampler - the sampler for getting negative samples"""
def calc_random_method_selection_rate(self, k, histogram, gamma):
"""Calculate 2 random type selection rate In this example, the sampler combines 2 random method - sample from dataset - sample fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoricalSampler:
"""Categoricl Sampler - the sampler for getting negative samples"""
def calc_random_method_selection_rate(self, k, histogram, gamma):
"""Calculate 2 random type selection rate In this example, the sampler combines 2 random method - sample from dataset - sample from uniform ran... | the_stack_v2_python_sparse | language-modeling/word2vec/word_embedding.py | sony/nnabla-examples | train | 308 |
ed9e175402b075bca6d1fabe8640635b0465da44 | [
"self.contains_change_event = contains_change_event\nself.end_seq_number = end_seq_number\nself.log_file_name = log_file_name\nself.log_rollover = log_rollover\nself.start_seq_number = start_seq_number",
"if dictionary is None:\n return None\ncontains_change_event = dictionary.get('containsChangeEvent')\nend_s... | <|body_start_0|>
self.contains_change_event = contains_change_event
self.end_seq_number = end_seq_number
self.log_file_name = log_file_name
self.log_rollover = log_rollover
self.start_seq_number = start_seq_number
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond to the range of logs inside this file whi... | NoSqlLogData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoSqlLogData:
"""Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond t... | stack_v2_sparse_classes_36k_train_013182 | 3,523 | permissive | [
{
"docstring": "Constructor for the NoSqlLogData class",
"name": "__init__",
"signature": "def __init__(self, contains_change_event=None, end_seq_number=None, log_file_name=None, log_rollover=None, start_seq_number=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Arg... | 2 | stack_v2_sparse_classes_30k_train_008281 | Implement the Python class `NoSqlLogData` described below.
Class description:
Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The star... | Implement the Python class `NoSqlLogData` described below.
Class description:
Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The star... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NoSqlLogData:
"""Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoSqlLogData:
"""Implementation of the 'NoSqlLogData' model. Proto that contains the information about a log file containing MongoDB cdp logs pertaining to an entity. This is populated from the data events written to scribe for corresponding entity. The start and end sequence numbers correspond to the range o... | the_stack_v2_python_sparse | cohesity_management_sdk/models/no_sql_log_data.py | cohesity/management-sdk-python | train | 24 |
ecb96a3a2ba4adacc3434459e291d6ebe958f56c | [
"self.xi = np.asarray(xi)\nself.T = T\nself.n_waypoints = self.xi.shape[0]\ntimesteps = np.linspace(0, self.T, self.n_waypoints)\nself.f1 = interp1d(timesteps, self.xi[:, 0], kind='cubic')\nself.f2 = interp1d(timesteps, self.xi[:, 1], kind='cubic')\nself.f3 = interp1d(timesteps, self.xi[:, 2], kind='cubic')\nself.f... | <|body_start_0|>
self.xi = np.asarray(xi)
self.T = T
self.n_waypoints = self.xi.shape[0]
timesteps = np.linspace(0, self.T, self.n_waypoints)
self.f1 = interp1d(timesteps, self.xi[:, 0], kind='cubic')
self.f2 = interp1d(timesteps, self.xi[:, 1], kind='cubic')
self... | Trajectory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
<|body_0|>
def get(self, t):
"""get interpolated position"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.xi = np.asarray(xi)
self.T = T
... | stack_v2_sparse_classes_36k_train_013183 | 4,949 | permissive | [
{
"docstring": "create cublic interpolators between waypoints",
"name": "__init__",
"signature": "def __init__(self, xi, T)"
},
{
"docstring": "get interpolated position",
"name": "get",
"signature": "def get(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007093 | Implement the Python class `Trajectory` described below.
Class description:
Implement the Trajectory class.
Method signatures and docstrings:
- def __init__(self, xi, T): create cublic interpolators between waypoints
- def get(self, t): get interpolated position | Implement the Python class `Trajectory` described below.
Class description:
Implement the Trajectory class.
Method signatures and docstrings:
- def __init__(self, xi, T): create cublic interpolators between waypoints
- def get(self, t): get interpolated position
<|skeleton|>
class Trajectory:
def __init__(self,... | 65695ac0ad4ffc28474f1920c2d2ff484481caf3 | <|skeleton|>
class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
<|body_0|>
def get(self, t):
"""get interpolated position"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
self.xi = np.asarray(xi)
self.T = T
self.n_waypoints = self.xi.shape[0]
timesteps = np.linspace(0, self.T, self.n_waypoints)
self.f1 = interp1d(timesteps, self.xi[:, 0], k... | the_stack_v2_python_sparse | simulations/panda/task2/collect_human_demos.py | VT-Collab/choice-sets | train | 1 | |
df34aca7b8174b152b3f13424165f592b2383f1f | [
"map_s = defaultdict(list)\nmap_t = defaultdict(list)\nfor i, ch in enumerate(s):\n map_s[ch].append(i)\nfor i, ch in enumerate(t):\n map_t[ch].append(i)\nreturn sorted(map_s.itervalues()) == sorted(map_t.itervalues())",
"map_s = defaultdict(lambda: -1)\nmap_t = defaultdict(lambda: -1)\nfor i, (ch_s, ch_t) ... | <|body_start_0|>
map_s = defaultdict(list)
map_t = defaultdict(list)
for i, ch in enumerate(s):
map_s[ch].append(i)
for i, ch in enumerate(t):
map_t[ch].append(i)
return sorted(map_s.itervalues()) == sorted(map_t.itervalues())
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isIsomorphic_hashmap_list(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
map_s = defaultdict(... | stack_v2_sparse_classes_36k_train_013184 | 992 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isIsomorphic_hashmap_list",
"signature": "def isIsomorphic_hashmap_list(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isIsomorphic",
"signature": "def isIsomorphic(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002887 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isIsomorphic_hashmap_list(self, s, t): :type s: str :type t: str :rtype: bool
- def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isIsomorphic_hashmap_list(self, s, t): :type s: str :type t: str :rtype: bool
- def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solut... | 5c2473f859da5efec73120256faad06ab8e0e359 | <|skeleton|>
class Solution:
def isIsomorphic_hashmap_list(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isIsomorphic_hashmap_list(self, s, t):
""":type s: str :type t: str :rtype: bool"""
map_s = defaultdict(list)
map_t = defaultdict(list)
for i, ch in enumerate(s):
map_s[ch].append(i)
for i, ch in enumerate(t):
map_t[ch].append(i)
... | the_stack_v2_python_sparse | leetcode/isomorphic_strings.py | chlos/exercises_in_futility | train | 0 | |
fe562d7ac4da2a2da9688a3d2e4a78a790565a36 | [
"if not isinstance(other, Tag):\n return -1\nif other.name != self.name:\n return cmp(self.name, other.name)\nif other.attributes != self.attributes:\n return cmp(self.attributes, other.attributes)\nif other.content != self.content:\n return cmp(self.content, other.content)\nreturn 0",
"fragments = []... | <|body_start_0|>
if not isinstance(other, Tag):
return -1
if other.name != self.name:
return cmp(self.name, other.name)
if other.attributes != self.attributes:
return cmp(self.attributes, other.attributes)
if other.content != self.content:
... | Represents a particular tag within a document | Tag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""Represents a particular tag within a document"""
def __cmp__(self, other):
"""Compare this tag to another"""
<|body_0|>
def __repr__(self):
"""Create a decent representation of this tag"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_36k_train_013185 | 2,813 | no_license | [
{
"docstring": "Compare this tag to another",
"name": "__cmp__",
"signature": "def __cmp__(self, other)"
},
{
"docstring": "Create a decent representation of this tag",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017410 | Implement the Python class `Tag` described below.
Class description:
Represents a particular tag within a document
Method signatures and docstrings:
- def __cmp__(self, other): Compare this tag to another
- def __repr__(self): Create a decent representation of this tag | Implement the Python class `Tag` described below.
Class description:
Represents a particular tag within a document
Method signatures and docstrings:
- def __cmp__(self, other): Compare this tag to another
- def __repr__(self): Create a decent representation of this tag
<|skeleton|>
class Tag:
"""Represents a par... | 496fc33954072147c379b8a9a1957bb04fd93670 | <|skeleton|>
class Tag:
"""Represents a particular tag within a document"""
def __cmp__(self, other):
"""Compare this tag to another"""
<|body_0|>
def __repr__(self):
"""Create a decent representation of this tag"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tag:
"""Represents a particular tag within a document"""
def __cmp__(self, other):
"""Compare this tag to another"""
if not isinstance(other, Tag):
return -1
if other.name != self.name:
return cmp(self.name, other.name)
if other.attributes != self.a... | the_stack_v2_python_sparse | basicproperty/xmlencoder.py | eshikvtumane/basicproperty | train | 0 |
fdc43cc153c0c47850c164e34e9dcdd79ebae420 | [
"assert isinstance(response, Response), 'Invalid response %s' % response\nassert isinstance(responseCnt, ResponseContent), 'Invalid response content %s' % responseCnt\nif Response.code in response and (not response.code.isSuccess):\n return\nif Response.encoder not in response:\n return\nresponseCnt.source = ... | <|body_start_0|>
assert isinstance(response, Response), 'Invalid response %s' % response
assert isinstance(responseCnt, ResponseContent), 'Invalid response content %s' % responseCnt
if Response.code in response and (not response.code.isSuccess):
return
if Response.encoder not... | Implementation for a handler that renders the response content encoder. | RenderEncoderHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenderEncoderHandler:
"""Implementation for a handler that renders the response content encoder."""
def process(self, response: Response, responseCnt: ResponseContent, **keyargs):
"""@see: HandlerProcessorProceed.process"""
<|body_0|>
def renderAsGenerator(self, value, e... | stack_v2_sparse_classes_36k_train_013186 | 3,021 | no_license | [
{
"docstring": "@see: HandlerProcessorProceed.process",
"name": "process",
"signature": "def process(self, response: Response, responseCnt: ResponseContent, **keyargs)"
},
{
"docstring": "Create a generator for rendering the encoder.",
"name": "renderAsGenerator",
"signature": "def rende... | 2 | stack_v2_sparse_classes_30k_train_004577 | Implement the Python class `RenderEncoderHandler` described below.
Class description:
Implementation for a handler that renders the response content encoder.
Method signatures and docstrings:
- def process(self, response: Response, responseCnt: ResponseContent, **keyargs): @see: HandlerProcessorProceed.process
- def ... | Implement the Python class `RenderEncoderHandler` described below.
Class description:
Implementation for a handler that renders the response content encoder.
Method signatures and docstrings:
- def process(self, response: Response, responseCnt: ResponseContent, **keyargs): @see: HandlerProcessorProceed.process
- def ... | a697e50feb0b113468e0297c4ed2f6b3c3cbc785 | <|skeleton|>
class RenderEncoderHandler:
"""Implementation for a handler that renders the response content encoder."""
def process(self, response: Response, responseCnt: ResponseContent, **keyargs):
"""@see: HandlerProcessorProceed.process"""
<|body_0|>
def renderAsGenerator(self, value, e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RenderEncoderHandler:
"""Implementation for a handler that renders the response content encoder."""
def process(self, response: Response, responseCnt: ResponseContent, **keyargs):
"""@see: HandlerProcessorProceed.process"""
assert isinstance(response, Response), 'Invalid response %s' % re... | the_stack_v2_python_sparse | components/ally-core/ally/core/impl/processor/render_encoder.py | ahilles107/Superdesk | train | 0 |
65201219c8f5bdc91e2aa7dd650edcdb828ca759 | [
"if map_size[0] < 5 and map_size[1] < 5:\n raise InvalidMapSizeError('Map size must be greater than 4.')\nself.size = map_size\nself.map_ = [[0] * map_size[1] for _ in range(map_size[0])]\nself.generatemap_(map_size, percent_of_traps, percent_of_treasures)",
"number_of_traps = max(3, floor(map_size[0] * map_si... | <|body_start_0|>
if map_size[0] < 5 and map_size[1] < 5:
raise InvalidMapSizeError('Map size must be greater than 4.')
self.size = map_size
self.map_ = [[0] * map_size[1] for _ in range(map_size[0])]
self.generatemap_(map_size, percent_of_traps, percent_of_treasures)
<|end_bo... | GameMap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameMap:
def __init__(self, map_size, percent_of_traps, percent_of_treasures):
"""Function creates map Args: map_size(list(int)): map size percent_of_traps(float): percent of traps percent_of_treasures(float): percent of treasures Returns: none"""
<|body_0|>
def generatemap_... | stack_v2_sparse_classes_36k_train_013187 | 2,548 | permissive | [
{
"docstring": "Function creates map Args: map_size(list(int)): map size percent_of_traps(float): percent of traps percent_of_treasures(float): percent of treasures Returns: none",
"name": "__init__",
"signature": "def __init__(self, map_size, percent_of_traps, percent_of_treasures)"
},
{
"docst... | 4 | null | Implement the Python class `GameMap` described below.
Class description:
Implement the GameMap class.
Method signatures and docstrings:
- def __init__(self, map_size, percent_of_traps, percent_of_treasures): Function creates map Args: map_size(list(int)): map size percent_of_traps(float): percent of traps percent_of_... | Implement the Python class `GameMap` described below.
Class description:
Implement the GameMap class.
Method signatures and docstrings:
- def __init__(self, map_size, percent_of_traps, percent_of_treasures): Function creates map Args: map_size(list(int)): map size percent_of_traps(float): percent of traps percent_of_... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class GameMap:
def __init__(self, map_size, percent_of_traps, percent_of_treasures):
"""Function creates map Args: map_size(list(int)): map size percent_of_traps(float): percent of traps percent_of_treasures(float): percent of treasures Returns: none"""
<|body_0|>
def generatemap_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameMap:
def __init__(self, map_size, percent_of_traps, percent_of_treasures):
"""Function creates map Args: map_size(list(int)): map size percent_of_traps(float): percent of traps percent_of_treasures(float): percent of treasures Returns: none"""
if map_size[0] < 5 and map_size[1] < 5:
... | the_stack_v2_python_sparse | Kateryna_Liukina/10/dangeon_game_package_kliukina/dangeon_game_package_kliukina/game_map.py | SmischenkoB/campus_2018_python | train | 0 | |
3443b642c15b47ee5a8f373b6f86c22c394f0a6a | [
"if 'cnpj_raiz' in options and options['cnpj_raiz'] is not None:\n result = self.find_row('empresa', options['cnpj_raiz'], options.get('column_family'), options.get('column'))\n nu_results = {}\n for ds_key in result:\n if not result[ds_key].empty and ds_key in self.PERSP_COLUMNS:\n for n... | <|body_start_0|>
if 'cnpj_raiz' in options and options['cnpj_raiz'] is not None:
result = self.find_row('empresa', options['cnpj_raiz'], options.get('column_family'), options.get('column'))
nu_results = {}
for ds_key in result:
if not result[ds_key].empty and ... | Definição do repo | EmpresaRepository | [
"MIT",
"BSD-3-Clause",
"ISC",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmpresaRepository:
"""Definição do repo"""
def find_datasets(self, options):
"""Localiza um município pelo código do IBGE"""
<|body_0|>
def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name):
"""Filter dataframe by person identification, according t... | stack_v2_sparse_classes_36k_train_013188 | 3,969 | permissive | [
{
"docstring": "Localiza um município pelo código do IBGE",
"name": "find_datasets",
"signature": "def find_datasets(self, options)"
},
{
"docstring": "Filter dataframe by person identification, according to options data",
"name": "filter_by_person",
"signature": "def filter_by_person(da... | 2 | stack_v2_sparse_classes_30k_train_005943 | Implement the Python class `EmpresaRepository` described below.
Class description:
Definição do repo
Method signatures and docstrings:
- def find_datasets(self, options): Localiza um município pelo código do IBGE
- def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name): Filter dataframe by person identi... | Implement the Python class `EmpresaRepository` described below.
Class description:
Definição do repo
Method signatures and docstrings:
- def find_datasets(self, options): Localiza um município pelo código do IBGE
- def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name): Filter dataframe by person identi... | 4f8b09f2dd1227c42d2788553b55159365168080 | <|skeleton|>
class EmpresaRepository:
"""Definição do repo"""
def find_datasets(self, options):
"""Localiza um município pelo código do IBGE"""
<|body_0|>
def filter_by_person(dataframe, options, col_cnpj_name, col_pf_name):
"""Filter dataframe by person identification, according t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmpresaRepository:
"""Definição do repo"""
def find_datasets(self, options):
"""Localiza um município pelo código do IBGE"""
if 'cnpj_raiz' in options and options['cnpj_raiz'] is not None:
result = self.find_row('empresa', options['cnpj_raiz'], options.get('column_family'), op... | the_stack_v2_python_sparse | app/repository/empresa/empresa.py | smartlab-br/suetonio-api | train | 1 |
1eb6e5ffbe1628eb6e46c4d5c984b2de69dbf8c7 | [
"store_view_obj = self.pool.get('magento.store.store_view')\nstore_view = store_view_obj.browse(cursor, user, context.get('active_id'))\ncontext.update({'magento_instance': store_view.instance.id})\nshipments = store_view_obj.export_shipment_status_to_magento(cursor, user, store_view, context)\nreturn self.open_shi... | <|body_start_0|>
store_view_obj = self.pool.get('magento.store.store_view')
store_view = store_view_obj.browse(cursor, user, context.get('active_id'))
context.update({'magento_instance': store_view.instance.id})
shipments = store_view_obj.export_shipment_status_to_magento(cursor, user, s... | Export Shipment Status | ExportShipmentStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportShipmentStatus:
"""Export Shipment Status"""
def export_shipment_status(self, cursor, user, ids, context):
"""Exports shipment status for sale orders related to current store view :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records ... | stack_v2_sparse_classes_36k_train_013189 | 2,251 | no_license | [
{
"docstring": "Exports shipment status for sale orders related to current store view :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records for this model :param context: Application context :return: View for shipments exported",
"name": "export_shipment_status",
... | 2 | stack_v2_sparse_classes_30k_train_003426 | Implement the Python class `ExportShipmentStatus` described below.
Class description:
Export Shipment Status
Method signatures and docstrings:
- def export_shipment_status(self, cursor, user, ids, context): Exports shipment status for sale orders related to current store view :param cursor: Database cursor :param use... | Implement the Python class `ExportShipmentStatus` described below.
Class description:
Export Shipment Status
Method signatures and docstrings:
- def export_shipment_status(self, cursor, user, ids, context): Exports shipment status for sale orders related to current store view :param cursor: Database cursor :param use... | f661c776973868c0414007791ae6a0b069b1038f | <|skeleton|>
class ExportShipmentStatus:
"""Export Shipment Status"""
def export_shipment_status(self, cursor, user, ids, context):
"""Exports shipment status for sale orders related to current store view :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExportShipmentStatus:
"""Export Shipment Status"""
def export_shipment_status(self, cursor, user, ids, context):
"""Exports shipment status for sale orders related to current store view :param cursor: Database cursor :param user: ID of current user :param ids: List of ids of records for this mode... | the_stack_v2_python_sparse | wizard/export_shipment_status.py | openlabs/magento_integration | train | 23 |
b8cb284d1143847643f4844c603cd9d7862bcfee | [
"if not tree.root:\n return\nqueue = [tree.root]\nresult = [tree.root.item]\nwhile len(queue) > 0:\n print(result)\n parent = queue.pop(0)\n if parent.lchild:\n queue.append(parent.lchild)\n result.append(parent.lchild.item)\n if parent.rchild:\n queue.append(parent.rchild)\n ... | <|body_start_0|>
if not tree.root:
return
queue = [tree.root]
result = [tree.root.item]
while len(queue) > 0:
print(result)
parent = queue.pop(0)
if parent.lchild:
queue.append(parent.lchild)
result.append(pa... | Display | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Display:
def traverse(self, tree):
"""层序遍历 :param tree: :return: None"""
<|body_0|>
def preorder(self, root, result):
"""先序遍历 :param tree: :return:"""
<|body_1|>
def inorder(self, root, result):
"""中序遍历 :param tree: :return:"""
<|body_2|>... | stack_v2_sparse_classes_36k_train_013190 | 1,877 | no_license | [
{
"docstring": "层序遍历 :param tree: :return: None",
"name": "traverse",
"signature": "def traverse(self, tree)"
},
{
"docstring": "先序遍历 :param tree: :return:",
"name": "preorder",
"signature": "def preorder(self, root, result)"
},
{
"docstring": "中序遍历 :param tree: :return:",
"n... | 4 | stack_v2_sparse_classes_30k_val_000423 | Implement the Python class `Display` described below.
Class description:
Implement the Display class.
Method signatures and docstrings:
- def traverse(self, tree): 层序遍历 :param tree: :return: None
- def preorder(self, root, result): 先序遍历 :param tree: :return:
- def inorder(self, root, result): 中序遍历 :param tree: :retur... | Implement the Python class `Display` described below.
Class description:
Implement the Display class.
Method signatures and docstrings:
- def traverse(self, tree): 层序遍历 :param tree: :return: None
- def preorder(self, root, result): 先序遍历 :param tree: :return:
- def inorder(self, root, result): 中序遍历 :param tree: :retur... | dca66459b4dd0bb1afe3ff73f4cd92430c35be41 | <|skeleton|>
class Display:
def traverse(self, tree):
"""层序遍历 :param tree: :return: None"""
<|body_0|>
def preorder(self, root, result):
"""先序遍历 :param tree: :return:"""
<|body_1|>
def inorder(self, root, result):
"""中序遍历 :param tree: :return:"""
<|body_2|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Display:
def traverse(self, tree):
"""层序遍历 :param tree: :return: None"""
if not tree.root:
return
queue = [tree.root]
result = [tree.root.item]
while len(queue) > 0:
print(result)
parent = queue.pop(0)
if parent.lchild:
... | the_stack_v2_python_sparse | binary_tree/tree_display.py | bobowang2017/python_study | train | 0 | |
dff422604925852beb33243f2541cb8ced386921 | [
"if x < 0:\n return False\nx_str = str(x)\ny_str = x_str[::-1]\nif y_str == x_str:\n return True\nelse:\n return False",
"if x < 0:\n return False\nelif x == 0:\n return True\nori_x = x\ntemp = 0\nwhile x != 0:\n temp = temp * 10 + x % 10\n x //= 10\nreturn temp == ori_x"
] | <|body_start_0|>
if x < 0:
return False
x_str = str(x)
y_str = x_str[::-1]
if y_str == x_str:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if x < 0:
return False
elif x == 0:
return Tru... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindromeByStr(self, x: int) -> bool:
"""使用字符串转置的方法 :param x: :return:"""
<|body_0|>
def isPalindromeByNum(self, x: int) -> bool:
"""使用数字运算的方法 :param x: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
... | stack_v2_sparse_classes_36k_train_013191 | 784 | no_license | [
{
"docstring": "使用字符串转置的方法 :param x: :return:",
"name": "isPalindromeByStr",
"signature": "def isPalindromeByStr(self, x: int) -> bool"
},
{
"docstring": "使用数字运算的方法 :param x: :return:",
"name": "isPalindromeByNum",
"signature": "def isPalindromeByNum(self, x: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_test_000388 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindromeByStr(self, x: int) -> bool: 使用字符串转置的方法 :param x: :return:
- def isPalindromeByNum(self, x: int) -> bool: 使用数字运算的方法 :param x: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindromeByStr(self, x: int) -> bool: 使用字符串转置的方法 :param x: :return:
- def isPalindromeByNum(self, x: int) -> bool: 使用数字运算的方法 :param x: :return:
<|skeleton|>
class Solutio... | 976d9185eca401587000dab56b6330542bc8437c | <|skeleton|>
class Solution:
def isPalindromeByStr(self, x: int) -> bool:
"""使用字符串转置的方法 :param x: :return:"""
<|body_0|>
def isPalindromeByNum(self, x: int) -> bool:
"""使用数字运算的方法 :param x: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindromeByStr(self, x: int) -> bool:
"""使用字符串转置的方法 :param x: :return:"""
if x < 0:
return False
x_str = str(x)
y_str = x_str[::-1]
if y_str == x_str:
return True
else:
return False
def isPalindromeByNum(... | the_stack_v2_python_sparse | leetcode/algorithm/9.py | baiasuka/PyhtonStudy | train | 0 | |
74d5a7459a82557c7613f8cce75e61c523729a15 | [
"self.agents = agents\nself.backup_type = backup_type\nself.build_number = build_number\nself.cluster_name = cluster_name\nself.datastore_info = datastore_info\nself.description = description\nself.host_type = host_type\nself.hyperv_uuid = hyperv_uuid\nself.name = name\nself.tag_attributes = tag_attributes\nself.mt... | <|body_start_0|>
self.agents = agents
self.backup_type = backup_type
self.build_number = build_number
self.cluster_name = cluster_name
self.datastore_info = datastore_info
self.description = description
self.host_type = host_type
self.hyperv_uuid = hyperv_... | Implementation of the 'HypervProtectionSource' model. Specifies a Protection Source in HyperV environment. Attributes: agents (list of AgentInformation): Array of Agents on the Physical Protection Source. Specifiles the agents running on the HyperV Protection Source and the status information. backup_type (BackupTypeEn... | HypervProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypervProtectionSource:
"""Implementation of the 'HypervProtectionSource' model. Specifies a Protection Source in HyperV environment. Attributes: agents (list of AgentInformation): Array of Agents on the Physical Protection Source. Specifiles the agents running on the HyperV Protection Source and... | stack_v2_sparse_classes_36k_train_013192 | 7,792 | permissive | [
{
"docstring": "Constructor for the HypervProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, agents=None, backup_type=None, build_number=None, cluster_name=None, datastore_info=None, description=None, host_type=None, hyperv_uuid=None, name=None, tag_attributes=None, mtype=None... | 2 | null | Implement the Python class `HypervProtectionSource` described below.
Class description:
Implementation of the 'HypervProtectionSource' model. Specifies a Protection Source in HyperV environment. Attributes: agents (list of AgentInformation): Array of Agents on the Physical Protection Source. Specifiles the agents runn... | Implement the Python class `HypervProtectionSource` described below.
Class description:
Implementation of the 'HypervProtectionSource' model. Specifies a Protection Source in HyperV environment. Attributes: agents (list of AgentInformation): Array of Agents on the Physical Protection Source. Specifiles the agents runn... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class HypervProtectionSource:
"""Implementation of the 'HypervProtectionSource' model. Specifies a Protection Source in HyperV environment. Attributes: agents (list of AgentInformation): Array of Agents on the Physical Protection Source. Specifiles the agents running on the HyperV Protection Source and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HypervProtectionSource:
"""Implementation of the 'HypervProtectionSource' model. Specifies a Protection Source in HyperV environment. Attributes: agents (list of AgentInformation): Array of Agents on the Physical Protection Source. Specifiles the agents running on the HyperV Protection Source and the status i... | the_stack_v2_python_sparse | cohesity_management_sdk/models/hyperv_protection_source.py | cohesity/management-sdk-python | train | 24 |
994230ab0479ed58e3b84eb43673850649f3c682 | [
"available = super().available\nin_delivery = 'g:delivery' in self.user_groups_slugs()\nreturn available and in_delivery",
"payload = super().transform()\ndata = self.data\npayload[0]['data'] = {'FIRSTNAME': data.get('first_name'), 'FULLNAME': data.get('fullname'), 'EMAIL': data.get('email'), 'PASSWORD': data.get... | <|body_start_0|>
available = super().available
in_delivery = 'g:delivery' in self.user_groups_slugs()
return available and in_delivery
<|end_body_0|>
<|body_start_1|>
payload = super().transform()
data = self.data
payload[0]['data'] = {'FIRSTNAME': data.get('first_name')... | After creating a new User with access to the delivery system, send an welcome email. | UserDeliveryCreated | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDeliveryCreated:
"""After creating a new User with access to the delivery system, send an welcome email."""
def available(self) -> bool:
"""Send email only if internal attribute is set on the payload and g:delivery is one ."""
<|body_0|>
def transform(self) -> t.List... | stack_v2_sparse_classes_36k_train_013193 | 4,062 | no_license | [
{
"docstring": "Send email only if internal attribute is set on the payload and g:delivery is one .",
"name": "available",
"signature": "def available(self) -> bool"
},
{
"docstring": "Transform data.",
"name": "transform",
"signature": "def transform(self) -> t.List[dict]"
}
] | 2 | null | Implement the Python class `UserDeliveryCreated` described below.
Class description:
After creating a new User with access to the delivery system, send an welcome email.
Method signatures and docstrings:
- def available(self) -> bool: Send email only if internal attribute is set on the payload and g:delivery is one .... | Implement the Python class `UserDeliveryCreated` described below.
Class description:
After creating a new User with access to the delivery system, send an welcome email.
Method signatures and docstrings:
- def available(self) -> bool: Send email only if internal attribute is set on the payload and g:delivery is one .... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class UserDeliveryCreated:
"""After creating a new User with access to the delivery system, send an welcome email."""
def available(self) -> bool:
"""Send email only if internal attribute is set on the payload and g:delivery is one ."""
<|body_0|>
def transform(self) -> t.List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDeliveryCreated:
"""After creating a new User with access to the delivery system, send an welcome email."""
def available(self) -> bool:
"""Send email only if internal attribute is set on the payload and g:delivery is one ."""
available = super().available
in_delivery = 'g:del... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/user.py | BriefyHQ/briefy.choreographer | train | 0 |
c3b2635fbaa08ff2f6ec66a10ebc1e781c8ad05d | [
"resNode = ListNode(0)\nmove = resNode\nreslist = []\nwhile head:\n reslist.append(head.val)\n head = head.next\nreslist.reverse()\nfor i in reslist:\n move.next = ListNode(i)\n move = move.next\nreturn resNode.next",
"if not head:\n return head\nstack = []\nwhile head:\n stack.append(head.val)\... | <|body_start_0|>
resNode = ListNode(0)
move = resNode
reslist = []
while head:
reslist.append(head.val)
head = head.next
reslist.reverse()
for i in reslist:
move.next = ListNode(i)
move = move.next
return resNode.nex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]"""
<|body_0|>
def reverseList(self, hea... | stack_v2_sparse_classes_36k_train_013194 | 4,109 | no_license | [
{
"docstring": "最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]",
"name": "reverseList",
"signature": "def reverseList(self, head: ListNode) -> ListNode"
},
{
"docstring": ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]"""
<|body_0|>
def reverseList(self, hea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""最简单的方法就是申请一个动态扩容 然后不断遍历链表,将链表中的元素添加到这个容器中 再利用容器自身的API,翻转整个容器,这就可以达到翻转的效果 最后同时遍历容器和链表,将链表中的值改为容器中的值 这种方法很简单,但是面试中,肯定需要更优的方法,比如不用外部空间 输入为:[1, 2, 3, 4, 5] 输出为:[5, 4, 3, 2, 1]"""
resNode = ListNode(0)
move = resNode
re... | the_stack_v2_python_sparse | LeetCode_practice/LinkedList/0206.ReverseLinkedList.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
5aac5c6838d935a925a7b4dc29bba06ad5ef82c3 | [
"self.n = n\nself.queens = list()\nif randomize:\n for q in range(n):\n empty_space = False\n while not empty_space:\n row = random.choice(range(n))\n col = random.choice(range(n))\n if not [row, col] in self.queens:\n empty_space = True\n self... | <|body_start_0|>
self.n = n
self.queens = list()
if randomize:
for q in range(n):
empty_space = False
while not empty_space:
row = random.choice(range(n))
col = random.choice(range(n))
if not ... | Class that represents n-queens placed on a chess board. | Board | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Board:
"""Class that represents n-queens placed on a chess board."""
def __init__(self, n, randomize=True):
"""This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen random... | stack_v2_sparse_classes_36k_train_013195 | 5,454 | no_license | [
{
"docstring": "This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen randomly. False indicates that the queen are placed on the first row.",
"name": "__init__",
"signature": "def __init__(se... | 5 | stack_v2_sparse_classes_30k_train_007317 | Implement the Python class `Board` described below.
Class description:
Class that represents n-queens placed on a chess board.
Method signatures and docstrings:
- def __init__(self, n, randomize=True): This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : T... | Implement the Python class `Board` described below.
Class description:
Class that represents n-queens placed on a chess board.
Method signatures and docstrings:
- def __init__(self, n, randomize=True): This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : T... | bc57784f95a8adfb0154a3fb3d1ef3245e7d22ae | <|skeleton|>
class Board:
"""Class that represents n-queens placed on a chess board."""
def __init__(self, n, randomize=True):
"""This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen random... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Board:
"""Class that represents n-queens placed on a chess board."""
def __init__(self, n, randomize=True):
"""This constructor initializes the board with n queens. n : The number of rows and columns of the chess. randomize : True indicates that the queen positions are choosen randomly. False ind... | the_stack_v2_python_sparse | Actividades/Problemas de busqueda local/n_queens_greedy_search.py | gherreraa1/ProjectoSistemasInteligentes | train | 0 |
b60734479f1c0cb2ccbcb23571f67dd1c408a627 | [
"clean_data = super(GradeSurveyTakeForm, self).setCleaners(post_dict=post_dict)\nif post_dict:\n clean_data['grade'] = post_dict.get('grade', None)\nreturn clean_data",
"grade = self.cleaned_data['grade']\ngrade_vals = {'pass': True, 'fail': False, '': ''}\nreturn grade_vals.get(grade, None)",
"post_dict = p... | <|body_start_0|>
clean_data = super(GradeSurveyTakeForm, self).setCleaners(post_dict=post_dict)
if post_dict:
clean_data['grade'] = post_dict.get('grade', None)
return clean_data
<|end_body_0|>
<|body_start_1|>
grade = self.cleaned_data['grade']
grade_vals = {'pass':... | Extends SurveyTakeForm by adding a grade field. The grade field logic is dependent on the kwarg 'grade_choices' (behavior should be the same as the base class's if this argument is missing). | GradeSurveyTakeForm | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradeSurveyTakeForm:
"""Extends SurveyTakeForm by adding a grade field. The grade field logic is dependent on the kwarg 'grade_choices' (behavior should be the same as the base class's if this argument is missing)."""
def setCleaners(self, post_dict=None):
"""Ensures that the grade f... | stack_v2_sparse_classes_36k_train_013196 | 9,757 | permissive | [
{
"docstring": "Ensures that the grade field is added to the clean data. For args see surveys.SurveyTakeForm.setCleaners().",
"name": "setCleaners",
"signature": "def setCleaners(self, post_dict=None)"
},
{
"docstring": "Validate the grade field.",
"name": "clean_grade",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_008994 | Implement the Python class `GradeSurveyTakeForm` described below.
Class description:
Extends SurveyTakeForm by adding a grade field. The grade field logic is dependent on the kwarg 'grade_choices' (behavior should be the same as the base class's if this argument is missing).
Method signatures and docstrings:
- def se... | Implement the Python class `GradeSurveyTakeForm` described below.
Class description:
Extends SurveyTakeForm by adding a grade field. The grade field logic is dependent on the kwarg 'grade_choices' (behavior should be the same as the base class's if this argument is missing).
Method signatures and docstrings:
- def se... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class GradeSurveyTakeForm:
"""Extends SurveyTakeForm by adding a grade field. The grade field logic is dependent on the kwarg 'grade_choices' (behavior should be the same as the base class's if this argument is missing)."""
def setCleaners(self, post_dict=None):
"""Ensures that the grade f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradeSurveyTakeForm:
"""Extends SurveyTakeForm by adding a grade field. The grade field logic is dependent on the kwarg 'grade_choices' (behavior should be the same as the base class's if this argument is missing)."""
def setCleaners(self, post_dict=None):
"""Ensures that the grade field is added... | the_stack_v2_python_sparse | app/soc/modules/gsoc/views/models/grading_project_survey.py | pombredanne/Melange-1 | train | 0 |
99dc51bae9e2b0277dbbee2388f3429992ad23fe | [
"if not height:\n return 0\ncount = 0\nfor i in range(max(height)):\n start = False\n tmp = 0\n for h in height:\n if h > i:\n if tmp:\n count += tmp\n tmp = 0\n start = True\n elif start:\n tmp += 1\nreturn count",
"count = ... | <|body_start_0|>
if not height:
return 0
count = 0
for i in range(max(height)):
start = False
tmp = 0
for h in height:
if h > i:
if tmp:
count += tmp
tmp = 0
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def __trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
def ___trap(self, height):
""":type height: List[int] :rtype: int"""
<|... | stack_v2_sparse_classes_36k_train_013197 | 5,487 | permissive | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "_trap",
"signature": "def _trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "__trap",
"signature": "def __trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int"... | 6 | stack_v2_sparse_classes_30k_train_011958 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _trap(self, height): :type height: List[int] :rtype: int
- def __trap(self, height): :type height: List[int] :rtype: int
- def ___trap(self, height): :type height: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _trap(self, height): :type height: List[int] :rtype: int
- def __trap(self, height): :type height: List[int] :rtype: int
- def ___trap(self, height): :type height: List[int] ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def __trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
def ___trap(self, height):
""":type height: List[int] :rtype: int"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _trap(self, height):
""":type height: List[int] :rtype: int"""
if not height:
return 0
count = 0
for i in range(max(height)):
start = False
tmp = 0
for h in height:
if h > i:
if tm... | the_stack_v2_python_sparse | 42.trapping-rain-water.py | windard/leeeeee | train | 0 | |
028e8e6c14ad8a6230d0ce5db20dce82c9cc8d3e | [
"assert 0.0 <= mixing_beta <= 1.0\nassert 0.0 <= summation\nassert 0.0 <= rotation\nsuper().__init__(model)\nself._observation_keys = [f'RMSE/{properties[0]}', f'RMSE/{properties[1]}', f'AbsMean/{properties[1]}', f'RMS/rot-{properties[1]}', 'total']\nself._mixing_beta = mixing_beta\nself._summation = summation\nsel... | <|body_start_0|>
assert 0.0 <= mixing_beta <= 1.0
assert 0.0 <= summation
assert 0.0 <= rotation
super().__init__(model)
self._observation_keys = [f'RMSE/{properties[0]}', f'RMSE/{properties[1]}', f'AbsMean/{properties[1]}', f'RMS/rot-{properties[1]}', 'total']
self._mixi... | Loss function to optimize 0th property as scalar potential. | Potential | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Potential:
"""Loss function to optimize 0th property as scalar potential."""
def __init__(self, model, properties, mixing_beta, summation, rotation, **_):
"""Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimiz... | stack_v2_sparse_classes_36k_train_013198 | 4,509 | permissive | [
{
"docstring": "Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimize. mixing_beta (float): Mixing parameter of errors of 0th and 1st order. It accepts 0.0 to 1.0. If 0.0 it optimizes HDNNP by only 0th order property and it is equal to lo... | 2 | stack_v2_sparse_classes_30k_train_006035 | Implement the Python class `Potential` described below.
Class description:
Loss function to optimize 0th property as scalar potential.
Method signatures and docstrings:
- def __init__(self, model, properties, mixing_beta, summation, rotation, **_): Args: model (HighDimensionalNNP): HDNNP object to optimize parameters... | Implement the Python class `Potential` described below.
Class description:
Loss function to optimize 0th property as scalar potential.
Method signatures and docstrings:
- def __init__(self, model, properties, mixing_beta, summation, rotation, **_): Args: model (HighDimensionalNNP): HDNNP object to optimize parameters... | 394544bf8e89534fa535ebfbc7fc8ecab870f17e | <|skeleton|>
class Potential:
"""Loss function to optimize 0th property as scalar potential."""
def __init__(self, model, properties, mixing_beta, summation, rotation, **_):
"""Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimiz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Potential:
"""Loss function to optimize 0th property as scalar potential."""
def __init__(self, model, properties, mixing_beta, summation, rotation, **_):
"""Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimize. mixing_bet... | the_stack_v2_python_sparse | hdnnpy/training/loss_function/potential.py | eminamitani/hdnnpy-update | train | 1 |
57ac49ff2cbd10e51d5a864969d7dc8f7092bd18 | [
"features = features.contiguous()\nindices = indices.contiguous()\nif features_batch_cnt is not None and indices_batch_cnt is not None:\n assert features_batch_cnt.dtype == torch.int\n assert indices_batch_cnt.dtype == torch.int\n M, nsample = indices.size()\n N, C = features.size()\n B = indices_bat... | <|body_start_0|>
features = features.contiguous()
indices = indices.contiguous()
if features_batch_cnt is not None and indices_batch_cnt is not None:
assert features_batch_cnt.dtype == torch.int
assert indices_batch_cnt.dtype == torch.int
M, nsample = indices.... | Group feature with given index. | GroupingOperation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupingOperation:
"""Group feature with given index."""
def forward(ctx, features: torch.Tensor, indices: torch.Tensor, features_batch_cnt: Optional[torch.Tensor]=None, indices_batch_cnt: Optional[torch.Tensor]=None) -> torch.Tensor:
"""Args: features (Tensor): Tensor of features to... | stack_v2_sparse_classes_36k_train_013199 | 10,890 | permissive | [
{
"docstring": "Args: features (Tensor): Tensor of features to group, input shape is (B, C, N) or stacked inputs (N1 + N2 ..., C). indices (Tensor): The indices of features to group with, input shape is (B, npoint, nsample) or stacked inputs (M1 + M2 ..., nsample). features_batch_cnt (Tensor, optional): Input f... | 2 | stack_v2_sparse_classes_30k_train_001300 | Implement the Python class `GroupingOperation` described below.
Class description:
Group feature with given index.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, indices: torch.Tensor, features_batch_cnt: Optional[torch.Tensor]=None, indices_batch_cnt: Optional[torch.Tensor]=None) -> tor... | Implement the Python class `GroupingOperation` described below.
Class description:
Group feature with given index.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, indices: torch.Tensor, features_batch_cnt: Optional[torch.Tensor]=None, indices_batch_cnt: Optional[torch.Tensor]=None) -> tor... | 6e9ee26718b22961d5c34caca4108413b1b7b3af | <|skeleton|>
class GroupingOperation:
"""Group feature with given index."""
def forward(ctx, features: torch.Tensor, indices: torch.Tensor, features_batch_cnt: Optional[torch.Tensor]=None, indices_batch_cnt: Optional[torch.Tensor]=None) -> torch.Tensor:
"""Args: features (Tensor): Tensor of features to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupingOperation:
"""Group feature with given index."""
def forward(ctx, features: torch.Tensor, indices: torch.Tensor, features_batch_cnt: Optional[torch.Tensor]=None, indices_batch_cnt: Optional[torch.Tensor]=None) -> torch.Tensor:
"""Args: features (Tensor): Tensor of features to group, input... | the_stack_v2_python_sparse | mmcv/ops/group_points.py | open-mmlab/mmcv | train | 5,319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.