blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93b189c64da156bade106a1d944314c3a9cb426a | [
"qs = super().get_queryset(request)\nif request.user.is_superuser:\n return qs\nelse:\n return qs.filter(course__in=request.user.courses.all())",
"if request.user.is_superuser:\n return True\ncourses = request.user.courses.all()\nif obj is not None:\n return obj.course in courses\nelse:\n return Tr... | <|body_start_0|>
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(course__in=request.user.courses.all())
<|end_body_0|>
<|body_start_1|>
if request.user.is_superuser:
return True
courses = reque... | Admin page for subjects. | SubjectAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubjectAdmin:
"""Admin page for subjects."""
def get_queryset(self, request):
"""Filter queryset to only show subjects the user has access to. :param request: The get_queryset request. :type request: WSGIRequestf :return: QuerySet filter on whether a user has access to this subject. ... | stack_v2_sparse_classes_75kplus_train_002700 | 17,049 | permissive | [
{
"docstring": "Filter queryset to only show subjects the user has access to. :param request: The get_queryset request. :type request: WSGIRequestf :return: QuerySet filter on whether a user has access to this subject. :rtype: QuerySet",
"name": "get_queryset",
"signature": "def get_queryset(self, reque... | 6 | null | Implement the Python class `SubjectAdmin` described below.
Class description:
Admin page for subjects.
Method signatures and docstrings:
- def get_queryset(self, request): Filter queryset to only show subjects the user has access to. :param request: The get_queryset request. :type request: WSGIRequestf :return: Query... | Implement the Python class `SubjectAdmin` described below.
Class description:
Admin page for subjects.
Method signatures and docstrings:
- def get_queryset(self, request): Filter queryset to only show subjects the user has access to. :param request: The get_queryset request. :type request: WSGIRequestf :return: Query... | ad351978faa37ab867a86d2f4023a2b3e5a2ce19 | <|skeleton|>
class SubjectAdmin:
"""Admin page for subjects."""
def get_queryset(self, request):
"""Filter queryset to only show subjects the user has access to. :param request: The get_queryset request. :type request: WSGIRequestf :return: QuerySet filter on whether a user has access to this subject. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubjectAdmin:
"""Admin page for subjects."""
def get_queryset(self, request):
"""Filter queryset to only show subjects the user has access to. :param request: The get_queryset request. :type request: WSGIRequestf :return: QuerySet filter on whether a user has access to this subject. :rtype: Query... | the_stack_v2_python_sparse | mofa/courses/admin.py | BoxInABoxICT/BoxPlugin | train | 0 |
c96b71a9590a709724d8c414ad03183c980f6f42 | [
"if p_schedule_obj.ScheduleType == 'Lighting':\n LOG.info('Execute_one_schedule type = Lighting')\n lightActionsAPI.DoSchedule(p_pyhouse_obj, p_schedule_obj)\nelif p_schedule_obj.ScheduleType == 'Hvac':\n LOG.info('Execute_one_schedule type = Hvac')\n hvacActionsAPI.DoSchedule(p_pyhouse_obj, p_schedule_... | <|body_start_0|>
if p_schedule_obj.ScheduleType == 'Lighting':
LOG.info('Execute_one_schedule type = Lighting')
lightActionsAPI.DoSchedule(p_pyhouse_obj, p_schedule_obj)
elif p_schedule_obj.ScheduleType == 'Hvac':
LOG.info('Execute_one_schedule type = Hvac')
... | ScheduleExecution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleExecution:
def dispatch_one_schedule(p_pyhouse_obj, p_schedule_obj):
"""Send information to one device to execute a schedule."""
<|body_0|>
def execute_schedules_list(p_pyhouse_obj, p_key_list=[]):
"""The timer calls this when a list of schedules is due to be... | stack_v2_sparse_classes_75kplus_train_002701 | 12,791 | permissive | [
{
"docstring": "Send information to one device to execute a schedule.",
"name": "dispatch_one_schedule",
"signature": "def dispatch_one_schedule(p_pyhouse_obj, p_schedule_obj)"
},
{
"docstring": "The timer calls this when a list of schedules is due to be executed. For each Schedule in the list, ... | 2 | stack_v2_sparse_classes_30k_train_009338 | Implement the Python class `ScheduleExecution` described below.
Class description:
Implement the ScheduleExecution class.
Method signatures and docstrings:
- def dispatch_one_schedule(p_pyhouse_obj, p_schedule_obj): Send information to one device to execute a schedule.
- def execute_schedules_list(p_pyhouse_obj, p_ke... | Implement the Python class `ScheduleExecution` described below.
Class description:
Implement the ScheduleExecution class.
Method signatures and docstrings:
- def dispatch_one_schedule(p_pyhouse_obj, p_schedule_obj): Send information to one device to execute a schedule.
- def execute_schedules_list(p_pyhouse_obj, p_ke... | 6444ed0b4c38ab59b9e419e4d54d65d598e6a54e | <|skeleton|>
class ScheduleExecution:
def dispatch_one_schedule(p_pyhouse_obj, p_schedule_obj):
"""Send information to one device to execute a schedule."""
<|body_0|>
def execute_schedules_list(p_pyhouse_obj, p_key_list=[]):
"""The timer calls this when a list of schedules is due to be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScheduleExecution:
def dispatch_one_schedule(p_pyhouse_obj, p_schedule_obj):
"""Send information to one device to execute a schedule."""
if p_schedule_obj.ScheduleType == 'Lighting':
LOG.info('Execute_one_schedule type = Lighting')
lightActionsAPI.DoSchedule(p_pyhouse_o... | the_stack_v2_python_sparse | src/Modules/Scheduling/schedule.py | bopopescu/PyHouse_1 | train | 0 | |
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115 | [
"if db_field.name == 'topic' and (not request.user.is_superuser):\n kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())\nreturn super(TopicTableAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)",
"topic = TopicTable.objects.get(id=object_id)\noff_days = [day for... | <|body_start_0|>
if db_field.name == 'topic' and (not request.user.is_superuser):
kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())
return super(TopicTableAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | TopicTableAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicTableAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits Topics field to user's topics."""
<|body_0|>
def change_view(self, request, object_id, form_url='', extra_context=None):
"""Overrides the change view that displays change_form... | stack_v2_sparse_classes_75kplus_train_002702 | 9,167 | permissive | [
{
"docstring": "limits Topics field to user's topics.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Overrides the change view that displays change_form.html",
"name": "change_view",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_000884 | Implement the Python class `TopicTableAdmin` described below.
Class description:
Implement the TopicTableAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits Topics field to user's topics.
- def change_view(self, request, object_id, form_url='', extr... | Implement the Python class `TopicTableAdmin` described below.
Class description:
Implement the TopicTableAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits Topics field to user's topics.
- def change_view(self, request, object_id, form_url='', extr... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class TopicTableAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits Topics field to user's topics."""
<|body_0|>
def change_view(self, request, object_id, form_url='', extra_context=None):
"""Overrides the change view that displays change_form... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopicTableAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits Topics field to user's topics."""
if db_field.name == 'topic' and (not request.user.is_superuser):
kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())
... | the_stack_v2_python_sparse | cms/admin.py | Ibrahem3amer/bala7 | train | 0 | |
39cb11ec2adb46b3502fb8686a59b1be41018a6f | [
"if sqrt:\n sigmas = [math.sqrt(float(i) * max_sigma / float(steps)) for i in range(0, steps + 1)]\nelse:\n sigmas = [float(i) * max_sigma / float(steps) for i in range(0, steps + 1)]\nstep_vector_diff = [sigmas[i + 1] - sigmas[i] for i in range(0, steps)]\ntotal_gradients = np.zeros_like(x_value)\nfor i in r... | <|body_start_0|>
if sqrt:
sigmas = [math.sqrt(float(i) * max_sigma / float(steps)) for i in range(0, steps + 1)]
else:
sigmas = [float(i) * max_sigma / float(steps) for i in range(0, steps + 1)]
step_vector_diff = [sigmas[i + 1] - sigmas[i] for i in range(0, steps)]
... | BlurIG | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlurIG:
def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True):
"""Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseli... | stack_v2_sparse_classes_75kplus_train_002703 | 2,360 | permissive | [
{
"docstring": "Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseline image to start with for interpolation num_steps: Number of interpolation steps between the baseline and the input use... | 2 | stack_v2_sparse_classes_30k_train_017965 | Implement the Python class `BlurIG` described below.
Class description:
Implement the BlurIG class.
Method signatures and docstrings:
- def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True): Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): ... | Implement the Python class `BlurIG` described below.
Class description:
Implement the BlurIG class.
Method signatures and docstrings:
- def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True): Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): ... | 55f73f4789c3be581f972dd231d2b4245b820d21 | <|skeleton|>
class BlurIG:
def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True):
"""Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlurIG:
def get_mask(self, image, max_sigma=50, num_steps=100, grad_step=0.01, sqrt=False, preprocess=True):
"""Computes Blur Integrated Gradients for a predicted label. Args: image (ndarray): Original image top_pred_idx: Predicted label for the input image baseline (ndarray): The baseline image to st... | the_stack_v2_python_sparse | methods/blur_IG.py | Castrol68/saliency-tensorflow2 | train | 0 | |
2dac4d3e10c065ea6c18b29b225cd4b1ed2b9eae | [
"try:\n args = parse_args(args, (('action', ('add', 'del', 'see', 'test')), ('jid', str), ('role', 'user')))\nexcept ArgError as ex:\n return ex.msg\nreturn getattr(self, 'acl_' + args.action)(command, args, msg)",
"try:\n args = parse_args(args, (('jid', str), ('role', 'user')))\nexcept ArgError as ex:\... | <|body_start_0|>
try:
args = parse_args(args, (('action', ('add', 'del', 'see', 'test')), ('jid', str), ('role', 'user')))
except ArgError as ex:
return ex.msg
return getattr(self, 'acl_' + args.action)(command, args, msg)
<|end_body_0|>
<|body_start_1|>
try:
... | A plugin to manage users. | ACL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACL:
"""A plugin to manage users."""
def acl(self, command, args, msg):
"""Access control list management"""
<|body_0|>
def acl_add(self, command, args, msg):
"""Add a jid with a given role If the user exists, modify the role."""
<|body_1|>
def acl_d... | stack_v2_sparse_classes_75kplus_train_002704 | 5,050 | permissive | [
{
"docstring": "Access control list management",
"name": "acl",
"signature": "def acl(self, command, args, msg)"
},
{
"docstring": "Add a jid with a given role If the user exists, modify the role.",
"name": "acl_add",
"signature": "def acl_add(self, command, args, msg)"
},
{
"doc... | 5 | null | Implement the Python class `ACL` described below.
Class description:
A plugin to manage users.
Method signatures and docstrings:
- def acl(self, command, args, msg): Access control list management
- def acl_add(self, command, args, msg): Add a jid with a given role If the user exists, modify the role.
- def acl_del(s... | Implement the Python class `ACL` described below.
Class description:
A plugin to manage users.
Method signatures and docstrings:
- def acl(self, command, args, msg): Access control list management
- def acl_add(self, command, args, msg): Add a jid with a given role If the user exists, modify the role.
- def acl_del(s... | 6690cc9f644d5b0c9f8eb6e3540eea336ed61847 | <|skeleton|>
class ACL:
"""A plugin to manage users."""
def acl(self, command, args, msg):
"""Access control list management"""
<|body_0|>
def acl_add(self, command, args, msg):
"""Add a jid with a given role If the user exists, modify the role."""
<|body_1|>
def acl_d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ACL:
"""A plugin to manage users."""
def acl(self, command, args, msg):
"""Access control list management"""
try:
args = parse_args(args, (('action', ('add', 'del', 'see', 'test')), ('jid', str), ('role', 'user')))
except ArgError as ex:
return ex.msg
... | the_stack_v2_python_sparse | sleekbot/plugins/admin.py | hgrecco/SleekBot | train | 2 |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY)\napi.publish_changes(key)\nreturn Response({})",
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permis... | <|body_start_0|>
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY)
api.publish_changes(key)
return Response({})
<|end_body_0|>
<|body_start_1|>
key = LibraryLocatorV2.from_string(l... | Commit/publish or revert all of the draft changes made to the library. | LibraryCommitView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryCommitView:
"""Commit/publish or revert all of the draft changes made to the library."""
def post(self, request, lib_key_str):
"""Commit the draft changes made to the specified block and its descendants."""
<|body_0|>
def delete(self, request, lib_key_str):
... | stack_v2_sparse_classes_75kplus_train_002705 | 42,120 | permissive | [
{
"docstring": "Commit the draft changes made to the specified block and its descendants.",
"name": "post",
"signature": "def post(self, request, lib_key_str)"
},
{
"docstring": "Revert the draft changes made to the specified block and its descendants. Restore it to the last published version",
... | 2 | stack_v2_sparse_classes_30k_train_047900 | Implement the Python class `LibraryCommitView` described below.
Class description:
Commit/publish or revert all of the draft changes made to the library.
Method signatures and docstrings:
- def post(self, request, lib_key_str): Commit the draft changes made to the specified block and its descendants.
- def delete(sel... | Implement the Python class `LibraryCommitView` described below.
Class description:
Commit/publish or revert all of the draft changes made to the library.
Method signatures and docstrings:
- def post(self, request, lib_key_str): Commit the draft changes made to the specified block and its descendants.
- def delete(sel... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryCommitView:
"""Commit/publish or revert all of the draft changes made to the library."""
def post(self, request, lib_key_str):
"""Commit the draft changes made to the specified block and its descendants."""
<|body_0|>
def delete(self, request, lib_key_str):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LibraryCommitView:
"""Commit/publish or revert all of the draft changes made to the library."""
def post(self, request, lib_key_str):
"""Commit the draft changes made to the specified block and its descendants."""
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permiss... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(RainbowDQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, acti... | <|body_start_0|>
super(RainbowDQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encode... | Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default | RainbowDQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainbowDQN:
"""Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], he... | stack_v2_sparse_classes_75kplus_train_002706 | 30,380 | permissive | [
{
"docstring": "Overview: Init the Rainbow Model according to arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation space shape. - action_shape (:obj:`Union[int, SequenceType]`): Action space shape. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pas... | 2 | stack_v2_sparse_classes_30k_train_049536 | Implement the Python class `RainbowDQN` described below.
Class description:
Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, Sequ... | Implement the Python class `RainbowDQN` described below.
Class description:
Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, Sequ... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class RainbowDQN:
"""Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], he... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RainbowDQN:
"""Overview: RainbowDQN network (C51 + Dueling + Noisy Block) .. note:: RainbowDQN contains dueling architecture by default"""
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_siz... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 |
c841186b2cdaefe63ba121340e77da1308c1308b | [
"SHA1_RE = re.compile('^[a-f0-9]{40}$')\ninstance = None\nif SHA1_RE.search(activation_key):\n try:\n instance = self.get(refuser=user, activation_key=activation_key)\n except (self.model.DoesNotExist, TypeError):\n return None\n return instance\nelse:\n return None",
"SHA1_RE = re.compi... | <|body_start_0|>
SHA1_RE = re.compile('^[a-f0-9]{40}$')
instance = None
if SHA1_RE.search(activation_key):
try:
instance = self.get(refuser=user, activation_key=activation_key)
except (self.model.DoesNotExist, TypeError):
return None
... | Access to ChangeEmail in a safe manner | ChangeEmailManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeEmailManager:
"""Access to ChangeEmail in a safe manner"""
def get_instance(self, user, activation_key):
"""Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instanc... | stack_v2_sparse_classes_75kplus_train_002707 | 5,619 | no_license | [
{
"docstring": "Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instance.",
"name": "get_instance",
"signature": "def get_instance(self, user, activation_key)"
},
{
"docstring": "Ge... | 2 | stack_v2_sparse_classes_30k_train_029377 | Implement the Python class `ChangeEmailManager` described below.
Class description:
Access to ChangeEmail in a safe manner
Method signatures and docstrings:
- def get_instance(self, user, activation_key): Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoi... | Implement the Python class `ChangeEmailManager` described below.
Class description:
Access to ChangeEmail in a safe manner
Method signatures and docstrings:
- def get_instance(self, user, activation_key): Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoi... | f2415fd82551ddaacba42eac9e2f2a1a3bc6fb88 | <|skeleton|>
class ChangeEmailManager:
"""Access to ChangeEmail in a safe manner"""
def get_instance(self, user, activation_key):
"""Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instanc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangeEmailManager:
"""Access to ChangeEmail in a safe manner"""
def get_instance(self, user, activation_key):
"""Get the given instance (should be unique under activation_key). The user lookup is excessive but provided to avoid errors in use @return is either None or a valid instance."""
... | the_stack_v2_python_sparse | wsgi/openshift/changeemail/models.py | idi-konkurranser/IDIOpen | train | 0 |
2f99b916045bd4d46cac38b927aafc384e8cd8c3 | [
"key = ndb.Key(models.InstanceGroupManager, 'fake-key')\ninstances.ensure_entities_exist(key)\nself.failIf(key.get())",
"key = models.InstanceGroupManager(key=instance_group_managers.get_instance_group_manager_key('base-name', 'revision', 'zone')).put()\ninstances.ensure_entities_exist(key)\nself.failIf(key.get()... | <|body_start_0|>
key = ndb.Key(models.InstanceGroupManager, 'fake-key')
instances.ensure_entities_exist(key)
self.failIf(key.get())
<|end_body_0|>
<|body_start_1|>
key = models.InstanceGroupManager(key=instance_group_managers.get_instance_group_manager_key('base-name', 'revision', 'zone... | Tests for instances.ensure_entities_exist. | EnsureEntitiesExistTest | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnsureEntitiesExistTest:
"""Tests for instances.ensure_entities_exist."""
def test_entity_doesnt_exist(self):
"""Ensures nothing happens when the entity doesn't exist."""
<|body_0|>
def test_url_unspecified(self):
"""Ensures nothing happens when URL is unspecifie... | stack_v2_sparse_classes_75kplus_train_002708 | 7,858 | permissive | [
{
"docstring": "Ensures nothing happens when the entity doesn't exist.",
"name": "test_entity_doesnt_exist",
"signature": "def test_entity_doesnt_exist(self)"
},
{
"docstring": "Ensures nothing happens when URL is unspecified.",
"name": "test_url_unspecified",
"signature": "def test_url_... | 5 | null | Implement the Python class `EnsureEntitiesExistTest` described below.
Class description:
Tests for instances.ensure_entities_exist.
Method signatures and docstrings:
- def test_entity_doesnt_exist(self): Ensures nothing happens when the entity doesn't exist.
- def test_url_unspecified(self): Ensures nothing happens w... | Implement the Python class `EnsureEntitiesExistTest` described below.
Class description:
Tests for instances.ensure_entities_exist.
Method signatures and docstrings:
- def test_entity_doesnt_exist(self): Ensures nothing happens when the entity doesn't exist.
- def test_url_unspecified(self): Ensures nothing happens w... | a2349b78d2dce6aa4e131e6f7afaa202ccd72ea8 | <|skeleton|>
class EnsureEntitiesExistTest:
"""Tests for instances.ensure_entities_exist."""
def test_entity_doesnt_exist(self):
"""Ensures nothing happens when the entity doesn't exist."""
<|body_0|>
def test_url_unspecified(self):
"""Ensures nothing happens when URL is unspecifie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnsureEntitiesExistTest:
"""Tests for instances.ensure_entities_exist."""
def test_entity_doesnt_exist(self):
"""Ensures nothing happens when the entity doesn't exist."""
key = ndb.Key(models.InstanceGroupManager, 'fake-key')
instances.ensure_entities_exist(key)
self.failI... | the_stack_v2_python_sparse | appengine/gce-backend/instances_test.py | mellowdistrict/luci-py | train | 1 |
51bf64826c61131d85d1ced664ab7094807bba67 | [
"super().__init__(name, **kwargs)\nself.website_id = 'gizbot'\nself.website_type = 'news'\nself.post_list_xpath = '//*[@id=\"content\"]/section/div/div[1]/div/ul/li'\nself.post_url_xpath = './div[1]/a/@href'\nself.post_list_url_xpath = '(//*[@id=\"content\"]/section/div/div[1]/div/ul/div[1]/div)[last()]/a/@href'\ns... | <|body_start_0|>
super().__init__(name, **kwargs)
self.website_id = 'gizbot'
self.website_type = 'news'
self.post_list_xpath = '//*[@id="content"]/section/div/div[1]/div/ul/li'
self.post_url_xpath = './div[1]/a/@href'
self.post_list_url_xpath = '(//*[@id="content"]/sectio... | 解析数据和爬虫逻辑类 | MySpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def parse(self, response):
"""解析列表页数据... | stack_v2_sparse_classes_75kplus_train_002709 | 3,809 | no_license | [
{
"docstring": "完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None",
"name": "__init__",
"signature": "def __init__(self, name=None, **kwargs)"
},
{
"docstring": "解析列表页数据以及构造新闻页和下一列表页请求",
"name": "parse... | 4 | stack_v2_sparse_classes_30k_train_045668 | Implement the Python class `MySpider` described below.
Class description:
解析数据和爬虫逻辑类
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None
- def parse(sel... | Implement the Python class `MySpider` described below.
Class description:
解析数据和爬虫逻辑类
Method signatures and docstrings:
- def __init__(self, name=None, **kwargs): 完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None
- def parse(sel... | 1b42878b694fabc65a02228662ffdf819e5dcc71 | <|skeleton|>
class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
<|body_0|>
def parse(self, response):
"""解析列表页数据... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MySpider:
"""解析数据和爬虫逻辑类"""
def __init__(self, name=None, **kwargs):
"""完成解析前的初始化工作,主要是将用的到 xpath 配合完成 :param self: 类的对象自身 :param name: scrapy 会将 name 属性传递进来 :param kwargs: 字典形式的参数,用于更新 self.__dict__ :return None"""
super().__init__(name, **kwargs)
self.website_id = 'gizbot'
... | the_stack_v2_python_sparse | wujian/gizbot/gizbot/spiders/gizbot.py | wangsanshi123/spiders | train | 0 |
271a600ffb2e02efe42609c6c121a3bbc2f5b8b1 | [
"self.ws = {}\nself.ls = ''\nfor w in words:\n lw = len(w)\n if lw not in self.ws:\n self.ws[lw] = set()\n self.ws[lw].add(w)",
"self.ls += letter\nfor i in self.ws.keys():\n if self.ls[-i:] in self.ws[i]:\n return True\nreturn False"
] | <|body_start_0|>
self.ws = {}
self.ls = ''
for w in words:
lw = len(w)
if lw not in self.ws:
self.ws[lw] = set()
self.ws[lw].add(w)
<|end_body_0|>
<|body_start_1|>
self.ls += letter
for i in self.ws.keys():
if self.... | StreamChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ws = {}
self.ls = ''
for w in words:
... | stack_v2_sparse_classes_75kplus_train_002710 | 747 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type letter: str :rtype: bool",
"name": "query",
"signature": "def query(self, letter)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050347 | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool
<|skeleton|>
class StreamChecker:
def __init__(self, w... | ef04457edd6343b49b66ba96425140baf03fc07f | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
self.ws = {}
self.ls = ''
for w in words:
lw = len(w)
if lw not in self.ws:
self.ws[lw] = set()
self.ws[lw].add(w)
def query(self, letter):
""... | the_stack_v2_python_sparse | leetcode/1032.py | geekben/codeiscool | train | 2 | |
a3d4a6ea94c95d0a12a0a2f8ed6f999bfcd4cbbf | [
"self.pump = Pump('127.0.0.1', 1)\nself.sensor = Sensor('127.0.0.2', 2)\nself.decider = Decider(300, 0.1)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=200)\nself.pump.get_state = MagicMock(return_value=Pump.PUMP_OFF)\nself.pump.set_state = Mag... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 1)
self.sensor = Sensor('127.0.0.2', 2)
self.decider = Decider(300, 0.1)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=200)
se... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Just some example syntax that you might use"""
<|body_0|>
def test_tick(self):
"""test for controller"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump... | stack_v2_sparse_classes_75kplus_train_002711 | 2,566 | no_license | [
{
"docstring": "Just some example syntax that you might use",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test for controller",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006468 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Just some example syntax that you might use
- def test_tick(self): test for controller | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Just some example syntax that you might use
- def test_tick(self): test for controller
<|skeleton|>
class ControllerTests:
"""Unit tests for th... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Just some example syntax that you might use"""
<|body_0|>
def test_tick(self):
"""test for controller"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Just some example syntax that you might use"""
self.pump = Pump('127.0.0.1', 1)
self.sensor = Sensor('127.0.0.2', 2)
self.decider = Decider(300, 0.1)
self.controller = Controller(self.se... | the_stack_v2_python_sparse | students/AurelP/lesson6/water-regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
729a3eb68034a3f73c67c66af776a625880feb83 | [
"self.fname = fname\nself.U = mean_flow\nself.d_max = d_max\nself.particles = {}\ndata = loadtxt(self.fname)\nself.times = list(set(data[:, -1]))\nfor tm in self.times:\n self.particles[tm] = []\n p_ = data[data[:, -1] == tm]\n for i in range(p_.shape[0]):\n p = array([-1] + list(p_[i, :]))\n ... | <|body_start_0|>
self.fname = fname
self.U = mean_flow
self.d_max = d_max
self.particles = {}
data = loadtxt(self.fname)
self.times = list(set(data[:, -1]))
for tm in self.times:
self.particles[tm] = []
p_ = data[data[:, -1] == tm]
... | A nearest-neighbour 3D particle tracking algorithm | tracker_nearest_neighbour | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tracker_nearest_neighbour:
"""A nearest-neighbour 3D particle tracking algorithm"""
def __init__(self, fname, mean_flow=0.0, d_max=10000000000.0):
"""fname - string, path of the particles containing file to which tracking should be performed. mean_flow - a numpy array of the mean flo... | stack_v2_sparse_classes_75kplus_train_002712 | 26,658 | permissive | [
{
"docstring": "fname - string, path of the particles containing file to which tracking should be performed. mean_flow - a numpy array of the mean flow vector, in units of the calibrations spatial units per frame (e.g. mm per frame). The mean flow is assumed not to change in space and time. d_max - maximum allo... | 6 | stack_v2_sparse_classes_30k_train_029357 | Implement the Python class `tracker_nearest_neighbour` described below.
Class description:
A nearest-neighbour 3D particle tracking algorithm
Method signatures and docstrings:
- def __init__(self, fname, mean_flow=0.0, d_max=10000000000.0): fname - string, path of the particles containing file to which tracking shoul... | Implement the Python class `tracker_nearest_neighbour` described below.
Class description:
A nearest-neighbour 3D particle tracking algorithm
Method signatures and docstrings:
- def __init__(self, fname, mean_flow=0.0, d_max=10000000000.0): fname - string, path of the particles containing file to which tracking shoul... | 6b81c66ce5b63b7e6b833db19ebf5f117c90c9e8 | <|skeleton|>
class tracker_nearest_neighbour:
"""A nearest-neighbour 3D particle tracking algorithm"""
def __init__(self, fname, mean_flow=0.0, d_max=10000000000.0):
"""fname - string, path of the particles containing file to which tracking should be performed. mean_flow - a numpy array of the mean flo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class tracker_nearest_neighbour:
"""A nearest-neighbour 3D particle tracking algorithm"""
def __init__(self, fname, mean_flow=0.0, d_max=10000000000.0):
"""fname - string, path of the particles containing file to which tracking should be performed. mean_flow - a numpy array of the mean flow vector, in ... | the_stack_v2_python_sparse | myptv/tracking_mod.py | ronshnapp/MyPTV | train | 28 |
8c69076d6771f495c32aedeb40fa7c6e1815beae | [
"assert next is Node.empty or isinstance(next, Node)\nself.item = item\nself.next = next",
"if self.next:\n next_str = ', ' + repr(self.next)\nelse:\n next_str = ''\nreturn 'Node({0}{1})'.format(self.item, next_str)"
] | <|body_start_0|>
assert next is Node.empty or isinstance(next, Node)
self.item = item
self.next = next
<|end_body_0|>
<|body_start_1|>
if self.next:
next_str = ', ' + repr(self.next)
else:
next_str = ''
return 'Node({0}{1})'.format(self.item, next... | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, item, next=empty):
"""init a node"""
<|body_0|>
def __repr__(self):
"""它实现Node类的repr()函数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert next is Node.empty or isinstance(next, Node)
self.item = item
se... | stack_v2_sparse_classes_75kplus_train_002713 | 3,171 | no_license | [
{
"docstring": "init a node",
"name": "__init__",
"signature": "def __init__(self, item, next=empty)"
},
{
"docstring": "它实现Node类的repr()函数",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006314 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, item, next=empty): init a node
- def __repr__(self): 它实现Node类的repr()函数 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, item, next=empty): init a node
- def __repr__(self): 它实现Node类的repr()函数
<|skeleton|>
class Node:
def __init__(self, item, next=empty):
"""init a node"""
... | c431569ae08fb77c67e948f5ded75c306af20ba2 | <|skeleton|>
class Node:
def __init__(self, item, next=empty):
"""init a node"""
<|body_0|>
def __repr__(self):
"""它实现Node类的repr()函数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
def __init__(self, item, next=empty):
"""init a node"""
assert next is Node.empty or isinstance(next, Node)
self.item = item
self.next = next
def __repr__(self):
"""它实现Node类的repr()函数"""
if self.next:
next_str = ', ' + repr(self.next)
... | the_stack_v2_python_sparse | algo-lib/1_basic/Python/LinkedQueue.py | itrowa/arsenal | train | 0 | |
c87507475cb9f09ab882ed421f2759872e370e53 | [
"self.assertEqual(investment(100, 10).positions, 100)\nself.assertEqual(investment(100, 10).num_trials, 10)\nself.assertEqual(investment(100, 10).position_value, 10)",
"self.assertTrue(len(investment.simulate(investment(100, 10))) == 10)\nself.assertTrue(all(investment.simulate(investment(100, 10))) <= 1)\nself.a... | <|body_start_0|>
self.assertEqual(investment(100, 10).positions, 100)
self.assertEqual(investment(100, 10).num_trials, 10)
self.assertEqual(investment(100, 10).position_value, 10)
<|end_body_0|>
<|body_start_1|>
self.assertTrue(len(investment.simulate(investment(100, 10))) == 10)
... | Tests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tests:
def testInvestment(self):
"""Tests for class Investment"""
<|body_0|>
def testSimulate(self):
"""Tests for function Simulate"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.assertEqual(investment(100, 10).positions, 100)
self.ass... | stack_v2_sparse_classes_75kplus_train_002714 | 757 | no_license | [
{
"docstring": "Tests for class Investment",
"name": "testInvestment",
"signature": "def testInvestment(self)"
},
{
"docstring": "Tests for function Simulate",
"name": "testSimulate",
"signature": "def testSimulate(self)"
}
] | 2 | null | Implement the Python class `Tests` described below.
Class description:
Implement the Tests class.
Method signatures and docstrings:
- def testInvestment(self): Tests for class Investment
- def testSimulate(self): Tests for function Simulate | Implement the Python class `Tests` described below.
Class description:
Implement the Tests class.
Method signatures and docstrings:
- def testInvestment(self): Tests for class Investment
- def testSimulate(self): Tests for function Simulate
<|skeleton|>
class Tests:
def testInvestment(self):
"""Tests fo... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class Tests:
def testInvestment(self):
"""Tests for class Investment"""
<|body_0|>
def testSimulate(self):
"""Tests for function Simulate"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tests:
def testInvestment(self):
"""Tests for class Investment"""
self.assertEqual(investment(100, 10).positions, 100)
self.assertEqual(investment(100, 10).num_trials, 10)
self.assertEqual(investment(100, 10).position_value, 10)
def testSimulate(self):
"""Tests for... | the_stack_v2_python_sparse | llq205/test.py | ds-ga-1007/assignment8 | train | 1 | |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY)\nserializer = LibraryBundleLinkUpdateSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\napi.update_bundle_link(key, link_id, version=serialize... | <|body_start_0|>
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permission_for_library_key(key, request.user, permissions.CAN_EDIT_THIS_CONTENT_LIBRARY)
serializer = LibraryBundleLinkUpdateSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
api.up... | View to update/delete an existing library link | LibraryLinkDetailView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryLinkDetailView:
"""View to update/delete an existing library link"""
def patch(self, request, lib_key_str, link_id):
"""Update the specified link to point to a different version of its target bundle. Pass e.g. {"version": 40} or pass {"version": None} to update to the latest p... | stack_v2_sparse_classes_75kplus_train_002715 | 42,120 | permissive | [
{
"docstring": "Update the specified link to point to a different version of its target bundle. Pass e.g. {\"version\": 40} or pass {\"version\": None} to update to the latest published version.",
"name": "patch",
"signature": "def patch(self, request, lib_key_str, link_id)"
},
{
"docstring": "D... | 2 | stack_v2_sparse_classes_30k_val_000383 | Implement the Python class `LibraryLinkDetailView` described below.
Class description:
View to update/delete an existing library link
Method signatures and docstrings:
- def patch(self, request, lib_key_str, link_id): Update the specified link to point to a different version of its target bundle. Pass e.g. {"version"... | Implement the Python class `LibraryLinkDetailView` described below.
Class description:
View to update/delete an existing library link
Method signatures and docstrings:
- def patch(self, request, lib_key_str, link_id): Update the specified link to point to a different version of its target bundle. Pass e.g. {"version"... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryLinkDetailView:
"""View to update/delete an existing library link"""
def patch(self, request, lib_key_str, link_id):
"""Update the specified link to point to a different version of its target bundle. Pass e.g. {"version": 40} or pass {"version": None} to update to the latest p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LibraryLinkDetailView:
"""View to update/delete an existing library link"""
def patch(self, request, lib_key_str, link_id):
"""Update the specified link to point to a different version of its target bundle. Pass e.g. {"version": 40} or pass {"version": None} to update to the latest published vers... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
19df958b8d89de3aeff4dd122fc0510d9c68f23a | [
"person = PersonServiceManagement.retrieve_object(person_id=person_id)\nshare = ShareModel.objects.create(person=person, **data)\nreturn share",
"person = PersonServiceManagement.retrieve_object(person_id=person_id)\ntry:\n ShareModel.objects.filter(share_id=share_id).update(person=person, **data)\nexcept Obje... | <|body_start_0|>
person = PersonServiceManagement.retrieve_object(person_id=person_id)
share = ShareModel.objects.create(person=person, **data)
return share
<|end_body_0|>
<|body_start_1|>
person = PersonServiceManagement.retrieve_object(person_id=person_id)
try:
Sha... | ShareServiceManagement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShareServiceManagement:
def create_object(data: dict, person_id: int) -> ShareModel:
"""Creates a share object Args: data (dict): information about the share person_id (int): unique identifier of the person object Returns: (ShareModel): created share"""
<|body_0|>
def update... | stack_v2_sparse_classes_75kplus_train_002716 | 4,864 | no_license | [
{
"docstring": "Creates a share object Args: data (dict): information about the share person_id (int): unique identifier of the person object Returns: (ShareModel): created share",
"name": "create_object",
"signature": "def create_object(data: dict, person_id: int) -> ShareModel"
},
{
"docstring... | 5 | stack_v2_sparse_classes_30k_train_006728 | Implement the Python class `ShareServiceManagement` described below.
Class description:
Implement the ShareServiceManagement class.
Method signatures and docstrings:
- def create_object(data: dict, person_id: int) -> ShareModel: Creates a share object Args: data (dict): information about the share person_id (int): un... | Implement the Python class `ShareServiceManagement` described below.
Class description:
Implement the ShareServiceManagement class.
Method signatures and docstrings:
- def create_object(data: dict, person_id: int) -> ShareModel: Creates a share object Args: data (dict): information about the share person_id (int): un... | 84ad5886ec3cd8d2aae43f5812e2c894b71685b5 | <|skeleton|>
class ShareServiceManagement:
def create_object(data: dict, person_id: int) -> ShareModel:
"""Creates a share object Args: data (dict): information about the share person_id (int): unique identifier of the person object Returns: (ShareModel): created share"""
<|body_0|>
def update... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShareServiceManagement:
def create_object(data: dict, person_id: int) -> ShareModel:
"""Creates a share object Args: data (dict): information about the share person_id (int): unique identifier of the person object Returns: (ShareModel): created share"""
person = PersonServiceManagement.retriev... | the_stack_v2_python_sparse | platform_inistock/inistock/models/service_management.py | MihailButnaru/Inistock-API | train | 0 | |
e92244f4b6c0999a9b853a86bc112e9af175cda2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingCustomer()",
"from .booking_customer_base import BookingCustomerBase\nfrom .phone import Phone\nfrom .physical_address import PhysicalAddress\nfrom .booking_customer_base import BookingCustomerBase\nfrom .phone import Phone\nfro... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingCustomer()
<|end_body_0|>
<|body_start_1|>
from .booking_customer_base import BookingCustomerBase
from .phone import Phone
from .physical_address import PhysicalAddress
... | Represents a customer of the business. | BookingCustomer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingCustomer:
"""Represents a customer of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read ... | stack_v2_sparse_classes_75kplus_train_002717 | 3,391 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BookingCustomer",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_007451 | Implement the Python class `BookingCustomer` described below.
Class description:
Represents a customer of the business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer: Creates a new instance of the appropriate class based on discriminat... | Implement the Python class `BookingCustomer` described below.
Class description:
Represents a customer of the business.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer: Creates a new instance of the appropriate class based on discriminat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingCustomer:
"""Represents a customer of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookingCustomer:
"""Represents a customer of the business."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingCustomer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin... | the_stack_v2_python_sparse | msgraph/generated/models/booking_customer.py | microsoftgraph/msgraph-sdk-python | train | 135 |
0dbd7c11be62197540c652848ca26a367fbb1505 | [
"cls.dirname = os.path.abspath(os.path.join(os.path.dirname(__file__), 'temp'))\nos.makedirs(os.path.join(cls.dirname, 'pdep'))\ntest_family = 'R_Recombination'\ncls.rmg = RMG()\nfrom rmgpy.rmg.input import set_global_rmg, pressure_dependence\nset_global_rmg(cls.rmg)\npressure_dependence(method='modified strong col... | <|body_start_0|>
cls.dirname = os.path.abspath(os.path.join(os.path.dirname(__file__), 'temp'))
os.makedirs(os.path.join(cls.dirname, 'pdep'))
test_family = 'R_Recombination'
cls.rmg = RMG()
from rmgpy.rmg.input import set_global_rmg, pressure_dependence
set_global_rmg(cl... | Contains unit tests for CoreEdgeReactionModel.enlarge. | TestEnlarge | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEnlarge:
"""Contains unit tests for CoreEdgeReactionModel.enlarge."""
def setUpClass(cls):
"""A method that is run ONCE before all unit tests in this class."""
<|body_0|>
def test_enlarge_1_add_nonreactive_species(self):
"""Test that we can add a nonreactive ... | stack_v2_sparse_classes_75kplus_train_002718 | 34,780 | permissive | [
{
"docstring": "A method that is run ONCE before all unit tests in this class.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Test that we can add a nonreactive species to CERM",
"name": "test_enlarge_1_add_nonreactive_species",
"signature": "def test_enlar... | 6 | stack_v2_sparse_classes_30k_train_032645 | Implement the Python class `TestEnlarge` described below.
Class description:
Contains unit tests for CoreEdgeReactionModel.enlarge.
Method signatures and docstrings:
- def setUpClass(cls): A method that is run ONCE before all unit tests in this class.
- def test_enlarge_1_add_nonreactive_species(self): Test that we c... | Implement the Python class `TestEnlarge` described below.
Class description:
Contains unit tests for CoreEdgeReactionModel.enlarge.
Method signatures and docstrings:
- def setUpClass(cls): A method that is run ONCE before all unit tests in this class.
- def test_enlarge_1_add_nonreactive_species(self): Test that we c... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestEnlarge:
"""Contains unit tests for CoreEdgeReactionModel.enlarge."""
def setUpClass(cls):
"""A method that is run ONCE before all unit tests in this class."""
<|body_0|>
def test_enlarge_1_add_nonreactive_species(self):
"""Test that we can add a nonreactive ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestEnlarge:
"""Contains unit tests for CoreEdgeReactionModel.enlarge."""
def setUpClass(cls):
"""A method that is run ONCE before all unit tests in this class."""
cls.dirname = os.path.abspath(os.path.join(os.path.dirname(__file__), 'temp'))
os.makedirs(os.path.join(cls.dirname, ... | the_stack_v2_python_sparse | rmgpy/rmg/modelTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
ea17631ac4dd76bd8f9486f65c6a1478b87d973c | [
"self._pubsub = pubsub_bus\nself._player = player_\nbuilder = Gtk.Builder.new_from_string(resources.read_text('pepper_music_player.ui', 'player_status_position_slider.glade'), length=-1)\nself.widget = builder.get_object('container')\nalignment.set_direction_recursive(self.widget, Gtk.TextDirection.LTR)\nself._posi... | <|body_start_0|>
self._pubsub = pubsub_bus
self._player = player_
builder = Gtk.Builder.new_from_string(resources.read_text('pepper_music_player.ui', 'player_status_position_slider.glade'), length=-1)
self.widget = builder.get_object('container')
alignment.set_direction_recursive... | Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only. | PositionSlider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionSlider:
"""Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only."""
def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Playe... | stack_v2_sparse_classes_75kplus_train_002719 | 7,252 | permissive | [
{
"docstring": "Initializer. Args: pubsub_bus: PubSub message bus. player_: Player.",
"name": "__init__",
"signature": "def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Player) -> None"
},
{
"docstring": "Handler for PlayStatus updates.",
"name": "_handle_play_status",
"s... | 3 | stack_v2_sparse_classes_30k_train_019842 | Implement the Python class `PositionSlider` described below.
Class description:
Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only.
Method signatures and docstrings:
- de... | Implement the Python class `PositionSlider` described below.
Class description:
Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only.
Method signatures and docstrings:
- de... | 2a45aef6deb6247c42d63b5f7475ec5517ea9321 | <|skeleton|>
class PositionSlider:
"""Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only."""
def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Playe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionSlider:
"""Position slider, including labels for the current position and duration. Attributes: widget: Widget containing the slider and labels. slider: Slider for seeking. This is public for use in tests only."""
def __init__(self, *, pubsub_bus: pubsub.PubSub, player_: player.Player) -> None:
... | the_stack_v2_python_sparse | pepper_music_player/ui/player_status.py | EmDBaum/pepper-music-player | train | 0 |
4505e5d322791156ea24b49dfa24d5e501d3c43a | [
"my_dict = defaultdict(list)\nfor index, num in enumerate(nums):\n if my_dict[num] and index - my_dict[num][-1] <= k:\n return True\n my_dict[num].append(index)\nreturn False",
"my_dict = {}\nfor index, num in enumerate(nums):\n if num in my_dict and index - my_dict[num] <= k:\n return True... | <|body_start_0|>
my_dict = defaultdict(list)
for index, num in enumerate(nums):
if my_dict[num] and index - my_dict[num][-1] <= k:
return True
my_dict[num].append(index)
return False
<|end_body_0|>
<|body_start_1|>
my_dict = {}
for index, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_002720 | 813 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate2",
"signature": "def contai... | 2 | stack_v2_sparse_classes_30k_train_010445 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | cefa2f08667de4d2973274de3ff29a31a7d25eda | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
my_dict = defaultdict(list)
for index, num in enumerate(nums):
if my_dict[num] and index - my_dict[num][-1] <= k:
return True
my_dict[num]... | the_stack_v2_python_sparse | 219/Solution.py | zhangruochi/leetcode | train | 14 | |
65b4d7d1b66139570e17da76c390eb3e3a73239f | [
"comments = Comment.objects.filter(item__pk=item_pk)\nserializer = serializers.CommentSerializer(comments, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"data = dict(request.data)\ndata['item'] = item_pk\ndata['person'] = int(request.data['person'])\ndata['text'] = request.data['text']... | <|body_start_0|>
comments = Comment.objects.filter(item__pk=item_pk)
serializer = serializers.CommentSerializer(comments, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
data = dict(request.data)
data['item'] = item_pk
... | Display comment list or create new | CommentList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentList:
"""Display comment list or create new"""
def get(self, request, item_pk, format=None):
"""Display comment list of selected item --- response_serializer: serializers.CommentSerializer"""
<|body_0|>
def post(self, request, item_pk, format=None):
"""Cre... | stack_v2_sparse_classes_75kplus_train_002721 | 12,511 | permissive | [
{
"docstring": "Display comment list of selected item --- response_serializer: serializers.CommentSerializer",
"name": "get",
"signature": "def get(self, request, item_pk, format=None)"
},
{
"docstring": "Create new comment for selected item --- request_serializer: serializers.CommentSerializer ... | 3 | stack_v2_sparse_classes_30k_train_024189 | Implement the Python class `CommentList` described below.
Class description:
Display comment list or create new
Method signatures and docstrings:
- def get(self, request, item_pk, format=None): Display comment list of selected item --- response_serializer: serializers.CommentSerializer
- def post(self, request, item_... | Implement the Python class `CommentList` described below.
Class description:
Display comment list or create new
Method signatures and docstrings:
- def get(self, request, item_pk, format=None): Display comment list of selected item --- response_serializer: serializers.CommentSerializer
- def post(self, request, item_... | 70b01c33e6167edfbb30a91ff76a5c7c5f02143f | <|skeleton|>
class CommentList:
"""Display comment list or create new"""
def get(self, request, item_pk, format=None):
"""Display comment list of selected item --- response_serializer: serializers.CommentSerializer"""
<|body_0|>
def post(self, request, item_pk, format=None):
"""Cre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentList:
"""Display comment list or create new"""
def get(self, request, item_pk, format=None):
"""Display comment list of selected item --- response_serializer: serializers.CommentSerializer"""
comments = Comment.objects.filter(item__pk=item_pk)
serializer = serializers.Comme... | the_stack_v2_python_sparse | workflow/apps/API/views.py | Findspire/workflow | train | 2 |
048c94c793535daeaa0db720d07eccaeceb72342 | [
"self.auto_minor_version_upgrade = auto_minor_version_upgrade\nself.availability_zone = availability_zone\nself.copy_tags_to_snapshots = copy_tags_to_snapshots\nself.db_instance_id = db_instance_id\nself.db_option_group = db_option_group\nself.db_parameter_group = db_parameter_group\nself.db_port = db_port\nself.ia... | <|body_start_0|>
self.auto_minor_version_upgrade = auto_minor_version_upgrade
self.availability_zone = availability_zone
self.copy_tags_to_snapshots = copy_tags_to_snapshots
self.db_instance_id = db_instance_id
self.db_option_group = db_option_group
self.db_parameter_grou... | Implementation of the 'DeployDBInstancesToRDSParams' model. Contains RDS specfic options that can be supplied while restoring the RDS DB instance. Attributes: auto_minor_version_upgrade (bool): Whether to enable auto minor version upgrade in the restored DB. availability_zone (EntityProto): Entity representing the avai... | DeployDBInstancesToRDSParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeployDBInstancesToRDSParams:
"""Implementation of the 'DeployDBInstancesToRDSParams' model. Contains RDS specfic options that can be supplied while restoring the RDS DB instance. Attributes: auto_minor_version_upgrade (bool): Whether to enable auto minor version upgrade in the restored DB. avail... | stack_v2_sparse_classes_75kplus_train_002722 | 5,831 | permissive | [
{
"docstring": "Constructor for the DeployDBInstancesToRDSParams class",
"name": "__init__",
"signature": "def __init__(self, auto_minor_version_upgrade=None, availability_zone=None, copy_tags_to_snapshots=None, db_instance_id=None, db_option_group=None, db_parameter_group=None, db_port=None, iam_db_aut... | 2 | null | Implement the Python class `DeployDBInstancesToRDSParams` described below.
Class description:
Implementation of the 'DeployDBInstancesToRDSParams' model. Contains RDS specfic options that can be supplied while restoring the RDS DB instance. Attributes: auto_minor_version_upgrade (bool): Whether to enable auto minor ve... | Implement the Python class `DeployDBInstancesToRDSParams` described below.
Class description:
Implementation of the 'DeployDBInstancesToRDSParams' model. Contains RDS specfic options that can be supplied while restoring the RDS DB instance. Attributes: auto_minor_version_upgrade (bool): Whether to enable auto minor ve... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DeployDBInstancesToRDSParams:
"""Implementation of the 'DeployDBInstancesToRDSParams' model. Contains RDS specfic options that can be supplied while restoring the RDS DB instance. Attributes: auto_minor_version_upgrade (bool): Whether to enable auto minor version upgrade in the restored DB. avail... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeployDBInstancesToRDSParams:
"""Implementation of the 'DeployDBInstancesToRDSParams' model. Contains RDS specfic options that can be supplied while restoring the RDS DB instance. Attributes: auto_minor_version_upgrade (bool): Whether to enable auto minor version upgrade in the restored DB. availability_zone ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/deploy_db_instances_to_rds_params.py | cohesity/management-sdk-python | train | 24 |
4b0095dafa7b9a7e50d97e494cd43c9da109398d | [
"super().__init__()\nhypo_parameters = hypo_module.meta_named_parameters()\nself.names = []\nself.nets = nn.ModuleList()\nself.param_shapes = []\nfor name, param in hypo_parameters:\n print(name)\n self.names.append(name)\n self.param_shapes.append(param.size())\n if linear:\n hn = modules.BatchL... | <|body_start_0|>
super().__init__()
hypo_parameters = hypo_module.meta_named_parameters()
self.names = []
self.nets = nn.ModuleList()
self.param_shapes = []
for name, param in hypo_parameters:
print(name)
self.names.append(name)
self.pa... | HyperNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperNetwork:
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False):
"""Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidden_features: Number of hidden units i... | stack_v2_sparse_classes_75kplus_train_002723 | 11,174 | no_license | [
{
"docstring": "Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidden_features: Number of hidden units in hypernetwork hypo_module: MetaModule. The module whose parameters are predicted.",
"name": "__init__",
"signature": "def __in... | 2 | null | Implement the Python class `HyperNetwork` described below.
Class description:
Implement the HyperNetwork class.
Method signatures and docstrings:
- def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False): Args: hyper_in_features: In features of hypernetwork hyper_h... | Implement the Python class `HyperNetwork` described below.
Class description:
Implement the HyperNetwork class.
Method signatures and docstrings:
- def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False): Args: hyper_in_features: In features of hypernetwork hyper_h... | 5519b184853be93fefa6b18d3cd39745bb151734 | <|skeleton|>
class HyperNetwork:
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False):
"""Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidden_features: Number of hidden units i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HyperNetwork:
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False):
"""Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidden_features: Number of hidden units in hypernetwork... | the_stack_v2_python_sparse | meta_modules.py | rspezialetti/gem | train | 0 | |
d9372c4e317161eddec8fc7847bc0ed8c401bc3a | [
"self.PLAYER_DEFAULT = {}\nself.PLAYER_DEFAULT['draft'] = ['name', 'pos', 'pre', 'pts']\nself.DEFAILT_BIO_MSG = '<br><br>Observe the positional slope/decay in the <strong>Points vs. Rank-by-Positon Plot</strong> below. This is one of the major factors in determining prerankings. Most prerank generators assume a li... | <|body_start_0|>
self.PLAYER_DEFAULT = {}
self.PLAYER_DEFAULT['draft'] = ['name', 'pos', 'pre', 'pts']
self.DEFAILT_BIO_MSG = '<br><br>Observe the positional slope/decay in the <strong>Points vs. Rank-by-Positon Plot</strong> below. This is one of the major factors in determining prerankings. M... | SubClass to Database and Artificial Player Classes. In general, this class should never be directly called. Let Database and Artificial Player inherit this class and set any needed properties. | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""SubClass to Database and Artificial Player Classes. In general, this class should never be directly called. Let Database and Artificial Player inherit this class and set any needed properties."""
def _set_player_defaults(self):
"""Set all player (general) default values he... | stack_v2_sparse_classes_75kplus_train_002724 | 13,571 | no_license | [
{
"docstring": "Set all player (general) default values here. This must specifically be called by sub class!",
"name": "_set_player_defaults",
"signature": "def _set_player_defaults(self)"
},
{
"docstring": "Generates players based on current state settings. Must recall this function anytime sta... | 3 | stack_v2_sparse_classes_30k_train_031832 | Implement the Python class `Player` described below.
Class description:
SubClass to Database and Artificial Player Classes. In general, this class should never be directly called. Let Database and Artificial Player inherit this class and set any needed properties.
Method signatures and docstrings:
- def _set_player_d... | Implement the Python class `Player` described below.
Class description:
SubClass to Database and Artificial Player Classes. In general, this class should never be directly called. Let Database and Artificial Player inherit this class and set any needed properties.
Method signatures and docstrings:
- def _set_player_d... | 3d5769b917507671c253f9880edbd4d815b96342 | <|skeleton|>
class Player:
"""SubClass to Database and Artificial Player Classes. In general, this class should never be directly called. Let Database and Artificial Player inherit this class and set any needed properties."""
def _set_player_defaults(self):
"""Set all player (general) default values he... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Player:
"""SubClass to Database and Artificial Player Classes. In general, this class should never be directly called. Let Database and Artificial Player inherit this class and set any needed properties."""
def _set_player_defaults(self):
"""Set all player (general) default values here. This must... | the_stack_v2_python_sparse | ffa/football_players.py | rkpatel0/Nkiru | train | 0 |
c8212843ab77e511a04c6935dca769a4f7674c8c | [
"try:\n dbclient = None\n dbclient = MyDB('ZENTAODB')\n query_sql = \"SELECT cast(id AS CHAR ) AS 'id', name AS 'name' FROM zt_project ORDER BY `order` DESC ;\"\n query_result = dbclient.select_many(query_sql, '', dictionary=True)\n if query_result[0]:\n all_projects = query_result[1]\n els... | <|body_start_0|>
try:
dbclient = None
dbclient = MyDB('ZENTAODB')
query_sql = "SELECT cast(id AS CHAR ) AS 'id', name AS 'name' FROM zt_project ORDER BY `order` DESC ;"
query_result = dbclient.select_many(query_sql, '', dictionary=True)
if query_result... | ZentaoProject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZentaoProject:
def get_all_projects():
"""获取所有满足条件的项目"""
<|body_0|>
def get_project_versions_by_project(project_id):
"""根据项目id获取项目版本"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
dbclient = None
dbclient = MyDB('ZENTAO... | stack_v2_sparse_classes_75kplus_train_002725 | 1,840 | permissive | [
{
"docstring": "获取所有满足条件的项目",
"name": "get_all_projects",
"signature": "def get_all_projects()"
},
{
"docstring": "根据项目id获取项目版本",
"name": "get_project_versions_by_project",
"signature": "def get_project_versions_by_project(project_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052574 | Implement the Python class `ZentaoProject` described below.
Class description:
Implement the ZentaoProject class.
Method signatures and docstrings:
- def get_all_projects(): 获取所有满足条件的项目
- def get_project_versions_by_project(project_id): 根据项目id获取项目版本 | Implement the Python class `ZentaoProject` described below.
Class description:
Implement the ZentaoProject class.
Method signatures and docstrings:
- def get_all_projects(): 获取所有满足条件的项目
- def get_project_versions_by_project(project_id): 根据项目id获取项目版本
<|skeleton|>
class ZentaoProject:
def get_all_projects():
... | 6e073808297eab642ff00b5ea39b6b283ee13ad2 | <|skeleton|>
class ZentaoProject:
def get_all_projects():
"""获取所有满足条件的项目"""
<|body_0|>
def get_project_versions_by_project(project_id):
"""根据项目id获取项目版本"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZentaoProject:
def get_all_projects():
"""获取所有满足条件的项目"""
try:
dbclient = None
dbclient = MyDB('ZENTAODB')
query_sql = "SELECT cast(id AS CHAR ) AS 'id', name AS 'name' FROM zt_project ORDER BY `order` DESC ;"
query_result = dbclient.select_many(q... | the_stack_v2_python_sparse | backend/zentao/project.py | themycode/test-management-platform | train | 0 | |
a3d5d0bd31588bb087f5f69fd873c142f8c0009a | [
"self.a = a\nself.s = s\nself.a_1 = inverse_x(a, len(alphabet))\nself.s_1 = -self.a_1 * s % len(alphabet)\nself.alphabet = alphabet.lower()",
"new_word = []\nfor w in word.lower():\n new_letter_idx = (self.a * self.alphabet.index(w) + self.s) % len(self.alphabet)\n new_word.append(self.alphabet[new_letter_i... | <|body_start_0|>
self.a = a
self.s = s
self.a_1 = inverse_x(a, len(alphabet))
self.s_1 = -self.a_1 * s % len(alphabet)
self.alphabet = alphabet.lower()
<|end_body_0|>
<|body_start_1|>
new_word = []
for w in word.lower():
new_letter_idx = (self.a * sel... | AffineCipher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AffineCipher:
def __init__(self, a, s, alphabet):
"""text – повідомлення; crypto – зашифроване повідомлення :param a, :param s: keys for monogram affine cipher :param alphabet: alphabet"""
<|body_0|>
def encode(self, word):
""":param word: input open message :return:... | stack_v2_sparse_classes_75kplus_train_002726 | 1,587 | no_license | [
{
"docstring": "text – повідомлення; crypto – зашифроване повідомлення :param a, :param s: keys for monogram affine cipher :param alphabet: alphabet",
"name": "__init__",
"signature": "def __init__(self, a, s, alphabet)"
},
{
"docstring": ":param word: input open message :return: encrypted input... | 3 | stack_v2_sparse_classes_30k_train_035677 | Implement the Python class `AffineCipher` described below.
Class description:
Implement the AffineCipher class.
Method signatures and docstrings:
- def __init__(self, a, s, alphabet): text – повідомлення; crypto – зашифроване повідомлення :param a, :param s: keys for monogram affine cipher :param alphabet: alphabet
-... | Implement the Python class `AffineCipher` described below.
Class description:
Implement the AffineCipher class.
Method signatures and docstrings:
- def __init__(self, a, s, alphabet): text – повідомлення; crypto – зашифроване повідомлення :param a, :param s: keys for monogram affine cipher :param alphabet: alphabet
-... | e89fe4fdbcede61c0118c8e61f54fb7350e1631b | <|skeleton|>
class AffineCipher:
def __init__(self, a, s, alphabet):
"""text – повідомлення; crypto – зашифроване повідомлення :param a, :param s: keys for monogram affine cipher :param alphabet: alphabet"""
<|body_0|>
def encode(self, word):
""":param word: input open message :return:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AffineCipher:
def __init__(self, a, s, alphabet):
"""text – повідомлення; crypto – зашифроване повідомлення :param a, :param s: keys for monogram affine cipher :param alphabet: alphabet"""
self.a = a
self.s = s
self.a_1 = inverse_x(a, len(alphabet))
self.s_1 = -self.a_1... | the_stack_v2_python_sparse | lab2/Ex1.py | olexandrkucher/Cryptology | train | 0 | |
dc05809537f4d3ebfd74c4febbfd758afbf8e2d3 | [
"get_parser = exp_parser.copy()\nget_parser.add_argument('exp_uid', type=str, required=True)\nget_parser.add_argument('exp_key', type=str, required=True)\nget_parser.add_argument('args', type=dict, required=False)\nif not keychain.verify_exp_key(exp_uid, exp_key):\n return (api_util.attach_meta({}, api_util.veri... | <|body_start_0|>
get_parser = exp_parser.copy()
get_parser.add_argument('exp_uid', type=str, required=True)
get_parser.add_argument('exp_key', type=str, required=True)
get_parser.add_argument('args', type=dict, required=False)
if not keychain.verify_exp_key(exp_uid, exp_key):
... | Experiment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Experiment:
def get(self, exp_uid, exp_key):
""".. http:get:: /experiment/<exp_uid>/<exp_key> Get an experiment initialization configuration from an exp_uid **Example request**: .. sourcecode:: http GET /experiment/<exp_uid> HTTP/1.1 Host: next_backend.next.discovery.wisc.edu **Example r... | stack_v2_sparse_classes_75kplus_train_002727 | 6,187 | permissive | [
{
"docstring": ".. http:get:: /experiment/<exp_uid>/<exp_key> Get an experiment initialization configuration from an exp_uid **Example request**: .. sourcecode:: http GET /experiment/<exp_uid> HTTP/1.1 Host: next_backend.next.discovery.wisc.edu **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Ac... | 2 | stack_v2_sparse_classes_30k_train_022308 | Implement the Python class `Experiment` described below.
Class description:
Implement the Experiment class.
Method signatures and docstrings:
- def get(self, exp_uid, exp_key): .. http:get:: /experiment/<exp_uid>/<exp_key> Get an experiment initialization configuration from an exp_uid **Example request**: .. sourceco... | Implement the Python class `Experiment` described below.
Class description:
Implement the Experiment class.
Method signatures and docstrings:
- def get(self, exp_uid, exp_key): .. http:get:: /experiment/<exp_uid>/<exp_key> Get an experiment initialization configuration from an exp_uid **Example request**: .. sourceco... | 2fcd8df29d274c86276bb5a039f7e61f201ebf61 | <|skeleton|>
class Experiment:
def get(self, exp_uid, exp_key):
""".. http:get:: /experiment/<exp_uid>/<exp_key> Get an experiment initialization configuration from an exp_uid **Example request**: .. sourcecode:: http GET /experiment/<exp_uid> HTTP/1.1 Host: next_backend.next.discovery.wisc.edu **Example r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Experiment:
def get(self, exp_uid, exp_key):
""".. http:get:: /experiment/<exp_uid>/<exp_key> Get an experiment initialization configuration from an exp_uid **Example request**: .. sourcecode:: http GET /experiment/<exp_uid> HTTP/1.1 Host: next_backend.next.discovery.wisc.edu **Example response**: .. ... | the_stack_v2_python_sparse | next/api/resources/experiment.py | kgjamieson/NEXT-psych | train | 4 | |
5147a515e1f1dacac08ce530dc271ed43b10a7f5 | [
"if np.sum(ratio_list) != 1:\n ratio_list = np.array(ratio_list)\n ratio_list = ratio_list / np.sum(ratio_list)\nreturn [data[int(sum(ratio_list[0:e]) * len(data)):int(sum(ratio_list[0:e + 1]) * len(data))] for e in range(len(ratio_list))]",
"if np.sum(ratio_list) != 1:\n ratio_list = np.array(ratio_list... | <|body_start_0|>
if np.sum(ratio_list) != 1:
ratio_list = np.array(ratio_list)
ratio_list = ratio_list / np.sum(ratio_list)
return [data[int(sum(ratio_list[0:e]) * len(data)):int(sum(ratio_list[0:e + 1]) * len(data))] for e in range(len(ratio_list))]
<|end_body_0|>
<|body_start_... | This class can help split data by calling split_data and split_feed_dict method. | SplitData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitData:
"""This class can help split data by calling split_data and split_feed_dict method."""
def split_data(data, ratio_list):
"""Divide the data based on the given parameter ratio_list. Args: data(ndarray):Data to be split. ratio_list(list):Split ratio, the `data` will be split... | stack_v2_sparse_classes_75kplus_train_002728 | 7,270 | permissive | [
{
"docstring": "Divide the data based on the given parameter ratio_list. Args: data(ndarray):Data to be split. ratio_list(list):Split ratio, the `data` will be split according to the ratio. :return:The elements in the returned list are the divided data, and the dimensions of the list are the same as ratio_list.... | 2 | null | Implement the Python class `SplitData` described below.
Class description:
This class can help split data by calling split_data and split_feed_dict method.
Method signatures and docstrings:
- def split_data(data, ratio_list): Divide the data based on the given parameter ratio_list. Args: data(ndarray):Data to be spli... | Implement the Python class `SplitData` described below.
Class description:
This class can help split data by calling split_data and split_feed_dict method.
Method signatures and docstrings:
- def split_data(data, ratio_list): Divide the data based on the given parameter ratio_list. Args: data(ndarray):Data to be spli... | c5a59769fe61c1126fe59ee4e7c8dcfb651bb6ee | <|skeleton|>
class SplitData:
"""This class can help split data by calling split_data and split_feed_dict method."""
def split_data(data, ratio_list):
"""Divide the data based on the given parameter ratio_list. Args: data(ndarray):Data to be split. ratio_list(list):Split ratio, the `data` will be split... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SplitData:
"""This class can help split data by calling split_data and split_feed_dict method."""
def split_data(data, ratio_list):
"""Divide the data based on the given parameter ratio_list. Args: data(ndarray):Data to be split. ratio_list(list):Split ratio, the `data` will be split according to... | the_stack_v2_python_sparse | UCTB/preprocess/preprocessor.py | GRE-EXAMINATION/UCTB | train | 2 |
60edad5ad0fe9cfb584bf7f4c1d33446714fd404 | [
"res = []\nqueue = deque([root])\nwhile queue:\n node = queue.popleft()\n if node:\n children = node.children\n res.append(node.val)\n res.append(len(children))\n for child in children:\n queue.append(child)\nreturn res",
"if not data:\n root = None\nelse:\n data... | <|body_start_0|>
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
children = node.children
res.append(node.val)
res.append(len(children))
for child in children:
... | CodecBFS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodecBFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_002729 | 2,626 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | stack_v2_sparse_classes_30k_train_014199 | Implement the Python class `CodecBFS` described below.
Class description:
Implement the CodecBFS class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | Implement the Python class `CodecBFS` described below.
Class description:
Implement the CodecBFS class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | c937fe19be665ba7ac345e1729ff531f370f30e8 | <|skeleton|>
class CodecBFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CodecBFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
children = node.children
res.append(nod... | the_stack_v2_python_sparse | facebook/onsite/serializeAndDeserializeNTree.py | nguyenngochuy91/companyQuestions | train | 1 | |
edd55279d4257561b6a95741631e4fdb1cd5e253 | [
"res = BaseResponse()\nall_coupon = models.Coupon.objects.all()\ncoupon_dict = {}\nfor item in all_coupon:\n coupon_dict[item.id] = {'id': item.id, 'object_id': item.object_id, 'title': item.title, 'brief': item.brief, 'equal_money': item.equal_money, 'off_percent': item.off_percent, 'coupon_type': item.coupon_t... | <|body_start_0|>
res = BaseResponse()
all_coupon = models.Coupon.objects.all()
coupon_dict = {}
for item in all_coupon:
coupon_dict[item.id] = {'id': item.id, 'object_id': item.object_id, 'title': item.title, 'brief': item.brief, 'equal_money': item.equal_money, 'off_percent'... | 优惠券发放接口 | CouponDistributionView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
<|body_0|>
def post(self, request):
"""领取优惠券"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = BaseResponse()
all_coupon = models.Coupon.objects.all()
... | stack_v2_sparse_classes_75kplus_train_002730 | 47,779 | permissive | [
{
"docstring": "查看优惠券",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "领取优惠券",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033454 | Implement the Python class `CouponDistributionView` described below.
Class description:
优惠券发放接口
Method signatures and docstrings:
- def get(self, request): 查看优惠券
- def post(self, request): 领取优惠券 | Implement the Python class `CouponDistributionView` described below.
Class description:
优惠券发放接口
Method signatures and docstrings:
- def get(self, request): 查看优惠券
- def post(self, request): 领取优惠券
<|skeleton|>
class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
<|bo... | 59053c88faf76de3592b5aa02b1425b126fe2f2d | <|skeleton|>
class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
<|body_0|>
def post(self, request):
"""领取优惠券"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CouponDistributionView:
"""优惠券发放接口"""
def get(self, request):
"""查看优惠券"""
res = BaseResponse()
all_coupon = models.Coupon.objects.all()
coupon_dict = {}
for item in all_coupon:
coupon_dict[item.id] = {'id': item.id, 'object_id': item.object_id, 'title':... | the_stack_v2_python_sparse | OnlineStudy/generic/views.py | NanRenTeam-9/MongoMicroCourse | train | 0 |
5b19be32309096009b34cba9ed69730ba9545aee | [
"self.student_feature_map = student_feature_map\nself.teacher_feature_map = teacher_feature_map\nself.distillation_loss_weight = distillation_loss_weight",
"distiller_pass = L2DistillerPass(self.student_feature_map, self.teacher_feature_map, self.distillation_loss_weight)\ndis_graph = distiller_pass.apply(graph)\... | <|body_start_0|>
self.student_feature_map = student_feature_map
self.teacher_feature_map = teacher_feature_map
self.distillation_loss_weight = distillation_loss_weight
<|end_body_0|>
<|body_start_1|>
distiller_pass = L2DistillerPass(self.student_feature_map, self.teacher_feature_map, se... | Combine two layers from student net and teacher net by l2-loss. And add the loss into the total loss using for distillation training. | L2Distiller | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2Distiller:
"""Combine two layers from student net and teacher net by l2-loss. And add the loss into the total loss using for distillation training."""
def __init__(self, student_feature_map, teacher_feature_map, distillation_loss_weight=1):
"""Args: student_feature_map(str): The na... | stack_v2_sparse_classes_75kplus_train_002731 | 12,323 | permissive | [
{
"docstring": "Args: student_feature_map(str): The name of feature map from student network. teacher_feature_map(str): The name of feature map from teacher network. It's shape should be the same with student network. distillation_loss_weight(float): The weight of the l2-loss.",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_030557 | Implement the Python class `L2Distiller` described below.
Class description:
Combine two layers from student net and teacher net by l2-loss. And add the loss into the total loss using for distillation training.
Method signatures and docstrings:
- def __init__(self, student_feature_map, teacher_feature_map, distillati... | Implement the Python class `L2Distiller` described below.
Class description:
Combine two layers from student net and teacher net by l2-loss. And add the loss into the total loss using for distillation training.
Method signatures and docstrings:
- def __init__(self, student_feature_map, teacher_feature_map, distillati... | 39ac41f137d685af66078adf2f35d65473978b4a | <|skeleton|>
class L2Distiller:
"""Combine two layers from student net and teacher net by l2-loss. And add the loss into the total loss using for distillation training."""
def __init__(self, student_feature_map, teacher_feature_map, distillation_loss_weight=1):
"""Args: student_feature_map(str): The na... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class L2Distiller:
"""Combine two layers from student net and teacher net by l2-loss. And add the loss into the total loss using for distillation training."""
def __init__(self, student_feature_map, teacher_feature_map, distillation_loss_weight=1):
"""Args: student_feature_map(str): The name of feature... | the_stack_v2_python_sparse | python/paddle/fluid/contrib/slim/distillation/distiller.py | cryoco/Paddle | train | 3 |
ccb8471bb4dbf360a11e35e44c3c4dc63b54392d | [
"n = len(height)\nif n == 0:\n return 0\nans = 0\nfor h in range(1, max(height) + 1):\n temp = 0\n isStart = False\n for v in height:\n if isStart and v < h:\n temp += 1\n if v >= h:\n ans += temp\n temp = 0\n isStart = True\nreturn ans",
"n = ... | <|body_start_0|>
n = len(height)
if n == 0:
return 0
ans = 0
for h in range(1, max(height) + 1):
temp = 0
isStart = False
for v in height:
if isStart and v < h:
temp += 1
if v >= h:
... | 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。"""
def trap_row_TLE(self, height) -> int:
"""从底部向上, 一层一层来"""
<|body_0|>
def trap_col(self, height) -> int:
"""分开来看每一列, 当前列能存住的雨滴: 两侧列中较低的与当前列高度的差值 时间复杂度:O(n²),遍历每一列需要 n, 找出左边最高和右边最高的墙加起来刚好又是一个 n,所以是 n... | stack_v2_sparse_classes_75kplus_train_002732 | 3,238 | permissive | [
{
"docstring": "从底部向上, 一层一层来",
"name": "trap_row_TLE",
"signature": "def trap_row_TLE(self, height) -> int"
},
{
"docstring": "分开来看每一列, 当前列能存住的雨滴: 两侧列中较低的与当前列高度的差值 时间复杂度:O(n²),遍历每一列需要 n, 找出左边最高和右边最高的墙加起来刚好又是一个 n,所以是 n² 空间复杂度:O(1)",
"name": "trap_col",
"signature": "def trap_col(self, hei... | 4 | stack_v2_sparse_classes_30k_train_050395 | Implement the Python class `Solution` described below.
Class description:
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
Method signatures and docstrings:
- def trap_row_TLE(self, height) -> int: 从底部向上, 一层一层来
- def trap_col(self, height) -> int: 分开来看每一列, 当前列能存住的雨滴: 两侧列中较低的与当前列高度的差值 时间复杂度:O(n²),遍历每一列需要 n, 找出左边最高和右边... | Implement the Python class `Solution` described below.
Class description:
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
Method signatures and docstrings:
- def trap_row_TLE(self, height) -> int: 从底部向上, 一层一层来
- def trap_col(self, height) -> int: 分开来看每一列, 当前列能存住的雨滴: 两侧列中较低的与当前列高度的差值 时间复杂度:O(n²),遍历每一列需要 n, 找出左边最高和右边... | 9f49766a2b375a6c65f7bfa96df513875ddd772d | <|skeleton|>
class Solution:
"""给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。"""
def trap_row_TLE(self, height) -> int:
"""从底部向上, 一层一层来"""
<|body_0|>
def trap_col(self, height) -> int:
"""分开来看每一列, 当前列能存住的雨滴: 两侧列中较低的与当前列高度的差值 时间复杂度:O(n²),遍历每一列需要 n, 找出左边最高和右边最高的墙加起来刚好又是一个 n,所以是 n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。"""
def trap_row_TLE(self, height) -> int:
"""从底部向上, 一层一层来"""
n = len(height)
if n == 0:
return 0
ans = 0
for h in range(1, max(height) + 1):
temp = 0
isStart = False
... | the_stack_v2_python_sparse | Leetcode/42.trap.py | Song2017/Leetcode_python | train | 1 |
735f63e38acbd54bf45560ab72e32ac16b119ff0 | [
"test = '3\\n1 2 1'\nd = Coat(test)\nself.assertEqual(d.n, 3)\nself.assertEqual(d.numl, [1, 2, 1])\nself.assertEqual(Coat(test).calculate(), '1')\ntest = '5\\n20 4 3 2 1'\nself.assertEqual(Coat(test).calculate(), '11')\ntest = ''\ntest = ''",
"import random\nimport timeit\ntest = str(nmax) + ' ' + str(nmax) + '\\... | <|body_start_0|>
test = '3\n1 2 1'
d = Coat(test)
self.assertEqual(d.n, 3)
self.assertEqual(d.numl, [1, 2, 1])
self.assertEqual(Coat(test).calculate(), '1')
test = '5\n20 4 3 2 1'
self.assertEqual(Coat(test).calculate(), '11')
test = ''
test = ''
<... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Coat class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '3\n1 2 1'
d = Coat(test)
self.assertEqual(d.n, 3... | stack_v2_sparse_classes_75kplus_train_002733 | 2,864 | permissive | [
{
"docstring": "Coat class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001811 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Coat class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Coat class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""C... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Coat class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class unitTests:
def test_single_test(self):
"""Coat class testing"""
test = '3\n1 2 1'
d = Coat(test)
self.assertEqual(d.n, 3)
self.assertEqual(d.numl, [1, 2, 1])
self.assertEqual(Coat(test).calculate(), '1')
test = '5\n20 4 3 2 1'
self.assertEqual(Co... | the_stack_v2_python_sparse | codeforces/667B_coat.py | snsokolov/contests | train | 1 | |
a02993dc65dc8c560bf78d241219bf9c9d38b0a9 | [
"self.train_dir = './data/arxiepiskopi'\nself.data_dir = './data'\ntrain_file = os.path.join(self.data_dir, 'train_trajectories_arxiepiskopi.cpkl')\nif not os.path.exists(train_file) or forcePreProcess:\n print('Creating pre-processed training data from raw data')\n self.frame_preprocess(self.train_dir, train... | <|body_start_0|>
self.train_dir = './data/arxiepiskopi'
self.data_dir = './data'
train_file = os.path.join(self.data_dir, 'train_trajectories_arxiepiskopi.cpkl')
if not os.path.exists(train_file) or forcePreProcess:
print('Creating pre-processed training data from raw data')
... | DataLoader_ETH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLoader_ETH:
def __init__(self, forcePreProcess=False):
"""Initialiser function for the SocialDataLoader class params: args: Arguments for the model forcePreProcess : Flag to forcefully preprocess the data again from the .txt files infer: Flag to process the data in inference mode"""
... | stack_v2_sparse_classes_75kplus_train_002734 | 4,221 | no_license | [
{
"docstring": "Initialiser function for the SocialDataLoader class params: args: Arguments for the model forcePreProcess : Flag to forcefully preprocess the data again from the .txt files infer: Flag to process the data in inference mode",
"name": "__init__",
"signature": "def __init__(self, forcePrePr... | 2 | stack_v2_sparse_classes_30k_train_048650 | Implement the Python class `DataLoader_ETH` described below.
Class description:
Implement the DataLoader_ETH class.
Method signatures and docstrings:
- def __init__(self, forcePreProcess=False): Initialiser function for the SocialDataLoader class params: args: Arguments for the model forcePreProcess : Flag to forcefu... | Implement the Python class `DataLoader_ETH` described below.
Class description:
Implement the DataLoader_ETH class.
Method signatures and docstrings:
- def __init__(self, forcePreProcess=False): Initialiser function for the SocialDataLoader class params: args: Arguments for the model forcePreProcess : Flag to forcefu... | 4cc6e520881ddcd27923d65016e2c9c7c909225f | <|skeleton|>
class DataLoader_ETH:
def __init__(self, forcePreProcess=False):
"""Initialiser function for the SocialDataLoader class params: args: Arguments for the model forcePreProcess : Flag to forcefully preprocess the data again from the .txt files infer: Flag to process the data in inference mode"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataLoader_ETH:
def __init__(self, forcePreProcess=False):
"""Initialiser function for the SocialDataLoader class params: args: Arguments for the model forcePreProcess : Flag to forcefully preprocess the data again from the .txt files infer: Flag to process the data in inference mode"""
self.t... | the_stack_v2_python_sparse | python/DeepLearningThesis/trajectory_validation-SOCIAL_MLP_COMPLETED/data_loaders/loader_arxiepiskopi.py | EvaRamaj/projects | train | 0 | |
bc5abca91a15d909a5fe66056eb1e3a4077ae82a | [
"review_id = self.kwargs.get('review_id')\ntitle = self.kwargs.get('title_id')\nreview = get_object_or_404(Review, pk=review_id, title=title)\nreturn review.comments.all()",
"title = self.kwargs.get('title_id')\nreview_id = get_object_or_404(Review, pk=self.kwargs.get('review_id'), title=title)\nserializer.save(a... | <|body_start_0|>
review_id = self.kwargs.get('review_id')
title = self.kwargs.get('title_id')
review = get_object_or_404(Review, pk=review_id, title=title)
return review.comments.all()
<|end_body_0|>
<|body_start_1|>
title = self.kwargs.get('title_id')
review_id = get_ob... | CommentViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentViewSet:
def get_queryset(self):
"""Getting a query of comments of a review via related_name. Or of an exact comment, if comment_id is provided"""
<|body_0|>
def perform_create(self, serializer):
"""Added author saving for comment creation via API"""
<... | stack_v2_sparse_classes_75kplus_train_002735 | 6,873 | no_license | [
{
"docstring": "Getting a query of comments of a review via related_name. Or of an exact comment, if comment_id is provided",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Added author saving for comment creation via API",
"name": "perform_create",
"sig... | 2 | stack_v2_sparse_classes_30k_train_051704 | Implement the Python class `CommentViewSet` described below.
Class description:
Implement the CommentViewSet class.
Method signatures and docstrings:
- def get_queryset(self): Getting a query of comments of a review via related_name. Or of an exact comment, if comment_id is provided
- def perform_create(self, seriali... | Implement the Python class `CommentViewSet` described below.
Class description:
Implement the CommentViewSet class.
Method signatures and docstrings:
- def get_queryset(self): Getting a query of comments of a review via related_name. Or of an exact comment, if comment_id is provided
- def perform_create(self, seriali... | b2d58b175c641b37eca20edd8de1ed39f9029199 | <|skeleton|>
class CommentViewSet:
def get_queryset(self):
"""Getting a query of comments of a review via related_name. Or of an exact comment, if comment_id is provided"""
<|body_0|>
def perform_create(self, serializer):
"""Added author saving for comment creation via API"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentViewSet:
def get_queryset(self):
"""Getting a query of comments of a review via related_name. Or of an exact comment, if comment_id is provided"""
review_id = self.kwargs.get('review_id')
title = self.kwargs.get('title_id')
review = get_object_or_404(Review, pk=review_id... | the_stack_v2_python_sparse | api/views.py | aleksizverev/YaMDb | train | 1 | |
27145d01eaeea0a65968b6d6b8a065566557ea04 | [
"virtual_product_id = int(request.GET.get('id', 0))\nvirtual_product = None\nif virtual_product_id:\n _virtual_product = promotion_models.VirtualProduct.objects.get(id=virtual_product_id)\n virtual_product = {'id': _virtual_product.id, 'name': _virtual_product.name, 'created_at': _virtual_product.created_at.s... | <|body_start_0|>
virtual_product_id = int(request.GET.get('id', 0))
virtual_product = None
if virtual_product_id:
_virtual_product = promotion_models.VirtualProduct.objects.get(id=virtual_product_id)
virtual_product = {'id': _virtual_product.id, 'name': _virtual_product.n... | VirtualProductCodes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualProductCodes:
def get(request):
"""创建福利卡券活动"""
<|body_0|>
def api_get(request):
"""获取虚拟商品和微众卡商品"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
virtual_product_id = int(request.GET.get('id', 0))
virtual_product = None
if virtu... | stack_v2_sparse_classes_75kplus_train_002736 | 5,320 | no_license | [
{
"docstring": "创建福利卡券活动",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "获取虚拟商品和微众卡商品",
"name": "api_get",
"signature": "def api_get(request)"
}
] | 2 | null | Implement the Python class `VirtualProductCodes` described below.
Class description:
Implement the VirtualProductCodes class.
Method signatures and docstrings:
- def get(request): 创建福利卡券活动
- def api_get(request): 获取虚拟商品和微众卡商品 | Implement the Python class `VirtualProductCodes` described below.
Class description:
Implement the VirtualProductCodes class.
Method signatures and docstrings:
- def get(request): 创建福利卡券活动
- def api_get(request): 获取虚拟商品和微众卡商品
<|skeleton|>
class VirtualProductCodes:
def get(request):
"""创建福利卡券活动"""
... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class VirtualProductCodes:
def get(request):
"""创建福利卡券活动"""
<|body_0|>
def api_get(request):
"""获取虚拟商品和微众卡商品"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VirtualProductCodes:
def get(request):
"""创建福利卡券活动"""
virtual_product_id = int(request.GET.get('id', 0))
virtual_product = None
if virtual_product_id:
_virtual_product = promotion_models.VirtualProduct.objects.get(id=virtual_product_id)
virtual_product =... | the_stack_v2_python_sparse | weapp/mall/promotion/virtual_product_codes.py | chengdg/weizoom | train | 1 | |
3cdf5ddd7311079b2f7727992b7d3d16e6b3c8ef | [
"square1 = PolybiusSquare(alphabet, key[0])\nsquare2 = PolybiusSquare(alphabet, key[1])\nsquare3 = PolybiusSquare(alphabet, key[2])\nres = []\nit = iter(text)\nrows = square1.get_rows()\ncols = square2.get_columns()\nwhile True:\n try:\n t = next(it)\n except StopIteration:\n break\n row1, co... | <|body_start_0|>
square1 = PolybiusSquare(alphabet, key[0])
square2 = PolybiusSquare(alphabet, key[1])
square3 = PolybiusSquare(alphabet, key[2])
res = []
it = iter(text)
rows = square1.get_rows()
cols = square2.get_columns()
while True:
try:
... | The Three Square Cipher | ThreeSquare | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: strin... | stack_v2_sparse_classes_75kplus_train_002737 | 2,590 | permissive | [
{
"docstring": "Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: string :type key: tuple of 3 strings :type alphabet: string :return: text :rtype: string",
"name": "encrypt",
"signa... | 2 | stack_v2_sparse_classes_30k_train_006914 | Implement the Python class `ThreeSquare` described below.
Class description:
The Three Square Cipher
Method signatures and docstrings:
- def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ): Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, ... | Implement the Python class `ThreeSquare` described below.
Class description:
The Three Square Cipher
Method signatures and docstrings:
- def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ): Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, ... | e464f998e5540f52e269fe360ec9d3a08e976b2e | <|skeleton|>
class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: strin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreeSquare:
"""The Three Square Cipher"""
def encrypt(self, text, key, alphabet=al.ENGLISH_SQUARE_IJ):
"""Encryption method :param text: Text to encrypt :param key: Encryption key :param alphabet: Alphabet which will be used, if there is no a value, English is used :type text: string :type key: ... | the_stack_v2_python_sparse | secretpy/ciphers/three_square.py | tigertv/secretpy | train | 65 |
b01661eb5ae09695bd75c0cd61a39b1516dc5c48 | [
"super().__init__(coordinator=coordinator)\nself._attr_name = f'{coordinator.data.info.name} Wi-Fi Signal'\nself._attr_unique_id = f'{coordinator.data.info.mac_address}_wifi_signal'",
"if not self.coordinator.data.info.wifi:\n return None\nreturn self.coordinator.data.info.wifi.signal"
] | <|body_start_0|>
super().__init__(coordinator=coordinator)
self._attr_name = f'{coordinator.data.info.name} Wi-Fi Signal'
self._attr_unique_id = f'{coordinator.data.info.mac_address}_wifi_signal'
<|end_body_0|>
<|body_start_1|>
if not self.coordinator.data.info.wifi:
return ... | Defines a WLED Wi-Fi signal sensor. | WLEDWifiSignalSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WLEDWifiSignalSensor:
"""Defines a WLED Wi-Fi signal sensor."""
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED Wi-Fi signal sensor."""
<|body_0|>
def state(self) -> int | None:
"""Return the state of the sensor."""
... | stack_v2_sparse_classes_75kplus_train_002738 | 6,830 | permissive | [
{
"docstring": "Initialize WLED Wi-Fi signal sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "state",
"signature": "def state(self) -> int | None"
}
] | 2 | null | Implement the Python class `WLEDWifiSignalSensor` described below.
Class description:
Defines a WLED Wi-Fi signal sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: Initialize WLED Wi-Fi signal sensor.
- def state(self) -> int | None: Return the state of th... | Implement the Python class `WLEDWifiSignalSensor` described below.
Class description:
Defines a WLED Wi-Fi signal sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: Initialize WLED Wi-Fi signal sensor.
- def state(self) -> int | None: Return the state of th... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class WLEDWifiSignalSensor:
"""Defines a WLED Wi-Fi signal sensor."""
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED Wi-Fi signal sensor."""
<|body_0|>
def state(self) -> int | None:
"""Return the state of the sensor."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WLEDWifiSignalSensor:
"""Defines a WLED Wi-Fi signal sensor."""
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED Wi-Fi signal sensor."""
super().__init__(coordinator=coordinator)
self._attr_name = f'{coordinator.data.info.name} Wi-Fi Signal'
... | the_stack_v2_python_sparse | homeassistant/components/wled/sensor.py | BenWoodford/home-assistant | train | 11 |
35574f34b2ea9c03002d728797b788d107fe1d8f | [
"resp = {}\nparsed_args = UserManager.process_query_param(query_param=request.args)\ndata = UserManager.list_users(parsed_args)\nresp['data'] = data\nreturn resp",
"resp = {}\nuser_data = request.get_json(force=True)\num = UserManager(data=user_data)\nuser_data = um.create_user()\nresp['message'] = 'User created ... | <|body_start_0|>
resp = {}
parsed_args = UserManager.process_query_param(query_param=request.args)
data = UserManager.list_users(parsed_args)
resp['data'] = data
return resp
<|end_body_0|>
<|body_start_1|>
resp = {}
user_data = request.get_json(force=True)
... | Users | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def get(self):
"""List users. Can also be used to search users based on certain filters"""
<|body_0|>
def post(self):
"""Create new User"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
resp = {}
parsed_args = UserManager.process_query... | stack_v2_sparse_classes_75kplus_train_002739 | 2,367 | no_license | [
{
"docstring": "List users. Can also be used to search users based on certain filters",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create new User",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def get(self): List users. Can also be used to search users based on certain filters
- def post(self): Create new User | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def get(self): List users. Can also be used to search users based on certain filters
- def post(self): Create new User
<|skeleton|>
class Users:
def get(self):
"""List us... | 7bca15c619e1fca5d3b756661cc336fadbad669a | <|skeleton|>
class Users:
def get(self):
"""List users. Can also be used to search users based on certain filters"""
<|body_0|>
def post(self):
"""Create new User"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Users:
def get(self):
"""List users. Can also be used to search users based on certain filters"""
resp = {}
parsed_args = UserManager.process_query_param(query_param=request.args)
data = UserManager.list_users(parsed_args)
resp['data'] = data
return resp
de... | the_stack_v2_python_sparse | demo/services/api/src/app/services/service_user_mgmt/controllers/v1/user.py | dipangshu15/flask_boilerplate | train | 0 | |
a458edf3cc29789a09326ebf0570b8c840d3321a | [
"AnyObject.setup_orientation(self)\nself.mtx = np.dot(self.rot_mtx.T, np.dot(self.mtx0, self.rot_mtx))\nself.rot_mtx_hc = gm.make_rotation_matrix_hc(self.rot_mtx)\nself.intersector.set_data(mtx=self.mtx)",
"self.centre = np.array(centre, dtype=np.float64)\nself.mtx_hc = self._get_matrix_hc()\nself.intersector.set... | <|body_start_0|>
AnyObject.setup_orientation(self)
self.mtx = np.dot(self.rot_mtx.T, np.dot(self.mtx0, self.rot_mtx))
self.rot_mtx_hc = gm.make_rotation_matrix_hc(self.rot_mtx)
self.intersector.set_data(mtx=self.mtx)
<|end_body_0|>
<|body_start_1|>
self.centre = np.array(centre,... | Base class of all geometrical objects to be sliced that are not compound (multi-object). | SingleObject | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleObject:
"""Base class of all geometrical objects to be sliced that are not compound (multi-object)."""
def setup_orientation(self):
"""Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation a... | stack_v2_sparse_classes_75kplus_train_002740 | 1,856 | permissive | [
{
"docstring": "Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation axis according to self.conf. Also update the intersector.",
"name": "setup_orientation",
"signature": "def setup_orientation(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_027520 | Implement the Python class `SingleObject` described below.
Class description:
Base class of all geometrical objects to be sliced that are not compound (multi-object).
Method signatures and docstrings:
- def setup_orientation(self): Sets rot_axis, the direction vector of rotation axis defining the orientation in space... | Implement the Python class `SingleObject` described below.
Class description:
Base class of all geometrical objects to be sliced that are not compound (multi-object).
Method signatures and docstrings:
- def setup_orientation(self): Sets rot_axis, the direction vector of rotation axis defining the orientation in space... | 8a8be511b545e1618a3140295a564b09001e095e | <|skeleton|>
class SingleObject:
"""Base class of all geometrical objects to be sliced that are not compound (multi-object)."""
def setup_orientation(self):
"""Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleObject:
"""Base class of all geometrical objects to be sliced that are not compound (multi-object)."""
def setup_orientation(self):
"""Sets rot_axis, the direction vector of rotation axis defining the orientation in space, and rot_angle, the rotation angle around the rotation axis according... | the_stack_v2_python_sparse | gensei/single_object.py | ramosapf/gensei | train | 0 |
5dce4a1ca7fa411b44b079291c2724066c947c83 | [
"self.net: cnn.Net\nself.optimizer: Union[optim.Adam, optim.SGD]\nself.criterion: nn.CrossEntropyLoss\nself.classes: Dict[int, str]\nself.input_size = toml_settings.input_size\nself.load_pth_path = load_pth_path\nself.use_gpu = torch.cuda.is_available() and use_gpu\nself.device = torch.device('cuda' if self.use_gpu... | <|body_start_0|>
self.net: cnn.Net
self.optimizer: Union[optim.Adam, optim.SGD]
self.criterion: nn.CrossEntropyLoss
self.classes: Dict[int, str]
self.input_size = toml_settings.input_size
self.load_pth_path = load_pth_path
self.use_gpu = torch.cuda.is_available() ... | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def _old_init__(self, toml_settings: Optional[_tms.TomlSettings]=None, classes: Optional[Dict[int, str]]=None, use_gpu: bool=True, log: Optional[ul.LogFile]=None, rate: Optional[ul.LogFile]=None, load_pth_path: Optional[str]=None) -> None:
"""Args: toml_settings (_tms.TomlSettings... | stack_v2_sparse_classes_75kplus_train_002741 | 4,400 | no_license | [
{
"docstring": "Args: toml_settings (_tms.TomlSettings): parameters of user's setting. classes (Optional[dict], optional): classes of dataset. Defaults to None. use_gpu (bool, optional): uisng gpu or cpu. Defaults to False. log (Optional[ul.LogFile], optional): logging for debug log. Defaults to None. rate (Opt... | 2 | null | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def _old_init__(self, toml_settings: Optional[_tms.TomlSettings]=None, classes: Optional[Dict[int, str]]=None, use_gpu: bool=True, log: Optional[ul.LogFile]=None, rate: Optional[ul.Log... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def _old_init__(self, toml_settings: Optional[_tms.TomlSettings]=None, classes: Optional[Dict[int, str]]=None, use_gpu: bool=True, log: Optional[ul.LogFile]=None, rate: Optional[ul.Log... | 066ea10fdeac35f49d82757571234b02da386095 | <|skeleton|>
class Model:
def _old_init__(self, toml_settings: Optional[_tms.TomlSettings]=None, classes: Optional[Dict[int, str]]=None, use_gpu: bool=True, log: Optional[ul.LogFile]=None, rate: Optional[ul.LogFile]=None, load_pth_path: Optional[str]=None) -> None:
"""Args: toml_settings (_tms.TomlSettings... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
def _old_init__(self, toml_settings: Optional[_tms.TomlSettings]=None, classes: Optional[Dict[int, str]]=None, use_gpu: bool=True, log: Optional[ul.LogFile]=None, rate: Optional[ul.LogFile]=None, load_pth_path: Optional[str]=None) -> None:
"""Args: toml_settings (_tms.TomlSettings): parameters ... | the_stack_v2_python_sparse | modules/_test_scripts/class_Model.py | kazuya0202/cnn-with-pytorch | train | 2 | |
b5773deb1210f2b601be84ad429209722783a316 | [
"data = self.get_json()\nuser_id = data.pop('user_id', None)\nif user_id is None:\n return self.error('User ID must be specified')\nstream_id = int(stream_id)\nwith self.Session() as session:\n su = session.scalars(StreamUser.select(session.user_or_token).where(StreamUser.stream_id == stream_id).where(StreamU... | <|body_start_0|>
data = self.get_json()
user_id = data.pop('user_id', None)
if user_id is None:
return self.error('User ID must be specified')
stream_id = int(stream_id)
with self.Session() as session:
su = session.scalars(StreamUser.select(session.user_or... | StreamUserHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamUserHandler:
def post(self, stream_id, *ignored_args):
"""--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user... | stack_v2_sparse_classes_75kplus_train_002742 | 8,804 | permissive | [
{
"docstring": "--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user_id: type: integer required: - user_id responses: 200: content: applicat... | 2 | stack_v2_sparse_classes_30k_train_016218 | Implement the Python class `StreamUserHandler` described below.
Class description:
Implement the StreamUserHandler class.
Method signatures and docstrings:
- def post(self, stream_id, *ignored_args): --- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required... | Implement the Python class `StreamUserHandler` described below.
Class description:
Implement the StreamUserHandler class.
Method signatures and docstrings:
- def post(self, stream_id, *ignored_args): --- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class StreamUserHandler:
def post(self, stream_id, *ignored_args):
"""--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamUserHandler:
def post(self, stream_id, *ignored_args):
"""--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user_id: type: int... | the_stack_v2_python_sparse | skyportal/handlers/api/stream.py | skyportal/skyportal | train | 80 | |
71315a3c867bc0c386139cb2e2ada264b26bdaa8 | [
"self.id = id\nself.provider_id = provider_id\nself.server_time = server_time\nself.username = username\nself.driver_license_number = driver_license_number\nself.country = country\nself.region = region\nself.driver_home_terminal = driver_home_terminal",
"if dictionary is None:\n return None\nid = dictionary.ge... | <|body_start_0|>
self.id = id
self.provider_id = provider_id
self.server_time = server_time
self.username = username
self.driver_license_number = driver_license_number
self.country = country
self.region = region
self.driver_home_terminal = driver_home_term... | Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was received at the TSP username (string): a username of this driver driver_licens... | Driver | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
"""Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was received at the TSP username (string): a use... | stack_v2_sparse_classes_75kplus_train_002743 | 3,303 | permissive | [
{
"docstring": "Constructor for the Driver class",
"name": "__init__",
"signature": "def __init__(self, id=None, provider_id=None, server_time=None, username=None, driver_license_number=None, country=None, region=None, driver_home_terminal=None)"
},
{
"docstring": "Creates an instance of this mo... | 2 | stack_v2_sparse_classes_30k_train_023981 | Implement the Python class `Driver` described below.
Class description:
Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was recei... | Implement the Python class `Driver` described below.
Class description:
Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was recei... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class Driver:
"""Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was received at the TSP username (string): a use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Driver:
"""Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was received at the TSP username (string): a username of this... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/driver.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
2eadc1864dab6b940f5c49b3d4bdfe5844025889 | [
"super().__init__(data_source)\ndata_flow, data_forcing, data_attr = read_yxc(data_source, data_params, loader_type)\nscaler_hub = ScalerHub(data_flow, data_forcing, data_attr, data_params=data_params, loader_type=loader_type, data_source=data_source)\nself.x = scaler_hub.x\nself.y = scaler_hub.y\nself.c = scaler_h... | <|body_start_0|>
super().__init__(data_source)
data_flow, data_forcing, data_attr = read_yxc(data_source, data_params, loader_type)
scaler_hub = ScalerHub(data_flow, data_forcing, data_attr, data_params=data_params, loader_type=loader_type, data_source=data_source)
self.x = scaler_hub.x
... | Basic basin's rainfall-runoff mini-batch data model | BasinFlowDataModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasinFlowDataModel:
"""Basic basin's rainfall-runoff mini-batch data model"""
def __init__(self, data_source: DataSourceBase, data_params: dict, loader_type: str):
"""Parameters ---------- data_source object for reading source data data_params parameters for reading source data loade... | stack_v2_sparse_classes_75kplus_train_002744 | 7,520 | permissive | [
{
"docstring": "Parameters ---------- data_source object for reading source data data_params parameters for reading source data loader_type train, vaild or test",
"name": "__init__",
"signature": "def __init__(self, data_source: DataSourceBase, data_params: dict, loader_type: str)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_020020 | Implement the Python class `BasinFlowDataModel` described below.
Class description:
Basic basin's rainfall-runoff mini-batch data model
Method signatures and docstrings:
- def __init__(self, data_source: DataSourceBase, data_params: dict, loader_type: str): Parameters ---------- data_source object for reading source ... | Implement the Python class `BasinFlowDataModel` described below.
Class description:
Basic basin's rainfall-runoff mini-batch data model
Method signatures and docstrings:
- def __init__(self, data_source: DataSourceBase, data_params: dict, loader_type: str): Parameters ---------- data_source object for reading source ... | 12d5f85d9dd62dbbf8a1ae446ee2bf72f09186b4 | <|skeleton|>
class BasinFlowDataModel:
"""Basic basin's rainfall-runoff mini-batch data model"""
def __init__(self, data_source: DataSourceBase, data_params: dict, loader_type: str):
"""Parameters ---------- data_source object for reading source data data_params parameters for reading source data loade... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasinFlowDataModel:
"""Basic basin's rainfall-runoff mini-batch data model"""
def __init__(self, data_source: DataSourceBase, data_params: dict, loader_type: str):
"""Parameters ---------- data_source object for reading source data data_params parameters for reading source data loader_type train,... | the_stack_v2_python_sparse | hydrospdb/data/loader/data_loaders.py | OuyangWenyu/HydroSPDB | train | 7 |
affc1953f1afbd0ae900d7439f782abc3b7917f2 | [
"super(EB_scipy, self).__init__(*args, **kwargs)\nself.testinstall = True\nself.testcmd = \"cd .. && python -c 'import numpy; import scipy; scipy.test(verbose=2)'\"",
"super(EB_scipy, self).configure_step()\nif LooseVersion(self.version) >= LooseVersion('0.13'):\n if self.toolchain.comp_family() in [toolchain.... | <|body_start_0|>
super(EB_scipy, self).__init__(*args, **kwargs)
self.testinstall = True
self.testcmd = "cd .. && python -c 'import numpy; import scipy; scipy.test(verbose=2)'"
<|end_body_0|>
<|body_start_1|>
super(EB_scipy, self).configure_step()
if LooseVersion(self.version) >... | Support for installing the scipy Python package as part of a Python installation. | EB_scipy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EB_scipy:
"""Support for installing the scipy Python package as part of a Python installation."""
def __init__(self, *args, **kwargs):
"""Set scipy-specific test command."""
<|body_0|>
def configure_step(self):
"""Custom configure step for scipy: set extra instal... | stack_v2_sparse_classes_75kplus_train_002745 | 2,494 | no_license | [
{
"docstring": "Set scipy-specific test command.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Custom configure step for scipy: set extra installation options when needed.",
"name": "configure_step",
"signature": "def configure_step(self)"
... | 2 | null | Implement the Python class `EB_scipy` described below.
Class description:
Support for installing the scipy Python package as part of a Python installation.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set scipy-specific test command.
- def configure_step(self): Custom configure step for sc... | Implement the Python class `EB_scipy` described below.
Class description:
Support for installing the scipy Python package as part of a Python installation.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set scipy-specific test command.
- def configure_step(self): Custom configure step for sc... | 3c5434f9a4193fbe4cf8107327faadda83d798ae | <|skeleton|>
class EB_scipy:
"""Support for installing the scipy Python package as part of a Python installation."""
def __init__(self, *args, **kwargs):
"""Set scipy-specific test command."""
<|body_0|>
def configure_step(self):
"""Custom configure step for scipy: set extra instal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EB_scipy:
"""Support for installing the scipy Python package as part of a Python installation."""
def __init__(self, *args, **kwargs):
"""Set scipy-specific test command."""
super(EB_scipy, self).__init__(*args, **kwargs)
self.testinstall = True
self.testcmd = "cd .. && py... | the_stack_v2_python_sparse | 1.13.0/easyblock/easyblocks/s/scipy.py | lsuhpchelp/easybuild_smic | train | 0 |
2b9a6b561fc21129e099ba4bcbb936c040a99ae3 | [
"Task.__init__(self)\nself.task_dict = task_dict\nself.name = self.task_dict['name']\nself.type = 'Initial_Dive'\nself.drive_functions = drive_functions",
"print('[INFO]: Starting Initial Dive.')\nset_dive_depth = 3.0\noffset = 0.3\nstart_time = time.time()\nconstant_offset = time.sleep\noffsets = np.arange(0, se... | <|body_start_0|>
Task.__init__(self)
self.task_dict = task_dict
self.name = self.task_dict['name']
self.type = 'Initial_Dive'
self.drive_functions = drive_functions
<|end_body_0|>
<|body_start_1|>
print('[INFO]: Starting Initial Dive.')
set_dive_depth = 3.0
... | When the sub is diving from the surface, this task will ramp up the thrusts to make the initial dive smoother. | Initial_Dive_Task | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Initial_Dive_Task:
"""When the sub is diving from the surface, this task will ramp up the thrusts to make the initial dive smoother."""
def __init__(self, task_dict, drive_functions):
"""Initialize the Dive task given the task dictionary. Parameters: task_dict: A python dictionary co... | stack_v2_sparse_classes_75kplus_train_002746 | 1,842 | permissive | [
{
"docstring": "Initialize the Dive task given the task dictionary. Parameters: task_dict: A python dictionary containing the data about ramping to a specific dive",
"name": "__init__",
"signature": "def __init__(self, task_dict, drive_functions)"
},
{
"docstring": "Run the initial dive task by ... | 2 | stack_v2_sparse_classes_30k_train_006941 | Implement the Python class `Initial_Dive_Task` described below.
Class description:
When the sub is diving from the surface, this task will ramp up the thrusts to make the initial dive smoother.
Method signatures and docstrings:
- def __init__(self, task_dict, drive_functions): Initialize the Dive task given the task ... | Implement the Python class `Initial_Dive_Task` described below.
Class description:
When the sub is diving from the surface, this task will ramp up the thrusts to make the initial dive smoother.
Method signatures and docstrings:
- def __init__(self, task_dict, drive_functions): Initialize the Dive task given the task ... | 26b476e1c8743f422c5affea744234e6322d4f59 | <|skeleton|>
class Initial_Dive_Task:
"""When the sub is diving from the surface, this task will ramp up the thrusts to make the initial dive smoother."""
def __init__(self, task_dict, drive_functions):
"""Initialize the Dive task given the task dictionary. Parameters: task_dict: A python dictionary co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Initial_Dive_Task:
"""When the sub is diving from the surface, this task will ramp up the thrusts to make the initial dive smoother."""
def __init__(self, task_dict, drive_functions):
"""Initialize the Dive task given the task dictionary. Parameters: task_dict: A python dictionary containing the ... | the_stack_v2_python_sparse | Sub/Src/Mission/initial_dive_task.py | senseishafi/mechatronics-2019 | train | 0 |
27e2db0f96453751978fe2b1455273cfe2e8b1f6 | [
"add_input_output_information(self, input_names, output_name, output_shape)\nself.bias = np.ascontiguousarray(bias, dtype=np.double)\nself.is_minuend = is_minuend",
"offset, old_length = self.abstract_information\nelement = ffn_sub_bias_zono(man, True, element, offset, self.bias, self.is_minuend, old_length)\nadd... | <|body_start_0|>
add_input_output_information(self, input_names, output_name, output_shape)
self.bias = np.ascontiguousarray(bias, dtype=np.double)
self.is_minuend = is_minuend
<|end_body_0|>
<|body_start_1|>
offset, old_length = self.abstract_information
element = ffn_sub_bias_... | DeepzonoSub | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepzonoSub:
def __init__(self, bias, is_minuend, input_names, output_name, output_shape):
"""Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_sha... | stack_v2_sparse_classes_75kplus_train_002747 | 34,420 | permissive | [
{
"docstring": "Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_shape : iterable iterable of ints with the shape of the output of this node",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_035159 | Implement the Python class `DeepzonoSub` described below.
Class description:
Implement the DeepzonoSub class.
Method signatures and docstrings:
- def __init__(self, bias, is_minuend, input_names, output_name, output_shape): Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable... | Implement the Python class `DeepzonoSub` described below.
Class description:
Implement the DeepzonoSub class.
Method signatures and docstrings:
- def __init__(self, bias, is_minuend, input_names, output_name, output_shape): Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable... | 8771d3158b2c64a360d5bdfd4433490863257dd6 | <|skeleton|>
class DeepzonoSub:
def __init__(self, bias, is_minuend, input_names, output_name, output_shape):
"""Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_sha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeepzonoSub:
def __init__(self, bias, is_minuend, input_names, output_name, output_shape):
"""Arguments --------- bias : numpy.ndarray the values of the first addend input_names : iterable iterable with the name of the second addend output_name : str name of this node's output output_shape : iterable ... | the_stack_v2_python_sparse | tf_verify/deepzono_nodes.py | eth-sri/eran | train | 306 | |
881c55f489aba19f8be3a747b2017e60f5543df5 | [
"if not isinstance(requires_filters, dict):\n requires_filters = {}\nif not isinstance(temporal_timeouts, dict):\n temporal_timeouts = {}\nif not requires_filters and (not temporal_timeouts):\n return configs\nnew_configs = {}\nfor field, config in configs.items():\n requirement, timeout = config\n e... | <|body_start_0|>
if not isinstance(requires_filters, dict):
requires_filters = {}
if not isinstance(temporal_timeouts, dict):
temporal_timeouts = {}
if not requires_filters and (not temporal_timeouts):
return configs
new_configs = {}
for field,... | Factory service for service registration handlers | _HandlerFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _HandlerFactory:
"""Factory service for service registration handlers"""
def _prepare_configs(configs, requires_filters, temporal_timeouts):
"""Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :para... | stack_v2_sparse_classes_75kplus_train_002748 | 11,500 | permissive | [
{
"docstring": "Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component property (field → string) :param temporal_timeouts: Content of the 'temporal.timeouts' compon... | 2 | stack_v2_sparse_classes_30k_test_002629 | Implement the Python class `_HandlerFactory` described below.
Class description:
Factory service for service registration handlers
Method signatures and docstrings:
- def _prepare_configs(configs, requires_filters, temporal_timeouts): Overrides the filters specified in the decorator with the given ones :param configs... | Implement the Python class `_HandlerFactory` described below.
Class description:
Factory service for service registration handlers
Method signatures and docstrings:
- def _prepare_configs(configs, requires_filters, temporal_timeouts): Overrides the filters specified in the decorator with the given ones :param configs... | 1d0add361ca219da8fdf72bb9ba8cb0ade01ad2f | <|skeleton|>
class _HandlerFactory:
"""Factory service for service registration handlers"""
def _prepare_configs(configs, requires_filters, temporal_timeouts):
"""Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _HandlerFactory:
"""Factory service for service registration handlers"""
def _prepare_configs(configs, requires_filters, temporal_timeouts):
"""Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :param requires_fi... | the_stack_v2_python_sparse | pelix/ipopo/handlers/temporal.py | tcalmant/ipopo | train | 67 |
43dd73d0599f9af4f50a0e239c7c3fa6bb09e6c4 | [
"self._registry_client = registry_client\nself._policy_evaluator = policy_evaluator\nself._permission_calculator = PermissionCalculator(policy_evaluator)",
"logger.debug(f'Rules: {self._policy_evaluator._policy_collection.policies()}')\npermissions = self._permission_calculator.calculate_permissions(job)\nlogger.... | <|body_start_0|>
self._registry_client = registry_client
self._policy_evaluator = policy_evaluator
self._permission_calculator = PermissionCalculator(policy_evaluator)
<|end_body_0|>
<|body_start_1|>
logger.debug(f'Rules: {self._policy_evaluator._policy_collection.policies()}')
... | Plans workflow execution across sites in a DDM. | WorkflowPlanner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowPlanner:
"""Plans workflow execution across sites in a DDM."""
def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None:
"""Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEv... | stack_v2_sparse_classes_75kplus_train_002749 | 11,293 | permissive | [
{
"docstring": "Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEvaluator to use for permissions.",
"name": "__init__",
"signature": "def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_015956 | Implement the Python class `WorkflowPlanner` described below.
Class description:
Plans workflow execution across sites in a DDM.
Method signatures and docstrings:
- def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None: Create a WorkflowOrchestrator. Args: registry_client: Reg... | Implement the Python class `WorkflowPlanner` described below.
Class description:
Plans workflow execution across sites in a DDM.
Method signatures and docstrings:
- def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None: Create a WorkflowOrchestrator. Args: registry_client: Reg... | 22f9533a506e039237227ca66faea5375cce5fcb | <|skeleton|>
class WorkflowPlanner:
"""Plans workflow execution across sites in a DDM."""
def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None:
"""Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEv... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowPlanner:
"""Plans workflow execution across sites in a DDM."""
def __init__(self, registry_client: RegistryClient, policy_evaluator: PolicyEvaluator) -> None:
"""Create a WorkflowOrchestrator. Args: registry_client: RegistryClient to get sites from. policy_evaluator: PolicyEvaluator to us... | the_stack_v2_python_sparse | mahiru/components/orchestration.py | SecConNet/mahiru | train | 4 |
246b89a5aafc6af7fda19c1693742dad812bc7ac | [
"QThread.__init__(self, parent)\nself.mainwindow = mainwindow\nself.stopped = True",
"self.stopped = False\nsources = self.mainwindow.sources\nmodule = self.mainwindow.module\ndetector = self.mainwindow.detector\nraysPerSource = self.mainwindow.raysPerSource\nallRays = self.mainwindow.allRays\nif raysPerSource > ... | <|body_start_0|>
QThread.__init__(self, parent)
self.mainwindow = mainwindow
self.stopped = True
<|end_body_0|>
<|body_start_1|>
self.stopped = False
sources = self.mainwindow.sources
module = self.mainwindow.module
detector = self.mainwindow.detector
ray... | A thread class to do simulation | SimThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimThread:
"""A thread class to do simulation"""
def __init__(self, parent=None, mainwindow=None):
"""Constructor"""
<|body_0|>
def run(self):
"""Does simulation, periodically sending signals to progressbar"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_002750 | 1,657 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent=None, mainwindow=None)"
},
{
"docstring": "Does simulation, periodically sending signals to progressbar",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `SimThread` described below.
Class description:
A thread class to do simulation
Method signatures and docstrings:
- def __init__(self, parent=None, mainwindow=None): Constructor
- def run(self): Does simulation, periodically sending signals to progressbar | Implement the Python class `SimThread` described below.
Class description:
A thread class to do simulation
Method signatures and docstrings:
- def __init__(self, parent=None, mainwindow=None): Constructor
- def run(self): Does simulation, periodically sending signals to progressbar
<|skeleton|>
class SimThread:
... | 60b4a15e5e552f0504627dbc336de9538d6cc5f3 | <|skeleton|>
class SimThread:
"""A thread class to do simulation"""
def __init__(self, parent=None, mainwindow=None):
"""Constructor"""
<|body_0|>
def run(self):
"""Does simulation, periodically sending signals to progressbar"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimThread:
"""A thread class to do simulation"""
def __init__(self, parent=None, mainwindow=None):
"""Constructor"""
QThread.__init__(self, parent)
self.mainwindow = mainwindow
self.stopped = True
def run(self):
"""Does simulation, periodically sending signals... | the_stack_v2_python_sparse | src/foxsisim_gui/simthread.py | foxsi/foxsi-optics-sim | train | 1 |
ef1a7e6b11dc4e17822889c6af4b523b160e0a3f | [
"parser = None\nif re.search('^http[s]?://www\\\\.google', url):\n parser = GoogleParser\nif not parser:\n raise Exception('No parser for {}.'.format(url))\nreturn parser",
"if search_engine == 'google' or search_engine == 'googleimg':\n return GoogleParser\nelse:\n raise Exception('No such parser for... | <|body_start_0|>
parser = None
if re.search('^http[s]?://www\\.google', url):
parser = GoogleParser
if not parser:
raise Exception('No parser for {}.'.format(url))
return parser
<|end_body_0|>
<|body_start_1|>
if search_engine == 'google' or search_engine... | This class handles HTML parsing | Parsing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parsing:
"""This class handles HTML parsing"""
def get_parser_by_url(self, url):
"""Get the appropriate parser by an search engine url."""
<|body_0|>
def get_parser_by_search_engine(self, search_engine):
"""Get the appropriate parser for the search_engine"""
... | stack_v2_sparse_classes_75kplus_train_002751 | 2,061 | permissive | [
{
"docstring": "Get the appropriate parser by an search engine url.",
"name": "get_parser_by_url",
"signature": "def get_parser_by_url(self, url)"
},
{
"docstring": "Get the appropriate parser for the search_engine",
"name": "get_parser_by_search_engine",
"signature": "def get_parser_by_... | 3 | stack_v2_sparse_classes_30k_train_054473 | Implement the Python class `Parsing` described below.
Class description:
This class handles HTML parsing
Method signatures and docstrings:
- def get_parser_by_url(self, url): Get the appropriate parser by an search engine url.
- def get_parser_by_search_engine(self, search_engine): Get the appropriate parser for the ... | Implement the Python class `Parsing` described below.
Class description:
This class handles HTML parsing
Method signatures and docstrings:
- def get_parser_by_url(self, url): Get the appropriate parser by an search engine url.
- def get_parser_by_search_engine(self, search_engine): Get the appropriate parser for the ... | b003de371ebd07cd296585bc4e077cc0f2ca03d5 | <|skeleton|>
class Parsing:
"""This class handles HTML parsing"""
def get_parser_by_url(self, url):
"""Get the appropriate parser by an search engine url."""
<|body_0|>
def get_parser_by_search_engine(self, search_engine):
"""Get the appropriate parser for the search_engine"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parsing:
"""This class handles HTML parsing"""
def get_parser_by_url(self, url):
"""Get the appropriate parser by an search engine url."""
parser = None
if re.search('^http[s]?://www\\.google', url):
parser = GoogleParser
if not parser:
raise Except... | the_stack_v2_python_sparse | scrapcore/parsing.py | nickmvincent/SerpScrap | train | 2 |
71d4c1e9cbf26e07253fb71bb9586ae00bc63297 | [
"super().__init__()\nself.input_dim = input_dim\nself.output_dim = output_dim\nself.hidden_dim = hidden_dim\nself.num_layers = num_layers\nself.learning_rate = learning_rate\nself.num_epochs = num_epochs\nself.threshold = threshold\nself.seq_len = seq_len\nself.dropout = dropout\nself.linear_dim = linear_dim\nself.... | <|body_start_0|>
super().__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.learning_rate = learning_rate
self.num_epochs = num_epochs
self.threshold = threshold
self.se... | The class for an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence | EncoderFNN_AllSeq | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderFNN_AllSeq:
"""The class for an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence"""
def __init__(self, input_dim, output_dim, hidden_dim=10, num_layers=2, seq_len=4, linear_dim=100, learning_rate=0.01, dropout=0.1, threshold... | stack_v2_sparse_classes_75kplus_train_002752 | 46,816 | no_license | [
{
"docstring": "Initilize an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence Args: input_dim: int -- the size/dimensionality of the vectors that will be input for encoder output_dim: int -- the size/dimensionality of the vectors that will be input fo... | 5 | stack_v2_sparse_classes_30k_train_012284 | Implement the Python class `EncoderFNN_AllSeq` described below.
Class description:
The class for an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, hidden_dim=10, num_layers=2, s... | Implement the Python class `EncoderFNN_AllSeq` described below.
Class description:
The class for an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, hidden_dim=10, num_layers=2, s... | d7e651024b07587b46497183d90934561a4839e2 | <|skeleton|>
class EncoderFNN_AllSeq:
"""The class for an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence"""
def __init__(self, input_dim, output_dim, hidden_dim=10, num_layers=2, seq_len=4, linear_dim=100, learning_rate=0.01, dropout=0.1, threshold... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderFNN_AllSeq:
"""The class for an encoder (LSTM)-decoder(FNN) model where the input of the decoder is the output of all steps in input sequence"""
def __init__(self, input_dim, output_dim, hidden_dim=10, num_layers=2, seq_len=4, linear_dim=100, learning_rate=0.01, dropout=0.1, threshold=0.1, num_epo... | the_stack_v2_python_sparse | model/autoencoder_multitask.py | SSF-climate/SSF | train | 7 |
8714fc3a90c9d4796b8adf41fdca19bd21c0692f | [
"shape_list = x.get_shape().as_list()\nassert len(shape_list) == 3\nself.x = x\nself.layer_index = layer_index\nself.d_model = d_model\nself.d_ff = d_ff\nself.initializer = tf.random_normal_initializer(stddev=0.1)",
"input = tf.expand_dims(self.x, axis=3)\noutput_conv1 = tf.layers.conv2d(input, filters=self.d_ff,... | <|body_start_0|>
shape_list = x.get_shape().as_list()
assert len(shape_list) == 3
self.x = x
self.layer_index = layer_index
self.d_model = d_model
self.d_ff = d_ff
self.initializer = tf.random_normal_initializer(stddev=0.1)
<|end_body_0|>
<|body_start_1|>
... | position-wise feed forward networks. formula as below: FFN(x)=max(0,xW1+b1)W2+b2 | PositionWiseFeedFoward | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionWiseFeedFoward:
"""position-wise feed forward networks. formula as below: FFN(x)=max(0,xW1+b1)W2+b2"""
def __init__(self, x, layer_index, d_model=512, d_ff=2048):
""":param x: shape should be:[batch,sequence_length,d_model] :param layer_index: index of layer :return: shape:[s... | stack_v2_sparse_classes_75kplus_train_002753 | 5,281 | permissive | [
{
"docstring": ":param x: shape should be:[batch,sequence_length,d_model] :param layer_index: index of layer :return: shape:[sequence_length,d_model]",
"name": "__init__",
"signature": "def __init__(self, x, layer_index, d_model=512, d_ff=2048)"
},
{
"docstring": "positional wise fully connected... | 3 | stack_v2_sparse_classes_30k_train_040253 | Implement the Python class `PositionWiseFeedFoward` described below.
Class description:
position-wise feed forward networks. formula as below: FFN(x)=max(0,xW1+b1)W2+b2
Method signatures and docstrings:
- def __init__(self, x, layer_index, d_model=512, d_ff=2048): :param x: shape should be:[batch,sequence_length,d_mo... | Implement the Python class `PositionWiseFeedFoward` described below.
Class description:
position-wise feed forward networks. formula as below: FFN(x)=max(0,xW1+b1)W2+b2
Method signatures and docstrings:
- def __init__(self, x, layer_index, d_model=512, d_ff=2048): :param x: shape should be:[batch,sequence_length,d_mo... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class PositionWiseFeedFoward:
"""position-wise feed forward networks. formula as below: FFN(x)=max(0,xW1+b1)W2+b2"""
def __init__(self, x, layer_index, d_model=512, d_ff=2048):
""":param x: shape should be:[batch,sequence_length,d_model] :param layer_index: index of layer :return: shape:[s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionWiseFeedFoward:
"""position-wise feed forward networks. formula as below: FFN(x)=max(0,xW1+b1)W2+b2"""
def __init__(self, x, layer_index, d_model=512, d_ff=2048):
""":param x: shape should be:[batch,sequence_length,d_model] :param layer_index: index of layer :return: shape:[sequence_lengt... | the_stack_v2_python_sparse | bert_language_understanding-master/bert_language_understanding-master/model/poistion_wise_feed_forward.py | yyht/BERT | train | 37 |
67adaa152a4bc9d06eee9596aaba2936532a9819 | [
"form = GameForm()\nform.urlsafe_key = self.key.urlsafe()\nform.user_email = self.user.get().email\nform.user_name = self.user.get().displayName\nform.total_rounds = self.total_rounds\nform.remaining_rounds = self.remaining_rounds\nform.user_wins = self.user_wins\nform.cpu_wins = self.cpu_wins\nform.game_over = sel... | <|body_start_0|>
form = GameForm()
form.urlsafe_key = self.key.urlsafe()
form.user_email = self.user.get().email
form.user_name = self.user.get().displayName
form.total_rounds = self.total_rounds
form.remaining_rounds = self.remaining_rounds
form.user_wins = self.... | Game object | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Game object"""
def to_form(self):
"""Returns a GameForm representation of the Game"""
<|body_0|>
def to_gamehistory_form(self):
"""Returns a GameHistoryForm RPC message from a Game entity"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002754 | 4,239 | no_license | [
{
"docstring": "Returns a GameForm representation of the Game",
"name": "to_form",
"signature": "def to_form(self)"
},
{
"docstring": "Returns a GameHistoryForm RPC message from a Game entity",
"name": "to_gamehistory_form",
"signature": "def to_gamehistory_form(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010547 | Implement the Python class `Game` described below.
Class description:
Game object
Method signatures and docstrings:
- def to_form(self): Returns a GameForm representation of the Game
- def to_gamehistory_form(self): Returns a GameHistoryForm RPC message from a Game entity | Implement the Python class `Game` described below.
Class description:
Game object
Method signatures and docstrings:
- def to_form(self): Returns a GameForm representation of the Game
- def to_gamehistory_form(self): Returns a GameHistoryForm RPC message from a Game entity
<|skeleton|>
class Game:
"""Game object"... | 3d22a7658ecd130d25ac927290da583d2bd30b8a | <|skeleton|>
class Game:
"""Game object"""
def to_form(self):
"""Returns a GameForm representation of the Game"""
<|body_0|>
def to_gamehistory_form(self):
"""Returns a GameHistoryForm RPC message from a Game entity"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Game:
"""Game object"""
def to_form(self):
"""Returns a GameForm representation of the Game"""
form = GameForm()
form.urlsafe_key = self.key.urlsafe()
form.user_email = self.user.get().email
form.user_name = self.user.get().displayName
form.total_rounds = s... | the_stack_v2_python_sparse | Rock-Paper-Scissors/models/Game.py | Drew-Kimberly/fullstack | train | 0 |
8a43a4e312599741b714f846f7ffc4fb938c7919 | [
"if grid == None or len(grid) == 0:\n return 0\ndirections = [[-1, 0], [1, 0], [0, -1], [0, 1]]\nstack = []\nrow = len(grid)\ncol = len(grid[0])\nmaxArea = 0\n\ndef dfs(gird, i, j):\n if i < 0 or i >= row or j < 0 or (j >= col) or (grid[i][j] == 0):\n return 0\n grid[i][j] = 0\n area = 1\n for... | <|body_start_0|>
if grid == None or len(grid) == 0:
return 0
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
stack = []
row = len(grid)
col = len(grid[0])
maxArea = 0
def dfs(gird, i, j):
if i < 0 or i >= row or j < 0 or (j >= col) or (gri... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def maxAreaOfIsland_1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if grid == None or len(... | stack_v2_sparse_classes_75kplus_train_002755 | 3,296 | permissive | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "maxAreaOfIsland_1",
"signature": "def maxAreaOfIsland_1(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053894 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): :type grid: List[List[int]] :rtype: int
- def maxAreaOfIsland_1(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): :type grid: List[List[int]] :rtype: int
- def maxAreaOfIsland_1(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution... | 7870a50311e67f431fa3907c7c6a74453f0795a5 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def maxAreaOfIsland_1(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxAreaOfIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
if grid == None or len(grid) == 0:
return 0
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
stack = []
row = len(grid)
col = len(grid[0])
maxArea = 0
... | the_stack_v2_python_sparse | searchAlgorith/maxAreaOfIsland_695.py | soarflighting/LeetCode_Notes | train | 0 | |
6560be5f42789662adf5800e76e00a477d0d3eb2 | [
"ser, err, code = ifc.get()\nif err:\n return (err, code)\nreturn (ser, code)",
"data, errors = ActionSchema().load(request.get_json())\nif errors:\n return (errors, 400)\nser, err, code = ifc.create(data)\nif err:\n return (err, code)\nreturn (ser, code)"
] | <|body_start_0|>
ser, err, code = ifc.get()
if err:
return (err, code)
return (ser, code)
<|end_body_0|>
<|body_start_1|>
data, errors = ActionSchema().load(request.get_json())
if errors:
return (errors, 400)
ser, err, code = ifc.create(data)
... | Class to interface with Actions. | ActionListApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionListApi:
"""Class to interface with Actions."""
def get(self):
"""Get list of all actions."""
<|body_0|>
def post(self):
"""Post/Edit Action."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ser, err, code = ifc.get()
if err:
... | stack_v2_sparse_classes_75kplus_train_002756 | 1,715 | permissive | [
{
"docstring": "Get list of all actions.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Post/Edit Action.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016277 | Implement the Python class `ActionListApi` described below.
Class description:
Class to interface with Actions.
Method signatures and docstrings:
- def get(self): Get list of all actions.
- def post(self): Post/Edit Action. | Implement the Python class `ActionListApi` described below.
Class description:
Class to interface with Actions.
Method signatures and docstrings:
- def get(self): Get list of all actions.
- def post(self): Post/Edit Action.
<|skeleton|>
class ActionListApi:
"""Class to interface with Actions."""
def get(sel... | cb5b5d037b6fd297463633d2d3315c722851161f | <|skeleton|>
class ActionListApi:
"""Class to interface with Actions."""
def get(self):
"""Get list of all actions."""
<|body_0|>
def post(self):
"""Post/Edit Action."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActionListApi:
"""Class to interface with Actions."""
def get(self):
"""Get list of all actions."""
ser, err, code = ifc.get()
if err:
return (err, code)
return (ser, code)
def post(self):
"""Post/Edit Action."""
data, errors = ActionSchema... | the_stack_v2_python_sparse | potnanny_api/apps/action/api.py | jeffleary00/potnanny-api | train | 0 |
009a0151156e75c959cb571a24ba89abe3096d05 | [
"super(DynamicNet, self).__init__()\nself.input_linear = torch.nn.Linear(D_in, H)\nself.middle_linear = torch.nn.Linear(H, H)\nself.output_linear = torch.nn.Linear(H, D_out)",
"h_relu = self.input_linear(x).clamp(min=0)\nfor _ in range(random.randint(0, 3)):\n h_relu = self.middle_linear(h_relu).clamp(min=0)\n... | <|body_start_0|>
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.input_linear(x).clamp(min=0)
for _ in ... | DynamicNet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicNet:
def __init__(self, D_in, H, D_out):
"""在构造函数中,我们创建3个 nn.Linear 的实例,它们将被用于前向传递中。"""
<|body_0|>
def forward(self, x):
"""在模型的前向传递中, 我们随机的选择 0, 1, 2, 或 3 中的一个数字, 然后我们就重复使用middle_linear Module那么多次 作为计算隐藏层的表示。 因为每一次前向传递都会构建一个动态的计算图,我们在定义模型的前向计算过程时 可以使用普通的Pytho... | stack_v2_sparse_classes_75kplus_train_002757 | 2,718 | permissive | [
{
"docstring": "在构造函数中,我们创建3个 nn.Linear 的实例,它们将被用于前向传递中。",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "在模型的前向传递中, 我们随机的选择 0, 1, 2, 或 3 中的一个数字, 然后我们就重复使用middle_linear Module那么多次 作为计算隐藏层的表示。 因为每一次前向传递都会构建一个动态的计算图,我们在定义模型的前向计算过程时 可以使用普通的Python控制流操作比如 for... | 2 | stack_v2_sparse_classes_30k_train_028735 | Implement the Python class `DynamicNet` described below.
Class description:
Implement the DynamicNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): 在构造函数中,我们创建3个 nn.Linear 的实例,它们将被用于前向传递中。
- def forward(self, x): 在模型的前向传递中, 我们随机的选择 0, 1, 2, 或 3 中的一个数字, 然后我们就重复使用middle_linear Module那么多次... | Implement the Python class `DynamicNet` described below.
Class description:
Implement the DynamicNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): 在构造函数中,我们创建3个 nn.Linear 的实例,它们将被用于前向传递中。
- def forward(self, x): 在模型的前向传递中, 我们随机的选择 0, 1, 2, 或 3 中的一个数字, 然后我们就重复使用middle_linear Module那么多次... | 631b817d2e98f351d1173b620d15c4a5efed11da | <|skeleton|>
class DynamicNet:
def __init__(self, D_in, H, D_out):
"""在构造函数中,我们创建3个 nn.Linear 的实例,它们将被用于前向传递中。"""
<|body_0|>
def forward(self, x):
"""在模型的前向传递中, 我们随机的选择 0, 1, 2, 或 3 中的一个数字, 然后我们就重复使用middle_linear Module那么多次 作为计算隐藏层的表示。 因为每一次前向传递都会构建一个动态的计算图,我们在定义模型的前向计算过程时 可以使用普通的Pytho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DynamicNet:
def __init__(self, D_in, H, D_out):
"""在构造函数中,我们创建3个 nn.Linear 的实例,它们将被用于前向传递中。"""
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out)
... | the_stack_v2_python_sparse | beginner_source/examples_nn/dynamic_net.py | ScorpioDoctor/antares02 | train | 0 | |
4244e230ea49e02f3f2e7c3dddc1e6e6355b2e7d | [
"DirectMethod.__init__(self, hyperparams=hyperparams, verbose=verbose)\nCRMEstimator.__init__(self, hyperparams=hyperparams, verbose=verbose, contextual_modelling=contextual_modelling)\nself.name = 'StochasticDirect'\nself.hyperparams['learning_distribution'] = 'normal'\nself.distribution = get_distribution_by_para... | <|body_start_0|>
DirectMethod.__init__(self, hyperparams=hyperparams, verbose=verbose)
CRMEstimator.__init__(self, hyperparams=hyperparams, verbose=verbose, contextual_modelling=contextual_modelling)
self.name = 'StochasticDirect'
self.hyperparams['learning_distribution'] = 'normal'
... | StochasticDirect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StochasticDirect:
def __init__(self, hyperparams, verbose, contextual_modelling):
"""Initializes the class Attributes: name (str): name of the estimator hyperparams (dict): dictionnary parameters distribution (distribution): see distribution class sigma (float): noise level of the SDM"""... | stack_v2_sparse_classes_75kplus_train_002758 | 4,935 | permissive | [
{
"docstring": "Initializes the class Attributes: name (str): name of the estimator hyperparams (dict): dictionnary parameters distribution (distribution): see distribution class sigma (float): noise level of the SDM",
"name": "__init__",
"signature": "def __init__(self, hyperparams, verbose, contextual... | 5 | stack_v2_sparse_classes_30k_train_045784 | Implement the Python class `StochasticDirect` described below.
Class description:
Implement the StochasticDirect class.
Method signatures and docstrings:
- def __init__(self, hyperparams, verbose, contextual_modelling): Initializes the class Attributes: name (str): name of the estimator hyperparams (dict): dictionnar... | Implement the Python class `StochasticDirect` described below.
Class description:
Implement the StochasticDirect class.
Method signatures and docstrings:
- def __init__(self, hyperparams, verbose, contextual_modelling): Initializes the class Attributes: name (str): name of the estimator hyperparams (dict): dictionnar... | 105f10eaa1c08fb5441dc1dc8b036c7a9f42ed40 | <|skeleton|>
class StochasticDirect:
def __init__(self, hyperparams, verbose, contextual_modelling):
"""Initializes the class Attributes: name (str): name of the estimator hyperparams (dict): dictionnary parameters distribution (distribution): see distribution class sigma (float): noise level of the SDM"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StochasticDirect:
def __init__(self, hyperparams, verbose, contextual_modelling):
"""Initializes the class Attributes: name (str): name of the estimator hyperparams (dict): dictionnary parameters distribution (distribution): see distribution class sigma (float): noise level of the SDM"""
Direc... | the_stack_v2_python_sparse | src/estimator/sdm.py | tuantx7110/optimization-continuous-action-crm | train | 0 | |
c076e95d1237b440d5b9d5e6da743f4d745af976 | [
"self.serializer = serializer\nself.datacentre = datacentre\nself.is_reference_quality = is_reference_quality",
"root = etree.Element('oai_datacite', nsmap={None: 'http://schema.datacite.org/oai/oai-1.0/', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xml': 'xml'}, attrib={'{http://www.w3.org/2001/XMLSchem... | <|body_start_0|>
self.serializer = serializer
self.datacentre = datacentre
self.is_reference_quality = is_reference_quality
<|end_body_0|>
<|body_start_1|>
root = etree.Element('oai_datacite', nsmap={None: 'http://schema.datacite.org/oai/oai-1.0/', 'xsi': 'http://www.w3.org/2001/XMLSche... | OAI DataCite serializer (only for OAI-PMH). | OAIDataCiteSerializer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAIDataCiteSerializer:
"""OAI DataCite serializer (only for OAI-PMH)."""
def __init__(self, serializer=None, datacentre=None, is_reference_quality='true'):
"""Initialize serializer."""
<|body_0|>
def serialize_oaipmh(self, pid, record):
"""Serialize a single reco... | stack_v2_sparse_classes_75kplus_train_002759 | 4,630 | permissive | [
{
"docstring": "Initialize serializer.",
"name": "__init__",
"signature": "def __init__(self, serializer=None, datacentre=None, is_reference_quality='true')"
},
{
"docstring": "Serialize a single record for OAI-PMH.",
"name": "serialize_oaipmh",
"signature": "def serialize_oaipmh(self, p... | 2 | stack_v2_sparse_classes_30k_train_000418 | Implement the Python class `OAIDataCiteSerializer` described below.
Class description:
OAI DataCite serializer (only for OAI-PMH).
Method signatures and docstrings:
- def __init__(self, serializer=None, datacentre=None, is_reference_quality='true'): Initialize serializer.
- def serialize_oaipmh(self, pid, record): Se... | Implement the Python class `OAIDataCiteSerializer` described below.
Class description:
OAI DataCite serializer (only for OAI-PMH).
Method signatures and docstrings:
- def __init__(self, serializer=None, datacentre=None, is_reference_quality='true'): Initialize serializer.
- def serialize_oaipmh(self, pid, record): Se... | bcb241206c712aa37ef5179555a4027b2b0c1bda | <|skeleton|>
class OAIDataCiteSerializer:
"""OAI DataCite serializer (only for OAI-PMH)."""
def __init__(self, serializer=None, datacentre=None, is_reference_quality='true'):
"""Initialize serializer."""
<|body_0|>
def serialize_oaipmh(self, pid, record):
"""Serialize a single reco... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OAIDataCiteSerializer:
"""OAI DataCite serializer (only for OAI-PMH)."""
def __init__(self, serializer=None, datacentre=None, is_reference_quality='true'):
"""Initialize serializer."""
self.serializer = serializer
self.datacentre = datacentre
self.is_reference_quality = is... | the_stack_v2_python_sparse | invenio_records_rest/serializers/datacite.py | inveniosoftware/invenio-records-rest | train | 5 |
441a13a3359174644eab0deca73e2743880ee24e | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(CompanyForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = 'Nazwa'",
"name = self.cleaned_data['name']\nquery = Company.objects.filter(name=name, caffe=self._caffe)\nif query.exists():\n raise ValidationError(_('Naz... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(CompanyForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Nazwa'
<|end_body_0|>
<|body_start_1|>
name = self.cleaned_data['name']
query = Company.objects.filter... | Responsible for creating a Company. | CompanyForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyForm:
"""Responsible for creating a Company."""
def __init__(self, *args, **kwargs):
"""Initialize all Company's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override of... | stack_v2_sparse_classes_75kplus_train_002760 | 4,623 | permissive | [
{
"docstring": "Initialize all Company's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override of save method, to add Caffe rela... | 3 | stack_v2_sparse_classes_30k_train_014102 | Implement the Python class `CompanyForm` described below.
Class description:
Responsible for creating a Company.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Company's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method, t... | Implement the Python class `CompanyForm` described below.
Class description:
Responsible for creating a Company.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Company's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method, t... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class CompanyForm:
"""Responsible for creating a Company."""
def __init__(self, *args, **kwargs):
"""Initialize all Company's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompanyForm:
"""Responsible for creating a Company."""
def __init__(self, *args, **kwargs):
"""Initialize all Company's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(CompanyForm, self).__init__(*args, **kwargs)
self.fields... | the_stack_v2_python_sparse | caffe/cash/forms.py | VirrageS/io-kawiarnie | train | 3 |
f081faa062dde9bd33d6f2b360a71e713dc07952 | [
"try:\n id = kwargs['id']\n user = kwargs['__user']\n item = get_application_model().objects.get(Q(user=user) | Q(user=None), id=id)\n response = RESPONSE.SUCCESS\n response['payload'] = {'id': item.id, 'name': item.name, 'user': None if not item.user else item.user.username, 'client_id': item.client... | <|body_start_0|>
try:
id = kwargs['id']
user = kwargs['__user']
item = get_application_model().objects.get(Q(user=user) | Q(user=None), id=id)
response = RESPONSE.SUCCESS
response['payload'] = {'id': item.id, 'name': item.name, 'user': None if not item... | ApplicationDetailHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationDetailHandler:
def get(self, _, **kwargs):
"""@api {get} /oauth/applications/<id> Get OAuth app detail @apiName GetOAuthAppDetail @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} id Primary key of the app @apiSuccess {Number} id Primary key @apiSuc... | stack_v2_sparse_classes_75kplus_train_002761 | 42,340 | no_license | [
{
"docstring": "@api {get} /oauth/applications/<id> Get OAuth app detail @apiName GetOAuthAppDetail @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} id Primary key of the app @apiSuccess {Number} id Primary key @apiSuccess {String} name Name of the app @apiSuccess {String} user Who ... | 3 | stack_v2_sparse_classes_30k_train_042555 | Implement the Python class `ApplicationDetailHandler` described below.
Class description:
Implement the ApplicationDetailHandler class.
Method signatures and docstrings:
- def get(self, _, **kwargs): @api {get} /oauth/applications/<id> Get OAuth app detail @apiName GetOAuthAppDetail @apiGroup OAuthMgmt @apiVersion 0.... | Implement the Python class `ApplicationDetailHandler` described below.
Class description:
Implement the ApplicationDetailHandler class.
Method signatures and docstrings:
- def get(self, _, **kwargs): @api {get} /oauth/applications/<id> Get OAuth app detail @apiName GetOAuthAppDetail @apiGroup OAuthMgmt @apiVersion 0.... | 251c7dd0d8ae4756a684ec90c38392866b67d0bb | <|skeleton|>
class ApplicationDetailHandler:
def get(self, _, **kwargs):
"""@api {get} /oauth/applications/<id> Get OAuth app detail @apiName GetOAuthAppDetail @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} id Primary key of the app @apiSuccess {Number} id Primary key @apiSuc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationDetailHandler:
def get(self, _, **kwargs):
"""@api {get} /oauth/applications/<id> Get OAuth app detail @apiName GetOAuthAppDetail @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} id Primary key of the app @apiSuccess {Number} id Primary key @apiSuccess {String} ... | the_stack_v2_python_sparse | backend/user_model/views.py | zx1239856/Cloud-Scheduler-OJ | train | 0 | |
5c1476821efd0b4f67704224e071a8b05b181148 | [
"self.lextrie.insert('shinn', 'anime character')\nself.lextrie.insert('shirt', 'thin piece of clothing')\nself.gametrie = GameTrie(self.lextrie._root, 2)\nassert str(self.gametrie) == 'False {s: False {h: False {i: False {r: False {t: False {}}, n: False {n: False {}}}}}}', 'Evaluated some part of the GameTrie wron... | <|body_start_0|>
self.lextrie.insert('shinn', 'anime character')
self.lextrie.insert('shirt', 'thin piece of clothing')
self.gametrie = GameTrie(self.lextrie._root, 2)
assert str(self.gametrie) == 'False {s: False {h: False {i: False {r: False {t: False {}}, n: False {n: False {}}}}}}', ... | Test whether the correct decision is made when choosing among all winning or all losing nodes. | CustomTestCase_2WordsOtherPlayerChoosingAmongAllLosingOrAllWinning | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomTestCase_2WordsOtherPlayerChoosingAmongAllLosingOrAllWinning:
"""Test whether the correct decision is made when choosing among all winning or all losing nodes."""
def testAllLosing(self):
"""Test when choosing among all losing leads to a loss."""
<|body_0|>
def tes... | stack_v2_sparse_classes_75kplus_train_002762 | 18,572 | no_license | [
{
"docstring": "Test when choosing among all losing leads to a loss.",
"name": "testAllLosing",
"signature": "def testAllLosing(self)"
},
{
"docstring": "Test when choosing among all winning leads to a win.",
"name": "testAllWinning",
"signature": "def testAllWinning(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014898 | Implement the Python class `CustomTestCase_2WordsOtherPlayerChoosingAmongAllLosingOrAllWinning` described below.
Class description:
Test whether the correct decision is made when choosing among all winning or all losing nodes.
Method signatures and docstrings:
- def testAllLosing(self): Test when choosing among all l... | Implement the Python class `CustomTestCase_2WordsOtherPlayerChoosingAmongAllLosingOrAllWinning` described below.
Class description:
Test whether the correct decision is made when choosing among all winning or all losing nodes.
Method signatures and docstrings:
- def testAllLosing(self): Test when choosing among all l... | bf76aed9c26553df29756c4a0931da32fdca6813 | <|skeleton|>
class CustomTestCase_2WordsOtherPlayerChoosingAmongAllLosingOrAllWinning:
"""Test whether the correct decision is made when choosing among all winning or all losing nodes."""
def testAllLosing(self):
"""Test when choosing among all losing leads to a loss."""
<|body_0|>
def tes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomTestCase_2WordsOtherPlayerChoosingAmongAllLosingOrAllWinning:
"""Test whether the correct decision is made when choosing among all winning or all losing nodes."""
def testAllLosing(self):
"""Test when choosing among all losing leads to a loss."""
self.lextrie.insert('shinn', 'anime ... | the_stack_v2_python_sparse | class projects/CSC148/gametree/testgametrie_extended.py | jianghong/code-samples | train | 0 |
21d1e5a6c4c7bacbf2cf4bbc825f01b7ae49149a | [
"if 'params' not in self.context['request'].keys():\n self.fail('invalid_data')\nparams = self.context['request']['params']\nif obj['method'] in ['gaussian', 'sp'] and 'intensity' not in params:\n self.fail('invalid_data')\nif obj['method'] == 'rain' and any((param not in params for param in ['intensity', 'ke... | <|body_start_0|>
if 'params' not in self.context['request'].keys():
self.fail('invalid_data')
params = self.context['request']['params']
if obj['method'] in ['gaussian', 'sp'] and 'intensity' not in params:
self.fail('invalid_data')
if obj['method'] == 'rain' and ... | Serializer validates image processing method and required parameters | ImageProcessingSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageProcessingSerializer:
"""Serializer validates image processing method and required parameters"""
def get_params(self, obj):
"""validation of method parameters"""
<|body_0|>
def validate_method(self, value):
"""validation of image processing method"""
... | stack_v2_sparse_classes_75kplus_train_002763 | 3,334 | no_license | [
{
"docstring": "validation of method parameters",
"name": "get_params",
"signature": "def get_params(self, obj)"
},
{
"docstring": "validation of image processing method",
"name": "validate_method",
"signature": "def validate_method(self, value)"
},
{
"docstring": "changes image ... | 3 | stack_v2_sparse_classes_30k_train_051035 | Implement the Python class `ImageProcessingSerializer` described below.
Class description:
Serializer validates image processing method and required parameters
Method signatures and docstrings:
- def get_params(self, obj): validation of method parameters
- def validate_method(self, value): validation of image process... | Implement the Python class `ImageProcessingSerializer` described below.
Class description:
Serializer validates image processing method and required parameters
Method signatures and docstrings:
- def get_params(self, obj): validation of method parameters
- def validate_method(self, value): validation of image process... | 525f4ced839fe0176304c3feacd436962bcd8a0e | <|skeleton|>
class ImageProcessingSerializer:
"""Serializer validates image processing method and required parameters"""
def get_params(self, obj):
"""validation of method parameters"""
<|body_0|>
def validate_method(self, value):
"""validation of image processing method"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageProcessingSerializer:
"""Serializer validates image processing method and required parameters"""
def get_params(self, obj):
"""validation of method parameters"""
if 'params' not in self.context['request'].keys():
self.fail('invalid_data')
params = self.context['re... | the_stack_v2_python_sparse | backend/images/serializers.py | jsz5/denoising_app | train | 0 |
61b76cb111914bf25a41549bc5d479cf805cda94 | [
"self.capacity = capacity\nself.counter = 0\nself.key_time = {}\nself.key_value = {}",
"self.counter += 1\nif self.key_value.has_key(key):\n self.key_time[key] = self.counter\n return self.key_value[key]\nelse:\n return -1",
"self.key_value[key] = value\nself.counter += 1\nself.key_time[key] = self.cou... | <|body_start_0|>
self.capacity = capacity
self.counter = 0
self.key_time = {}
self.key_value = {}
<|end_body_0|>
<|body_start_1|>
self.counter += 1
if self.key_value.has_key(key):
self.key_time[key] = self.counter
return self.key_value[key]
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_002764 | 1,082 | 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_train_025227 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | c8f6ec8033486aa4b38e6f8170b6482527e30860 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.counter = 0
self.key_time = {}
self.key_value = {}
def get(self, key):
""":type key: int :rtype: int"""
self.counter += 1
if self.key_value.has_k... | the_stack_v2_python_sparse | leetcode/lru-cache.py | jasujaayush/Random | train | 0 | |
120dab200c3109aededeffda58951351287bed1e | [
"returned = super().__init__(*args, **kwargs)\nnew_fields = OrderedDict()\nfor symptom in SYMPTOM_CHOICES:\n if symptom[0] not in self.initial:\n self.initial[symptom[0]] = 0\n new_fields[symptom[0]] = forms.IntegerField(required=False, min_value=min([x[0] for x in SYMPTOM_INTENSITY_CHOICES]), max_valu... | <|body_start_0|>
returned = super().__init__(*args, **kwargs)
new_fields = OrderedDict()
for symptom in SYMPTOM_CHOICES:
if symptom[0] not in self.initial:
self.initial[symptom[0]] = 0
new_fields[symptom[0]] = forms.IntegerField(required=False, min_value=m... | SymptomReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymptomReportForm:
def __init__(self, *args, **kwargs):
"""Add fields to the form for each potential symptom. This reorders to place the symptom list first, in the order of SYMPTOM_CHOICES. The value is initialized to 0 if none is provided."""
<|body_0|>
def save(self):
... | stack_v2_sparse_classes_75kplus_train_002765 | 2,503 | permissive | [
{
"docstring": "Add fields to the form for each potential symptom. This reorders to place the symptom list first, in the order of SYMPTOM_CHOICES. The value is initialized to 0 if none is provided.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Add sa... | 2 | stack_v2_sparse_classes_30k_train_011209 | Implement the Python class `SymptomReportForm` described below.
Class description:
Implement the SymptomReportForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add fields to the form for each potential symptom. This reorders to place the symptom list first, in the order of SYMPTOM_C... | Implement the Python class `SymptomReportForm` described below.
Class description:
Implement the SymptomReportForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add fields to the form for each potential symptom. This reorders to place the symptom list first, in the order of SYMPTOM_C... | 3ee9bdefbd567299b27bb22f0bf35d64f7764b3a | <|skeleton|>
class SymptomReportForm:
def __init__(self, *args, **kwargs):
"""Add fields to the form for each potential symptom. This reorders to place the symptom list first, in the order of SYMPTOM_CHOICES. The value is initialized to 0 if none is provided."""
<|body_0|>
def save(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SymptomReportForm:
def __init__(self, *args, **kwargs):
"""Add fields to the form for each potential symptom. This reorders to place the symptom list first, in the order of SYMPTOM_CHOICES. The value is initialized to 0 if none is provided."""
returned = super().__init__(*args, **kwargs)
... | the_stack_v2_python_sparse | reports/forms.py | OpenHumans/quantified-flu | train | 18 | |
20e841202d99ae745f8555313623f54e72a9f1fc | [
"payload = cls.payload_for_create(type, value)\nbase_doc = base_document.update(virtual_documents=[payload])\nvirtual_doc = [doc for doc in base_doc.virtual_documents if doc.type == type][0]\nreturn virtual_doc",
"doc = super(VirtualDocument, cls).from_response(response)\nif response.get('status') == 'SUBMITTED|M... | <|body_start_0|>
payload = cls.payload_for_create(type, value)
base_doc = base_document.update(virtual_documents=[payload])
virtual_doc = [doc for doc in base_doc.virtual_documents if doc.type == type][0]
return virtual_doc
<|end_body_0|>
<|body_start_1|>
doc = super(VirtualDocu... | Object representation of a supporting virtual document. Virtual documents are normally ID numbers that help verify the user's identity. https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types | VirtualDocument | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualDocument:
"""Object representation of a supporting virtual document. Virtual documents are normally ID numbers that help verify the user's identity. https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types"""
def create(cls, base_document, type=None, value=None):... | stack_v2_sparse_classes_75kplus_train_002766 | 2,913 | permissive | [
{
"docstring": "Add a VirtualDocument to the BaseDocument. Args: type (str): https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types value (str): SSN or TIN, for example Returns: VirtualDocument: a new VirtualDocument instance",
"name": "create",
"signature": "def create(cls, base... | 4 | stack_v2_sparse_classes_30k_train_049139 | Implement the Python class `VirtualDocument` described below.
Class description:
Object representation of a supporting virtual document. Virtual documents are normally ID numbers that help verify the user's identity. https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types
Method signatures and ... | Implement the Python class `VirtualDocument` described below.
Class description:
Object representation of a supporting virtual document. Virtual documents are normally ID numbers that help verify the user's identity. https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types
Method signatures and ... | e7647191b386bdda84c0f2f1eb097569e36c27ae | <|skeleton|>
class VirtualDocument:
"""Object representation of a supporting virtual document. Virtual documents are normally ID numbers that help verify the user's identity. https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types"""
def create(cls, base_document, type=None, value=None):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VirtualDocument:
"""Object representation of a supporting virtual document. Virtual documents are normally ID numbers that help verify the user's identity. https://docs.synapsepay.com/docs/user-resources#section-virtual-document-types"""
def create(cls, base_document, type=None, value=None):
"""A... | the_stack_v2_python_sparse | synapse_pay_rest/models/users/virtual_document.py | SynapseFI/SynapseFI-Python | train | 4 |
652e099769f8e1bea3745242bb8a264afcda222e | [
"datetime_object = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC)\nif not timestamp:\n if raise_error:\n raise ValueError('Missing timestamp value')\n return datetime_object.isoformat()\ntry:\n datetime_object += datetime.timedelta(microseconds=timestamp)\n datetime_object = datetime_... | <|body_start_0|>
datetime_object = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC)
if not timestamp:
if raise_error:
raise ValueError('Missing timestamp value')
return datetime_object.isoformat()
try:
datetime_object += datetime.time... | Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC. | Timestamp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timestamp:
"""Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC."""
def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):... | stack_v2_sparse_classes_75kplus_train_002767 | 3,596 | permissive | [
{
"docstring": "Copies the timestamp to an ISO 8601 formatted string. Args: timestamp (int): a timestamp containing the number of microseconds since January 1, 1970, 00:00:00 UTC. timezone (Optional[pytz.timezone]): time zone. raise_error (Optional[bool]): True if an OverflowError should be raised if the timest... | 2 | stack_v2_sparse_classes_30k_train_048666 | Implement the Python class `Timestamp` described below.
Class description:
Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC.
Method signatures and docstrings:
- def Co... | Implement the Python class `Timestamp` described below.
Class description:
Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC.
Method signatures and docstrings:
- def Co... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class Timestamp:
"""Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC."""
def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Timestamp:
"""Class for converting timestamps to Plaso timestamps. The Plaso timestamp is a 64-bit signed timestamp value containing: microseconds since 1970-01-01 00:00:00. The timestamp is not necessarily in UTC."""
def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):
"""C... | the_stack_v2_python_sparse | plaso/lib/timelib.py | cyb3rfox/plaso | train | 3 |
a9d5d9a33fb66e9ba9a53ad2d5874222ffcf4239 | [
"i = 0\nj = len(nums)\nif len(nums) == 0 or len(nums) == 1:\n pass\nelse:\n while i < j:\n if nums[i] == 0:\n nums.append(nums.pop(i))\n j -= 1\n else:\n i += 1",
"if not nums:\n return nums\nanother = []\nwhile True:\n try:\n nums.remove(0)\n ... | <|body_start_0|>
i = 0
j = len(nums)
if len(nums) == 0 or len(nums) == 1:
pass
else:
while i < j:
if nums[i] == 0:
nums.append(nums.pop(i))
j -= 1
else:
i += 1
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus_train_002768 | 1,463 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, n... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modi... | dee4ac95b849e7be52ecbe38c9846028aed8a807 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
i = 0
j = len(nums)
if len(nums) == 0 or len(nums) == 1:
pass
else:
while i < j:
if nums[i] == 0:
... | the_stack_v2_python_sparse | 283_MoveZeros.py | PandaWSH/PythonPractices | train | 0 | |
5399670195a90da9244284fba0df02658a1034bc | [
"orchestrate(obj=self, config=stencil_factory.config.dace_config)\nself._no_compute = False\nif (damp_c.view[:] <= 0.0001).all():\n self._no_compute = True\nelif (damp_c.view[:-1] <= 0.0001).any():\n raise NotImplementedError('damp_c currently must be always greater than 10^-4 for delnflux')\ngrid_indexing = ... | <|body_start_0|>
orchestrate(obj=self, config=stencil_factory.config.dace_config)
self._no_compute = False
if (damp_c.view[:] <= 0.0001).all():
self._no_compute = True
elif (damp_c.view[:-1] <= 0.0001).any():
raise NotImplementedError('damp_c currently must be alw... | Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them. | DelnFlux | [
"Apache-2.0",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelnFlux:
"""Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them."""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea: pace.util.... | stack_v2_sparse_classes_75kplus_train_002769 | 45,540 | permissive | [
{
"docstring": "nord sets the order of damping to apply: nord = 0: del-2 nord = 1: del-4 nord = 2: del-6 nord and damp_c define the damping coefficient used in DelnFluxNoSG",
"name": "__init__",
"signature": "def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory... | 2 | stack_v2_sparse_classes_30k_train_027660 | Implement the Python class `DelnFlux` described below.
Class description:
Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them.
Method signatures and docstrings:
- def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityF... | Implement the Python class `DelnFlux` described below.
Class description:
Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them.
Method signatures and docstrings:
- def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityF... | c543e8ec478d46d88b48cdd3beaaa1717a95b935 | <|skeleton|>
class DelnFlux:
"""Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them."""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea: pace.util.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DelnFlux:
"""Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them."""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea: pace.util.Quantity, nor... | the_stack_v2_python_sparse | fv3core/pace/fv3core/stencils/delnflux.py | ai2cm/pace | train | 27 |
56d4948c9dedbe24f9707be0f76742caba6b6a1a | [
"self.uid = uid or str(uuid.uuid4())\nself.battlearea = battlearea\nself.target_missile_locs = target_missile_locs",
"target = None\nif len(self.target_missile_locs) > 0:\n target = self.target_missile_locs.pop(0)\nreturn target"
] | <|body_start_0|>
self.uid = uid or str(uuid.uuid4())
self.battlearea = battlearea
self.target_missile_locs = target_missile_locs
<|end_body_0|>
<|body_start_1|>
target = None
if len(self.target_missile_locs) > 0:
target = self.target_missile_locs.pop(0)
retur... | An instance of this class represents a player. | Player | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""An instance of this class represents a player."""
def __init__(self, battlearea, target_missile_locs, uid=None):
""":param battlearea: Underlying player's battlearea :param target_missile_locs: Missile targets. e.e. [A1, B2, C6, D2] :param uid Unique id of player."""
... | stack_v2_sparse_classes_75kplus_train_002770 | 808 | permissive | [
{
"docstring": ":param battlearea: Underlying player's battlearea :param target_missile_locs: Missile targets. e.e. [A1, B2, C6, D2] :param uid Unique id of player.",
"name": "__init__",
"signature": "def __init__(self, battlearea, target_missile_locs, uid=None)"
},
{
"docstring": "Get and remov... | 2 | stack_v2_sparse_classes_30k_train_036100 | Implement the Python class `Player` described below.
Class description:
An instance of this class represents a player.
Method signatures and docstrings:
- def __init__(self, battlearea, target_missile_locs, uid=None): :param battlearea: Underlying player's battlearea :param target_missile_locs: Missile targets. e.e. ... | Implement the Python class `Player` described below.
Class description:
An instance of this class represents a player.
Method signatures and docstrings:
- def __init__(self, battlearea, target_missile_locs, uid=None): :param battlearea: Underlying player's battlearea :param target_missile_locs: Missile targets. e.e. ... | 1ca9470c33236016cbb88a38b2f19db41535e457 | <|skeleton|>
class Player:
"""An instance of this class represents a player."""
def __init__(self, battlearea, target_missile_locs, uid=None):
""":param battlearea: Underlying player's battlearea :param target_missile_locs: Missile targets. e.e. [A1, B2, C6, D2] :param uid Unique id of player."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Player:
"""An instance of this class represents a player."""
def __init__(self, battlearea, target_missile_locs, uid=None):
""":param battlearea: Underlying player's battlearea :param target_missile_locs: Missile targets. e.e. [A1, B2, C6, D2] :param uid Unique id of player."""
self.uid =... | the_stack_v2_python_sparse | Misc/battleshipGame/src/entity/player/player.py | suyash248/ds_algo | train | 8 |
76a98042424e29a13375250e5198d9ec7f86de30 | [
"super(RNNAnswerer, self).__init__(name=name)\nself.units = hidden_units\nself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\nself.gru = tf.keras.layers.GRU(self.units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.fc1 = tf.keras.layers.Dense(self.units)\... | <|body_start_0|>
super(RNNAnswerer, self).__init__(name=name)
self.units = hidden_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.keras.layers.GRU(self.units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')
... | Decoder that is used for VQA. Attributes: units: number of unites the GRU has embedding: word embedding matrix gru: the GRU layer this answerer uses fc1: first fully connected layer fc2: second fully connected layer | RNNAnswerer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNAnswerer:
"""Decoder that is used for VQA. Attributes: units: number of unites the GRU has embedding: word embedding matrix gru: the GRU layer this answerer uses fc1: first fully connected layer fc2: second fully connected layer"""
def __init__(self, embedding_dim, hidden_units, vocab_siz... | stack_v2_sparse_classes_75kplus_train_002771 | 2,684 | permissive | [
{
"docstring": "Initializes the RNN answerer. Args: embedding_dim: size of the word embedding hidden_units: size of the memory state vocab_size: number of vocabulary name: optional name for the name scope",
"name": "__init__",
"signature": "def __init__(self, embedding_dim, hidden_units, vocab_size, nam... | 2 | stack_v2_sparse_classes_30k_train_053455 | Implement the Python class `RNNAnswerer` described below.
Class description:
Decoder that is used for VQA. Attributes: units: number of unites the GRU has embedding: word embedding matrix gru: the GRU layer this answerer uses fc1: first fully connected layer fc2: second fully connected layer
Method signatures and doc... | Implement the Python class `RNNAnswerer` described below.
Class description:
Decoder that is used for VQA. Attributes: units: number of unites the GRU has embedding: word embedding matrix gru: the GRU layer this answerer uses fc1: first fully connected layer fc2: second fully connected layer
Method signatures and doc... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class RNNAnswerer:
"""Decoder that is used for VQA. Attributes: units: number of unites the GRU has embedding: word embedding matrix gru: the GRU layer this answerer uses fc1: first fully connected layer fc2: second fully connected layer"""
def __init__(self, embedding_dim, hidden_units, vocab_siz... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNAnswerer:
"""Decoder that is used for VQA. Attributes: units: number of unites the GRU has embedding: word embedding matrix gru: the GRU layer this answerer uses fc1: first fully connected layer fc2: second fully connected layer"""
def __init__(self, embedding_dim, hidden_units, vocab_size, name='RNND... | the_stack_v2_python_sparse | hal/labeler/answerers.py | Jimmy-INL/google-research | train | 1 |
06909c02d086ede7a7e7697ab06c825a0d06deb3 | [
"serializer_class = self.get_serializer_class()\nkwargs['context'] = self.get_serializer_context()\nif settings.PROFILE_API_ACTION_FUNCTION:\n global SERIALIZER_TIME\n serializer_start = time.time()\n serializer = serializer_class(instance, data=data, **kwargs)\n SERIALIZER_TIME = time.time() - serializ... | <|body_start_0|>
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
if settings.PROFILE_API_ACTION_FUNCTION:
global SERIALIZER_TIME
serializer_start = time.time()
serializer = serializer_class(instance, data=data, ... | Implements a ProfilerMixin - profiles a Django Rest Framework viewset. | ProfilerMixin | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilerMixin:
"""Implements a ProfilerMixin - profiles a Django Rest Framework viewset."""
def get_serializer(self, instance=None, data=empty, **kwargs):
"""Override the get_serializer() method."""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""Over... | stack_v2_sparse_classes_75kplus_train_002772 | 2,873 | permissive | [
{
"docstring": "Override the get_serializer() method.",
"name": "get_serializer",
"signature": "def get_serializer(self, instance=None, data=empty, **kwargs)"
},
{
"docstring": "Override the viewset dispatch method.",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, *... | 2 | stack_v2_sparse_classes_30k_test_001935 | Implement the Python class `ProfilerMixin` described below.
Class description:
Implements a ProfilerMixin - profiles a Django Rest Framework viewset.
Method signatures and docstrings:
- def get_serializer(self, instance=None, data=empty, **kwargs): Override the get_serializer() method.
- def dispatch(self, request, *... | Implement the Python class `ProfilerMixin` described below.
Class description:
Implements a ProfilerMixin - profiles a Django Rest Framework viewset.
Method signatures and docstrings:
- def get_serializer(self, instance=None, data=empty, **kwargs): Override the get_serializer() method.
- def dispatch(self, request, *... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class ProfilerMixin:
"""Implements a ProfilerMixin - profiles a Django Rest Framework viewset."""
def get_serializer(self, instance=None, data=empty, **kwargs):
"""Override the get_serializer() method."""
<|body_0|>
def dispatch(self, request, *args, **kwargs):
"""Over... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfilerMixin:
"""Implements a ProfilerMixin - profiles a Django Rest Framework viewset."""
def get_serializer(self, instance=None, data=empty, **kwargs):
"""Override the get_serializer() method."""
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serial... | the_stack_v2_python_sparse | onadata/libs/mixins/profiler_mixin.py | onaio/onadata | train | 177 |
c89969d2dc917bef875f0ea8d6aacb561278d585 | [
"self._msw = magicseaweed.MSW_Forecast(api_key, spot_id, None, units)\nself.currently = None\nself.hourly = {}\nself.update = Throttle(MIN_TIME_BETWEEN_UPDATES)(self._update)",
"try:\n forecasts = self._msw.get_future()\n self.currently = forecasts.data[0]\n for forecast in forecasts.data[:8]:\n h... | <|body_start_0|>
self._msw = magicseaweed.MSW_Forecast(api_key, spot_id, None, units)
self.currently = None
self.hourly = {}
self.update = Throttle(MIN_TIME_BETWEEN_UPDATES)(self._update)
<|end_body_0|>
<|body_start_1|>
try:
forecasts = self._msw.get_future()
... | Get the latest data from MagicSeaweed. | MagicSeaweedData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicSeaweedData:
"""Get the latest data from MagicSeaweed."""
def __init__(self, api_key, spot_id, units):
"""Initialize the data object."""
<|body_0|>
def _update(self):
"""Get the latest data from MagicSeaweed."""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_002773 | 6,249 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, api_key, spot_id, units)"
},
{
"docstring": "Get the latest data from MagicSeaweed.",
"name": "_update",
"signature": "def _update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003398 | Implement the Python class `MagicSeaweedData` described below.
Class description:
Get the latest data from MagicSeaweed.
Method signatures and docstrings:
- def __init__(self, api_key, spot_id, units): Initialize the data object.
- def _update(self): Get the latest data from MagicSeaweed. | Implement the Python class `MagicSeaweedData` described below.
Class description:
Get the latest data from MagicSeaweed.
Method signatures and docstrings:
- def __init__(self, api_key, spot_id, units): Initialize the data object.
- def _update(self): Get the latest data from MagicSeaweed.
<|skeleton|>
class MagicSea... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class MagicSeaweedData:
"""Get the latest data from MagicSeaweed."""
def __init__(self, api_key, spot_id, units):
"""Initialize the data object."""
<|body_0|>
def _update(self):
"""Get the latest data from MagicSeaweed."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MagicSeaweedData:
"""Get the latest data from MagicSeaweed."""
def __init__(self, api_key, spot_id, units):
"""Initialize the data object."""
self._msw = magicseaweed.MSW_Forecast(api_key, spot_id, None, units)
self.currently = None
self.hourly = {}
self.update = T... | the_stack_v2_python_sparse | homeassistant/components/magicseaweed/sensor.py | BenWoodford/home-assistant | train | 11 |
0cb010fec95294db88560c917b9bb2ec7568225b | [
"form.instance.noodle = Noodle.objects.get(pk=self.kwargs['id'])\nform.instance.type = 'ND'\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['name'] = Noodle.objects.get(pk=self.kwargs['id']).name\nreturn context"
] | <|body_start_0|>
form.instance.noodle = Noodle.objects.get(pk=self.kwargs['id'])
form.instance.type = 'ND'
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['name'] = Noodle.objects.get(pk=self.kwargs['id']).name... | Class based view for reporting noodles | NoodleReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoodleReportForm:
"""Class based view for reporting noodles"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_002774 | 10,733 | permissive | [
{
"docstring": "Ensures hidden form values are filled",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Passes item name to template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015747 | Implement the Python class `NoodleReportForm` described below.
Class description:
Class based view for reporting noodles
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template | Implement the Python class `NoodleReportForm` described below.
Class description:
Class based view for reporting noodles
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template
<|skeleton|>
class Noodle... | 6bf8e75a1f279ac584daa4ee19927ffccaa67551 | <|skeleton|>
class NoodleReportForm:
"""Class based view for reporting noodles"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoodleReportForm:
"""Class based view for reporting noodles"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
form.instance.noodle = Noodle.objects.get(pk=self.kwargs['id'])
form.instance.type = 'ND'
return super().form_valid(form)
def get_con... | the_stack_v2_python_sparse | rameniaapp/views/report.py | awlane/ramenia | train | 0 |
d19f9d8532fe858ea869db7a4d0e892fa7eaae33 | [
"res = super(inherits_sale, self)._prepare_invoice(cr, uid, order, lines, context)\nres.update({'payment_terms_id': order.payment_terms_id and order.payment_terms_id.id})\nreturn res",
"res = super(inherits_sale, self).onchange_partner_id(cr, uid, ids, part, context)\npart = self.pool.get('res.partner').browse(cr... | <|body_start_0|>
res = super(inherits_sale, self)._prepare_invoice(cr, uid, order, lines, context)
res.update({'payment_terms_id': order.payment_terms_id and order.payment_terms_id.id})
return res
<|end_body_0|>
<|body_start_1|>
res = super(inherits_sale, self).onchange_partner_id(cr, u... | Inherit sale order to add a new field, Payment Terms | inherits_sale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class inherits_sale:
"""Inherit sale order to add a new field, Payment Terms"""
def _prepare_invoice(self, cr, uid, order, lines, context=None):
"""Overwrite this method to send the payment term new to invoice"""
<|body_0|>
def onchange_partner_id(self, cr, uid, ids, part, con... | stack_v2_sparse_classes_75kplus_train_002775 | 3,503 | no_license | [
{
"docstring": "Overwrite this method to send the payment term new to invoice",
"name": "_prepare_invoice",
"signature": "def _prepare_invoice(self, cr, uid, order, lines, context=None)"
},
{
"docstring": "Overwrite this method to set payment term new to sale order",
"name": "onchange_partne... | 3 | null | Implement the Python class `inherits_sale` described below.
Class description:
Inherit sale order to add a new field, Payment Terms
Method signatures and docstrings:
- def _prepare_invoice(self, cr, uid, order, lines, context=None): Overwrite this method to send the payment term new to invoice
- def onchange_partner_... | Implement the Python class `inherits_sale` described below.
Class description:
Inherit sale order to add a new field, Payment Terms
Method signatures and docstrings:
- def _prepare_invoice(self, cr, uid, order, lines, context=None): Overwrite this method to send the payment term new to invoice
- def onchange_partner_... | c9b20ef5ec8f79489a29a27acd04a19f7e33019c | <|skeleton|>
class inherits_sale:
"""Inherit sale order to add a new field, Payment Terms"""
def _prepare_invoice(self, cr, uid, order, lines, context=None):
"""Overwrite this method to send the payment term new to invoice"""
<|body_0|>
def onchange_partner_id(self, cr, uid, ids, part, con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class inherits_sale:
"""Inherit sale order to add a new field, Payment Terms"""
def _prepare_invoice(self, cr, uid, order, lines, context=None):
"""Overwrite this method to send the payment term new to invoice"""
res = super(inherits_sale, self)._prepare_invoice(cr, uid, order, lines, context)
... | the_stack_v2_python_sparse | payment_terms/model/sale.py | jboyleca/addons-vauxoo | train | 1 |
39169200e8d9c68df372639aea8b5e6bea969551 | [
"inorder_traversal = []\nsmall_node = None\nlarge_node = None\n\ndef dfs(node):\n if node:\n dfs(node.left)\n inorder_traversal.append(node)\n dfs(node.right)\ndfs(root)\nfor i in range(len(inorder_traversal) - 1):\n if inorder_traversal[i + 1].val < inorder_traversal[i].val:\n sma... | <|body_start_0|>
inorder_traversal = []
small_node = None
large_node = None
def dfs(node):
if node:
dfs(node.left)
inorder_traversal.append(node)
dfs(node.right)
dfs(root)
for i in range(len(inorder_traversal) -... | - dfs + Sort an Almost Sorted Array Where Two Elements Are Swapped - O(n), O(n) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""- dfs + Sort an Almost Sorted Array Where Two Elements Are Swapped - O(n), O(n)"""
def recoverTree(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree(self, root: TreeNode) -> None:
""... | stack_v2_sparse_classes_75kplus_train_002776 | 5,020 | no_license | [
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "recoverTree",
"signature": "def recoverTree(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "recoverTree",
"signature": "def recoverTree(self... | 4 | stack_v2_sparse_classes_30k_train_043768 | Implement the Python class `Solution` described below.
Class description:
- dfs + Sort an Almost Sorted Array Where Two Elements Are Swapped - O(n), O(n)
Method signatures and docstrings:
- def recoverTree(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def recoverTree(self, roo... | Implement the Python class `Solution` described below.
Class description:
- dfs + Sort an Almost Sorted Array Where Two Elements Are Swapped - O(n), O(n)
Method signatures and docstrings:
- def recoverTree(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def recoverTree(self, roo... | 085d868ba0458fc8e6b5549aa00fa151c335fa7f | <|skeleton|>
class Solution:
"""- dfs + Sort an Almost Sorted Array Where Two Elements Are Swapped - O(n), O(n)"""
def recoverTree(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree(self, root: TreeNode) -> None:
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""- dfs + Sort an Almost Sorted Array Where Two Elements Are Swapped - O(n), O(n)"""
def recoverTree(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
inorder_traversal = []
small_node = None
large_node = None
de... | the_stack_v2_python_sparse | 099-Recover_Binary_Search_Tree.py | chanyoonzhu/leetcode-python | train | 0 |
2155d160a19ea80a6e73257ac6e97261660ebe67 | [
"QWidget.__init__(self)\nself.setGeometry(QRect(400, 200, 700, 600))\nlayout = QtWidgets.QGridLayout(self)\nself.table = QtWidgets.QTableWidget()\nself.table.setColumnCount(2)\nself.table.horizontalHeader().setStretchLastSection(True)\nself.table.verticalHeader().setStretchLastSection(False)\nlayout.addWidget(self.... | <|body_start_0|>
QWidget.__init__(self)
self.setGeometry(QRect(400, 200, 700, 600))
layout = QtWidgets.QGridLayout(self)
self.table = QtWidgets.QTableWidget()
self.table.setColumnCount(2)
self.table.horizontalHeader().setStretchLastSection(True)
self.table.vertica... | Popup window with the list of shorcuts. | ShortcutPopup | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShortcutPopup:
"""Popup window with the list of shorcuts."""
def __init__(self):
"""Init."""
<|body_0|>
def set_shortcuts(self, shdic):
"""Fill table."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
QWidget.__init__(self)
self.setGeometr... | stack_v2_sparse_classes_75kplus_train_002777 | 5,904 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fill table.",
"name": "set_shortcuts",
"signature": "def set_shortcuts(self, shdic)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000598 | Implement the Python class `ShortcutPopup` described below.
Class description:
Popup window with the list of shorcuts.
Method signatures and docstrings:
- def __init__(self): Init.
- def set_shortcuts(self, shdic): Fill table. | Implement the Python class `ShortcutPopup` described below.
Class description:
Popup window with the list of shorcuts.
Method signatures and docstrings:
- def __init__(self): Init.
- def set_shortcuts(self, shdic): Fill table.
<|skeleton|>
class ShortcutPopup:
"""Popup window with the list of shorcuts."""
d... | be096aa8a7058c329e7120d0bdb45d3c9eb8be42 | <|skeleton|>
class ShortcutPopup:
"""Popup window with the list of shorcuts."""
def __init__(self):
"""Init."""
<|body_0|>
def set_shortcuts(self, shdic):
"""Fill table."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShortcutPopup:
"""Popup window with the list of shorcuts."""
def __init__(self):
"""Init."""
QWidget.__init__(self)
self.setGeometry(QRect(400, 200, 700, 600))
layout = QtWidgets.QGridLayout(self)
self.table = QtWidgets.QTableWidget()
self.table.setColumnCo... | the_stack_v2_python_sparse | visbrain/utils/gui/popup.py | lassemadsen/visbrain | train | 0 |
2d38b33e2636bc1ec99784cc23de2ea956052afb | [
"for rec in self:\n if rec.date_from and rec.date_to:\n f_date = datetime.strptime(rec.date_from, OE_DATEFORMAT)\n e_date = datetime.strptime(rec.date_to, OE_DATEFORMAT)\n delta = e_date - f_date\n rec.number_of_days = delta.days + 1",
"worked_day_lines = []\nfor contract in contracts.filte... | <|body_start_0|>
for rec in self:
if rec.date_from and rec.date_to:
f_date = datetime.strptime(rec.date_from, OE_DATEFORMAT)
e_date = datetime.strptime(rec.date_to, OE_DATEFORMAT)
delta = e_date - f_date
rec.number_of_days = delta.days + 1
<|en... | HRPayslip | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HRPayslip:
def compute_number_of_days(self):
""":return:"""
<|body_0|>
def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to):
""":param contracts: :param date_from: :param date_to: :return:"""
<|body_1|>
def get_worked_day_lines(s... | stack_v2_sparse_classes_75kplus_train_002778 | 3,163 | no_license | [
{
"docstring": ":return:",
"name": "compute_number_of_days",
"signature": "def compute_number_of_days(self)"
},
{
"docstring": ":param contracts: :param date_from: :param date_to: :return:",
"name": "get_worked_day_lines_from_timesheets",
"signature": "def get_worked_day_lines_from_times... | 3 | stack_v2_sparse_classes_30k_train_018879 | Implement the Python class `HRPayslip` described below.
Class description:
Implement the HRPayslip class.
Method signatures and docstrings:
- def compute_number_of_days(self): :return:
- def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to): :param contracts: :param date_from: :param date_to: ... | Implement the Python class `HRPayslip` described below.
Class description:
Implement the HRPayslip class.
Method signatures and docstrings:
- def compute_number_of_days(self): :return:
- def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to): :param contracts: :param date_from: :param date_to: ... | 437cf88c26a23b54efeed903233be6ee5d9a16aa | <|skeleton|>
class HRPayslip:
def compute_number_of_days(self):
""":return:"""
<|body_0|>
def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to):
""":param contracts: :param date_from: :param date_to: :return:"""
<|body_1|>
def get_worked_day_lines(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HRPayslip:
def compute_number_of_days(self):
""":return:"""
for rec in self:
if rec.date_from and rec.date_to:
f_date = datetime.strptime(rec.date_from, OE_DATEFORMAT)
e_date = datetime.strptime(rec.date_to, OE_DATEFORMAT)
delta = e_date ... | the_stack_v2_python_sparse | sapcle_dxb/custom-addons/hr_timesheet_ess/models/hr_payslip.py | ketulpatel35/sapcle | train | 0 | |
5d1aadb7c69aab49f4a3ba6a4c20d9919aaa38fb | [
"style = wx.CB_READONLY | wx.CB_DROPDOWN\niqBitmapComboBox.__init__(self, parent, id=wx.NewId(), size=DEFAULT_COMBO_SIZE, style=style)\nif compare_funcs:\n self.appendItems(compare_funcs)",
"selection = self.getCurrentSelection()\nif selection >= 0:\n return self.items[selection]\nreturn None"
] | <|body_start_0|>
style = wx.CB_READONLY | wx.CB_DROPDOWN
iqBitmapComboBox.__init__(self, parent, id=wx.NewId(), size=DEFAULT_COMBO_SIZE, style=style)
if compare_funcs:
self.appendItems(compare_funcs)
<|end_body_0|>
<|body_start_1|>
selection = self.getCurrentSelection()
... | Select requisite comparison function combobox class. | iqFuncComboBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqFuncComboBox:
"""Select requisite comparison function combobox class."""
def __init__(self, parent, compare_funcs=None):
"""Constructor."""
<|body_0|>
def getSelectedFunc(self):
"""Get selected function data."""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_002779 | 19,825 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, parent, compare_funcs=None)"
},
{
"docstring": "Get selected function data.",
"name": "getSelectedFunc",
"signature": "def getSelectedFunc(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049851 | Implement the Python class `iqFuncComboBox` described below.
Class description:
Select requisite comparison function combobox class.
Method signatures and docstrings:
- def __init__(self, parent, compare_funcs=None): Constructor.
- def getSelectedFunc(self): Get selected function data. | Implement the Python class `iqFuncComboBox` described below.
Class description:
Select requisite comparison function combobox class.
Method signatures and docstrings:
- def __init__(self, parent, compare_funcs=None): Constructor.
- def getSelectedFunc(self): Get selected function data.
<|skeleton|>
class iqFuncCombo... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqFuncComboBox:
"""Select requisite comparison function combobox class."""
def __init__(self, parent, compare_funcs=None):
"""Constructor."""
<|body_0|>
def getSelectedFunc(self):
"""Get selected function data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class iqFuncComboBox:
"""Select requisite comparison function combobox class."""
def __init__(self, parent, compare_funcs=None):
"""Constructor."""
style = wx.CB_READONLY | wx.CB_DROPDOWN
iqBitmapComboBox.__init__(self, parent, id=wx.NewId(), size=DEFAULT_COMBO_SIZE, style=style)
... | the_stack_v2_python_sparse | iq/components/wx_filterchoicectrl/filter_builder_ctrl.py | XHermitOne/iq_framework | train | 1 |
b16d58859e7e659a1fefdc1883cff38ca916b48b | [
"template = loader.get_template('main/ccnmtl/course_dash/student_activation_notice.txt')\nsubject = 'Welcome to Brownfield!'\nctx = {'student': student, 'team': student.profile.team, 'site': Site.objects.get_current()}\nmessage = template.render(ctx)\n'who is the sender?'\nsender = settings.SERVER_EMAIL\nsend_mail(... | <|body_start_0|>
template = loader.get_template('main/ccnmtl/course_dash/student_activation_notice.txt')
subject = 'Welcome to Brownfield!'
ctx = {'student': student, 'team': student.profile.team, 'site': Site.objects.get_current()}
message = template.render(ctx)
'who is the send... | ActivateCourseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivateCourseView:
def send_student_email(self, student):
"""Should instructors be sent emails saying their class is activated?"""
<|body_0|>
def post(self, request, pk):
"""This is really really ugly as is get method need to clean up."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_002780 | 28,063 | no_license | [
{
"docstring": "Should instructors be sent emails saying their class is activated?",
"name": "send_student_email",
"signature": "def send_student_email(self, student)"
},
{
"docstring": "This is really really ugly as is get method need to clean up.",
"name": "post",
"signature": "def pos... | 2 | null | Implement the Python class `ActivateCourseView` described below.
Class description:
Implement the ActivateCourseView class.
Method signatures and docstrings:
- def send_student_email(self, student): Should instructors be sent emails saying their class is activated?
- def post(self, request, pk): This is really really... | Implement the Python class `ActivateCourseView` described below.
Class description:
Implement the ActivateCourseView class.
Method signatures and docstrings:
- def send_student_email(self, student): Should instructors be sent emails saying their class is activated?
- def post(self, request, pk): This is really really... | 65ccdafff8b6ba17913c2f06853328a469f32acd | <|skeleton|>
class ActivateCourseView:
def send_student_email(self, student):
"""Should instructors be sent emails saying their class is activated?"""
<|body_0|>
def post(self, request, pk):
"""This is really really ugly as is get method need to clean up."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivateCourseView:
def send_student_email(self, student):
"""Should instructors be sent emails saying their class is activated?"""
template = loader.get_template('main/ccnmtl/course_dash/student_activation_notice.txt')
subject = 'Welcome to Brownfield!'
ctx = {'student': stude... | the_stack_v2_python_sparse | brownfield_django/main/views.py | ccnmtl/brownfield_django | train | 4 | |
33cb531d016b53d9e66de77beab3280ef808fe8e | [
"authenticated = request.user.is_authenticated()\nif action == Limiter.PASTE_UPLOAD and settings.MAX_PASTE_UPLOADS_PER_USER == -1 and (settings.MAX_PASTE_UPLOADS_PER_GUEST == -1):\n return 0\nelif action == Limiter.PASTE_EDIT and settings.MAX_PASTE_EDITS_PER_USER == -1:\n return 0\nelif action == Limiter.COMM... | <|body_start_0|>
authenticated = request.user.is_authenticated()
if action == Limiter.PASTE_UPLOAD and settings.MAX_PASTE_UPLOADS_PER_USER == -1 and (settings.MAX_PASTE_UPLOADS_PER_GUEST == -1):
return 0
elif action == Limiter.PASTE_EDIT and settings.MAX_PASTE_EDITS_PER_USER == -1:
... | Throttles the amount of actions an user can do | Limiter | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Limiter:
"""Throttles the amount of actions an user can do"""
def get_action_count(request, action):
"""Get the raw count of actions a certain IP address has done"""
<|body_0|>
def increase_action_count(request, action, amount=1):
"""Increase the amount of action... | stack_v2_sparse_classes_75kplus_train_002781 | 6,890 | permissive | [
{
"docstring": "Get the raw count of actions a certain IP address has done",
"name": "get_action_count",
"signature": "def get_action_count(request, action)"
},
{
"docstring": "Increase the amount of actions by a certain amount (default=1)",
"name": "increase_action_count",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_008123 | Implement the Python class `Limiter` described below.
Class description:
Throttles the amount of actions an user can do
Method signatures and docstrings:
- def get_action_count(request, action): Get the raw count of actions a certain IP address has done
- def increase_action_count(request, action, amount=1): Increase... | Implement the Python class `Limiter` described below.
Class description:
Throttles the amount of actions an user can do
Method signatures and docstrings:
- def get_action_count(request, action): Get the raw count of actions a certain IP address has done
- def increase_action_count(request, action, amount=1): Increase... | 5e38637e5a417ab907a353af8544f64a0ad2b127 | <|skeleton|>
class Limiter:
"""Throttles the amount of actions an user can do"""
def get_action_count(request, action):
"""Get the raw count of actions a certain IP address has done"""
<|body_0|>
def increase_action_count(request, action, amount=1):
"""Increase the amount of action... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Limiter:
"""Throttles the amount of actions an user can do"""
def get_action_count(request, action):
"""Get the raw count of actions a certain IP address has done"""
authenticated = request.user.is_authenticated()
if action == Limiter.PASTE_UPLOAD and settings.MAX_PASTE_UPLOADS_PE... | the_stack_v2_python_sparse | users/models.py | xeddmc/pastebin-django | train | 0 |
28ed4e79d2e6b0f8ef00647e529db4e312dfea9f | [
"try:\n tinify.key = apiKey\n return tinify.validate()\nexcept tinify.Error as e:\n LogUtil.e('TinifyUtil Validation of API key failed. 错误信息:', e)\n return False",
"try:\n tinify.key = apiKey\n source = tinify.from_file(sourceFp)\n if preserves:\n source = source.preserve(preserves)\n ... | <|body_start_0|>
try:
tinify.key = apiKey
return tinify.validate()
except tinify.Error as e:
LogUtil.e('TinifyUtil Validation of API key failed. 错误信息:', e)
return False
<|end_body_0|>
<|body_start_1|>
try:
tinify.key = apiKey
... | TinifyUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TinifyUtil:
def validate(apiKey: str):
"""验证用户的api key是否有效 :param apiKey: 用户的api key :return: True 有效用户"""
<|body_0|>
def compressing(apiKey: str, sourceFp: str, toFp: str, preserves: []=None, resizeParams: {}=None):
"""获取指定账户当前剩余使用数量 :param apiKey: 用户的api key :param... | stack_v2_sparse_classes_75kplus_train_002782 | 4,887 | permissive | [
{
"docstring": "验证用户的api key是否有效 :param apiKey: 用户的api key :return: True 有效用户",
"name": "validate",
"signature": "def validate(apiKey: str)"
},
{
"docstring": "获取指定账户当前剩余使用数量 :param apiKey: 用户的api key :param sourceFp: 原文件 :param toFp: 压缩后文件 :param preserves: 需要保留的metadata 取值[\"copyright\", \"cre... | 2 | stack_v2_sparse_classes_30k_train_012305 | Implement the Python class `TinifyUtil` described below.
Class description:
Implement the TinifyUtil class.
Method signatures and docstrings:
- def validate(apiKey: str): 验证用户的api key是否有效 :param apiKey: 用户的api key :return: True 有效用户
- def compressing(apiKey: str, sourceFp: str, toFp: str, preserves: []=None, resizePa... | Implement the Python class `TinifyUtil` described below.
Class description:
Implement the TinifyUtil class.
Method signatures and docstrings:
- def validate(apiKey: str): 验证用户的api key是否有效 :param apiKey: 用户的api key :return: True 有效用户
- def compressing(apiKey: str, sourceFp: str, toFp: str, preserves: []=None, resizePa... | 24cca5e9aaa56392200da48a1692201e2dfa25c8 | <|skeleton|>
class TinifyUtil:
def validate(apiKey: str):
"""验证用户的api key是否有效 :param apiKey: 用户的api key :return: True 有效用户"""
<|body_0|>
def compressing(apiKey: str, sourceFp: str, toFp: str, preserves: []=None, resizeParams: {}=None):
"""获取指定账户当前剩余使用数量 :param apiKey: 用户的api key :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TinifyUtil:
def validate(apiKey: str):
"""验证用户的api key是否有效 :param apiKey: 用户的api key :return: True 有效用户"""
try:
tinify.key = apiKey
return tinify.validate()
except tinify.Error as e:
LogUtil.e('TinifyUtil Validation of API key failed. 错误信息:', e)
... | the_stack_v2_python_sparse | util/TinifyUtil.py | lkl22/CommonTools | train | 2 | |
9c9b465ab1ff35fff59f09b577b56a5355fbb789 | [
"res = []\nn, m = (len(s), len(p))\nif n < m:\n return res\np_char_count, s_char_count = ([0] * 128, [0] * 128)\nfor x in p:\n p_char_count[ord(x)] += 1\nfor x in s[:m - 1]:\n s_char_count[ord(x)] += 1\nfor i in range(m - 1, n):\n s_char_count[ord(s[i])] += 1\n if i - m >= 0:\n s_char_count[or... | <|body_start_0|>
res = []
n, m = (len(s), len(p))
if n < m:
return res
p_char_count, s_char_count = ([0] * 128, [0] * 128)
for x in p:
p_char_count[ord(x)] += 1
for x in s[:m - 1]:
s_char_count[ord(x)] += 1
for i in range(m - 1,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams_old(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
n,... | stack_v2_sparse_classes_75kplus_train_002783 | 3,116 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams_old",
"signature": "def findAnagrams_old(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008687 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams_old(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams_old(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton|>
class Solu... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams_old(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
res = []
n, m = (len(s), len(p))
if n < m:
return res
p_char_count, s_char_count = ([0] * 128, [0] * 128)
for x in p:
p_char_count[ord(x)] += 1
... | the_stack_v2_python_sparse | Problems/0400_0499/0438_Find_All_Anagrams_in_a_String/Project_Python3/Find_All_Anagrams_in_a_String.py | NobuyukiInoue/LeetCode | train | 0 | |
d398ada4db8572f893f17ff9ef33147998361b6a | [
"tamplate = '%s/{}' % cls.my_site\npram = (('q', query),)\nr = requests.get(cls.search_api, params=pram, **kwargs).json()\nif r:\n return [Utils.pickup_class(link=tamplate.format(movie['u']), title=movie['t']) for elem in r for movie in r[elem]]\nreturn None",
"material = material.lower()\nif material not in c... | <|body_start_0|>
tamplate = '%s/{}' % cls.my_site
pram = (('q', query),)
r = requests.get(cls.search_api, params=pram, **kwargs).json()
if r:
return [Utils.pickup_class(link=tamplate.format(movie['u']), title=movie['t']) for elem in r for movie in r[elem]]
return None... | a class that hold site functionality : search, login ... | Site | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Site:
"""a class that hold site functionality : search, login ..."""
def search(cls, query: str, access=True, **kwargs) -> list or None:
"""a class to search inside the site : movies, series ... return instance of class's that blong the the type of result"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_002784 | 2,591 | no_license | [
{
"docstring": "a class to search inside the site : movies, series ... return instance of class's that blong the the type of result",
"name": "search",
"signature": "def search(cls, query: str, access=True, **kwargs) -> list or None"
},
{
"docstring": "filter movies based on options options supp... | 2 | stack_v2_sparse_classes_30k_train_015446 | Implement the Python class `Site` described below.
Class description:
a class that hold site functionality : search, login ...
Method signatures and docstrings:
- def search(cls, query: str, access=True, **kwargs) -> list or None: a class to search inside the site : movies, series ... return instance of class's that ... | Implement the Python class `Site` described below.
Class description:
a class that hold site functionality : search, login ...
Method signatures and docstrings:
- def search(cls, query: str, access=True, **kwargs) -> list or None: a class to search inside the site : movies, series ... return instance of class's that ... | 9527ef626a4f4966b3069cf1df0927cad81a274f | <|skeleton|>
class Site:
"""a class that hold site functionality : search, login ..."""
def search(cls, query: str, access=True, **kwargs) -> list or None:
"""a class to search inside the site : movies, series ... return instance of class's that blong the the type of result"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Site:
"""a class that hold site functionality : search, login ..."""
def search(cls, query: str, access=True, **kwargs) -> list or None:
"""a class to search inside the site : movies, series ... return instance of class's that blong the the type of result"""
tamplate = '%s/{}' % cls.my_si... | the_stack_v2_python_sparse | egy_best/site.py | xgrons/egy_best | train | 0 |
d0886dea4a083db79b295d4d67930d37342e563d | [
"if not root:\n return ''\nstack = [root]\nres = []\nwhile stack:\n node = stack.pop()\n if node:\n res.append(str(node.val))\n stack.append(node.left)\n stack.append(node.right)\n else:\n res.append('null')\nreturn ','.join(res)",
"if not data:\n return None\nvals = dat... | <|body_start_0|>
if not root:
return ''
stack = [root]
res = []
while stack:
node = stack.pop()
if node:
res.append(str(node.val))
stack.append(node.left)
stack.append(node.right)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_002785 | 3,621 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_043062 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
stack = [root]
res = []
while stack:
node = stack.pop()
if node:
res.append(str(node.va... | the_stack_v2_python_sparse | LC297.py | Qiao-Liang/LeetCode | train | 0 | |
9ca0e6bedc1a59ab127e33fbe8a19f5908cf9817 | [
"self.nlevels = nlevels\nself.hitcount = [0] * nlevels\nself.accessCount = [0] * nlevels\nself.evictCount = [0] * nlevels\nself.prefEvictCount = [0] * nlevels\nself.hit_rate = [0] * nlevels\nself.miss_rate = [0] * nlevels\nself.evict_rate = [0] * nlevels\nself.total_hits = 0\nself.total_misses = 0\nself.total_cycle... | <|body_start_0|>
self.nlevels = nlevels
self.hitcount = [0] * nlevels
self.accessCount = [0] * nlevels
self.evictCount = [0] * nlevels
self.prefEvictCount = [0] * nlevels
self.hit_rate = [0] * nlevels
self.miss_rate = [0] * nlevels
self.evict_rate = [0] * ... | An object for collecting stats about a simulation run. Usage: (1) Initialize your Stats object and specify the number of cache levels you have. e.g. stats = Stats(3) (2) Fill it with data as you see fit. | Stats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stats:
"""An object for collecting stats about a simulation run. Usage: (1) Initialize your Stats object and specify the number of cache levels you have. e.g. stats = Stats(3) (2) Fill it with data as you see fit."""
def __init__(self, nlevels):
"""Parameters ---------- nlevels: The ... | stack_v2_sparse_classes_75kplus_train_002786 | 16,468 | permissive | [
{
"docstring": "Parameters ---------- nlevels: The number of cache levels you are collecting stats for.",
"name": "__init__",
"signature": "def __init__(self, nlevels)"
},
{
"docstring": "Print the stats for this object. WARNING - This does not print everything, for instance, it doesn't print an... | 2 | stack_v2_sparse_classes_30k_train_035967 | Implement the Python class `Stats` described below.
Class description:
An object for collecting stats about a simulation run. Usage: (1) Initialize your Stats object and specify the number of cache levels you have. e.g. stats = Stats(3) (2) Fill it with data as you see fit.
Method signatures and docstrings:
- def __i... | Implement the Python class `Stats` described below.
Class description:
An object for collecting stats about a simulation run. Usage: (1) Initialize your Stats object and specify the number of cache levels you have. e.g. stats = Stats(3) (2) Fill it with data as you see fit.
Method signatures and docstrings:
- def __i... | f7064a9deee66a19be03f0c3ce12c6eaff1a8a33 | <|skeleton|>
class Stats:
"""An object for collecting stats about a simulation run. Usage: (1) Initialize your Stats object and specify the number of cache levels you have. e.g. stats = Stats(3) (2) Fill it with data as you see fit."""
def __init__(self, nlevels):
"""Parameters ---------- nlevels: The ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stats:
"""An object for collecting stats about a simulation run. Usage: (1) Initialize your Stats object and specify the number of cache levels you have. e.g. stats = Stats(3) (2) Fill it with data as you see fit."""
def __init__(self, nlevels):
"""Parameters ---------- nlevels: The number of cac... | the_stack_v2_python_sparse | sveCacheSim.py | plavin/ModelSwapping | train | 1 |
7fff6e1b6d69d0f59b6483df6bb86636850deeeb | [
"self.external_tagging_restriction = external_tagging_restriction\nself.node_template = node_template\nself.fix_it = fix_it\nself.active_only = active_only\nsuper(TermTreeWidget, self).__init__(attrs)",
"if value is None:\n value = []\nreturn render_to_string('edw/admin/term/widgets/tree/widget.html', {'name':... | <|body_start_0|>
self.external_tagging_restriction = external_tagging_restriction
self.node_template = node_template
self.fix_it = fix_it
self.active_only = active_only
super(TermTreeWidget, self).__init__(attrs)
<|end_body_0|>
<|body_start_1|>
if value is None:
... | Приложение терминов дерева | TermTreeWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TermTreeWidget:
"""Приложение терминов дерева"""
def __init__(self, attrs=None, external_tagging_restriction=False, node_template='extended', fix_it=True, active_only=0):
"""Конструктор класса"""
<|body_0|>
def render(self, name, value, attrs=None, choices=(), renderer=N... | stack_v2_sparse_classes_75kplus_train_002787 | 1,868 | permissive | [
{
"docstring": "Конструктор класса",
"name": "__init__",
"signature": "def __init__(self, attrs=None, external_tagging_restriction=False, node_template='extended', fix_it=True, active_only=0)"
},
{
"docstring": "Выполняет запрос и возвращает страницу терминов",
"name": "render",
"signatu... | 2 | stack_v2_sparse_classes_30k_test_002205 | Implement the Python class `TermTreeWidget` described below.
Class description:
Приложение терминов дерева
Method signatures and docstrings:
- def __init__(self, attrs=None, external_tagging_restriction=False, node_template='extended', fix_it=True, active_only=0): Конструктор класса
- def render(self, name, value, at... | Implement the Python class `TermTreeWidget` described below.
Class description:
Приложение терминов дерева
Method signatures and docstrings:
- def __init__(self, attrs=None, external_tagging_restriction=False, node_template='extended', fix_it=True, active_only=0): Конструктор класса
- def render(self, name, value, at... | 2f7c535cb9f91d6bcb2f1e91b58edebc01255612 | <|skeleton|>
class TermTreeWidget:
"""Приложение терминов дерева"""
def __init__(self, attrs=None, external_tagging_restriction=False, node_template='extended', fix_it=True, active_only=0):
"""Конструктор класса"""
<|body_0|>
def render(self, name, value, attrs=None, choices=(), renderer=N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TermTreeWidget:
"""Приложение терминов дерева"""
def __init__(self, attrs=None, external_tagging_restriction=False, node_template='extended', fix_it=True, active_only=0):
"""Конструктор класса"""
self.external_tagging_restriction = external_tagging_restriction
self.node_template =... | the_stack_v2_python_sparse | backend/edw/admin/term/widgets.py | infolabs/django-edw | train | 5 |
21e4031005342cd709fd5827054782d6c2b45bac | [
"if isinstance(device, ndarray.DGLContext):\n ctx = device\nelse:\n ctx = utils.to_dgl_context(device)\nself._handle = _CAPI_DGLAsyncTransfererCreate(ctx)",
"if isinstance(device, ndarray.DGLContext):\n ctx = device\nelse:\n ctx = utils.to_dgl_context(device)\nif ctx.device_type != ndarray.DGLContext.... | <|body_start_0|>
if isinstance(device, ndarray.DGLContext):
ctx = device
else:
ctx = utils.to_dgl_context(device)
self._handle = _CAPI_DGLAsyncTransfererCreate(ctx)
<|end_body_0|>
<|body_start_1|>
if isinstance(device, ndarray.DGLContext):
ctx = devic... | Class for initiating asynchronous copies to the GPU on a second GPU stream. To initiate a transfer to a GPU: >>> tensor_cpu = torch.ones(100000).pin_memory() >>> transferer = dgl.dataloading.AsyncTransferer(torch.device(0)) >>> future = transferer.async_copy(tensor_cpu, torch.device(0)) And then to wait for the transfe... | AsyncTransferer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncTransferer:
"""Class for initiating asynchronous copies to the GPU on a second GPU stream. To initiate a transfer to a GPU: >>> tensor_cpu = torch.ones(100000).pin_memory() >>> transferer = dgl.dataloading.AsyncTransferer(torch.device(0)) >>> future = transferer.async_copy(tensor_cpu, torch.... | stack_v2_sparse_classes_75kplus_train_002788 | 3,202 | permissive | [
{
"docstring": "Create a new AsyncTransferer object. Parameters ---------- device : Device or context object. The context in which the second stream will be created. Must be a GPU context for the copy to be asynchronous.",
"name": "__init__",
"signature": "def __init__(self, device)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_035710 | Implement the Python class `AsyncTransferer` described below.
Class description:
Class for initiating asynchronous copies to the GPU on a second GPU stream. To initiate a transfer to a GPU: >>> tensor_cpu = torch.ones(100000).pin_memory() >>> transferer = dgl.dataloading.AsyncTransferer(torch.device(0)) >>> future = t... | Implement the Python class `AsyncTransferer` described below.
Class description:
Class for initiating asynchronous copies to the GPU on a second GPU stream. To initiate a transfer to a GPU: >>> tensor_cpu = torch.ones(100000).pin_memory() >>> transferer = dgl.dataloading.AsyncTransferer(torch.device(0)) >>> future = t... | 195f99362d883f8b6d131b70a7868a537e55b786 | <|skeleton|>
class AsyncTransferer:
"""Class for initiating asynchronous copies to the GPU on a second GPU stream. To initiate a transfer to a GPU: >>> tensor_cpu = torch.ones(100000).pin_memory() >>> transferer = dgl.dataloading.AsyncTransferer(torch.device(0)) >>> future = transferer.async_copy(tensor_cpu, torch.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AsyncTransferer:
"""Class for initiating asynchronous copies to the GPU on a second GPU stream. To initiate a transfer to a GPU: >>> tensor_cpu = torch.ones(100000).pin_memory() >>> transferer = dgl.dataloading.AsyncTransferer(torch.device(0)) >>> future = transferer.async_copy(tensor_cpu, torch.device(0)) An... | the_stack_v2_python_sparse | python/dgl/dataloading/async_transferer.py | hengruizhang98/dgl | train | 3 |
58223a5755289cb41d090f31f16a1f492c9f3b46 | [
"sampleAtom = atoms[-1]\nself.atoms = []\nself.name = sampleAtom.resName\nself.chainID = sampleAtom.chainID\nself.resSeq = sampleAtom.resSeq\nself.iCode = sampleAtom.iCode\nself.fixed = 0\nself.ffname = 'WAT'\nself.map = {}\nself.reference = ref\nfor a in atoms:\n if a.name in ref.altnames:\n a.name = ref... | <|body_start_0|>
sampleAtom = atoms[-1]
self.atoms = []
self.name = sampleAtom.resName
self.chainID = sampleAtom.chainID
self.resSeq = sampleAtom.resSeq
self.iCode = sampleAtom.iCode
self.fixed = 0
self.ffname = 'WAT'
self.map = {}
self.ref... | Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class. | LIG | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LIG:
"""Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_002789 | 22,508 | permissive | [
{
"docstring": "Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)",
"name": "__init__",
"signature": "def __init__(self, atoms, ref)"
},
{
"docstring": "Create a water atom. Note the HETATM field. Parameters atomname: The name of the atom (string) ne... | 3 | stack_v2_sparse_classes_30k_train_021252 | Implement the Python class `LIG` described below.
Class description:
Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to... | Implement the Python class `LIG` described below.
Class description:
Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to... | a50f0b2f7104007c730baa51b4ec65c891008c47 | <|skeleton|>
class LIG:
"""Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LIG:
"""Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
sampleAtom = atoms[-1]
... | the_stack_v2_python_sparse | mscreen/autodocktools_prepare_py3k/MolKit/pdb2pqr/src/aa.py | e-mayo/mscreen | train | 10 |
a764b0131e3533b74a24a52798018960a73cb851 | [
"RAMSTKDataModel.__init__(self, dao)\nself.dtm_site_options = SiteOptionsDataModel(site_dao)\nself.dtm_program_options = ProgramOptionsDataModel(dao)\nself.site_options = None\nself.program_options = None",
"_site = kwargs['site']\n_program = kwargs['program']\nif _site:\n self.site_options = self.dtm_site_opt... | <|body_start_0|>
RAMSTKDataModel.__init__(self, dao)
self.dtm_site_options = SiteOptionsDataModel(site_dao)
self.dtm_program_options = ProgramOptionsDataModel(dao)
self.site_options = None
self.program_options = None
<|end_body_0|>
<|body_start_1|>
_site = kwargs['site']... | Contains the attributes and methods of an Options data model. | OptionsDataModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionsDataModel:
"""Contains the attributes and methods of an Options data model."""
def __init__(self, dao, site_dao):
"""Initialize an Options data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :class:`ramstk.dao.... | stack_v2_sparse_classes_75kplus_train_002790 | 6,635 | permissive | [
{
"docstring": "Initialize an Options data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :class:`ramstk.dao.DAO.DAO`",
"name": "__init__",
"signature": "def __init__(self, dao, site_dao)"
},
{
"docstring": "Retrieve Options from... | 3 | stack_v2_sparse_classes_30k_train_017356 | Implement the Python class `OptionsDataModel` described below.
Class description:
Contains the attributes and methods of an Options data model.
Method signatures and docstrings:
- def __init__(self, dao, site_dao): Initialize an Options data model instance. :param dao: the data access object for communicating with th... | Implement the Python class `OptionsDataModel` described below.
Class description:
Contains the attributes and methods of an Options data model.
Method signatures and docstrings:
- def __init__(self, dao, site_dao): Initialize an Options data model instance. :param dao: the data access object for communicating with th... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class OptionsDataModel:
"""Contains the attributes and methods of an Options data model."""
def __init__(self, dao, site_dao):
"""Initialize an Options data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :class:`ramstk.dao.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptionsDataModel:
"""Contains the attributes and methods of an Options data model."""
def __init__(self, dao, site_dao):
"""Initialize an Options data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :class:`ramstk.dao.DAO.DAO`"""
... | the_stack_v2_python_sparse | src/ramstk/modules/options/Model.py | JmiXIII/ramstk | train | 0 |
8454e463807f5b085eceeb9cb649d746b8419e99 | [
"self.trie = Trie()\nfor word in words:\n self.trie.insert(word[::-1])\nself.stream = collections.deque([])",
"self.stream.appendleft(letter)\nnode = self.trie.root\nfor char in self.stream:\n if not char in node.nxt:\n return False\n node = node.nxt[char]\n if node.word:\n return True\n... | <|body_start_0|>
self.trie = Trie()
for word in words:
self.trie.insert(word[::-1])
self.stream = collections.deque([])
<|end_body_0|>
<|body_start_1|>
self.stream.appendleft(letter)
node = self.trie.root
for char in self.stream:
if not char in no... | StreamChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie = Trie()
for word in words:
se... | stack_v2_sparse_classes_75kplus_train_002791 | 4,956 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type letter: str :rtype: bool",
"name": "query",
"signature": "def query(self, letter)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022417 | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool
<|skeleton|>
class StreamChecker:
def __init__(self, w... | d2037e521a3ee6fdcc14fd5228ea1fd32d57d637 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
self.trie = Trie()
for word in words:
self.trie.insert(word[::-1])
self.stream = collections.deque([])
def query(self, letter):
""":type letter: str :rtype: bool"""
self.stre... | the_stack_v2_python_sparse | monthlyChallenge/2020-08(augustchallenge)/8_23(****)StreamOfCharacters.py | phu-n-tran/LeetCode | train | 2 | |
346bce882963d238122a74866be31bee3457cefc | [
"expected = {'login': '12345', 'password': 'qwerty', 'serverName': 'HugosWay-Demo3', 'investorPassword': 'qwerty'}\naccount = {'balance': 10, 'email': 'test@test.com', 'leverage': 15, 'serverName': 'server'}\nrsps = respx.post(f'{PROVISIONING_API_URL}/users/current/provisioning-profiles/profileId1/mt4-demo-accounts... | <|body_start_0|>
expected = {'login': '12345', 'password': 'qwerty', 'serverName': 'HugosWay-Demo3', 'investorPassword': 'qwerty'}
account = {'balance': 10, 'email': 'test@test.com', 'leverage': 15, 'serverName': 'server'}
rsps = respx.post(f'{PROVISIONING_API_URL}/users/current/provisioning-pro... | TestMetatraderDemoAccountClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMetatraderDemoAccountClient:
async def test_create_mt4(self):
"""Should create new MetaTrader 4 demo from API."""
<|body_0|>
async def test_not_create_mt4_demo_with_account_token(self):
"""Should not create MetaTrader 4 demo account via API with account token'.""... | stack_v2_sparse_classes_75kplus_train_002792 | 3,929 | no_license | [
{
"docstring": "Should create new MetaTrader 4 demo from API.",
"name": "test_create_mt4",
"signature": "async def test_create_mt4(self)"
},
{
"docstring": "Should not create MetaTrader 4 demo account via API with account token'.",
"name": "test_not_create_mt4_demo_with_account_token",
"... | 4 | stack_v2_sparse_classes_30k_train_045357 | Implement the Python class `TestMetatraderDemoAccountClient` described below.
Class description:
Implement the TestMetatraderDemoAccountClient class.
Method signatures and docstrings:
- async def test_create_mt4(self): Should create new MetaTrader 4 demo from API.
- async def test_not_create_mt4_demo_with_account_tok... | Implement the Python class `TestMetatraderDemoAccountClient` described below.
Class description:
Implement the TestMetatraderDemoAccountClient class.
Method signatures and docstrings:
- async def test_create_mt4(self): Should create new MetaTrader 4 demo from API.
- async def test_not_create_mt4_demo_with_account_tok... | b410e4c6bc4b11fc6ed85c91aca43e07fcd5fd2c | <|skeleton|>
class TestMetatraderDemoAccountClient:
async def test_create_mt4(self):
"""Should create new MetaTrader 4 demo from API."""
<|body_0|>
async def test_not_create_mt4_demo_with_account_token(self):
"""Should not create MetaTrader 4 demo account via API with account token'.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMetatraderDemoAccountClient:
async def test_create_mt4(self):
"""Should create new MetaTrader 4 demo from API."""
expected = {'login': '12345', 'password': 'qwerty', 'serverName': 'HugosWay-Demo3', 'investorPassword': 'qwerty'}
account = {'balance': 10, 'email': 'test@test.com', 'l... | the_stack_v2_python_sparse | lib/clients/metaApi/metatraderDemoAccount_client_test.py | alading241/metaapi-python-sdk | train | 0 | |
ffb50588b53355aa5e320c30d1631be9fec3b144 | [
"self.undo = nuke.Undo\nself.__disabled = self.undo.disabled()\nself.script = script\nif save_func:\n self.save_func = save_func\nelse:\n self.save_func = nuke.scriptSave",
"if self.__disabled:\n self.undo.enable()\nself.undo.begin()",
"self.save_func(self.script)\nself.undo.cancel()\nif self.__disable... | <|body_start_0|>
self.undo = nuke.Undo
self.__disabled = self.undo.disabled()
self.script = script
if save_func:
self.save_func = save_func
else:
self.save_func = nuke.scriptSave
<|end_body_0|>
<|body_start_1|>
if self.__disabled:
self... | Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100) | WriteChanges | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteChanges:
"""Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)"""
def __init__(sel... | stack_v2_sparse_classes_75kplus_train_002793 | 23,998 | no_license | [
{
"docstring": "Initialize a WriteChanges context manager. Must provide a script to write to. If you provide a save_func, it will be called instead of the default `nuke.scriptSave`. The function must have the same interface as `nuke.scriptSave`. A possible alternative is `nuke.nodeCopy`.",
"name": "__init__... | 3 | stack_v2_sparse_classes_30k_train_032851 | Implement the Python class `WriteChanges` described below.
Class description:
Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): nod... | Implement the Python class `WriteChanges` described below.
Class description:
Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): nod... | ffd112312632731db53aa94c77a0bb6d63243474 | <|skeleton|>
class WriteChanges:
"""Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)"""
def __init__(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WriteChanges:
"""Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)"""
def __init__(self, script, sa... | the_stack_v2_python_sparse | apps/nuke/scripts/python/zync_nuke.py | tws0002/gs-code | train | 1 |
c02cf210ffae9dcc0d017e25aeea0dc638175314 | [
"try:\n StoreManagement.valid_store_user(store_name, request.user)\nexcept UserNotInStoreException:\n raise Http404()\ninvoice = get_object_or_404(Invoice, pk=pk)\ncontext = {'invoice': invoice, 'store_name': store_name}\nreturn render(request, template_name=self.template_name, context=context)",
"try:\n ... | <|body_start_0|>
try:
StoreManagement.valid_store_user(store_name, request.user)
except UserNotInStoreException:
raise Http404()
invoice = get_object_or_404(Invoice, pk=pk)
context = {'invoice': invoice, 'store_name': store_name}
return render(request, tem... | InvoiceDetailUpdateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceDetailUpdateView:
def get(self, request, store_name, pk):
"""Get invoice detail"""
<|body_0|>
def patch(self, request, store_name, pk):
"""Method for updating invoice status"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
Sto... | stack_v2_sparse_classes_75kplus_train_002794 | 13,421 | permissive | [
{
"docstring": "Get invoice detail",
"name": "get",
"signature": "def get(self, request, store_name, pk)"
},
{
"docstring": "Method for updating invoice status",
"name": "patch",
"signature": "def patch(self, request, store_name, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024550 | Implement the Python class `InvoiceDetailUpdateView` described below.
Class description:
Implement the InvoiceDetailUpdateView class.
Method signatures and docstrings:
- def get(self, request, store_name, pk): Get invoice detail
- def patch(self, request, store_name, pk): Method for updating invoice status | Implement the Python class `InvoiceDetailUpdateView` described below.
Class description:
Implement the InvoiceDetailUpdateView class.
Method signatures and docstrings:
- def get(self, request, store_name, pk): Get invoice detail
- def patch(self, request, store_name, pk): Method for updating invoice status
<|skeleto... | 3f0a6977c8c26743373a70b4296516b7a71ccf4a | <|skeleton|>
class InvoiceDetailUpdateView:
def get(self, request, store_name, pk):
"""Get invoice detail"""
<|body_0|>
def patch(self, request, store_name, pk):
"""Method for updating invoice status"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvoiceDetailUpdateView:
def get(self, request, store_name, pk):
"""Get invoice detail"""
try:
StoreManagement.valid_store_user(store_name, request.user)
except UserNotInStoreException:
raise Http404()
invoice = get_object_or_404(Invoice, pk=pk)
... | the_stack_v2_python_sparse | sales/views.py | sLeeNguyen/sales-support | train | 1 | |
1581ff6bd114e785bf644c929903a3395d963456 | [
"self.open_member_grade_management()\nattr = self.get_button_attribute(u'启用', u'disabled')\nif attr:\n self.stop_status()\n stop_tips = self.get_tips()\n self.assert_result_equal(u'操作成功', stop_tips, u'会员等级-冻结')\n sleep(2)\n self.start_status()\n start_tips = self.get_tips()\n self.assert_result... | <|body_start_0|>
self.open_member_grade_management()
attr = self.get_button_attribute(u'启用', u'disabled')
if attr:
self.stop_status()
stop_tips = self.get_tips()
self.assert_result_equal(u'操作成功', stop_tips, u'会员等级-冻结')
sleep(2)
self.sta... | 会员积分管理 | MemberGradeManageTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberGradeManageTest:
"""会员积分管理"""
def test_member_grade_start_and_stop(self):
"""会员等级启用-冻结"""
<|body_0|>
def test_member_grade_check_detail(self):
"""会员等级查看详情"""
<|body_1|>
def test_member_grade_edit(self):
"""会员等级编辑"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_002795 | 3,656 | no_license | [
{
"docstring": "会员等级启用-冻结",
"name": "test_member_grade_start_and_stop",
"signature": "def test_member_grade_start_and_stop(self)"
},
{
"docstring": "会员等级查看详情",
"name": "test_member_grade_check_detail",
"signature": "def test_member_grade_check_detail(self)"
},
{
"docstring": "会员等... | 3 | null | Implement the Python class `MemberGradeManageTest` described below.
Class description:
会员积分管理
Method signatures and docstrings:
- def test_member_grade_start_and_stop(self): 会员等级启用-冻结
- def test_member_grade_check_detail(self): 会员等级查看详情
- def test_member_grade_edit(self): 会员等级编辑 | Implement the Python class `MemberGradeManageTest` described below.
Class description:
会员积分管理
Method signatures and docstrings:
- def test_member_grade_start_and_stop(self): 会员等级启用-冻结
- def test_member_grade_check_detail(self): 会员等级查看详情
- def test_member_grade_edit(self): 会员等级编辑
<|skeleton|>
class MemberGradeManageT... | dcae68955b2857bbfe411145432865c57561c9ef | <|skeleton|>
class MemberGradeManageTest:
"""会员积分管理"""
def test_member_grade_start_and_stop(self):
"""会员等级启用-冻结"""
<|body_0|>
def test_member_grade_check_detail(self):
"""会员等级查看详情"""
<|body_1|>
def test_member_grade_edit(self):
"""会员等级编辑"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemberGradeManageTest:
"""会员积分管理"""
def test_member_grade_start_and_stop(self):
"""会员等级启用-冻结"""
self.open_member_grade_management()
attr = self.get_button_attribute(u'启用', u'disabled')
if attr:
self.stop_status()
stop_tips = self.get_tips()
... | the_stack_v2_python_sparse | genlot_vlt2/cases/BusinessOperation/member_manage/member_grade_manage_test.py | bbwdi/auto | train | 1 |
8b4742ec2e047edf74ace413674ec963f05ebd2a | [
"bfs = deque()\nbfs.append((root, 1))\nwhile bfs:\n node, level = bfs.popleft()\n if not node:\n continue\n if not node.left and (not node.right):\n return level\n bfs.append((node.left, level + 1))\n bfs.append((node.right, level + 1))\nreturn 0",
"if not root:\n return 0\nif not ... | <|body_start_0|>
bfs = deque()
bfs.append((root, 1))
while bfs:
node, level = bfs.popleft()
if not node:
continue
if not node.left and (not node.right):
return level
bfs.append((node.left, level + 1))
bfs... | LeetCode Monthly Challenge problem for October 22nd, 2020. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""LeetCode Monthly Challenge problem for October 22nd, 2020."""
def minDepth(self, root: TreeNode) -> int:
"""Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Exampl... | stack_v2_sparse_classes_75kplus_train_002796 | 2,267 | no_license | [
{
"docstring": "Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Example: Given the following tree, t: 3 / 9 20 / 15 7 minDepth(t) -> 2",
"name": "minDepth",
"signature": "def minDepth(self, root:... | 2 | stack_v2_sparse_classes_30k_train_012575 | Implement the Python class `Solution` described below.
Class description:
LeetCode Monthly Challenge problem for October 22nd, 2020.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. ... | Implement the Python class `Solution` described below.
Class description:
LeetCode Monthly Challenge problem for October 22nd, 2020.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. ... | c6d600bc74afd14e00d4f0ffed40696192b229c3 | <|skeleton|>
class Solution:
"""LeetCode Monthly Challenge problem for October 22nd, 2020."""
def minDepth(self, root: TreeNode) -> int:
"""Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Exampl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""LeetCode Monthly Challenge problem for October 22nd, 2020."""
def minDepth(self, root: TreeNode) -> int:
"""Returns the minimum depth of a binary tree. # Queue method Params: root - The root node of a binary tree. Returns: int - The minimum depth of a binary tree. Example: Given the ... | the_stack_v2_python_sparse | python/Monthly/Oct2020/minbinarytreedepth.py | Hilldrupca/LeetCode | train | 0 |
c1deb029777d7e28e3b88c3835574e1e663dc02b | [
"for i in range(len(nums) - 1):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\nreturn None",
"hashmap = {}\nfor index, num in enumerate(nums):\n hashmap[num] = index\nfor current_index, num in enumerate(nums):\n find_index = hashmap.get(target - n... | <|body_start_0|>
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return None
<|end_body_0|>
<|body_start_1|>
hashmap = {}
for index, num in enumerate(nums):
hashmap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_force(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
"""模拟哈希表: 建立完字典后查找"""
<|body_1|>
def twoSum_2(self, nums, target):
"""模拟哈希表: 边建立边查找"""
... | stack_v2_sparse_classes_75kplus_train_002797 | 1,880 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_force",
"signature": "def twoSum_force(self, nums, target)"
},
{
"docstring": "模拟哈希表: 建立完字典后查找",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": "模拟哈希表: 边... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_force(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): 模拟哈希表: 建立完字典后查找
- def twoSum_2(self, nums, targe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_force(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): 模拟哈希表: 建立完字典后查找
- def twoSum_2(self, nums, targe... | 7dbd6da4cf42e422f1425a9de134ab31da52792a | <|skeleton|>
class Solution:
def twoSum_force(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
"""模拟哈希表: 建立完字典后查找"""
<|body_1|>
def twoSum_2(self, nums, target):
"""模拟哈希表: 边建立边查找"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_force(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return None
... | the_stack_v2_python_sparse | 查找计算/两数之和.py | VixeruntR/leetcode | train | 1 | |
cc464626d59fcd88a311c6d6cec534da3ff4ed6a | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A RemoteIdentityGroup is a named grouping of Remote Identities for Accounts. An Account's relationship to a RemoteIdentityGroup is defined via RemoteIdentity objects. | RemoteIdentityGroupsServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteIdentityGroupsServicer:
"""A RemoteIdentityGroup is a named grouping of Remote Identities for Accounts. An Account's relationship to a RemoteIdentityGroup is defined via RemoteIdentity objects."""
def Get(self, request, context):
"""// Create registers a new RemoteIdentityGroup... | stack_v2_sparse_classes_75kplus_train_002798 | 6,176 | permissive | [
{
"docstring": "// Create registers a new RemoteIdentityGroup. rpc Create(RemoteIdentityGroupCreateRequest) returns (RemoteIdentityGroupCreateResponse) { option (v1.method_options).method = \"post\"; option (v1.method_options).url = \"/v1/remote-identity-groups\"; } Get reads one RemoteIdentityGroup by ID.",
... | 2 | stack_v2_sparse_classes_30k_train_031250 | Implement the Python class `RemoteIdentityGroupsServicer` described below.
Class description:
A RemoteIdentityGroup is a named grouping of Remote Identities for Accounts. An Account's relationship to a RemoteIdentityGroup is defined via RemoteIdentity objects.
Method signatures and docstrings:
- def Get(self, request... | Implement the Python class `RemoteIdentityGroupsServicer` described below.
Class description:
A RemoteIdentityGroup is a named grouping of Remote Identities for Accounts. An Account's relationship to a RemoteIdentityGroup is defined via RemoteIdentity objects.
Method signatures and docstrings:
- def Get(self, request... | 1f3a53ef8c404e64d9324f9fd13f5c39c71eaca5 | <|skeleton|>
class RemoteIdentityGroupsServicer:
"""A RemoteIdentityGroup is a named grouping of Remote Identities for Accounts. An Account's relationship to a RemoteIdentityGroup is defined via RemoteIdentity objects."""
def Get(self, request, context):
"""// Create registers a new RemoteIdentityGroup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoteIdentityGroupsServicer:
"""A RemoteIdentityGroup is a named grouping of Remote Identities for Accounts. An Account's relationship to a RemoteIdentityGroup is defined via RemoteIdentity objects."""
def Get(self, request, context):
"""// Create registers a new RemoteIdentityGroup. rpc Create(... | the_stack_v2_python_sparse | strongdm/remote_identity_groups_pb2_grpc.py | strongdm/strongdm-sdk-python | train | 9 |
fc446fb0160f5448cba83a5c7753e91d32187296 | [
"self.sname = name\nself.sage = age\nself.smarks = marks",
"self.ab = 222\nself.cd = 333\nprint('My name is ', self.sname)\nprint('My age is: ', self.sage)\nprint('My marks are: ', self.smarks)"
] | <|body_start_0|>
self.sname = name
self.sage = age
self.smarks = marks
<|end_body_0|>
<|body_start_1|>
self.ab = 222
self.cd = 333
print('My name is ', self.sname)
print('My age is: ', self.sage)
print('My marks are: ', self.smarks)
<|end_body_1|>
| student | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class student:
def __init__(self, name, age, marks):
"""(A) Instance veriable are mostly declared in constructor"""
<|body_0|>
def talk(self):
"""(B) If needed instance variable can be declared in Instance Method also"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_002799 | 1,106 | no_license | [
{
"docstring": "(A) Instance veriable are mostly declared in constructor",
"name": "__init__",
"signature": "def __init__(self, name, age, marks)"
},
{
"docstring": "(B) If needed instance variable can be declared in Instance Method also",
"name": "talk",
"signature": "def talk(self)"
... | 2 | stack_v2_sparse_classes_30k_train_035476 | Implement the Python class `student` described below.
Class description:
Implement the student class.
Method signatures and docstrings:
- def __init__(self, name, age, marks): (A) Instance veriable are mostly declared in constructor
- def talk(self): (B) If needed instance variable can be declared in Instance Method ... | Implement the Python class `student` described below.
Class description:
Implement the student class.
Method signatures and docstrings:
- def __init__(self, name, age, marks): (A) Instance veriable are mostly declared in constructor
- def talk(self): (B) If needed instance variable can be declared in Instance Method ... | c230f0ac2579c4c458d94f7c811aa6534eb1587b | <|skeleton|>
class student:
def __init__(self, name, age, marks):
"""(A) Instance veriable are mostly declared in constructor"""
<|body_0|>
def talk(self):
"""(B) If needed instance variable can be declared in Instance Method also"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class student:
def __init__(self, name, age, marks):
"""(A) Instance veriable are mostly declared in constructor"""
self.sname = name
self.sage = age
self.smarks = marks
def talk(self):
"""(B) If needed instance variable can be declared in Instance Method also"""
... | the_stack_v2_python_sparse | scripts/OOPs_Student.py | lalitsshejao/Python_PractiseCode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.