blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95922261f9503ab038f3120bd5d6da275902fa7c | [
"if self.is_active:\n raise Exception('{0} was already active'.format(self._meta.verbose_name))\nself.is_active = True\nself.status_changed = timezone.now()\nif save:\n self.save()",
"if not self.is_active:\n raise Exception('{0} was already not active'.format(self._meta.verbose_name))\nself.is_active = ... | <|body_start_0|>
if self.is_active:
raise Exception('{0} was already active'.format(self._meta.verbose_name))
self.is_active = True
self.status_changed = timezone.now()
if save:
self.save()
<|end_body_0|>
<|body_start_1|>
if not self.is_active:
... | Mixin for models that keep an active/inactive state. | ActiveStateMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveStateMixin:
"""Mixin for models that keep an active/inactive state."""
def activate(self, save=True):
"""Activate the object, raise an exception if it was already active."""
<|body_0|>
def deactivate(self, save=True):
"""Deactivate the object, raise an exce... | stack_v2_sparse_classes_36k_train_034000 | 5,009 | permissive | [
{
"docstring": "Activate the object, raise an exception if it was already active.",
"name": "activate",
"signature": "def activate(self, save=True)"
},
{
"docstring": "Deactivate the object, raise an exception if it was already active.",
"name": "deactivate",
"signature": "def deactivate... | 2 | stack_v2_sparse_classes_30k_val_000841 | Implement the Python class `ActiveStateMixin` described below.
Class description:
Mixin for models that keep an active/inactive state.
Method signatures and docstrings:
- def activate(self, save=True): Activate the object, raise an exception if it was already active.
- def deactivate(self, save=True): Deactivate the ... | Implement the Python class `ActiveStateMixin` described below.
Class description:
Mixin for models that keep an active/inactive state.
Method signatures and docstrings:
- def activate(self, save=True): Activate the object, raise an exception if it was already active.
- def deactivate(self, save=True): Deactivate the ... | 6cb8320509f2446fa569c3345b7625c50aa63b81 | <|skeleton|>
class ActiveStateMixin:
"""Mixin for models that keep an active/inactive state."""
def activate(self, save=True):
"""Activate the object, raise an exception if it was already active."""
<|body_0|>
def deactivate(self, save=True):
"""Deactivate the object, raise an exce... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveStateMixin:
"""Mixin for models that keep an active/inactive state."""
def activate(self, save=True):
"""Activate the object, raise an exception if it was already active."""
if self.is_active:
raise Exception('{0} was already active'.format(self._meta.verbose_name))
... | the_stack_v2_python_sparse | core/models/mixins.py | emergence-lab/emergence-lab | train | 3 |
dc69eff9bb07d104cf822482c048f07af91fc9c9 | [
"try:\n return obj.next_item_id\nexcept AttributeError:\n try:\n item = Item.objects.get(branch=obj.branch, lesson=obj.lesson, order=obj.order + 1)\n return {'item_id': item.item_id, 'type': item.type.id, 'category': item.type.category}\n except Item.DoesNotExist:\n return {'item_id': ... | <|body_start_0|>
try:
return obj.next_item_id
except AttributeError:
try:
item = Item.objects.get(branch=obj.branch, lesson=obj.lesson, order=obj.order + 1)
return {'item_id': item.item_id, 'type': item.type.id, 'category': item.type.category}
... | Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. average_grade: The average grade of all students who comp... | AssignmentAnalyticsSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignmentAnalyticsSerializer:
"""Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. ... | stack_v2_sparse_classes_36k_train_034001 | 12,166 | no_license | [
{
"docstring": "Return the next item in the lesson, if any.",
"name": "get_next_item",
"signature": "def get_next_item(self, obj)"
},
{
"docstring": "Return the next assignment in the lesson, if any.",
"name": "get_next_assignment",
"signature": "def get_next_assignment(self, obj)"
}
] | 2 | null | Implement the Python class `AssignmentAnalyticsSerializer` described below.
Class description:
Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divid... | Implement the Python class `AssignmentAnalyticsSerializer` described below.
Class description:
Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divid... | f701eee3e8ced9a839401e268031c2d497252e8a | <|skeleton|>
class AssignmentAnalyticsSerializer:
"""Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssignmentAnalyticsSerializer:
"""Serialize an Item of type Assignment with its basic properties and calculated analytics. Calculates the following analytics: submissions: Number of submissions to the assignment. submission_ratio: Number of submissions divided by the number of enrolled students. average_grade... | the_stack_v2_python_sparse | coursera/serializers/items.py | cornytrace/SEP-Autumn-2018-Group2-Coursera | train | 0 |
5e2bb67efc64eb2b17155acec0568ff8558c3e12 | [
"guides = deepcopy(manager.all())\nseen_ids = set(AssistantActivity.objects.filter(user=request.user).values_list('guide_id', flat=True))\nfor _key, v in guides.items():\n v['seen'] = v['id'] in seen_ids\nreturn Response(guides)",
"serializer = AssistantSerializer(data=request.data, partial=True)\nif not seria... | <|body_start_0|>
guides = deepcopy(manager.all())
seen_ids = set(AssistantActivity.objects.filter(user=request.user).values_list('guide_id', flat=True))
for _key, v in guides.items():
v['seen'] = v['id'] in seen_ids
return Response(guides)
<|end_body_0|>
<|body_start_1|>
... | AssistantEndpoint | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssistantEndpoint:
def get(self, request):
"""Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'."""
<|body_0|>
def put(self, request):
"""Mark a guide as viewed or dismissed. Request is of the form { 'guide_id': <guide_id>, 'status'... | stack_v2_sparse_classes_36k_train_034002 | 2,689 | permissive | [
{
"docstring": "Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Mark a guide as viewed or dismissed. Request is of the form { 'guide_id': <guide_id>, 'status': 'viewed' / 'dismissed', ... | 2 | stack_v2_sparse_classes_30k_train_006337 | Implement the Python class `AssistantEndpoint` described below.
Class description:
Implement the AssistantEndpoint class.
Method signatures and docstrings:
- def get(self, request): Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'.
- def put(self, request): Mark a guide as viewed o... | Implement the Python class `AssistantEndpoint` described below.
Class description:
Implement the AssistantEndpoint class.
Method signatures and docstrings:
- def get(self, request): Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'.
- def put(self, request): Mark a guide as viewed o... | 36a02ed244c7b59ee1f2523e64e4749e404ab0f7 | <|skeleton|>
class AssistantEndpoint:
def get(self, request):
"""Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'."""
<|body_0|>
def put(self, request):
"""Mark a guide as viewed or dismissed. Request is of the form { 'guide_id': <guide_id>, 'status'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssistantEndpoint:
def get(self, request):
"""Return all the guides with a 'seen' attribute if it has been 'viewed' or 'dismissed'."""
guides = deepcopy(manager.all())
seen_ids = set(AssistantActivity.objects.filter(user=request.user).values_list('guide_id', flat=True))
for _ke... | the_stack_v2_python_sparse | src/sentry/api/endpoints/assistant.py | commonlims/commonlims | train | 4 | |
5284ea7f59cbc5feb22fecdf99f88f664a644450 | [
"fields = super(BaseDynamicInlineAdmin, self).get_fields(request, obj)\nif issubclass(self.model, Orderable):\n fields = list(fields)\n try:\n fields.remove('_order')\n except ValueError:\n pass\n fields.append('_order')\nreturn fields",
"fieldsets = super(BaseDynamicInlineAdmin, self).g... | <|body_start_0|>
fields = super(BaseDynamicInlineAdmin, self).get_fields(request, obj)
if issubclass(self.model, Orderable):
fields = list(fields)
try:
fields.remove('_order')
except ValueError:
pass
fields.append('_order')
... | Admin inline that uses JS to inject an "Add another" link which when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``. | BaseDynamicInlineAdmin | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDynamicInlineAdmin:
"""Admin inline that uses JS to inject an "Add another" link which when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``."""
def get_fields(self, request, obj=None):
"... | stack_v2_sparse_classes_36k_train_034003 | 17,362 | permissive | [
{
"docstring": "For subclasses of ``Orderable``, the ``_order`` field must always be present and be the last field.",
"name": "get_fields",
"signature": "def get_fields(self, request, obj=None)"
},
{
"docstring": "Same as above, but for fieldsets.",
"name": "get_fieldsets",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_009904 | Implement the Python class `BaseDynamicInlineAdmin` described below.
Class description:
Admin inline that uses JS to inject an "Add another" link which when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``.
Method signatures ... | Implement the Python class `BaseDynamicInlineAdmin` described below.
Class description:
Admin inline that uses JS to inject an "Add another" link which when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``.
Method signatures ... | 29203de1d111a6d94d576a89430b37edd24cef55 | <|skeleton|>
class BaseDynamicInlineAdmin:
"""Admin inline that uses JS to inject an "Add another" link which when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``."""
def get_fields(self, request, obj=None):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseDynamicInlineAdmin:
"""Admin inline that uses JS to inject an "Add another" link which when clicked, dynamically reveals another fieldset. Also handles adding the ``_order`` field and its widget for models that subclass ``Orderable``."""
def get_fields(self, request, obj=None):
"""For subclas... | the_stack_v2_python_sparse | mezzanine/core/admin.py | fermorltd/mezzanine | train | 6 |
72968719268b7fce826896dfd4d79427213819d5 | [
"self.state_num = state_num\nself.state_dim = state_dim\nself.action_dim = action_dim\nself.reset()",
"self.state_list = deque(maxlen=self.state_num)\nself.action_list = deque(maxlen=self.state_num - 1)\nfor i in range(self.state_num):\n self.state_list.append([0] * self.state_dim)\nfor i in range(self.state_n... | <|body_start_0|>
self.state_num = state_num
self.state_dim = state_dim
self.action_dim = action_dim
self.reset()
<|end_body_0|>
<|body_start_1|>
self.state_list = deque(maxlen=self.state_num)
self.action_list = deque(maxlen=self.state_num - 1)
for i in range(self... | state_manager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class state_manager:
def __init__(self, state_num: int=1, state_dim: int=1, action_dim: int=1):
"""在Main函数里有state_manager()的具体用法。 :param state_num: 拼接过去多少步的状态? :param state_dim: 单步状态的维度 :param action_dim: 单步动作的维度"""
<|body_0|>
def reset(self):
"""When start a new game, cal... | stack_v2_sparse_classes_36k_train_034004 | 2,676 | no_license | [
{
"docstring": "在Main函数里有state_manager()的具体用法。 :param state_num: 拼接过去多少步的状态? :param state_dim: 单步状态的维度 :param action_dim: 单步动作的维度",
"name": "__init__",
"signature": "def __init__(self, state_num: int=1, state_dim: int=1, action_dim: int=1)"
},
{
"docstring": "When start a new game, call this.",
... | 4 | stack_v2_sparse_classes_30k_train_004039 | Implement the Python class `state_manager` described below.
Class description:
Implement the state_manager class.
Method signatures and docstrings:
- def __init__(self, state_num: int=1, state_dim: int=1, action_dim: int=1): 在Main函数里有state_manager()的具体用法。 :param state_num: 拼接过去多少步的状态? :param state_dim: 单步状态的维度 :param... | Implement the Python class `state_manager` described below.
Class description:
Implement the state_manager class.
Method signatures and docstrings:
- def __init__(self, state_num: int=1, state_dim: int=1, action_dim: int=1): 在Main函数里有state_manager()的具体用法。 :param state_num: 拼接过去多少步的状态? :param state_dim: 单步状态的维度 :param... | 4d0f9a828867e54b058e247441f8f376cecdedc1 | <|skeleton|>
class state_manager:
def __init__(self, state_num: int=1, state_dim: int=1, action_dim: int=1):
"""在Main函数里有state_manager()的具体用法。 :param state_num: 拼接过去多少步的状态? :param state_dim: 单步状态的维度 :param action_dim: 单步动作的维度"""
<|body_0|>
def reset(self):
"""When start a new game, cal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class state_manager:
def __init__(self, state_num: int=1, state_dim: int=1, action_dim: int=1):
"""在Main函数里有state_manager()的具体用法。 :param state_num: 拼接过去多少步的状态? :param state_dim: 单步状态的维度 :param action_dim: 单步动作的维度"""
self.state_num = state_num
self.state_dim = state_dim
self.action_di... | the_stack_v2_python_sparse | utils/state_manager.py | lafmdp/rl_labtory | train | 1 | |
773b41d9f6a9ad8133fda4c9954c35ca45dece2d | [
"if isinstance(coconut, Coconut):\n self.coconuts.append(coconut)\nelse:\n raise AttributeError('Only coconuts can be added to inventory.')",
"weight = 0\nfor coconut in self.coconuts:\n weight += coconut.coconut_weight\nreturn weight"
] | <|body_start_0|>
if isinstance(coconut, Coconut):
self.coconuts.append(coconut)
else:
raise AttributeError('Only coconuts can be added to inventory.')
<|end_body_0|>
<|body_start_1|>
weight = 0
for coconut in self.coconuts:
weight += coconut.coconut_w... | An inventory object for managing Coconuts. | Inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inventory:
"""An inventory object for managing Coconuts."""
def add_coconut(self, coconut):
"""Add a coconut to inventory. Raise AttributeError if object isn't a coconut."""
<|body_0|>
def total_weight(self):
"""Calculate the total weight of coconuts in inventory... | stack_v2_sparse_classes_36k_train_034005 | 1,034 | no_license | [
{
"docstring": "Add a coconut to inventory. Raise AttributeError if object isn't a coconut.",
"name": "add_coconut",
"signature": "def add_coconut(self, coconut)"
},
{
"docstring": "Calculate the total weight of coconuts in inventory.",
"name": "total_weight",
"signature": "def total_wei... | 2 | stack_v2_sparse_classes_30k_train_017600 | Implement the Python class `Inventory` described below.
Class description:
An inventory object for managing Coconuts.
Method signatures and docstrings:
- def add_coconut(self, coconut): Add a coconut to inventory. Raise AttributeError if object isn't a coconut.
- def total_weight(self): Calculate the total weight of ... | Implement the Python class `Inventory` described below.
Class description:
An inventory object for managing Coconuts.
Method signatures and docstrings:
- def add_coconut(self, coconut): Add a coconut to inventory. Raise AttributeError if object isn't a coconut.
- def total_weight(self): Calculate the total weight of ... | b5041e71badd1ca2c013828e3b2910fb02e9728f | <|skeleton|>
class Inventory:
"""An inventory object for managing Coconuts."""
def add_coconut(self, coconut):
"""Add a coconut to inventory. Raise AttributeError if object isn't a coconut."""
<|body_0|>
def total_weight(self):
"""Calculate the total weight of coconuts in inventory... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inventory:
"""An inventory object for managing Coconuts."""
def add_coconut(self, coconut):
"""Add a coconut to inventory. Raise AttributeError if object isn't a coconut."""
if isinstance(coconut, Coconut):
self.coconuts.append(coconut)
else:
raise Attribut... | the_stack_v2_python_sparse | python_3/homework/Data_as_structured_objects/src/coconuts.py | patrickbeeson/python-classes | train | 0 |
04e25737aee015a20168bc5f3362769de3a706df | [
"delete_id = request.query_params.get('ids', None)\nif not delete_id:\n return JsonResponse(code=4004, msg='服务器开小差了', status=status.HTTP_404_NOT_FOUND)\nmodels.Case.objects.extra(where=['id IN (' + delete_id + ')']).delete()\nlogger.info('-' * 10 + '删除case by:{} '.format(request.user) + '-' * 10)\nreturn JsonRes... | <|body_start_0|>
delete_id = request.query_params.get('ids', None)
if not delete_id:
return JsonResponse(code=4004, msg='服务器开小差了', status=status.HTTP_404_NOT_FOUND)
models.Case.objects.extra(where=['id IN (' + delete_id + ')']).delete()
logger.info('-' * 10 + '删除case by:{} '.... | CaseViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseViewSet:
def deleteLots(self, request, *args, **kwargs):
"""批量删除 :param request: {'ids': []} :param args: :param kwargs: :return:"""
<|body_0|>
def runById(self, request, *args, **kwargs):
"""批量运行 :param request: {'ids':[], config:''} :param args: :param kwargs: ... | stack_v2_sparse_classes_36k_train_034006 | 6,617 | no_license | [
{
"docstring": "批量删除 :param request: {'ids': []} :param args: :param kwargs: :return:",
"name": "deleteLots",
"signature": "def deleteLots(self, request, *args, **kwargs)"
},
{
"docstring": "批量运行 :param request: {'ids':[], config:''} :param args: :param kwargs: :return:",
"name": "runById",
... | 4 | stack_v2_sparse_classes_30k_train_014827 | Implement the Python class `CaseViewSet` described below.
Class description:
Implement the CaseViewSet class.
Method signatures and docstrings:
- def deleteLots(self, request, *args, **kwargs): 批量删除 :param request: {'ids': []} :param args: :param kwargs: :return:
- def runById(self, request, *args, **kwargs): 批量运行 :p... | Implement the Python class `CaseViewSet` described below.
Class description:
Implement the CaseViewSet class.
Method signatures and docstrings:
- def deleteLots(self, request, *args, **kwargs): 批量删除 :param request: {'ids': []} :param args: :param kwargs: :return:
- def runById(self, request, *args, **kwargs): 批量运行 :p... | e8407fdd97e821779f2abb4c2debfb246f44e4ed | <|skeleton|>
class CaseViewSet:
def deleteLots(self, request, *args, **kwargs):
"""批量删除 :param request: {'ids': []} :param args: :param kwargs: :return:"""
<|body_0|>
def runById(self, request, *args, **kwargs):
"""批量运行 :param request: {'ids':[], config:''} :param args: :param kwargs: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CaseViewSet:
def deleteLots(self, request, *args, **kwargs):
"""批量删除 :param request: {'ids': []} :param args: :param kwargs: :return:"""
delete_id = request.query_params.get('ids', None)
if not delete_id:
return JsonResponse(code=4004, msg='服务器开小差了', status=status.HTTP_404_... | the_stack_v2_python_sparse | begin/views1/case.py | aaas19920513/ApiDemo | train | 0 | |
e5aa52f0f9d5643e5b1e208b6a6255d20e8503ef | [
"current_lyrics = ''\nlyrics_list = []\nseparator = LyricsReader.LYRICS_SEPARATOR\nseparator_chars_read = 0\nseparator_length = len(separator)\nmin_length = LyricsReader.MIN_LYRICS_LENGTH\nfile = open(file_path, 'rt', encoding='utf-8')\nnext = file.read(1)\nwhile next != '':\n if separator_chars_read == separato... | <|body_start_0|>
current_lyrics = ''
lyrics_list = []
separator = LyricsReader.LYRICS_SEPARATOR
separator_chars_read = 0
separator_length = len(separator)
min_length = LyricsReader.MIN_LYRICS_LENGTH
file = open(file_path, 'rt', encoding='utf-8')
next = fil... | LyricsReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LyricsReader:
def read_english_lyrics_from_file_streaming(file_path):
"""Read lyrics from a file and return an array containing only lyrics in english. :param file_path: path to the file containing the lyrics :return: array of strings containing all english lyrics from the file"""
... | stack_v2_sparse_classes_36k_train_034007 | 2,889 | no_license | [
{
"docstring": "Read lyrics from a file and return an array containing only lyrics in english. :param file_path: path to the file containing the lyrics :return: array of strings containing all english lyrics from the file",
"name": "read_english_lyrics_from_file_streaming",
"signature": "def read_englis... | 2 | stack_v2_sparse_classes_30k_train_017262 | Implement the Python class `LyricsReader` described below.
Class description:
Implement the LyricsReader class.
Method signatures and docstrings:
- def read_english_lyrics_from_file_streaming(file_path): Read lyrics from a file and return an array containing only lyrics in english. :param file_path: path to the file ... | Implement the Python class `LyricsReader` described below.
Class description:
Implement the LyricsReader class.
Method signatures and docstrings:
- def read_english_lyrics_from_file_streaming(file_path): Read lyrics from a file and return an array containing only lyrics in english. :param file_path: path to the file ... | 3ab84bf20059f21c3f80a35e7d1d289c816b87c9 | <|skeleton|>
class LyricsReader:
def read_english_lyrics_from_file_streaming(file_path):
"""Read lyrics from a file and return an array containing only lyrics in english. :param file_path: path to the file containing the lyrics :return: array of strings containing all english lyrics from the file"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LyricsReader:
def read_english_lyrics_from_file_streaming(file_path):
"""Read lyrics from a file and return an array containing only lyrics in english. :param file_path: path to the file containing the lyrics :return: array of strings containing all english lyrics from the file"""
current_lyri... | the_stack_v2_python_sparse | src/utils/lyrics_reader.py | mdojic/genre-lyrics-classifier | train | 0 | |
3a33bb497ea6281b6ce41d076ce36547b105cb0b | [
"self._trees_num = trees_num\nself._depth = depth\nself._output_logits_dim = output_logits_dim\nself._smooth_step_param = smooth_step_param\nself._parallelize_over_samples = parallelize_over_samples\nself._sum_outputs = sum_outputs\nself._split_initializer = keras.initializers.get(split_initializer)\nself._leaf_ini... | <|body_start_0|>
self._trees_num = trees_num
self._depth = depth
self._output_logits_dim = output_logits_dim
self._smooth_step_param = smooth_step_param
self._parallelize_over_samples = parallelize_over_samples
self._sum_outputs = sum_outputs
self._split_initializ... | A custom layer containing additive differentiable decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only one child) or in a soft way. T... | TEL | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TEL:
"""A custom layer containing additive differentiable decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only... | stack_v2_sparse_classes_36k_train_034008 | 8,204 | permissive | [
{
"docstring": "Initializes neural trees layer.",
"name": "__init__",
"signature": "def __init__(self, output_logits_dim, trees_num=1, depth=3, smooth_step_param=1.0, sum_outputs=True, parallelize_over_samples=False, split_initializer=RandomUniform(-0.01, 0.01), leaf_initializer=RandomUniform(-0.01, 0.0... | 5 | null | Implement the Python class `TEL` described below.
Class description:
A custom layer containing additive differentiable decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be r... | Implement the Python class `TEL` described below.
Class description:
A custom layer containing additive differentiable decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be r... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class TEL:
"""A custom layer containing additive differentiable decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TEL:
"""A custom layer containing additive differentiable decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only one child) o... | the_stack_v2_python_sparse | tf_trees/tel.py | Ayoob7/google-research | train | 2 |
d4a3377e098432ed5a9ab28ef17334c8c08f6e9b | [
"self.dbName = dbName\nself.dbDir = dbDir\nself.dbExtens = dbExtens\nself.scriptref = scriptref\nself.outDir = outDir\nself.nproccomp = nproccomp\nself.saveData = saveData\nself.metric = metric\nself.toprocess = toprocess\nself.nodither = nodither\nself.RA_min = RA_min\nself.RA_max = RA_max\nself.Dec_min = Dec_min\... | <|body_start_0|>
self.dbName = dbName
self.dbDir = dbDir
self.dbExtens = dbExtens
self.scriptref = scriptref
self.outDir = outDir
self.nproccomp = nproccomp
self.saveData = saveData
self.metric = metric
self.toprocess = toprocess
self.nodit... | batchclass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class batchclass:
def __init__(self, dbName, dbDir, dbExtens, scriptref, outDir, nproccomp, saveData, metric, toprocess, nodither, nside, fieldType='WFD', RA_min=0.0, RA_max=360.0, Dec_min=-1.0, Dec_max=-1.0, band='', pixelmap_dir='', npixels=0, npixels_tot=0, proxy_level=-1):
"""class to prep... | stack_v2_sparse_classes_36k_train_034009 | 13,378 | permissive | [
{
"docstring": "class to prepare and launch batches Parameters ---------------- dbName: str observing strategy name dbDir: str location dir of obs. strat. file dbExtens: str obs. strat. file extension (db or npy) scriptref: str reference script to use in the batch outDir: str output directory location nproccomp... | 4 | null | Implement the Python class `batchclass` described below.
Class description:
Implement the batchclass class.
Method signatures and docstrings:
- def __init__(self, dbName, dbDir, dbExtens, scriptref, outDir, nproccomp, saveData, metric, toprocess, nodither, nside, fieldType='WFD', RA_min=0.0, RA_max=360.0, Dec_min=-1.... | Implement the Python class `batchclass` described below.
Class description:
Implement the batchclass class.
Method signatures and docstrings:
- def __init__(self, dbName, dbDir, dbExtens, scriptref, outDir, nproccomp, saveData, metric, toprocess, nodither, nside, fieldType='WFD', RA_min=0.0, RA_max=360.0, Dec_min=-1.... | d42c7490ba5ff8c52f62e70a20c922172a6baff1 | <|skeleton|>
class batchclass:
def __init__(self, dbName, dbDir, dbExtens, scriptref, outDir, nproccomp, saveData, metric, toprocess, nodither, nside, fieldType='WFD', RA_min=0.0, RA_max=360.0, Dec_min=-1.0, Dec_max=-1.0, band='', pixelmap_dir='', npixels=0, npixels_tot=0, proxy_level=-1):
"""class to prep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class batchclass:
def __init__(self, dbName, dbDir, dbExtens, scriptref, outDir, nproccomp, saveData, metric, toprocess, nodither, nside, fieldType='WFD', RA_min=0.0, RA_max=360.0, Dec_min=-1.0, Dec_max=-1.0, band='', pixelmap_dir='', npixels=0, npixels_tot=0, proxy_level=-1):
"""class to prepare and launch... | the_stack_v2_python_sparse | for_batch/scripts/batch_metrics.py | LSSTDESC/sn_pipe | train | 1 | |
4d2e6baa951e353dfb6b831a27fb26a243413e1d | [
"if instance:\n self.send_error(httplib.NOT_FOUND)\nelse:\n self.write({'index': self.application.stores.keys()})",
"if instance in self.application.stores:\n self.set_status(httplib.NO_CONTENT)\n logger.warning('silently ignored store re-creation request: \"{}\"'.format(instance))\nelif self.request.... | <|body_start_0|>
if instance:
self.send_error(httplib.NOT_FOUND)
else:
self.write({'index': self.application.stores.keys()})
<|end_body_0|>
<|body_start_1|>
if instance in self.application.stores:
self.set_status(httplib.NO_CONTENT)
logger.warning... | Handler for GET, PUT, and DELETE for manipulating `Store` instances. | ManagerHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagerHandler:
"""Handler for GET, PUT, and DELETE for manipulating `Store` instances."""
def get(self, instance=None):
"""Access the store index."""
<|body_0|>
def put(self, instance=None):
"""Create a new store named `instance`. If a request body is provided, ... | stack_v2_sparse_classes_36k_train_034010 | 15,544 | no_license | [
{
"docstring": "Access the store index.",
"name": "get",
"signature": "def get(self, instance=None)"
},
{
"docstring": "Create a new store named `instance`. If a request body is provided, it is decoded as a JSON object to specify the parent store. The JSON object must has the structure below. ``... | 3 | stack_v2_sparse_classes_30k_train_017255 | Implement the Python class `ManagerHandler` described below.
Class description:
Handler for GET, PUT, and DELETE for manipulating `Store` instances.
Method signatures and docstrings:
- def get(self, instance=None): Access the store index.
- def put(self, instance=None): Create a new store named `instance`. If a reque... | Implement the Python class `ManagerHandler` described below.
Class description:
Handler for GET, PUT, and DELETE for manipulating `Store` instances.
Method signatures and docstrings:
- def get(self, instance=None): Access the store index.
- def put(self, instance=None): Create a new store named `instance`. If a reque... | 8b633ffca45fdc8861628e31311cd13521643844 | <|skeleton|>
class ManagerHandler:
"""Handler for GET, PUT, and DELETE for manipulating `Store` instances."""
def get(self, instance=None):
"""Access the store index."""
<|body_0|>
def put(self, instance=None):
"""Create a new store named `instance`. If a request body is provided, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManagerHandler:
"""Handler for GET, PUT, and DELETE for manipulating `Store` instances."""
def get(self, instance=None):
"""Access the store index."""
if instance:
self.send_error(httplib.NOT_FOUND)
else:
self.write({'index': self.application.stores.keys()}... | the_stack_v2_python_sparse | src/pensive/server.py | branchvincent/arc-reactor | train | 0 |
96a19ae28090fb7340b0bbe18b3a13d0bb1c170d | [
"user = request.user\ncheck_user_status(user)\nuser_id = user.id\nrestaurant_owner = RestaurantOwner.get_by_user_id(user_id=user_id)\nreturn JsonResponse(model_to_json(restaurant_owner))",
"user = request.user\ncheck_user_status(user)\nuser_id = user.id\nvalidate(instance=request.data, schema=schemas.restaurant_o... | <|body_start_0|>
user = request.user
check_user_status(user)
user_id = user.id
restaurant_owner = RestaurantOwner.get_by_user_id(user_id=user_id)
return JsonResponse(model_to_json(restaurant_owner))
<|end_body_0|>
<|body_start_1|>
user = request.user
check_user_s... | Restaurant Owner view | RestaurantOwnerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestaurantOwnerView:
"""Restaurant Owner view"""
def get(self, request):
"""Retrieves a restaurant owner profile"""
<|body_0|>
def put(self, request):
"""Updates a restaurant owner profile"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = r... | stack_v2_sparse_classes_36k_train_034011 | 3,080 | no_license | [
{
"docstring": "Retrieves a restaurant owner profile",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Updates a restaurant owner profile",
"name": "put",
"signature": "def put(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002924 | Implement the Python class `RestaurantOwnerView` described below.
Class description:
Restaurant Owner view
Method signatures and docstrings:
- def get(self, request): Retrieves a restaurant owner profile
- def put(self, request): Updates a restaurant owner profile | Implement the Python class `RestaurantOwnerView` described below.
Class description:
Restaurant Owner view
Method signatures and docstrings:
- def get(self, request): Retrieves a restaurant owner profile
- def put(self, request): Updates a restaurant owner profile
<|skeleton|>
class RestaurantOwnerView:
"""Resta... | 2707062c9a9a8bb4baca955e8a60ba08cc9f8953 | <|skeleton|>
class RestaurantOwnerView:
"""Restaurant Owner view"""
def get(self, request):
"""Retrieves a restaurant owner profile"""
<|body_0|>
def put(self, request):
"""Updates a restaurant owner profile"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestaurantOwnerView:
"""Restaurant Owner view"""
def get(self, request):
"""Retrieves a restaurant owner profile"""
user = request.user
check_user_status(user)
user_id = user.id
restaurant_owner = RestaurantOwner.get_by_user_id(user_id=user_id)
return JsonR... | the_stack_v2_python_sparse | backend/restaurant_owner/views.py | MochiTarts/Find-Dining-The-Bridge | train | 1 |
995bc8c311521d9f65aacaeba9c2001784cfc421 | [
"super().__init__()\nself.func = func\nself.state = {}",
"if isinstance(args[0], list):\n ys = IdentityLossScalingHook(self.state).apply(tuple(args[0]))\n zs = self.func(ys)\nelse:\n ys = IdentityLossScalingHook(self.state).apply(args)\n zs = self.func(*ys)\nif not isinstance(zs, tuple):\n zs = (zs... | <|body_start_0|>
super().__init__()
self.func = func
self.state = {}
<|end_body_0|>
<|body_start_1|>
if isinstance(args[0], list):
ys = IdentityLossScalingHook(self.state).apply(tuple(args[0]))
zs = self.func(ys)
else:
ys = IdentityLossScaling... | Wraps a function and passes the loss scaling. | IdentityLossScalingWrapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityLossScalingWrapper:
"""Wraps a function and passes the loss scaling."""
def __init__(self, func):
"""func is what to be wrapped."""
<|body_0|>
def forward(self, *args):
"""Passes identical loss scale"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_034012 | 2,036 | permissive | [
{
"docstring": "func is what to be wrapped.",
"name": "__init__",
"signature": "def __init__(self, func)"
},
{
"docstring": "Passes identical loss scale",
"name": "forward",
"signature": "def forward(self, *args)"
}
] | 2 | null | Implement the Python class `IdentityLossScalingWrapper` described below.
Class description:
Wraps a function and passes the loss scaling.
Method signatures and docstrings:
- def __init__(self, func): func is what to be wrapped.
- def forward(self, *args): Passes identical loss scale | Implement the Python class `IdentityLossScalingWrapper` described below.
Class description:
Wraps a function and passes the loss scaling.
Method signatures and docstrings:
- def __init__(self, func): func is what to be wrapped.
- def forward(self, *args): Passes identical loss scale
<|skeleton|>
class IdentityLossSc... | 0ca435433b9953e33656173c4d60ebd61c5c5e87 | <|skeleton|>
class IdentityLossScalingWrapper:
"""Wraps a function and passes the loss scaling."""
def __init__(self, func):
"""func is what to be wrapped."""
<|body_0|>
def forward(self, *args):
"""Passes identical loss scale"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityLossScalingWrapper:
"""Wraps a function and passes the loss scaling."""
def __init__(self, func):
"""func is what to be wrapped."""
super().__init__()
self.func = func
self.state = {}
def forward(self, *args):
"""Passes identical loss scale"""
... | the_stack_v2_python_sparse | ada_loss/chainer_impl/links/identity_loss_scaling.py | MetaVai/gradient-scaling | train | 0 |
e9859f15fc33064f436c41e178854d999408df69 | [
"img = copy.deepcopy(cv2.cvtColor(src, cv2.COLOR_BGR2GRAY))\nsizes = range(5, 2 * scale + 5, 2)\nkernels = map(lambda x: cv2.getGaborKernel(ksize=(x, x), sigma=sigma, theta=direction, lambd=x, gamma=25.0 / x, psi=np.pi * 1 / 2), sizes)\nfor i, kernel in enumerate(kernels):\n kernels[i] = 1.0 * kernel / np.amax(k... | <|body_start_0|>
img = copy.deepcopy(cv2.cvtColor(src, cv2.COLOR_BGR2GRAY))
sizes = range(5, 2 * scale + 5, 2)
kernels = map(lambda x: cv2.getGaborKernel(ksize=(x, x), sigma=sigma, theta=direction, lambd=x, gamma=25.0 / x, psi=np.pi * 1 / 2), sizes)
for i, kernel in enumerate(kernels):
... | ViolaJones | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViolaJones:
def vj_main(self, src, direction, scale, sigma, bias):
"""入力画像に複数のスケールのカーネルを用いてテンプレートマッチングを行う。 そもそもfilterlingじゃなくてTMにする? src: dst: seed scaleの数だけ返す psiは位相"""
<|body_0|>
def get_seed(self, vjmaps, thresh):
"""vjmapsから,種を選択する。 seed_imgとseed_listとそれぞれのscaleを... | stack_v2_sparse_classes_36k_train_034013 | 13,550 | no_license | [
{
"docstring": "入力画像に複数のスケールのカーネルを用いてテンプレートマッチングを行う。 そもそもfilterlingじゃなくてTMにする? src: dst: seed scaleの数だけ返す psiは位相",
"name": "vj_main",
"signature": "def vj_main(self, src, direction, scale, sigma, bias)"
},
{
"docstring": "vjmapsから,種を選択する。 seed_imgとseed_listとそれぞれのscaleを返す。 seed_img : seedにvjmapsの... | 4 | stack_v2_sparse_classes_30k_train_012227 | Implement the Python class `ViolaJones` described below.
Class description:
Implement the ViolaJones class.
Method signatures and docstrings:
- def vj_main(self, src, direction, scale, sigma, bias): 入力画像に複数のスケールのカーネルを用いてテンプレートマッチングを行う。 そもそもfilterlingじゃなくてTMにする? src: dst: seed scaleの数だけ返す psiは位相
- def get_seed(self, v... | Implement the Python class `ViolaJones` described below.
Class description:
Implement the ViolaJones class.
Method signatures and docstrings:
- def vj_main(self, src, direction, scale, sigma, bias): 入力画像に複数のスケールのカーネルを用いてテンプレートマッチングを行う。 そもそもfilterlingじゃなくてTMにする? src: dst: seed scaleの数だけ返す psiは位相
- def get_seed(self, v... | 1d5c534fbc7a5415c9b3f297b41f651e55d88c95 | <|skeleton|>
class ViolaJones:
def vj_main(self, src, direction, scale, sigma, bias):
"""入力画像に複数のスケールのカーネルを用いてテンプレートマッチングを行う。 そもそもfilterlingじゃなくてTMにする? src: dst: seed scaleの数だけ返す psiは位相"""
<|body_0|>
def get_seed(self, vjmaps, thresh):
"""vjmapsから,種を選択する。 seed_imgとseed_listとそれぞれのscaleを... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViolaJones:
def vj_main(self, src, direction, scale, sigma, bias):
"""入力画像に複数のスケールのカーネルを用いてテンプレートマッチングを行う。 そもそもfilterlingじゃなくてTMにする? src: dst: seed scaleの数だけ返す psiは位相"""
img = copy.deepcopy(cv2.cvtColor(src, cv2.COLOR_BGR2GRAY))
sizes = range(5, 2 * scale + 5, 2)
kernels = map(... | the_stack_v2_python_sparse | scripts/etc/small_rock_detection.py | DriesDries/shangri-la | train | 0 | |
36de83eaf8cae08613c6d337aa429e062c4f2b2b | [
"super().__init__(hass, LOGGER, name=f'{DOMAIN} base {base}', update_interval=update_interval)\nself.base = base\nself.client = Client(api_key, session)",
"try:\n async with asyncio.timeout(CLIENT_TIMEOUT):\n latest = await self.client.get_latest(base=self.base)\nexcept OpenExchangeRatesAuthError as err... | <|body_start_0|>
super().__init__(hass, LOGGER, name=f'{DOMAIN} base {base}', update_interval=update_interval)
self.base = base
self.client = Client(api_key, session)
<|end_body_0|>
<|body_start_1|>
try:
async with asyncio.timeout(CLIENT_TIMEOUT):
latest = aw... | Represent a coordinator for Open Exchange Rates API. | OpenexchangeratesCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenexchangeratesCoordinator:
"""Represent a coordinator for Open Exchange Rates API."""
def __init__(self, hass: HomeAssistant, session: ClientSession, api_key: str, base: str, update_interval: timedelta) -> None:
"""Initialize the coordinator."""
<|body_0|>
async def _... | stack_v2_sparse_classes_36k_train_034014 | 1,607 | permissive | [
{
"docstring": "Initialize the coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, session: ClientSession, api_key: str, base: str, update_interval: timedelta) -> None"
},
{
"docstring": "Update data from Open Exchange Rates.",
"name": "_async_update_data... | 2 | null | Implement the Python class `OpenexchangeratesCoordinator` described below.
Class description:
Represent a coordinator for Open Exchange Rates API.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, session: ClientSession, api_key: str, base: str, update_interval: timedelta) -> None: Initializ... | Implement the Python class `OpenexchangeratesCoordinator` described below.
Class description:
Represent a coordinator for Open Exchange Rates API.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, session: ClientSession, api_key: str, base: str, update_interval: timedelta) -> None: Initializ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OpenexchangeratesCoordinator:
"""Represent a coordinator for Open Exchange Rates API."""
def __init__(self, hass: HomeAssistant, session: ClientSession, api_key: str, base: str, update_interval: timedelta) -> None:
"""Initialize the coordinator."""
<|body_0|>
async def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenexchangeratesCoordinator:
"""Represent a coordinator for Open Exchange Rates API."""
def __init__(self, hass: HomeAssistant, session: ClientSession, api_key: str, base: str, update_interval: timedelta) -> None:
"""Initialize the coordinator."""
super().__init__(hass, LOGGER, name=f'{D... | the_stack_v2_python_sparse | homeassistant/components/openexchangerates/coordinator.py | home-assistant/core | train | 35,501 |
42b8ac7ca91354596ffe2993503869dc9408f67a | [
"index = {a: i for i, a in enumerate(A)}\nlongest = defaultdict(lambda: 2)\nans = 0\nfor k, z in enumerate(A):\n for j in range(k):\n i = index.get(z - A[j], None)\n if i is not None and i < j:\n cand = longest[j, k] = longest[i, j] + 1\n ans = max(ans, cand)\nreturn ans if an... | <|body_start_0|>
index = {a: i for i, a in enumerate(A)}
longest = defaultdict(lambda: 2)
ans = 0
for k, z in enumerate(A):
for j in range(k):
i = index.get(z - A[j], None)
if i is not None and i < j:
cand = longest[j, k] = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseq2(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
index = {a: i for i, a in enumerate(A)}
... | stack_v2_sparse_classes_36k_train_034015 | 2,821 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq",
"signature": "def lenLongestFibSubseq(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq2",
"signature": "def lenLongestFibSubseq2(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
- def lenLongestFibSubseq2(self, A): :type A: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
- def lenLongestFibSubseq2(self, A): :type A: List[int] :rtype: int
<|skeleton|>
class Solution:
def lenLon... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseq2(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
index = {a: i for i, a in enumerate(A)}
longest = defaultdict(lambda: 2)
ans = 0
for k, z in enumerate(A):
for j in range(k):
i = index.get(z - A[j], None)
... | the_stack_v2_python_sparse | code873LengthOfLongestFibonacciSubsequence.py | cybelewang/leetcode-python | train | 0 | |
a3ac01b465bcaf541c7789b907369192bae807dd | [
"wm = context.window_manager\nif wm.verse_connected is True and context.scene.subscribed is not False:\n return True\nelse:\n return False",
"scene = context.scene\nlayout = self.layout\nrow = layout.row()\nrow.template_list('VerseObjectUlSlot', 'verse_objects_widget_id', scene, 'verse_objects', scene, 'cur... | <|body_start_0|>
wm = context.window_manager
if wm.verse_connected is True and context.scene.subscribed is not False:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
scene = context.scene
layout = self.layout
row = layout.row()
... | GUI of Blender objects shared at Verse server | VerseObjectPanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerseObjectPanel:
"""GUI of Blender objects shared at Verse server"""
def poll(cls, context):
"""Can be this panel visible"""
<|body_0|>
def draw(self, context):
"""This method draw panel of Verse scenes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_034016 | 18,592 | no_license | [
{
"docstring": "Can be this panel visible",
"name": "poll",
"signature": "def poll(cls, context)"
},
{
"docstring": "This method draw panel of Verse scenes",
"name": "draw",
"signature": "def draw(self, context)"
}
] | 2 | null | Implement the Python class `VerseObjectPanel` described below.
Class description:
GUI of Blender objects shared at Verse server
Method signatures and docstrings:
- def poll(cls, context): Can be this panel visible
- def draw(self, context): This method draw panel of Verse scenes | Implement the Python class `VerseObjectPanel` described below.
Class description:
GUI of Blender objects shared at Verse server
Method signatures and docstrings:
- def poll(cls, context): Can be this panel visible
- def draw(self, context): This method draw panel of Verse scenes
<|skeleton|>
class VerseObjectPanel:
... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class VerseObjectPanel:
"""GUI of Blender objects shared at Verse server"""
def poll(cls, context):
"""Can be this panel visible"""
<|body_0|>
def draw(self, context):
"""This method draw panel of Verse scenes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerseObjectPanel:
"""GUI of Blender objects shared at Verse server"""
def poll(cls, context):
"""Can be this panel visible"""
wm = context.window_manager
if wm.verse_connected is True and context.scene.subscribed is not False:
return True
else:
retu... | the_stack_v2_python_sparse | All_In_One/addons/io_verse/ui_object3d.py | 2434325680/Learnbgame | train | 0 |
5f0aeb7d9f50e5327dc8b797a78e699b363e5e60 | [
"super(SubwordSequencer, self).__init__(maxngrams)\nself.maxngrams = maxngrams\nself.maxwords = maxwords\nself.wordbreaker = CountVectorizer(lowercase=True).build_analyzer()",
"if isinstance(strings, str):\n strings = [strings]\nelse:\n strings = list(strings)\nbuffer = np.zeros((len(strings), self.maxwords... | <|body_start_0|>
super(SubwordSequencer, self).__init__(maxngrams)
self.maxngrams = maxngrams
self.maxwords = maxwords
self.wordbreaker = CountVectorizer(lowercase=True).build_analyzer()
<|end_body_0|>
<|body_start_1|>
if isinstance(strings, str):
strings = [strings]... | To support FastText type encodings, treat text as a series of words, and then break those words into character ngram subwords. Attributes ---------- maxwords: Limit to this number of words. maxngrams: For each word limit to this number of ngrams. features: Total number of unique features, which may allow collisions. wo... | SubwordSequencer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubwordSequencer:
"""To support FastText type encodings, treat text as a series of words, and then break those words into character ngram subwords. Attributes ---------- maxwords: Limit to this number of words. maxngrams: For each word limit to this number of ngrams. features: Total number of uni... | stack_v2_sparse_classes_36k_train_034017 | 6,153 | no_license | [
{
"docstring": "Configure word analysis for character trigrams. Parameters ---------- maxlen : int Limit parsing to this number of words. maxngrams: For each word limit to this number of ngrams.",
"name": "__init__",
"signature": "def __init__(self, maxwords=1024, maxngrams=32)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_012116 | Implement the Python class `SubwordSequencer` described below.
Class description:
To support FastText type encodings, treat text as a series of words, and then break those words into character ngram subwords. Attributes ---------- maxwords: Limit to this number of words. maxngrams: For each word limit to this number o... | Implement the Python class `SubwordSequencer` described below.
Class description:
To support FastText type encodings, treat text as a series of words, and then break those words into character ngram subwords. Attributes ---------- maxwords: Limit to this number of words. maxngrams: For each word limit to this number o... | 6ada50adf63078ba28464c59808234bca3fcc9b7 | <|skeleton|>
class SubwordSequencer:
"""To support FastText type encodings, treat text as a series of words, and then break those words into character ngram subwords. Attributes ---------- maxwords: Limit to this number of words. maxngrams: For each word limit to this number of ngrams. features: Total number of uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubwordSequencer:
"""To support FastText type encodings, treat text as a series of words, and then break those words into character ngram subwords. Attributes ---------- maxwords: Limit to this number of words. maxngrams: For each word limit to this number of ngrams. features: Total number of unique features,... | the_stack_v2_python_sparse | _7_Keras/KerasText/Section 2/vectoria/Sequencers.py | cyrsis/TensorflowPY36CPU | train | 5 |
341a71566b9a7ccdb72765b6112b42e696647dc0 | [
"if architecture not in _OUTPUT_DIM.keys():\n raise ValueError('Architecture {} is not supported.'.format(architecture))\nsuper(GlobalFeatureNet, self).__init__()\ndim = _OUTPUT_DIM[architecture]\nif pretrained:\n net_in = getattr(tf.keras.applications, architecture)(include_top=False, weights='imagenet')\nel... | <|body_start_0|>
if architecture not in _OUTPUT_DIM.keys():
raise ValueError('Architecture {} is not supported.'.format(architecture))
super(GlobalFeatureNet, self).__init__()
dim = _OUTPUT_DIM[architecture]
if pretrained:
net_in = getattr(tf.keras.applications, a... | Instantiates global model for image retrieval. This class implements the [GlobalFeatureNet]( https://arxiv.org/abs/1711.02512) for image retrieval. The model uses a user-defined model as a backbone. | GlobalFeatureNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalFeatureNet:
"""Instantiates global model for image retrieval. This class implements the [GlobalFeatureNet]( https://arxiv.org/abs/1711.02512) for image retrieval. The model uses a user-defined model as a backbone."""
def __init__(self, architecture='ResNet101', pooling='gem', whitening... | stack_v2_sparse_classes_36k_train_034018 | 10,634 | permissive | [
{
"docstring": "GlobalFeatureNet network initialization. Args: architecture: Network backbone. pooling: Pooling method used 'mac'/'spoc'/'gem'. whitening: Bool, whether to use whitening. pretrained: Bool, whether to initialize the network with the weights pretrained on ImageNet. data_root: String, path to the d... | 3 | null | Implement the Python class `GlobalFeatureNet` described below.
Class description:
Instantiates global model for image retrieval. This class implements the [GlobalFeatureNet]( https://arxiv.org/abs/1711.02512) for image retrieval. The model uses a user-defined model as a backbone.
Method signatures and docstrings:
- d... | Implement the Python class `GlobalFeatureNet` described below.
Class description:
Instantiates global model for image retrieval. This class implements the [GlobalFeatureNet]( https://arxiv.org/abs/1711.02512) for image retrieval. The model uses a user-defined model as a backbone.
Method signatures and docstrings:
- d... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class GlobalFeatureNet:
"""Instantiates global model for image retrieval. This class implements the [GlobalFeatureNet]( https://arxiv.org/abs/1711.02512) for image retrieval. The model uses a user-defined model as a backbone."""
def __init__(self, architecture='ResNet101', pooling='gem', whitening... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlobalFeatureNet:
"""Instantiates global model for image retrieval. This class implements the [GlobalFeatureNet]( https://arxiv.org/abs/1711.02512) for image retrieval. The model uses a user-defined model as a backbone."""
def __init__(self, architecture='ResNet101', pooling='gem', whitening=False, pretr... | the_stack_v2_python_sparse | research/delf/delf/python/training/model/global_model.py | jianzhnie/models | train | 2 |
3f8dfc77f05e6e8b8a8c1066a77b50ed5d4bdd7a | [
"chart = None\nif mixed_type:\n if mixed_type == 'MIXED_MAP':\n chart = Mixed([cls.create(each_option, each_dataframe) for each_option, each_dataframe in zip(options, dataframe)])\nelse:\n if options.get('chart_type') == 'MAP_TOPOJSON':\n chart = Choropleth(options, dataframe)\n if options.ge... | <|body_start_0|>
chart = None
if mixed_type:
if mixed_type == 'MIXED_MAP':
chart = Mixed([cls.create(each_option, each_dataframe) for each_option, each_dataframe in zip(options, dataframe)])
else:
if options.get('chart_type') == 'MAP_TOPOJSON':
... | Factory to instantiate the correct chart implementation | ChartFactory | [
"MIT",
"BSD-3-Clause",
"ISC",
"GPL-2.0-only",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChartFactory:
"""Factory to instantiate the correct chart implementation"""
def create(cls, options={'chart_type': 'LINE'}, dataframe=None, mixed_type=None):
"""Factory method"""
<|body_0|>
def select_bar_by_options(options, dataframe):
"""Select the adequate BAR... | stack_v2_sparse_classes_36k_train_034019 | 4,191 | permissive | [
{
"docstring": "Factory method",
"name": "create",
"signature": "def create(cls, options={'chart_type': 'LINE'}, dataframe=None, mixed_type=None)"
},
{
"docstring": "Select the adequate BAR implementation, according to options",
"name": "select_bar_by_options",
"signature": "def select_b... | 3 | stack_v2_sparse_classes_30k_train_005972 | Implement the Python class `ChartFactory` described below.
Class description:
Factory to instantiate the correct chart implementation
Method signatures and docstrings:
- def create(cls, options={'chart_type': 'LINE'}, dataframe=None, mixed_type=None): Factory method
- def select_bar_by_options(options, dataframe): Se... | Implement the Python class `ChartFactory` described below.
Class description:
Factory to instantiate the correct chart implementation
Method signatures and docstrings:
- def create(cls, options={'chart_type': 'LINE'}, dataframe=None, mixed_type=None): Factory method
- def select_bar_by_options(options, dataframe): Se... | 5b5a3f207de80f55857384846bb739fcd17806be | <|skeleton|>
class ChartFactory:
"""Factory to instantiate the correct chart implementation"""
def create(cls, options={'chart_type': 'LINE'}, dataframe=None, mixed_type=None):
"""Factory method"""
<|body_0|>
def select_bar_by_options(options, dataframe):
"""Select the adequate BAR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChartFactory:
"""Factory to instantiate the correct chart implementation"""
def create(cls, options={'chart_type': 'LINE'}, dataframe=None, mixed_type=None):
"""Factory method"""
chart = None
if mixed_type:
if mixed_type == 'MIXED_MAP':
chart = Mixed([c... | the_stack_v2_python_sparse | app/factory/chart.py | smartlab-br/datahub-api | train | 1 |
1ce6e17ec0e401b693a36391a9ea3404ef2050e7 | [
"vrfs = set()\ndisplay_vrfs = set()\nvrf_objects = set()\nall_nos = set()\nobjects = set()\nhostnames = set()\n_ids = set()\ninit_kwargs = {}\nfor definition in input_params:\n device = Device(**definition)\n hostnames.add(device.name)\n _ids.add(device._id)\n objects.add(device)\n all_nos.add(device... | <|body_start_0|>
vrfs = set()
display_vrfs = set()
vrf_objects = set()
all_nos = set()
objects = set()
hostnames = set()
_ids = set()
init_kwargs = {}
for definition in input_params:
device = Device(**definition)
hostnames.a... | Validation model for device configurations. | Devices | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Devices:
"""Validation model for device configurations."""
def __init__(self, input_params: List[Dict]) -> None:
"""Import loaded YAML, initialize per-network definitions. Remove unsupported characters from device names, dynamically set attributes for the devices class. Builds lists ... | stack_v2_sparse_classes_36k_train_034020 | 13,256 | permissive | [
{
"docstring": "Import loaded YAML, initialize per-network definitions. Remove unsupported characters from device names, dynamically set attributes for the devices class. Builds lists of common attributes for easy access in other modules. Arguments: input_params {dict} -- Unvalidated router definitions Returns:... | 2 | null | Implement the Python class `Devices` described below.
Class description:
Validation model for device configurations.
Method signatures and docstrings:
- def __init__(self, input_params: List[Dict]) -> None: Import loaded YAML, initialize per-network definitions. Remove unsupported characters from device names, dynami... | Implement the Python class `Devices` described below.
Class description:
Validation model for device configurations.
Method signatures and docstrings:
- def __init__(self, input_params: List[Dict]) -> None: Import loaded YAML, initialize per-network definitions. Remove unsupported characters from device names, dynami... | 90c179f46ecc58562dbcd9ec6d761075a8699f79 | <|skeleton|>
class Devices:
"""Validation model for device configurations."""
def __init__(self, input_params: List[Dict]) -> None:
"""Import loaded YAML, initialize per-network definitions. Remove unsupported characters from device names, dynamically set attributes for the devices class. Builds lists ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Devices:
"""Validation model for device configurations."""
def __init__(self, input_params: List[Dict]) -> None:
"""Import loaded YAML, initialize per-network definitions. Remove unsupported characters from device names, dynamically set attributes for the devices class. Builds lists of common att... | the_stack_v2_python_sparse | hyperglass/models/config/devices.py | GeeZeeS/hyperglass | train | 0 |
e7328d03f5696e1e2f9556deafc134bada5772aa | [
"if not await get_data_from_req(self.request).samples.has_right(sample_id, self.request['client'], SampleRight.read):\n raise InsufficientRights\ntry:\n sample = await get_data_from_req(self.request).samples.get(sample_id)\nexcept ResourceNotFoundError:\n raise NotFound\nreturn json_response(sample)",
"i... | <|body_start_0|>
if not await get_data_from_req(self.request).samples.has_right(sample_id, self.request['client'], SampleRight.read):
raise InsufficientRights
try:
sample = await get_data_from_req(self.request).samples.get(sample_id)
except ResourceNotFoundError:
... | SampleView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleView:
async def get(self, sample_id: str, /) -> Union[r200[GetSampleResponse], r403, r404]:
"""Get a sample. Fetches the details for a sample. Status Codes: 200: Successful operation 400: Invalid query"""
<|body_0|>
async def patch(self, sample_id: str, /, data: Update... | stack_v2_sparse_classes_36k_train_034021 | 29,048 | permissive | [
{
"docstring": "Get a sample. Fetches the details for a sample. Status Codes: 200: Successful operation 400: Invalid query",
"name": "get",
"signature": "async def get(self, sample_id: str, /) -> Union[r200[GetSampleResponse], r403, r404]"
},
{
"docstring": "Update a sample. Updates a sample usi... | 3 | null | Implement the Python class `SampleView` described below.
Class description:
Implement the SampleView class.
Method signatures and docstrings:
- async def get(self, sample_id: str, /) -> Union[r200[GetSampleResponse], r403, r404]: Get a sample. Fetches the details for a sample. Status Codes: 200: Successful operation ... | Implement the Python class `SampleView` described below.
Class description:
Implement the SampleView class.
Method signatures and docstrings:
- async def get(self, sample_id: str, /) -> Union[r200[GetSampleResponse], r403, r404]: Get a sample. Fetches the details for a sample. Status Codes: 200: Successful operation ... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class SampleView:
async def get(self, sample_id: str, /) -> Union[r200[GetSampleResponse], r403, r404]:
"""Get a sample. Fetches the details for a sample. Status Codes: 200: Successful operation 400: Invalid query"""
<|body_0|>
async def patch(self, sample_id: str, /, data: Update... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleView:
async def get(self, sample_id: str, /) -> Union[r200[GetSampleResponse], r403, r404]:
"""Get a sample. Fetches the details for a sample. Status Codes: 200: Successful operation 400: Invalid query"""
if not await get_data_from_req(self.request).samples.has_right(sample_id, self.requ... | the_stack_v2_python_sparse | virtool/samples/api.py | virtool/virtool | train | 45 | |
71a72a789de5512dded3a006aa6158d210a103f4 | [
"specs = super().getInputSpecification()\nspecs.name = 'quantiletransformer'\nspecs.description = 'transforms the data to fit a given distribution by mapping the data to\\n a uniform distribution and then to the desired distribution.'\ndistType = InputTypes.makeEnumType('outputDist', 'outputDistType', ['normal',... | <|body_start_0|>
specs = super().getInputSpecification()
specs.name = 'quantiletransformer'
specs.description = 'transforms the data to fit a given distribution by mapping the data to\n a uniform distribution and then to the desired distribution.'
distType = InputTypes.makeEnumType('o... | Wrapper of scikit-learn's QuantileTransformer | QuantileTransformer | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuantileTransformer:
"""Wrapper of scikit-learn's QuantileTransformer"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.""... | stack_v2_sparse_classes_36k_train_034022 | 8,927 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Reads... | 3 | null | Implement the Python class `QuantileTransformer` described below.
Class description:
Wrapper of scikit-learn's QuantileTransformer
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.Pa... | Implement the Python class `QuantileTransformer` described below.
Class description:
Wrapper of scikit-learn's QuantileTransformer
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.Pa... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class QuantileTransformer:
"""Wrapper of scikit-learn's QuantileTransformer"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuantileTransformer:
"""Wrapper of scikit-learn's QuantileTransformer"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls."""
spe... | the_stack_v2_python_sparse | ravenframework/TSA/Transformers/Distributions.py | idaholab/raven | train | 201 |
51730c82ff06cb3e69d96796a0cc6d88103dde5d | [
"book = get_edition(book_id)\nif not book.description:\n book.description = book.parent_work.description\ndata = {'book': book, 'form': forms.EditionForm(instance=book)}\nreturn TemplateResponse(request, 'book/edit/edit_book.html', data)",
"book = get_object_or_404(models.Edition, id=book_id)\nform = forms.Edi... | <|body_start_0|>
book = get_edition(book_id)
if not book.description:
book.description = book.parent_work.description
data = {'book': book, 'form': forms.EditionForm(instance=book)}
return TemplateResponse(request, 'book/edit/edit_book.html', data)
<|end_body_0|>
<|body_star... | edit a book | EditBook | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditBook:
"""edit a book"""
def get(self, request, book_id):
"""info about a book"""
<|body_0|>
def post(self, request, book_id):
"""edit a book cool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
book = get_edition(book_id)
if not book... | stack_v2_sparse_classes_36k_train_034023 | 11,818 | no_license | [
{
"docstring": "info about a book",
"name": "get",
"signature": "def get(self, request, book_id)"
},
{
"docstring": "edit a book cool",
"name": "post",
"signature": "def post(self, request, book_id)"
}
] | 2 | null | Implement the Python class `EditBook` described below.
Class description:
edit a book
Method signatures and docstrings:
- def get(self, request, book_id): info about a book
- def post(self, request, book_id): edit a book cool | Implement the Python class `EditBook` described below.
Class description:
edit a book
Method signatures and docstrings:
- def get(self, request, book_id): info about a book
- def post(self, request, book_id): edit a book cool
<|skeleton|>
class EditBook:
"""edit a book"""
def get(self, request, book_id):
... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class EditBook:
"""edit a book"""
def get(self, request, book_id):
"""info about a book"""
<|body_0|>
def post(self, request, book_id):
"""edit a book cool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditBook:
"""edit a book"""
def get(self, request, book_id):
"""info about a book"""
book = get_edition(book_id)
if not book.description:
book.description = book.parent_work.description
data = {'book': book, 'form': forms.EditionForm(instance=book)}
ret... | the_stack_v2_python_sparse | bookwyrm/views/books/edit_book.py | bookwyrm-social/bookwyrm | train | 1,398 |
f4333f44be7d5e17f2981128c8a271053b2d741f | [
"self.OPEN = []\nself.CLOSED = []\nself.initial_state = tree\nself.n_states = n_states\nself.k = k\nself.all_k_pairs = {}\nfor i in range(1, self.k + 1):\n self.all_k_pairs[i] = []",
"open_history = []\nself.OPEN.append(self.initial_state)\nself.CLOSED.append(self.initial_state)\nself.initial_state.update_k_pa... | <|body_start_0|>
self.OPEN = []
self.CLOSED = []
self.initial_state = tree
self.n_states = n_states
self.k = k
self.all_k_pairs = {}
for i in range(1, self.k + 1):
self.all_k_pairs[i] = []
<|end_body_0|>
<|body_start_1|>
open_history = []
... | IteratedWidth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IteratedWidth:
def __init__(self, tree, n_states, k):
"""- OPEN is a list of states discovered but not yet expanded. - CLOSED is a list that includes all states in OPEN and states that have already been expanded."""
<|body_0|>
def run(self):
"""Main routine of the IW... | stack_v2_sparse_classes_36k_train_034024 | 3,736 | no_license | [
{
"docstring": "- OPEN is a list of states discovered but not yet expanded. - CLOSED is a list that includes all states in OPEN and states that have already been expanded.",
"name": "__init__",
"signature": "def __init__(self, tree, n_states, k)"
},
{
"docstring": "Main routine of the IW algorit... | 5 | stack_v2_sparse_classes_30k_train_020208 | Implement the Python class `IteratedWidth` described below.
Class description:
Implement the IteratedWidth class.
Method signatures and docstrings:
- def __init__(self, tree, n_states, k): - OPEN is a list of states discovered but not yet expanded. - CLOSED is a list that includes all states in OPEN and states that h... | Implement the Python class `IteratedWidth` described below.
Class description:
Implement the IteratedWidth class.
Method signatures and docstrings:
- def __init__(self, tree, n_states, k): - OPEN is a list of states discovered but not yet expanded. - CLOSED is a list that includes all states in OPEN and states that h... | 221c60560343e709eea2cfbebdf283845f2f20ea | <|skeleton|>
class IteratedWidth:
def __init__(self, tree, n_states, k):
"""- OPEN is a list of states discovered but not yet expanded. - CLOSED is a list that includes all states in OPEN and states that have already been expanded."""
<|body_0|>
def run(self):
"""Main routine of the IW... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IteratedWidth:
def __init__(self, tree, n_states, k):
"""- OPEN is a list of states discovered but not yet expanded. - CLOSED is a list that includes all states in OPEN and states that have already been expanded."""
self.OPEN = []
self.CLOSED = []
self.initial_state = tree
... | the_stack_v2_python_sparse | IteratedWidth/iterated_width.py | leandrocouto/cant_stop | train | 0 | |
8490fd537ed5d3c28cd597e45f54b5668d6934b4 | [
"super().__init__()\nassert method in ('max', 'avg', 'sum')\nself._method = method",
"assert x.dim() == 3, 'Requires x shape (batch_size x seq_len x feature_dim)'\nb, t = (x.shape[0], x.shape[1])\nif mask is None:\n mask = torch.ones((b, t), dtype=torch.bool)\nif self._method == 'max':\n x[~mask, :] = float... | <|body_start_0|>
super().__init__()
assert method in ('max', 'avg', 'sum')
self._method = method
<|end_body_0|>
<|body_start_1|>
assert x.dim() == 3, 'Requires x shape (batch_size x seq_len x feature_dim)'
b, t = (x.shape[0], x.shape[1])
if mask is None:
mask... | Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored. | MaskedTemporalPooling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskedTemporalPooling:
"""Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored."""
def __init__(self, method: str):
"""method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max va... | stack_v2_sparse_classes_36k_train_034025 | 13,032 | permissive | [
{
"docstring": "method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max value. 'avg': averages valid values in the temporal dimension. 'sum': sums valid values in the temporal dimension. Note if all batch row elements are invalid, the temporal dimension is pooled... | 2 | stack_v2_sparse_classes_30k_train_007569 | Implement the Python class `MaskedTemporalPooling` described below.
Class description:
Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored.
Method signatures and docstrings:
- def __init__(self, method: str): method (str): the method of pooling to use. Option... | Implement the Python class `MaskedTemporalPooling` described below.
Class description:
Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored.
Method signatures and docstrings:
- def __init__(self, method: str): method (str): the method of pooling to use. Option... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class MaskedTemporalPooling:
"""Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored."""
def __init__(self, method: str):
"""method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskedTemporalPooling:
"""Applies temporal pooling operations on masked inputs. For each pooling operation all masked values are ignored."""
def __init__(self, method: str):
"""method (str): the method of pooling to use. Options: 'max': reduces temporal dimension to each valid max value. 'avg': a... | the_stack_v2_python_sparse | pytorchvideo/models/masked_multistream.py | xchani/pytorchvideo | train | 0 |
59ca5f8784bd33817ac726e3d2a96354863e9ee1 | [
"self.conv = conv\nself.scale = scale\nself.out_ch = out_ch",
"net = tensor\nif self.conv is not None:\n net = self.conv(tensor)\n_, h, w, ic = tensor.shape.as_list()\nr = self.scale\nf_h, f_w = (math.floor(h * r), math.floor(w * r))\nnet = tf.reshape(net, [-1, w, h, r, r, self.out_ch])\nnet = tf.transpose(net... | <|body_start_0|>
self.conv = conv
self.scale = scale
self.out_ch = out_ch
<|end_body_0|>
<|body_start_1|>
net = tensor
if self.conv is not None:
net = self.conv(tensor)
_, h, w, ic = tensor.shape.as_list()
r = self.scale
f_h, f_w = (math.floor... | Declare PixelShuffler. | PixelShuffler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelShuffler:
"""Declare PixelShuffler."""
def __init__(self, conv, out_ch, scale):
"""@param conv convolution layer such as encoder. This layer should be able to convert input channels to output channels ** scale. @param out_ch the channels of output want to convert @param scale sc... | stack_v2_sparse_classes_36k_train_034026 | 8,198 | no_license | [
{
"docstring": "@param conv convolution layer such as encoder. This layer should be able to convert input channels to output channels ** scale. @param out_ch the channels of output want to convert @param scale scaling of PixelShuffler",
"name": "__init__",
"signature": "def __init__(self, conv, out_ch, ... | 2 | null | Implement the Python class `PixelShuffler` described below.
Class description:
Declare PixelShuffler.
Method signatures and docstrings:
- def __init__(self, conv, out_ch, scale): @param conv convolution layer such as encoder. This layer should be able to convert input channels to output channels ** scale. @param out_... | Implement the Python class `PixelShuffler` described below.
Class description:
Declare PixelShuffler.
Method signatures and docstrings:
- def __init__(self, conv, out_ch, scale): @param conv convolution layer such as encoder. This layer should be able to convert input channels to output channels ** scale. @param out_... | 0691deb9749e91a23a9eb2b7bab8e83bb1afc732 | <|skeleton|>
class PixelShuffler:
"""Declare PixelShuffler."""
def __init__(self, conv, out_ch, scale):
"""@param conv convolution layer such as encoder. This layer should be able to convert input channels to output channels ** scale. @param out_ch the channels of output want to convert @param scale sc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PixelShuffler:
"""Declare PixelShuffler."""
def __init__(self, conv, out_ch, scale):
"""@param conv convolution layer such as encoder. This layer should be able to convert input channels to output channels ** scale. @param out_ch the channels of output want to convert @param scale scaling of Pixe... | the_stack_v2_python_sparse | tflib/operations.py | derui/painter-tensorflow | train | 0 |
e6ef78007a4e0ed5904b72b50e2d0e941384de24 | [
"super().__init__()\nself.cost_class = cost_class\nself.cost_bbox = cost_bbox\nself.cost_giou = cost_giou\nassert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'",
"bs, num_queries = outputs['pred_logits'].shape[:2]\nout_prob = outputs['pred_logits'].flatten(0, 1).softmax(-1)\nout_bbox ... | <|body_start_0|>
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'
<|end_body_0|>
<|body_start_1|>
bs, num_queries = outputs['pred_logits... | This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (... | HungarianMatcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_36k_train_034027 | 4,250 | permissive | [
{
"docstring": "Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_giou: This is the relative weight of the giou loss of the bounding... | 2 | stack_v2_sparse_classes_30k_train_005369 | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | 3af9fa878e73b6894ce3596450a8d9b89d918ca9 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, wh... | the_stack_v2_python_sparse | models/matcher.py | facebookresearch/detr | train | 12,104 |
892a0febbd6b404751d2300f310c391f04b1673b | [
"self.game = game\nself.menu_width = menu_width\nself.menu_height = menu_height\nif menu_screens == None:\n self.menu_screens = [MenuScreen(screen_width=self.menu_width, screen_height=self.menu_height, screen_name='Main Menu')]\n self.selected_menu_screen = self.menu_screens[0]\nelse:\n self.menu_screens =... | <|body_start_0|>
self.game = game
self.menu_width = menu_width
self.menu_height = menu_height
if menu_screens == None:
self.menu_screens = [MenuScreen(screen_width=self.menu_width, screen_height=self.menu_height, screen_name='Main Menu')]
self.selected_menu_screen... | MenuSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuSystem:
def __init__(self, menu_width, menu_height, menu_screens=None, default_menu_screen_idx=None, game=None):
"""Takes in a list menu screens Requires a index of starting menu screen Has its own associated renderer system in renderer sublib"""
<|body_0|>
def handle_me... | stack_v2_sparse_classes_36k_train_034028 | 2,192 | no_license | [
{
"docstring": "Takes in a list menu screens Requires a index of starting menu screen Has its own associated renderer system in renderer sublib",
"name": "__init__",
"signature": "def __init__(self, menu_width, menu_height, menu_screens=None, default_menu_screen_idx=None, game=None)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_019124 | Implement the Python class `MenuSystem` described below.
Class description:
Implement the MenuSystem class.
Method signatures and docstrings:
- def __init__(self, menu_width, menu_height, menu_screens=None, default_menu_screen_idx=None, game=None): Takes in a list menu screens Requires a index of starting menu screen... | Implement the Python class `MenuSystem` described below.
Class description:
Implement the MenuSystem class.
Method signatures and docstrings:
- def __init__(self, menu_width, menu_height, menu_screens=None, default_menu_screen_idx=None, game=None): Takes in a list menu screens Requires a index of starting menu screen... | 2de7779cbc8a8af63048d2bfbb59fc5ecb29cbb5 | <|skeleton|>
class MenuSystem:
def __init__(self, menu_width, menu_height, menu_screens=None, default_menu_screen_idx=None, game=None):
"""Takes in a list menu screens Requires a index of starting menu screen Has its own associated renderer system in renderer sublib"""
<|body_0|>
def handle_me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MenuSystem:
def __init__(self, menu_width, menu_height, menu_screens=None, default_menu_screen_idx=None, game=None):
"""Takes in a list menu screens Requires a index of starting menu screen Has its own associated renderer system in renderer sublib"""
self.game = game
self.menu_width = ... | the_stack_v2_python_sparse | engine/menu/menu_system.py | Mechasparrow/RogueLike-For-Funz | train | 0 | |
45f9a14b40a5267d1d89f337bfd4211fda452139 | [
"all_mpis = []\nall_modules = []\nall_purposes = []\nfor sub_class in monitor.common.Monitor.__subclasses__():\n all_mpis.append((sub_class.module(sub_class), sub_class.purpose(sub_class)))\n all_modules.append(sub_class.module(sub_class))\n all_purposes.append(sub_class.purpose(sub_class))\nself.get_monit... | <|body_start_0|>
all_mpis = []
all_modules = []
all_purposes = []
for sub_class in monitor.common.Monitor.__subclasses__():
all_mpis.append((sub_class.module(sub_class), sub_class.purpose(sub_class)))
all_modules.append(sub_class.module(sub_class))
all... | The monitor plugin | MPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPI:
"""The monitor plugin"""
def __init__(self):
"""Initialize. :param: None :returns: None :raises: None"""
<|body_0|>
def get_monitors(cls, module=None, purpose=None):
"""Get monitors of 'module' for 'purpose'. :param module(optional): %s :param purpose(option... | stack_v2_sparse_classes_36k_train_034029 | 7,577 | no_license | [
{
"docstring": "Initialize. :param: None :returns: None :raises: None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get monitors of 'module' for 'purpose'. :param module(optional): %s :param purpose(optional): %s :returns list: Success, all found monitors or null :ra... | 5 | stack_v2_sparse_classes_30k_train_011195 | Implement the Python class `MPI` described below.
Class description:
The monitor plugin
Method signatures and docstrings:
- def __init__(self): Initialize. :param: None :returns: None :raises: None
- def get_monitors(cls, module=None, purpose=None): Get monitors of 'module' for 'purpose'. :param module(optional): %s ... | Implement the Python class `MPI` described below.
Class description:
The monitor plugin
Method signatures and docstrings:
- def __init__(self): Initialize. :param: None :returns: None :raises: None
- def get_monitors(cls, module=None, purpose=None): Get monitors of 'module' for 'purpose'. :param module(optional): %s ... | e4f257d00305849b9a52a033651da09412436785 | <|skeleton|>
class MPI:
"""The monitor plugin"""
def __init__(self):
"""Initialize. :param: None :returns: None :raises: None"""
<|body_0|>
def get_monitors(cls, module=None, purpose=None):
"""Get monitors of 'module' for 'purpose'. :param module(optional): %s :param purpose(option... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPI:
"""The monitor plugin"""
def __init__(self):
"""Initialize. :param: None :returns: None :raises: None"""
all_mpis = []
all_modules = []
all_purposes = []
for sub_class in monitor.common.Monitor.__subclasses__():
all_mpis.append((sub_class.module(su... | the_stack_v2_python_sparse | analysis/plugin/plugin.py | hanxinke/A-Tune | train | 0 |
8e22dc5fc37206bed3caa2dc815598852c1a32dd | [
"self.K = len(book_chars)\nself.char_to_ind = {char: i for char, i in zip(book_chars, np.identity(self.K))}\nself.ind_to_char = {i: char for char, i in zip(book_chars, range(self.K))}",
"if type(key) == str:\n return np.array([self.char_to_ind[k] for k in key]).T\nif type(key) == int:\n print(key)\n retu... | <|body_start_0|>
self.K = len(book_chars)
self.char_to_ind = {char: i for char, i in zip(book_chars, np.identity(self.K))}
self.ind_to_char = {i: char for char, i in zip(book_chars, range(self.K))}
<|end_body_0|>
<|body_start_1|>
if type(key) == str:
return np.array([self.ch... | Mapp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mapp:
def __init__(self, book_chars):
"""[Initializes the mapping class.] Arguments: book_chars {[dic]} -- [dictionary of all letters]"""
<|body_0|>
def __getitem__(self, key):
"""[A generic mapper, transforming chars and indexes to hot-encoded vectors and visa-versa... | stack_v2_sparse_classes_36k_train_034030 | 19,053 | no_license | [
{
"docstring": "[Initializes the mapping class.] Arguments: book_chars {[dic]} -- [dictionary of all letters]",
"name": "__init__",
"signature": "def __init__(self, book_chars)"
},
{
"docstring": "[A generic mapper, transforming chars and indexes to hot-encoded vectors and visa-versa.] Arguments... | 2 | null | Implement the Python class `Mapp` described below.
Class description:
Implement the Mapp class.
Method signatures and docstrings:
- def __init__(self, book_chars): [Initializes the mapping class.] Arguments: book_chars {[dic]} -- [dictionary of all letters]
- def __getitem__(self, key): [A generic mapper, transformin... | Implement the Python class `Mapp` described below.
Class description:
Implement the Mapp class.
Method signatures and docstrings:
- def __init__(self, book_chars): [Initializes the mapping class.] Arguments: book_chars {[dic]} -- [dictionary of all letters]
- def __getitem__(self, key): [A generic mapper, transformin... | 26de9802912415f5ecb85b8ede816cd5ede50e7b | <|skeleton|>
class Mapp:
def __init__(self, book_chars):
"""[Initializes the mapping class.] Arguments: book_chars {[dic]} -- [dictionary of all letters]"""
<|body_0|>
def __getitem__(self, key):
"""[A generic mapper, transforming chars and indexes to hot-encoded vectors and visa-versa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mapp:
def __init__(self, book_chars):
"""[Initializes the mapping class.] Arguments: book_chars {[dic]} -- [dictionary of all letters]"""
self.K = len(book_chars)
self.char_to_ind = {char: i for char, i in zip(book_chars, np.identity(self.K))}
self.ind_to_char = {i: char for ch... | the_stack_v2_python_sparse | DD2424-Deep-Learning/Lab4/Code/Harry Potter and the Goblet of Fire/Lab4_basic_code.py | jotix16/Courses | train | 0 | |
2738a587cdebd824e5a118e99e4aefeb834e1e21 | [
"super(SEopt, self).__init__()\nif nonlinearity is None:\n nonlinearity = nn.Sigmoid\nself._reduced_planes = int(inplanes / reduction)\nself.avgpool = nn.AdaptiveAvgPool2d((1, 1))\nself.fc1 = nn.Linear(inplanes, self._reduced_planes)\nself.relu = nn.ReLU(inplace=True)\nself.fc2 = nn.Linear(self._reduced_planes, ... | <|body_start_0|>
super(SEopt, self).__init__()
if nonlinearity is None:
nonlinearity = nn.Sigmoid
self._reduced_planes = int(inplanes / reduction)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc1 = nn.Linear(inplanes, self._reduced_planes)
self.relu = nn.R... | squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd fc recovers channels to c - scale ... | SEopt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEopt:
"""squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd f... | stack_v2_sparse_classes_36k_train_034031 | 20,656 | no_license | [
{
"docstring": "Constructor Args: inplanes: (int) number of input channels reduction: (int) reduction ratio nonlinearity: (nn.Module) non-linearity used in SE module; default = nn.sigmoid",
"name": "__init__",
"signature": "def __init__(self, inplanes, reduction=8, nonlinearity=None)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_001686 | Implement the Python class `SEopt` described below.
Class description:
squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to... | Implement the Python class `SEopt` described below.
Class description:
squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to... | a0c51824b9c4c458918ef9a40a925cd576137d75 | <|skeleton|>
class SEopt:
"""squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEopt:
"""squeeze-and-excitation optimization layer structure: - global pooling > fc > relu > fc > sigmoid > skip connect: scale notes: - global pooling = AdaptiveAvgPool((1,1)) -> reduces fmap dimensions to 1x1 - reduction ratio - 1st fc squeeze channels to c/r, where r = reduction ratio - 2nd fc recovers ch... | the_stack_v2_python_sparse | model/mnasnet.py | baihuaxie/ConvLab | train | 0 |
f4925c088c1a78c3f5e5e35ebba5d6dc528e92d5 | [
"if order is None:\n raise ValueError('Polynomial order cannot be None')\nCenteredBasisFn.__init__(self, **kwargs)\nTimefnCollection.__init__(self)\nself.build(order=order, tau=tau, minorder=minorder)",
"for exp in range(minorder, order + 1):\n if exp == 0:\n fn = Constant(tmin=self.tmin, tmax=self.t... | <|body_start_0|>
if order is None:
raise ValueError('Polynomial order cannot be None')
CenteredBasisFn.__init__(self, **kwargs)
TimefnCollection.__init__(self)
self.build(order=order, tau=tau, minorder=minorder)
<|end_body_0|>
<|body_start_1|>
for exp in range(minord... | Collection of power objects to represent a polynomial. | Polynomial | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Polynomial:
"""Collection of power objects to represent a polynomial."""
def __init__(self, order=None, tau=1, minorder=0, **kwargs):
"""Constructor of a polynomial of specified order."""
<|body_0|>
def build(self, order=None, tau=1, minorder=0):
"""Build the pow... | stack_v2_sparse_classes_36k_train_034032 | 1,827 | permissive | [
{
"docstring": "Constructor of a polynomial of specified order.",
"name": "__init__",
"signature": "def __init__(self, order=None, tau=1, minorder=0, **kwargs)"
},
{
"docstring": "Build the power objects and add it to collection.",
"name": "build",
"signature": "def build(self, order=Non... | 2 | stack_v2_sparse_classes_30k_train_006356 | Implement the Python class `Polynomial` described below.
Class description:
Collection of power objects to represent a polynomial.
Method signatures and docstrings:
- def __init__(self, order=None, tau=1, minorder=0, **kwargs): Constructor of a polynomial of specified order.
- def build(self, order=None, tau=1, minor... | Implement the Python class `Polynomial` described below.
Class description:
Collection of power objects to represent a polynomial.
Method signatures and docstrings:
- def __init__(self, order=None, tau=1, minorder=0, **kwargs): Constructor of a polynomial of specified order.
- def build(self, order=None, tau=1, minor... | d53d6bc102dc4eb1b8d153fad80e10bd12f98029 | <|skeleton|>
class Polynomial:
"""Collection of power objects to represent a polynomial."""
def __init__(self, order=None, tau=1, minorder=0, **kwargs):
"""Constructor of a polynomial of specified order."""
<|body_0|>
def build(self, order=None, tau=1, minorder=0):
"""Build the pow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Polynomial:
"""Collection of power objects to represent a polynomial."""
def __init__(self, order=None, tau=1, minorder=0, **kwargs):
"""Constructor of a polynomial of specified order."""
if order is None:
raise ValueError('Polynomial order cannot be None')
CenteredBas... | the_stack_v2_python_sparse | src/timefn/Polynomial.py | isce-framework/fringe | train | 74 |
5eaaaf7a891fe628366957175dac812bb10f7455 | [
"result = False\nif pRoot1 != None and pRoot2 != None:\n if pRoot1.val == pRoot2.val:\n result = self.same(pRoot1, pRoot2)\n if not result:\n result = self.HasSubtree(pRoot1.left, pRoot2)\n if not result:\n result = self.HasSubtree(pRoot1.right, pRoot2)\nreturn result",
"if pRoot2 ==... | <|body_start_0|>
result = False
if pRoot1 != None and pRoot2 != None:
if pRoot1.val == pRoot2.val:
result = self.same(pRoot1, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.left, pRoot2)
if not result:
result = s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
"""递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点"""
<|body_0|>
def same(self, pRoot1, pRoot2):
"""如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空"""
<|body_1|>
def HasSubtree2(self, pRoot1, pRoot2):
"""非递归实现:判断二叉树B是否为二叉树A的子... | stack_v2_sparse_classes_36k_train_034033 | 4,104 | no_license | [
{
"docstring": "递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点",
"name": "HasSubtree",
"signature": "def HasSubtree(self, pRoot1, pRoot2)"
},
{
"docstring": "如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空",
"name": "same",
"signature": "def same(self, pRoot1, pRoot2)"
},
{
"docstring": "非递归实现:判断二叉树B是否为二叉... | 4 | stack_v2_sparse_classes_30k_train_013085 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def HasSubtree(self, pRoot1, pRoot2): 递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点
- def same(self, pRoot1, pRoot2): 如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空
- def HasSubtree2(self, pRoot1, pRoot... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def HasSubtree(self, pRoot1, pRoot2): 递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点
- def same(self, pRoot1, pRoot2): 如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空
- def HasSubtree2(self, pRoot1, pRoot... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
"""递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点"""
<|body_0|>
def same(self, pRoot1, pRoot2):
"""如果根结点相同,则分别判断左右子结点是否相同,直到二叉树B的子节点为空"""
<|body_1|>
def HasSubtree2(self, pRoot1, pRoot2):
"""非递归实现:判断二叉树B是否为二叉树A的子... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def HasSubtree(self, pRoot1, pRoot2):
"""递归实现:判断二叉树B是否为二叉树A的子结构,首先找到相同根结点"""
result = False
if pRoot1 != None and pRoot2 != None:
if pRoot1.val == pRoot2.val:
result = self.same(pRoot1, pRoot2)
if not result:
result = se... | the_stack_v2_python_sparse | 剑指offer/17.树的子结构.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
a45b53526e266e37d14d480d8b891d8a847fa6b0 | [
"from collections import defaultdict\nself.table = defaultdict(int)\nself.counter = 0",
"self.counter += 1\nl = len(word)\nfor i, char in enumerate(word):\n self.table[l, i, char] |= 1 << self.counter\n self.table[l, i, '.'] |= 1 << self.counter",
"res = None\nl = len(word)\nfor i, char in enumerate(word)... | <|body_start_0|>
from collections import defaultdict
self.table = defaultdict(int)
self.counter = 0
<|end_body_0|>
<|body_start_1|>
self.counter += 1
l = len(word)
for i, char in enumerate(word):
self.table[l, i, char] |= 1 << self.counter
self.ta... | WordDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word i... | stack_v2_sparse_classes_36k_train_034034 | 1,066 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a word into the data structure. :type word: str :rtype: void",
"name": "addWord",
"signature": "def addWord(self, word)"
},
{
"docstring": "Returns... | 3 | null | Implement the Python class `WordDictionary` described below.
Class description:
Implement the WordDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addWord(self, word): Adds a word into the data structure. :type word: str :rtype: void
- def search(sel... | Implement the Python class `WordDictionary` described below.
Class description:
Implement the WordDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addWord(self, word): Adds a word into the data structure. :type word: str :rtype: void
- def search(sel... | 86ec13f47506a2495ab6b6bbb58d4e8b2a21538b | <|skeleton|>
class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
from collections import defaultdict
self.table = defaultdict(int)
self.counter = 0
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
... | the_stack_v2_python_sparse | leetcode/facebook/l300.py | tariqrahiman/pyComPro | train | 0 | |
d0a6a39dd60bea10526e952203637ff086a093e1 | [
"if not email:\n raise ValueError('A user must have an email address!')\nif not email:\n raise ValueError('A user must have a email!')\nemail = self.normalize_email(email)\nuser = self.model(email=email, **kwargs)\nif password:\n user.set_password(password)\nelse:\n user.set_unusable_password()\n use... | <|body_start_0|>
if not email:
raise ValueError('A user must have an email address!')
if not email:
raise ValueError('A user must have a email!')
email = self.normalize_email(email)
user = self.model(email=email, **kwargs)
if password:
user.set... | Model manager for customized user model UserProfile | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
"""Model manager for customized user model UserProfile"""
def create_user(self, email, password, **kwargs):
"""Create a new user profile with no special permissions."""
<|body_0|>
def create_superuser(self, email, password):
"""Create a new su... | stack_v2_sparse_classes_36k_train_034035 | 2,727 | no_license | [
{
"docstring": "Create a new user profile with no special permissions.",
"name": "create_user",
"signature": "def create_user(self, email, password, **kwargs)"
},
{
"docstring": "Create a new super user",
"name": "create_superuser",
"signature": "def create_superuser(self, email, passwor... | 2 | stack_v2_sparse_classes_30k_train_019303 | Implement the Python class `UserProfileManager` described below.
Class description:
Model manager for customized user model UserProfile
Method signatures and docstrings:
- def create_user(self, email, password, **kwargs): Create a new user profile with no special permissions.
- def create_superuser(self, email, passw... | Implement the Python class `UserProfileManager` described below.
Class description:
Model manager for customized user model UserProfile
Method signatures and docstrings:
- def create_user(self, email, password, **kwargs): Create a new user profile with no special permissions.
- def create_superuser(self, email, passw... | dc046f42a4d570abd7837490e41062eb43387816 | <|skeleton|>
class UserProfileManager:
"""Model manager for customized user model UserProfile"""
def create_user(self, email, password, **kwargs):
"""Create a new user profile with no special permissions."""
<|body_0|>
def create_superuser(self, email, password):
"""Create a new su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
"""Model manager for customized user model UserProfile"""
def create_user(self, email, password, **kwargs):
"""Create a new user profile with no special permissions."""
if not email:
raise ValueError('A user must have an email address!')
if not emai... | the_stack_v2_python_sparse | src/usuarios/models.py | overflow/canchas | train | 0 |
6d8964c999013cf9977488687b806acf9a02c107 | [
"shots = 100\ncircuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(final_measure=True)\ntargets = ref_diagonal_gate.diagonal_gate_counts_deterministic(shots)\nresult = execute(circuits, self.SIMULATOR, shots=shots).result()\nself.assertTrue(getattr(result, 'success', False))\nself.compare_counts(result... | <|body_start_0|>
shots = 100
circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(final_measure=True)
targets = ref_diagonal_gate.diagonal_gate_counts_deterministic(shots)
result = execute(circuits, self.SIMULATOR, shots=shots).result()
self.assertTrue(getattr(result... | QasmSimulator additional tests. | QasmDiagonalGateTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QasmDiagonalGateTests:
"""QasmSimulator additional tests."""
def test_diagonal_gate(self):
"""Test simulation with unitary gate circuit instructions."""
<|body_0|>
def test_diagonal_gate_wrapper(self):
"""Test simulation with unitary gate circuit instructions."""... | stack_v2_sparse_classes_36k_train_034036 | 3,511 | permissive | [
{
"docstring": "Test simulation with unitary gate circuit instructions.",
"name": "test_diagonal_gate",
"signature": "def test_diagonal_gate(self)"
},
{
"docstring": "Test simulation with unitary gate circuit instructions.",
"name": "test_diagonal_gate_wrapper",
"signature": "def test_di... | 2 | stack_v2_sparse_classes_30k_train_005742 | Implement the Python class `QasmDiagonalGateTests` described below.
Class description:
QasmSimulator additional tests.
Method signatures and docstrings:
- def test_diagonal_gate(self): Test simulation with unitary gate circuit instructions.
- def test_diagonal_gate_wrapper(self): Test simulation with unitary gate cir... | Implement the Python class `QasmDiagonalGateTests` described below.
Class description:
QasmSimulator additional tests.
Method signatures and docstrings:
- def test_diagonal_gate(self): Test simulation with unitary gate circuit instructions.
- def test_diagonal_gate_wrapper(self): Test simulation with unitary gate cir... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class QasmDiagonalGateTests:
"""QasmSimulator additional tests."""
def test_diagonal_gate(self):
"""Test simulation with unitary gate circuit instructions."""
<|body_0|>
def test_diagonal_gate_wrapper(self):
"""Test simulation with unitary gate circuit instructions."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QasmDiagonalGateTests:
"""QasmSimulator additional tests."""
def test_diagonal_gate(self):
"""Test simulation with unitary gate circuit instructions."""
shots = 100
circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic(final_measure=True)
targets = ref_diagonal... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits/qiskit-aer/qiskit-aer#707/before/qasm_unitary_gate.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
8ebbd73431e72e56461f59a566870a7c621bce95 | [
"super(Unet, self).__init__()\nfeatures = init_features\nself.encoder1 = self._block(in_channels, features)\nself.pool1 = MaxPool2d(kernel_size=2, stride=2)\nself.encoder2 = self._block(features, features * 2)\nself.pool2 = MaxPool2d(kernel_size=2, stride=2)\nself.encoder3 = self._block(features * 2, features * 4)\... | <|body_start_0|>
super(Unet, self).__init__()
features = init_features
self.encoder1 = self._block(in_channels, features)
self.pool1 = MaxPool2d(kernel_size=2, stride=2)
self.encoder2 = self._block(features, features * 2)
self.pool2 = MaxPool2d(kernel_size=2, stride=2)
... | Create ResNet SearchSpace. | Unet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unet:
"""Create ResNet SearchSpace."""
def __init__(self, in_channels=3, out_channels=1, init_features=32):
"""Create layers. :param in_channels: in channel :type in_channels: int :param out_channels: out_channels :type out_channels: int :param init_features: features :type init_feat... | stack_v2_sparse_classes_36k_train_034037 | 3,918 | permissive | [
{
"docstring": "Create layers. :param in_channels: in channel :type in_channels: int :param out_channels: out_channels :type out_channels: int :param init_features: features :type init_features: int",
"name": "__init__",
"signature": "def __init__(self, in_channels=3, out_channels=1, init_features=32)"
... | 3 | null | Implement the Python class `Unet` described below.
Class description:
Create ResNet SearchSpace.
Method signatures and docstrings:
- def __init__(self, in_channels=3, out_channels=1, init_features=32): Create layers. :param in_channels: in channel :type in_channels: int :param out_channels: out_channels :type out_cha... | Implement the Python class `Unet` described below.
Class description:
Create ResNet SearchSpace.
Method signatures and docstrings:
- def __init__(self, in_channels=3, out_channels=1, init_features=32): Create layers. :param in_channels: in channel :type in_channels: int :param out_channels: out_channels :type out_cha... | 52b53582fe7df95d7aacc8425013fd18645d079f | <|skeleton|>
class Unet:
"""Create ResNet SearchSpace."""
def __init__(self, in_channels=3, out_channels=1, init_features=32):
"""Create layers. :param in_channels: in channel :type in_channels: int :param out_channels: out_channels :type out_channels: int :param init_features: features :type init_feat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Unet:
"""Create ResNet SearchSpace."""
def __init__(self, in_channels=3, out_channels=1, init_features=32):
"""Create layers. :param in_channels: in channel :type in_channels: int :param out_channels: out_channels :type out_channels: int :param init_features: features :type init_features: int"""
... | the_stack_v2_python_sparse | vega/networks/unet.py | yiziqi/vega | train | 0 |
377810d07b9d61c9129779459ac6f0ecbb23a903 | [
"file = open(postgap.Globals.DATABASES_DIR + '/GWAS_DB.txt')\nres = [self.get_association(line, diseases, iris) for line in file]\nres = filter(lambda X: X is not None, res)\nlogging.info('\\tFound %i GWAS SNPs associated to diseases (%s) or EFO IDs (%s) in GWAS DB' % (len(res), ', '.join(diseases), ', '.join(iris)... | <|body_start_0|>
file = open(postgap.Globals.DATABASES_DIR + '/GWAS_DB.txt')
res = [self.get_association(line, diseases, iris) for line in file]
res = filter(lambda X: X is not None, res)
logging.info('\tFound %i GWAS SNPs associated to diseases (%s) or EFO IDs (%s) in GWAS DB' % (len(re... | GWAS_DB | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GWAS_DB:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in GWAS_DB Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
<|body_0|>
def get_association(self, line, diseases, iris):
... | stack_v2_sparse_classes_36k_train_034038 | 27,853 | permissive | [
{
"docstring": "Returns all GWAS SNPs associated to a disease in GWAS_DB Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]",
"name": "run",
"signature": "def run(self, diseases, iris)"
},
{
"docstring": "GWAS DB data 1. CHR 2. POS 3. SNPI... | 2 | stack_v2_sparse_classes_30k_train_000250 | Implement the Python class `GWAS_DB` described below.
Class description:
Implement the GWAS_DB class.
Method signatures and docstrings:
- def run(self, diseases, iris): Returns all GWAS SNPs associated to a disease in GWAS_DB Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWA... | Implement the Python class `GWAS_DB` described below.
Class description:
Implement the GWAS_DB class.
Method signatures and docstrings:
- def run(self, diseases, iris): Returns all GWAS SNPs associated to a disease in GWAS_DB Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWA... | d5a2d7b9238347c9a598fa8ac0da8cb737c6b6a6 | <|skeleton|>
class GWAS_DB:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in GWAS_DB Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
<|body_0|>
def get_association(self, line, diseases, iris):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GWAS_DB:
def run(self, diseases, iris):
"""Returns all GWAS SNPs associated to a disease in GWAS_DB Args: * [ string ] (trait descriptions) * [ string ] (trait Ontology IRIs) Returntype: [ GWAS_Association ]"""
file = open(postgap.Globals.DATABASES_DIR + '/GWAS_DB.txt')
res = [self.get... | the_stack_v2_python_sparse | lib/postgap/GWAS.py | Ensembl/postgap | train | 41 | |
976aa770ac9f0c536f90d9c75624ed001447dfc8 | [
"super(AttributeProperty, self).__init__()\nself.instance = instance\nself.attribute = attribute",
"if not hasattr(self.instance, self.attribute):\n raise Exception('Attribute or instance has not been set')\nreturn getattr(self.instance, self.attribute)",
"if not hasattr(self.instance, self.attribute):\n ... | <|body_start_0|>
super(AttributeProperty, self).__init__()
self.instance = instance
self.attribute = attribute
<|end_body_0|>
<|body_start_1|>
if not hasattr(self.instance, self.attribute):
raise Exception('Attribute or instance has not been set')
return getattr(self... | Provides a property that sets and gets attributes from a python object. | AttributeProperty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeProperty:
"""Provides a property that sets and gets attributes from a python object."""
def __init__(self, instance=None, attribute=None):
"""Constructor"""
<|body_0|>
def get(self):
"""Returns the value of the attribute specified by self.attribute onto ... | stack_v2_sparse_classes_36k_train_034039 | 1,578 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, instance=None, attribute=None)"
},
{
"docstring": "Returns the value of the attribute specified by self.attribute onto self.instance. For example, if self.attribute is \"test\" and self.instance is myobj, this wil... | 3 | stack_v2_sparse_classes_30k_test_000753 | Implement the Python class `AttributeProperty` described below.
Class description:
Provides a property that sets and gets attributes from a python object.
Method signatures and docstrings:
- def __init__(self, instance=None, attribute=None): Constructor
- def get(self): Returns the value of the attribute specified by... | Implement the Python class `AttributeProperty` described below.
Class description:
Provides a property that sets and gets attributes from a python object.
Method signatures and docstrings:
- def __init__(self, instance=None, attribute=None): Constructor
- def get(self): Returns the value of the attribute specified by... | 31773128238830d3d335c1915877dc0db56836cd | <|skeleton|>
class AttributeProperty:
"""Provides a property that sets and gets attributes from a python object."""
def __init__(self, instance=None, attribute=None):
"""Constructor"""
<|body_0|>
def get(self):
"""Returns the value of the attribute specified by self.attribute onto ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeProperty:
"""Provides a property that sets and gets attributes from a python object."""
def __init__(self, instance=None, attribute=None):
"""Constructor"""
super(AttributeProperty, self).__init__()
self.instance = instance
self.attribute = attribute
def get(... | the_stack_v2_python_sparse | fp_py/src/main/fruitpunch/attribute_property.py | leolimasa/fruitpunch | train | 0 |
65ca49bce06a7c4c2daad8ba181efe25dd920020 | [
"users = UserModel.query.all()\ndata = {'users': [u.to_json() for u in users]}\nreturn data",
"data = parser.parse_args()\nname = data['name']\npassword = data['password']\nif not UserModel.find_by_name(name):\n try:\n u = UserModel(name=name, password=password)\n u.hashed_password(password)\n ... | <|body_start_0|>
users = UserModel.query.all()
data = {'users': [u.to_json() for u in users]}
return data
<|end_body_0|>
<|body_start_1|>
data = parser.parse_args()
name = data['name']
password = data['password']
if not UserModel.find_by_name(name):
t... | UserResourse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserResourse:
def get(self):
"""hint: curl 127.0.0.1:5000/users -X GET :return: json data with name of users"""
<|body_0|>
def post(self):
"""hint: curl 127.0.0.1:5000/users -X POST -d "name=borko" -d "password=borko" :return: json message"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_034040 | 1,834 | permissive | [
{
"docstring": "hint: curl 127.0.0.1:5000/users -X GET :return: json data with name of users",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "hint: curl 127.0.0.1:5000/users -X POST -d \"name=borko\" -d \"password=borko\" :return: json message",
"name": "post",
"signature... | 2 | stack_v2_sparse_classes_30k_train_003572 | Implement the Python class `UserResourse` described below.
Class description:
Implement the UserResourse class.
Method signatures and docstrings:
- def get(self): hint: curl 127.0.0.1:5000/users -X GET :return: json data with name of users
- def post(self): hint: curl 127.0.0.1:5000/users -X POST -d "name=borko" -d "... | Implement the Python class `UserResourse` described below.
Class description:
Implement the UserResourse class.
Method signatures and docstrings:
- def get(self): hint: curl 127.0.0.1:5000/users -X GET :return: json data with name of users
- def post(self): hint: curl 127.0.0.1:5000/users -X POST -d "name=borko" -d "... | 0e7e20f303b7e5908bee94fff72a2710e0a78283 | <|skeleton|>
class UserResourse:
def get(self):
"""hint: curl 127.0.0.1:5000/users -X GET :return: json data with name of users"""
<|body_0|>
def post(self):
"""hint: curl 127.0.0.1:5000/users -X POST -d "name=borko" -d "password=borko" :return: json message"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserResourse:
def get(self):
"""hint: curl 127.0.0.1:5000/users -X GET :return: json data with name of users"""
users = UserModel.query.all()
data = {'users': [u.to_json() for u in users]}
return data
def post(self):
"""hint: curl 127.0.0.1:5000/users -X POST -d "n... | the_stack_v2_python_sparse | lot_parking/config/user_resourse.py | borko81/flask_sqlalchemy | train | 0 | |
6462764d828bb9c3ff693be233290e524d3f22f6 | [
"user = get_a_user(UserId)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn get_a_user(data=data)",
"user = complete_users(UserId)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn complete_users(data=data)",
"user = delete_user(UserId)\... | <|body_start_0|>
user = get_a_user(UserId)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
<|end_body_0|>
<|body_start_1|>
user = complete_users(UserId)
if not user:
api.abort(404)... | Users | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def get(self, UserId):
"""get a user given its identifier"""
<|body_0|>
def put(self, UserId):
"""Users Updated"""
<|body_1|>
def delete(self, UserId):
"""Users Deleted"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
user... | stack_v2_sparse_classes_36k_train_034041 | 2,487 | no_license | [
{
"docstring": "get a user given its identifier",
"name": "get",
"signature": "def get(self, UserId)"
},
{
"docstring": "Users Updated",
"name": "put",
"signature": "def put(self, UserId)"
},
{
"docstring": "Users Deleted",
"name": "delete",
"signature": "def delete(self,... | 3 | stack_v2_sparse_classes_30k_train_010065 | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def get(self, UserId): get a user given its identifier
- def put(self, UserId): Users Updated
- def delete(self, UserId): Users Deleted | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def get(self, UserId): get a user given its identifier
- def put(self, UserId): Users Updated
- def delete(self, UserId): Users Deleted
<|skeleton|>
class Users:
def get(self, Us... | 4fa4042304ee01cf23ecc81f9c27977fd12c31b9 | <|skeleton|>
class Users:
def get(self, UserId):
"""get a user given its identifier"""
<|body_0|>
def put(self, UserId):
"""Users Updated"""
<|body_1|>
def delete(self, UserId):
"""Users Deleted"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Users:
def get(self, UserId):
"""get a user given its identifier"""
user = get_a_user(UserId)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
def put(self, UserId):
"""Users Upda... | the_stack_v2_python_sparse | main/controller/users_controller.py | Gauravkumar45/Flask-RESTPlus-API | train | 0 | |
609b39ad42b1045a89206a0365bf90a8483d2596 | [
"if obj.source_host.site:\n return obj.source_host.site.site\nreturn 'Pleae assign a site to the bot that sent this event ASAP'",
"actions = super().get_actions(request)\nif 'enable_selected' in actions:\n del actions['enable_selected']\nif 'disable_selected' in actions:\n del actions['disable_selected']... | <|body_start_0|>
if obj.source_host.site:
return obj.source_host.site.site
return 'Pleae assign a site to the bot that sent this event ASAP'
<|end_body_0|>
<|body_start_1|>
actions = super().get_actions(request)
if 'enable_selected' in actions:
del actions['enabl... | admin forms for mail bot log events | MailBotLogEventAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MailBotLogEventAdmin:
"""admin forms for mail bot log events"""
def show_site(self, obj):
"""show the site"""
<|body_0|>
def get_actions(self, request):
"""we don't need no actions for these events, they are controlled entirely by background processes"""
... | stack_v2_sparse_classes_36k_train_034042 | 17,456 | no_license | [
{
"docstring": "show the site",
"name": "show_site",
"signature": "def show_site(self, obj)"
},
{
"docstring": "we don't need no actions for these events, they are controlled entirely by background processes",
"name": "get_actions",
"signature": "def get_actions(self, request)"
}
] | 2 | null | Implement the Python class `MailBotLogEventAdmin` described below.
Class description:
admin forms for mail bot log events
Method signatures and docstrings:
- def show_site(self, obj): show the site
- def get_actions(self, request): we don't need no actions for these events, they are controlled entirely by background ... | Implement the Python class `MailBotLogEventAdmin` described below.
Class description:
admin forms for mail bot log events
Method signatures and docstrings:
- def show_site(self, obj): show the site
- def get_actions(self, request): we don't need no actions for these events, they are controlled entirely by background ... | 08bf0cc90e4d63a84fcd4e35bf5d196430c43319 | <|skeleton|>
class MailBotLogEventAdmin:
"""admin forms for mail bot log events"""
def show_site(self, obj):
"""show the site"""
<|body_0|>
def get_actions(self, request):
"""we don't need no actions for these events, they are controlled entirely by background processes"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MailBotLogEventAdmin:
"""admin forms for mail bot log events"""
def show_site(self, obj):
"""show the site"""
if obj.source_host.site:
return obj.source_host.site.site
return 'Pleae assign a site to the bot that sent this event ASAP'
def get_actions(self, request)... | the_stack_v2_python_sparse | mail_collector/admin.py | PHSAServiceOperationsCenter/PHSA-SOC | train | 0 |
06883f8b7cc9deda5bbdcddd6c269f037751ecca | [
"import collections\ntotal = collections.defaultdict(int)\nfor b in B:\n temp = collections.Counter(b)\n for key in temp:\n total[key] = max(total[key], temp[key])\nresult = []\nfor a in A:\n temp = collections.Counter(a)\n if all([temp[key] >= total[key] for key in total]):\n result.appen... | <|body_start_0|>
import collections
total = collections.defaultdict(int)
for b in B:
temp = collections.Counter(b)
for key in temp:
total[key] = max(total[key], temp[key])
result = []
for a in A:
temp = collections.Counter(a)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordSubsets(self, A, B):
""":type A: List[str] :type B: List[str] :rtype: List[str] 1260 ms"""
<|body_0|>
def wordSubsets_1(self, A, B):
"""260ms :type A: List[str] :type B: List[str] :rtype: List[str] 主要差异在all可能会计算所有之后再判断,而这个算到不满足就跳出"""
<|body_... | stack_v2_sparse_classes_36k_train_034043 | 3,366 | no_license | [
{
"docstring": ":type A: List[str] :type B: List[str] :rtype: List[str] 1260 ms",
"name": "wordSubsets",
"signature": "def wordSubsets(self, A, B)"
},
{
"docstring": "260ms :type A: List[str] :type B: List[str] :rtype: List[str] 主要差异在all可能会计算所有之后再判断,而这个算到不满足就跳出",
"name": "wordSubsets_1",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSubsets(self, A, B): :type A: List[str] :type B: List[str] :rtype: List[str] 1260 ms
- def wordSubsets_1(self, A, B): 260ms :type A: List[str] :type B: List[str] :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSubsets(self, A, B): :type A: List[str] :type B: List[str] :rtype: List[str] 1260 ms
- def wordSubsets_1(self, A, B): 260ms :type A: List[str] :type B: List[str] :rtype: ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def wordSubsets(self, A, B):
""":type A: List[str] :type B: List[str] :rtype: List[str] 1260 ms"""
<|body_0|>
def wordSubsets_1(self, A, B):
"""260ms :type A: List[str] :type B: List[str] :rtype: List[str] 主要差异在all可能会计算所有之后再判断,而这个算到不满足就跳出"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordSubsets(self, A, B):
""":type A: List[str] :type B: List[str] :rtype: List[str] 1260 ms"""
import collections
total = collections.defaultdict(int)
for b in B:
temp = collections.Counter(b)
for key in temp:
total[key] = m... | the_stack_v2_python_sparse | WordSubsets_MID_916.py | 953250587/leetcode-python | train | 2 | |
0305fb0d454ed58c554b012b4db6fb1813ecee58 | [
"if model is SyncQueue:\n return SYNC_QUEUE\nreturn None",
"if model is SyncQueue:\n return SYNC_QUEUE\nreturn None",
"if obj1._meta.model is SyncQueue and obj2._meta.model is SyncQueue:\n return True\nelif SyncQueue not in [obj1._meta.model, obj2._meta.model]:\n return None\nreturn False",
"if ap... | <|body_start_0|>
if model is SyncQueue:
return SYNC_QUEUE
return None
<|end_body_0|>
<|body_start_1|>
if model is SyncQueue:
return SYNC_QUEUE
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.model is SyncQueue and obj2._meta.model is SyncQueue:... | Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database. | SyncQueueRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncQueueRouter:
"""Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on the SyncQueue model to SYNC_QUEUE."""
<|body_0|>
def db_fo... | stack_v2_sparse_classes_36k_train_034044 | 18,207 | permissive | [
{
"docstring": "Send all read operations on the SyncQueue model to SYNC_QUEUE.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Send all write operations on the SyncQueue model to SYNC_QUEUE.",
"name": "db_for_write",
"signature": "def db_f... | 4 | stack_v2_sparse_classes_30k_train_003252 | Implement the Python class `SyncQueueRouter` described below.
Class description:
Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on the SyncQueue ... | Implement the Python class `SyncQueueRouter` described below.
Class description:
Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on the SyncQueue ... | cc9da2a6acd139acac3cd71c4cb05c15d4465712 | <|skeleton|>
class SyncQueueRouter:
"""Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on the SyncQueue model to SYNC_QUEUE."""
<|body_0|>
def db_fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SyncQueueRouter:
"""Determine how to route database calls for the SyncQueue model. All other models will be routed to the default database."""
def db_for_read(self, model, **hints):
"""Send all read operations on the SyncQueue model to SYNC_QUEUE."""
if model is SyncQueue:
ret... | the_stack_v2_python_sparse | kolibri/core/device/models.py | learningequality/kolibri | train | 689 |
b7dc81606048cf0d1afa32129aa5a1b5b32f79f8 | [
"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... | Missing associated documentation comment in .proto file. | DatasetFeedServicer | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetFeedServicer:
"""Missing associated documentation comment in .proto file."""
def get_examples(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def shutdown(self, request, context):
"""Missing associated doc... | stack_v2_sparse_classes_36k_train_034045 | 3,867 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_examples",
"signature": "def get_examples(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "shutdown",
"signature": "def shutdown(self, re... | 2 | stack_v2_sparse_classes_30k_train_006285 | Implement the Python class `DatasetFeedServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def get_examples(self, request, context): Missing associated documentation comment in .proto file.
- def shutdown(self, request, context): M... | Implement the Python class `DatasetFeedServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def get_examples(self, request, context): Missing associated documentation comment in .proto file.
- def shutdown(self, request, context): M... | 43dae4b28531cde167598f104f582168b0a4141f | <|skeleton|>
class DatasetFeedServicer:
"""Missing associated documentation comment in .proto file."""
def get_examples(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def shutdown(self, request, context):
"""Missing associated doc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetFeedServicer:
"""Missing associated documentation comment in .proto file."""
def get_examples(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!... | the_stack_v2_python_sparse | training/heterogeneous-clusters/pt.grpc.sagemaker/code/dataset_feed_pb2_grpc.py | aws/amazon-sagemaker-examples | train | 4,797 |
2b87986897b4c1a914fc6d44e0fd0a9501f56877 | [
"self.split_by_sentence = split_by_sentence\nself.eol = end_of_line_token\ntrain_path = self.PTB_URL + 'train.txt'\nval_path = self.PTB_URL + 'valid.txt'\ntest_path = self.PTB_URL + 'test.txt'\ntrain = self._process(requests.get(train_path).content)\nval = self._process(requests.get(val_path).content)\ntest = self.... | <|body_start_0|>
self.split_by_sentence = split_by_sentence
self.eol = end_of_line_token
train_path = self.PTB_URL + 'train.txt'
val_path = self.PTB_URL + 'valid.txt'
test_path = self.PTB_URL + 'test.txt'
train = self._process(requests.get(train_path).content)
val... | The official PTB dataset. | PTBDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PTBDataset:
"""The official PTB dataset."""
def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the PTBDataset builtin. Parameters ---------- split_by_sent... | stack_v2_sparse_classes_36k_train_034046 | 6,879 | permissive | [
{
"docstring": "Initialize the PTBDataset builtin. Parameters ---------- split_by_sentence: bool, Optional If true, tokenizes per sentence. Default ``False``. end_of_line_token: str, Optional Token added at the end of every line. see TabularDataset for other arguments.",
"name": "__init__",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_015567 | Implement the Python class `PTBDataset` described below.
Class description:
The official PTB dataset.
Method signatures and docstrings:
- def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None: Initialize th... | Implement the Python class `PTBDataset` described below.
Class description:
The official PTB dataset.
Method signatures and docstrings:
- def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None: Initialize th... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class PTBDataset:
"""The official PTB dataset."""
def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the PTBDataset builtin. Parameters ---------- split_by_sent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PTBDataset:
"""The official PTB dataset."""
def __init__(self, split_by_sentence: bool=False, end_of_line_token: Optional[str]='<eol>', cache: bool=False, transform: Dict[str, Union[Field, Dict]]=None) -> None:
"""Initialize the PTBDataset builtin. Parameters ---------- split_by_sentence: bool, O... | the_stack_v2_python_sparse | flambe/nlp/language_modeling/datasets.py | cle-ros/flambe | train | 1 |
371886ac69563f5777787774a92f074d2fdaa20f | [
"self._readCommonHeader()\nself.DX = nappy.utils.text_parser.readItemsFromLine(self.file.readline(), self.NIV, float)\nself.DX.reverse()\nself.XNAME = nappy.utils.text_parser.readItemsFromLines(self._readLines(self.NIV), self.NIV, str)\nself.XNAME.reverse()\nself._readVariablesHeaderSection()\nself._readAuxVariable... | <|body_start_0|>
self._readCommonHeader()
self.DX = nappy.utils.text_parser.readItemsFromLine(self.file.readline(), self.NIV, float)
self.DX.reverse()
self.XNAME = nappy.utils.text_parser.readItemsFromLines(self._readLines(self.NIV), self.NIV, str)
self.XNAME.reverse()
se... | Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 2110. | NAFile2110 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NAFile2110:
"""Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 2110."""
def readHeader(self):
"""Reads FFI-specifc header section."""
<|body_0|>
def writeHeader(self):
"""Writes FFI-specific header section."""
... | stack_v2_sparse_classes_36k_train_034047 | 5,018 | permissive | [
{
"docstring": "Reads FFI-specifc header section.",
"name": "readHeader",
"signature": "def readHeader(self)"
},
{
"docstring": "Writes FFI-specific header section.",
"name": "writeHeader",
"signature": "def writeHeader(self)"
},
{
"docstring": "Sets up FFI-specific arrays to fil... | 6 | stack_v2_sparse_classes_30k_train_019490 | Implement the Python class `NAFile2110` described below.
Class description:
Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 2110.
Method signatures and docstrings:
- def readHeader(self): Reads FFI-specifc header section.
- def writeHeader(self): Writes FFI-specific he... | Implement the Python class `NAFile2110` described below.
Class description:
Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 2110.
Method signatures and docstrings:
- def readHeader(self): Reads FFI-specifc header section.
- def writeHeader(self): Writes FFI-specific he... | 71e42a91112f52eef86183e35129b9ee2019e55b | <|skeleton|>
class NAFile2110:
"""Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 2110."""
def readHeader(self):
"""Reads FFI-specifc header section."""
<|body_0|>
def writeHeader(self):
"""Writes FFI-specific header section."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NAFile2110:
"""Class to read, write and interact with NASA Ames files conforming to the File Format Index (FFI) 2110."""
def readHeader(self):
"""Reads FFI-specifc header section."""
self._readCommonHeader()
self.DX = nappy.utils.text_parser.readItemsFromLine(self.file.readline(),... | the_stack_v2_python_sparse | nappy/na_file/na_file_2110.py | cedadev/nappy | train | 9 |
2be866b765d97b151da286ee113080d9177bf2c5 | [
"self.keyToFreq = {}\nself.freqToKeyValue = defaultdict(OrderedDict)\nself.capacity = capacity\nself.minFreq = 1",
"if key not in self.keyToFreq:\n return -1\nif len(self.freqToKeyValue[self.keyToFreq[key]]) == 1 and self.keyToFreq[key] == self.minFreq:\n self.minFreq = self.keyToFreq[key] + 1\nfreq = self.... | <|body_start_0|>
self.keyToFreq = {}
self.freqToKeyValue = defaultdict(OrderedDict)
self.capacity = capacity
self.minFreq = 1
<|end_body_0|>
<|body_start_1|>
if key not in self.keyToFreq:
return -1
if len(self.freqToKeyValue[self.keyToFreq[key]]) == 1 and sel... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
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_36k_train_034048 | 3,574 | 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_018449 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache 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 `LFUCache` described below.
Class description:
Implement the LFUCache 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... | ea3e6aa7efd570e6a2a32b269198027ccf1d6a3b | <|skeleton|>
class LFUCache:
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_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.keyToFreq = {}
self.freqToKeyValue = defaultdict(OrderedDict)
self.capacity = capacity
self.minFreq = 1
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.ke... | the_stack_v2_python_sparse | Python/HashTablePlusList/LfuCache.py | DreamOfTheRedChamber/leetcode | train | 51 | |
9b2cac6bbb261194b97e49dfa1bcb6530e094884 | [
"super(BASNET, self).__init__(n_channels=3, n_classes=1)\nself.device = device\nself.batch_size = batch_size\nif isinstance(input_image_size, list):\n self.input_image_size = input_image_size[:2]\nelse:\n self.input_image_size = (input_image_size, input_image_size)\nself.to(device)\nif load_pretrained:\n s... | <|body_start_0|>
super(BASNET, self).__init__(n_channels=3, n_classes=1)
self.device = device
self.batch_size = batch_size
if isinstance(input_image_size, list):
self.input_image_size = input_image_size[:2]
else:
self.input_image_size = (input_image_size, ... | BASNet model interface | BASNET | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BASNET:
"""BASNet model interface"""
def __init__(self, device='cpu', input_image_size: Union[List[int], int]=320, batch_size: int=10, load_pretrained: bool=True, fp16: bool=False):
"""Initialize the BASNET model Args: device: processing device input_image_size: input image size batc... | stack_v2_sparse_classes_36k_train_034049 | 4,874 | permissive | [
{
"docstring": "Initialize the BASNET model Args: device: processing device input_image_size: input image size batch_size: the number of images that the neural network processes in one run load_pretrained: loading pretrained model fp16: use fp16 precision // not supported at this moment",
"name": "__init__"... | 4 | stack_v2_sparse_classes_30k_train_017384 | Implement the Python class `BASNET` described below.
Class description:
BASNet model interface
Method signatures and docstrings:
- def __init__(self, device='cpu', input_image_size: Union[List[int], int]=320, batch_size: int=10, load_pretrained: bool=True, fp16: bool=False): Initialize the BASNET model Args: device: ... | Implement the Python class `BASNET` described below.
Class description:
BASNet model interface
Method signatures and docstrings:
- def __init__(self, device='cpu', input_image_size: Union[List[int], int]=320, batch_size: int=10, load_pretrained: bool=True, fp16: bool=False): Initialize the BASNET model Args: device: ... | 2935e4655d2c0260195e22ac08af6c43b5969fdd | <|skeleton|>
class BASNET:
"""BASNet model interface"""
def __init__(self, device='cpu', input_image_size: Union[List[int], int]=320, batch_size: int=10, load_pretrained: bool=True, fp16: bool=False):
"""Initialize the BASNET model Args: device: processing device input_image_size: input image size batc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BASNET:
"""BASNet model interface"""
def __init__(self, device='cpu', input_image_size: Union[List[int], int]=320, batch_size: int=10, load_pretrained: bool=True, fp16: bool=False):
"""Initialize the BASNET model Args: device: processing device input_image_size: input image size batch_size: the n... | the_stack_v2_python_sparse | carvekit/ml/wrap/basnet.py | OPHoperHPO/image-background-remove-tool | train | 1,029 |
507c5b05644f68ecb1f3caa663836e6a1e84b4d6 | [
"self.cur_sent = ''\nself.trie = Trie()\nfor sentence, time in zip(sentences, times):\n self.trie.insert(sentence, time)",
"if c == '#':\n self.trie.insert(self.cur_sent, 1)\n self.cur_sent = ''\n return []\nresults = []\nself.cur_sent += c\nresults = self.trie.lookup(self.cur_sent)\nresults.sort()\nr... | <|body_start_0|>
self.cur_sent = ''
self.trie = Trie()
for sentence, time in zip(sentences, times):
self.trie.insert(sentence, time)
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.trie.insert(self.cur_sent, 1)
self.cur_sent = ''
return ... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.cur_sent = ''
... | stack_v2_sparse_classes_36k_train_034050 | 2,141 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | c08fdd1556b6dbbdda8ad6210aa0eaa97074ae3b | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.cur_sent = ''
self.trie = Trie()
for sentence, time in zip(sentences, times):
self.trie.insert(sentence, time)
def input(self, c):
"""... | the_stack_v2_python_sparse | python/review/str_auto_complete_trie.py | sumitkrm/lang-1 | train | 0 | |
927b204d4c01368f82f4daa91f881857a877aaf8 | [
"self.testcase_paths = testcase_paths\nself.verbose = verbose\nif checker == None:\n self.checker = lambda *_: True\nelse:\n self.checker = checker",
"delete_q = []\nfor testcase in testcases:\n metadata_files = nh.get_metadata_files(testcase)\n delete_q += metadata_files.values()\n placeholder_f =... | <|body_start_0|>
self.testcase_paths = testcase_paths
self.verbose = verbose
if checker == None:
self.checker = lambda *_: True
else:
self.checker = checker
<|end_body_0|>
<|body_start_1|>
delete_q = []
for testcase in testcases:
metad... | @class DedupEngine @brief Performs deduplication on files | DedupEngine | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DedupEngine:
"""@class DedupEngine @brief Performs deduplication on files"""
def __init__(self, testcase_paths, verbose, checker=None):
"""@brief create a DedupEngine object @param testcase_path List of path pointing to testcases to deduplicate @param checker Function that maps a fil... | stack_v2_sparse_classes_36k_train_034051 | 2,774 | permissive | [
{
"docstring": "@brief create a DedupEngine object @param testcase_path List of path pointing to testcases to deduplicate @param checker Function that maps a filename to a boolean indicating if that case should be processed, default: None",
"name": "__init__",
"signature": "def __init__(self, testcase_p... | 3 | stack_v2_sparse_classes_30k_train_012450 | Implement the Python class `DedupEngine` described below.
Class description:
@class DedupEngine @brief Performs deduplication on files
Method signatures and docstrings:
- def __init__(self, testcase_paths, verbose, checker=None): @brief create a DedupEngine object @param testcase_path List of path pointing to testcas... | Implement the Python class `DedupEngine` described below.
Class description:
@class DedupEngine @brief Performs deduplication on files
Method signatures and docstrings:
- def __init__(self, testcase_paths, verbose, checker=None): @brief create a DedupEngine object @param testcase_path List of path pointing to testcas... | 4318d1daf2720a2164ca609ca35f7e33dd312e91 | <|skeleton|>
class DedupEngine:
"""@class DedupEngine @brief Performs deduplication on files"""
def __init__(self, testcase_paths, verbose, checker=None):
"""@brief create a DedupEngine object @param testcase_path List of path pointing to testcases to deduplicate @param checker Function that maps a fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DedupEngine:
"""@class DedupEngine @brief Performs deduplication on files"""
def __init__(self, testcase_paths, verbose, checker=None):
"""@brief create a DedupEngine object @param testcase_path List of path pointing to testcases to deduplicate @param checker Function that maps a filename to a bo... | the_stack_v2_python_sparse | src/pmfuzz/core/dedupengine.py | Brokenice0415/pmfuzz | train | 0 |
816e186e6055271ac2835763078c42f718656f02 | [
"if filters is None:\n filters = {}\norm_filters = super(SpecialResource, self).build_filters(filters)\nquery = filters.get('q')\ncategory_pk = filters.get('catpk')\nif query is not None:\n sqs = SearchQuerySet().models(Special).load_all().auto_query(query)\n orm_filters['pk__in'] = [i.pk for i in sqs]\nif... | <|body_start_0|>
if filters is None:
filters = {}
orm_filters = super(SpecialResource, self).build_filters(filters)
query = filters.get('q')
category_pk = filters.get('catpk')
if query is not None:
sqs = SearchQuerySet().models(Special).load_all().auto_que... | SpecialResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecialResource:
def build_filters(self, filters=None):
"""Custom filters used for category and searching."""
<|body_0|>
def dehydrate(self, bundle):
"""If idonly is specified as a flag, the bundle will be reduced to just the resource id."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_034052 | 1,770 | no_license | [
{
"docstring": "Custom filters used for category and searching.",
"name": "build_filters",
"signature": "def build_filters(self, filters=None)"
},
{
"docstring": "If idonly is specified as a flag, the bundle will be reduced to just the resource id.",
"name": "dehydrate",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_013470 | Implement the Python class `SpecialResource` described below.
Class description:
Implement the SpecialResource class.
Method signatures and docstrings:
- def build_filters(self, filters=None): Custom filters used for category and searching.
- def dehydrate(self, bundle): If idonly is specified as a flag, the bundle w... | Implement the Python class `SpecialResource` described below.
Class description:
Implement the SpecialResource class.
Method signatures and docstrings:
- def build_filters(self, filters=None): Custom filters used for category and searching.
- def dehydrate(self, bundle): If idonly is specified as a flag, the bundle w... | 3ed85e856a026001a1d91d09d31d944c64704824 | <|skeleton|>
class SpecialResource:
def build_filters(self, filters=None):
"""Custom filters used for category and searching."""
<|body_0|>
def dehydrate(self, bundle):
"""If idonly is specified as a flag, the bundle will be reduced to just the resource id."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecialResource:
def build_filters(self, filters=None):
"""Custom filters used for category and searching."""
if filters is None:
filters = {}
orm_filters = super(SpecialResource, self).build_filters(filters)
query = filters.get('q')
category_pk = filters.ge... | the_stack_v2_python_sparse | scenable/specials/api.py | gregarious/betasite | train | 0 | |
d9bb81a4c648ca92f8e753db6a63f96372010783 | [
"path = os.path.join(URDF_ROOT, self.filepath)\norn = pybullet.getQuaternionFromEuler(self.orientation)\ncollisionScale = self.scale\nself.visualShapeId = physics.createVisualShape(shapeType=pybullet.GEOM_MESH, fileName=path, rgbaColor=self.rgbaColor, specularColor=self.specularColor, visualFramePosition=self.shift... | <|body_start_0|>
path = os.path.join(URDF_ROOT, self.filepath)
orn = pybullet.getQuaternionFromEuler(self.orientation)
collisionScale = self.scale
self.visualShapeId = physics.createVisualShape(shapeType=pybullet.GEOM_MESH, fileName=path, rgbaColor=self.rgbaColor, specularColor=self.spec... | PhysicsObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhysicsObject:
def __init__(self, physics, position, orientation, visual_only=True):
"""Create a new object at position and orientation"""
<|body_0|>
def move(self, X, Y, Z, orientation=None):
"""Move an object to position X,Y,Z in the global coordinate system Vertic... | stack_v2_sparse_classes_36k_train_034053 | 5,491 | permissive | [
{
"docstring": "Create a new object at position and orientation",
"name": "__init__",
"signature": "def __init__(self, physics, position, orientation, visual_only=True)"
},
{
"docstring": "Move an object to position X,Y,Z in the global coordinate system Vertical position and orientation are not ... | 3 | stack_v2_sparse_classes_30k_val_000009 | Implement the Python class `PhysicsObject` described below.
Class description:
Implement the PhysicsObject class.
Method signatures and docstrings:
- def __init__(self, physics, position, orientation, visual_only=True): Create a new object at position and orientation
- def move(self, X, Y, Z, orientation=None): Move ... | Implement the Python class `PhysicsObject` described below.
Class description:
Implement the PhysicsObject class.
Method signatures and docstrings:
- def __init__(self, physics, position, orientation, visual_only=True): Create a new object at position and orientation
- def move(self, X, Y, Z, orientation=None): Move ... | 6eed945af797f164dddd0d69a7f47183b621db22 | <|skeleton|>
class PhysicsObject:
def __init__(self, physics, position, orientation, visual_only=True):
"""Create a new object at position and orientation"""
<|body_0|>
def move(self, X, Y, Z, orientation=None):
"""Move an object to position X,Y,Z in the global coordinate system Vertic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhysicsObject:
def __init__(self, physics, position, orientation, visual_only=True):
"""Create a new object at position and orientation"""
path = os.path.join(URDF_ROOT, self.filepath)
orn = pybullet.getQuaternionFromEuler(self.orientation)
collisionScale = self.scale
s... | the_stack_v2_python_sparse | src/simulator/sim/simulation/environment/simulation_objects.py | maxkferg/point-cloud-buffers | train | 8 | |
74d8c37775bcba9cac2315c1d7f9a27e52f89daf | [
"needed_size = 2 * length - 1\nif hasattr(self, 'pe') and self.pe.size(1) >= needed_size:\n return\npositions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1)\nself.create_pe(positions=positions)",
"if self.xscale:\n x = x * self.xscale\ninput_len = x.size(1) + cache_... | <|body_start_0|>
needed_size = 2 * length - 1
if hasattr(self, 'pe') and self.pe.size(1) >= needed_size:
return
positions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1)
self.create_pe(positions=positions)
<|end_body_0|>
<|body_start_... | Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_model) dropout_rate_emb (float): dropout rate for the... | RelPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_mode... | stack_v2_sparse_classes_36k_train_034054 | 45,820 | permissive | [
{
"docstring": "Reset and extend the positional encodings if needed.",
"name": "extend_pe",
"signature": "def extend_pe(self, length, device)"
},
{
"docstring": "Compute positional encoding. Args: x (torch.Tensor): Input. Its shape is (batch, time, feature_size) cache_len (int): the size of the ... | 2 | stack_v2_sparse_classes_30k_train_006636 | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): wh... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): wh... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding for TransformerXL's layers See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): embedding dim dropout_rate (float): dropout rate max_len (int): maximum input length xscale (bool): whether to scale the input by sqrt(d_model) dropout_ra... | the_stack_v2_python_sparse | nemo/collections/asr/parts/submodules/multi_head_attention.py | NVIDIA/NeMo | train | 7,957 |
91425c5d7ce527039483f69d6551b7de3bc112bc | [
"longsentence = ' '.join(['word'] * 20) + ' lastword'\nsentence = create_dummy_sentence(longsentence)\nsentence_id = int(str(sentence).split(':')[0])\nstring_representation = str(sentence).split(':')[1].strip()\nself.assertEqual(len(string_representation.split()), 20, msg='The sentence chopper failed to ... | <|body_start_0|>
longsentence = ' '.join(['word'] * 20) + ' lastword'
sentence = create_dummy_sentence(longsentence)
sentence_id = int(str(sentence).split(':')[0])
string_representation = str(sentence).split(':')[1].strip()
self.assertEqual(len(string_representation.split()), 20,... | SentenceTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentenceTests:
def test_longsentence_chopping(self):
"""Make sure that the shortening of the sentence text for the string representation of the object works properly"""
<|body_0|>
def test_shortsentence_chopping(self):
"""Make sure that the shorter sentences remain u... | stack_v2_sparse_classes_36k_train_034055 | 3,820 | no_license | [
{
"docstring": "Make sure that the shortening of the sentence text for the string representation of the object works properly",
"name": "test_longsentence_chopping",
"signature": "def test_longsentence_chopping(self)"
},
{
"docstring": "Make sure that the shorter sentences remain unshortened",
... | 2 | stack_v2_sparse_classes_30k_train_003509 | Implement the Python class `SentenceTests` described below.
Class description:
Implement the SentenceTests class.
Method signatures and docstrings:
- def test_longsentence_chopping(self): Make sure that the shortening of the sentence text for the string representation of the object works properly
- def test_shortsent... | Implement the Python class `SentenceTests` described below.
Class description:
Implement the SentenceTests class.
Method signatures and docstrings:
- def test_longsentence_chopping(self): Make sure that the shortening of the sentence text for the string representation of the object works properly
- def test_shortsent... | 3255f19ef53b8c994d53d9e5f1a6b8404c33e4b6 | <|skeleton|>
class SentenceTests:
def test_longsentence_chopping(self):
"""Make sure that the shortening of the sentence text for the string representation of the object works properly"""
<|body_0|>
def test_shortsentence_chopping(self):
"""Make sure that the shorter sentences remain u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentenceTests:
def test_longsentence_chopping(self):
"""Make sure that the shortening of the sentence text for the string representation of the object works properly"""
longsentence = ' '.join(['word'] * 20) + ' lastword'
sentence = create_dummy_sentence(longsentence)
sentence_... | the_stack_v2_python_sparse | qe/tests.py | lefterav/qegui | train | 1 | |
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_36k_train_034056 | 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_010295 | 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_36k | data/stack_v2_sparse_classes_30k | 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 |
2f610b4b5584da8fd85e59b4b565e598a98c7a8d | [
"try:\n logging.info(f'Start Training Job Controller: {request}')\n start_training_request = request.dict(exclude_none=True)\n response = start_training_job(training_job=start_training_request.get('TrainingJobName'), algorithm_specification=start_training_request.get('AlgorithmSpecification'), role_arn=sta... | <|body_start_0|>
try:
logging.info(f'Start Training Job Controller: {request}')
start_training_request = request.dict(exclude_none=True)
response = start_training_job(training_job=start_training_request.get('TrainingJobName'), algorithm_specification=start_training_request.ge... | SagemakerController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SagemakerController:
def start_training_job_controller(self, request):
"""[Start a Training Job in AWS Sagemaker] Args: request ([type]): [Based on Input Schema] Raises: error: [Error] Returns: [type]: [Unique Identifier of your Training Job]"""
<|body_0|>
def stop_training_... | stack_v2_sparse_classes_36k_train_034057 | 3,268 | permissive | [
{
"docstring": "[Start a Training Job in AWS Sagemaker] Args: request ([type]): [Based on Input Schema] Raises: error: [Error] Returns: [type]: [Unique Identifier of your Training Job]",
"name": "start_training_job_controller",
"signature": "def start_training_job_controller(self, request)"
},
{
... | 4 | null | Implement the Python class `SagemakerController` described below.
Class description:
Implement the SagemakerController class.
Method signatures and docstrings:
- def start_training_job_controller(self, request): [Start a Training Job in AWS Sagemaker] Args: request ([type]): [Based on Input Schema] Raises: error: [Er... | Implement the Python class `SagemakerController` described below.
Class description:
Implement the SagemakerController class.
Method signatures and docstrings:
- def start_training_job_controller(self, request): [Start a Training Job in AWS Sagemaker] Args: request ([type]): [Based on Input Schema] Raises: error: [Er... | c71b1324ed270caa3724c0a8c58c4883b28dc19c | <|skeleton|>
class SagemakerController:
def start_training_job_controller(self, request):
"""[Start a Training Job in AWS Sagemaker] Args: request ([type]): [Based on Input Schema] Raises: error: [Error] Returns: [type]: [Unique Identifier of your Training Job]"""
<|body_0|>
def stop_training_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SagemakerController:
def start_training_job_controller(self, request):
"""[Start a Training Job in AWS Sagemaker] Args: request ([type]): [Based on Input Schema] Raises: error: [Error] Returns: [type]: [Unique Identifier of your Training Job]"""
try:
logging.info(f'Start Training J... | the_stack_v2_python_sparse | core_engine/core_engine/controllers/aws/sagemaker_controller.py | Chronicles-of-AI/osAIris | train | 4 | |
9f190a343c5ab3989764494d5ebcd2da33667816 | [
"if config_dict is not None and 'prefix' in config_dict:\n self.prefix = config_dict['prefix']\nelse:\n self.prefix = ''\nif config_dict is not None and 'log_level' in config_dict:\n self.log_level = config_dict['log_level']\nelse:\n self.log_level = 'debug'\nget_logger().debug('Creating LoggingAlertLis... | <|body_start_0|>
if config_dict is not None and 'prefix' in config_dict:
self.prefix = config_dict['prefix']
else:
self.prefix = ''
if config_dict is not None and 'log_level' in config_dict:
self.log_level = config_dict['log_level']
else:
s... | This listener logs the alerts | LoggingAlertListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggingAlertListener:
"""This listener logs the alerts"""
def __init__(self, name, config_dict):
"""Constructor"""
<|body_0|>
def process_alert(self, alert):
"""process the alert by logging it"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if c... | stack_v2_sparse_classes_36k_train_034058 | 1,761 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, name, config_dict)"
},
{
"docstring": "process the alert by logging it",
"name": "process_alert",
"signature": "def process_alert(self, alert)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010813 | Implement the Python class `LoggingAlertListener` described below.
Class description:
This listener logs the alerts
Method signatures and docstrings:
- def __init__(self, name, config_dict): Constructor
- def process_alert(self, alert): process the alert by logging it | Implement the Python class `LoggingAlertListener` described below.
Class description:
This listener logs the alerts
Method signatures and docstrings:
- def __init__(self, name, config_dict): Constructor
- def process_alert(self, alert): process the alert by logging it
<|skeleton|>
class LoggingAlertListener:
"""... | eba6c1489b503fdcf040a126942643b355867bcd | <|skeleton|>
class LoggingAlertListener:
"""This listener logs the alerts"""
def __init__(self, name, config_dict):
"""Constructor"""
<|body_0|>
def process_alert(self, alert):
"""process the alert by logging it"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoggingAlertListener:
"""This listener logs the alerts"""
def __init__(self, name, config_dict):
"""Constructor"""
if config_dict is not None and 'prefix' in config_dict:
self.prefix = config_dict['prefix']
else:
self.prefix = ''
if config_dict is n... | the_stack_v2_python_sparse | src/ibm/teal/listener/logging_alert_listener.py | ppjsand/pyteal | train | 1 |
f05419b77dc5c1ddf35010e6a6cf8f0ae36df2ee | [
"cl = KMeansClustering([876])\nself.assertEqual([876], cl.getclusters(2))\nself.assertEqual([876], cl.getclusters(5))",
"cl = KMeansClustering([])\nself.assertEqual([], cl.getclusters(2))\nself.assertEqual([], cl.getclusters(7))"
] | <|body_start_0|>
cl = KMeansClustering([876])
self.assertEqual([876], cl.getclusters(2))
self.assertEqual([876], cl.getclusters(5))
<|end_body_0|>
<|body_start_1|>
cl = KMeansClustering([])
self.assertEqual([], cl.getclusters(2))
self.assertEqual([], cl.getclusters(7))
<... | KClusterSmallListTestCase | [
"MIT",
"BSD-3-Clause-LBNL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KClusterSmallListTestCase:
def testClusterLen1(self):
"""Testing that a search space of length 1 returns only one cluster"""
<|body_0|>
def testClusterLen0(self):
"""Testing if clustering an empty set, returns an empty set"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_034059 | 7,070 | permissive | [
{
"docstring": "Testing that a search space of length 1 returns only one cluster",
"name": "testClusterLen1",
"signature": "def testClusterLen1(self)"
},
{
"docstring": "Testing if clustering an empty set, returns an empty set",
"name": "testClusterLen0",
"signature": "def testClusterLen... | 2 | null | Implement the Python class `KClusterSmallListTestCase` described below.
Class description:
Implement the KClusterSmallListTestCase class.
Method signatures and docstrings:
- def testClusterLen1(self): Testing that a search space of length 1 returns only one cluster
- def testClusterLen0(self): Testing if clustering a... | Implement the Python class `KClusterSmallListTestCase` described below.
Class description:
Implement the KClusterSmallListTestCase class.
Method signatures and docstrings:
- def testClusterLen1(self): Testing that a search space of length 1 returns only one cluster
- def testClusterLen0(self): Testing if clustering a... | 17ef63ad1717553ab2abb50592f8de79228c8523 | <|skeleton|>
class KClusterSmallListTestCase:
def testClusterLen1(self):
"""Testing that a search space of length 1 returns only one cluster"""
<|body_0|>
def testClusterLen0(self):
"""Testing if clustering an empty set, returns an empty set"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KClusterSmallListTestCase:
def testClusterLen1(self):
"""Testing that a search space of length 1 returns only one cluster"""
cl = KMeansClustering([876])
self.assertEqual([876], cl.getclusters(2))
self.assertEqual([876], cl.getclusters(5))
def testClusterLen0(self):
... | the_stack_v2_python_sparse | fable/fable_sources/libtbx/clusterTests.py | hickerson/bbn | train | 4 | |
40de1d0469401716d56951cd0cba3f8f09de9f19 | [
"if self.project:\n return self.project\nparent_folder = self.parent_folder\nreturn parent_folder.retrieve_project()",
"dct = model_to_dict(self)\nfolders_children = self.folders_set.all()\ndct['type'] = 'folder'\ndct['children'] = list()\ndct['title'] = escape(self.name)\ndct['folder'] = True\ndct['role'] = r... | <|body_start_0|>
if self.project:
return self.project
parent_folder = self.parent_folder
return parent_folder.retrieve_project()
<|end_body_0|>
<|body_start_1|>
dct = model_to_dict(self)
folders_children = self.folders_set.all()
dct['type'] = 'folder'
... | Folders | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Folders:
def retrieve_project(self):
"""Retrieve project for current folder :return:"""
<|body_0|>
def get_tree_children(self, role):
"""Retrieve children of Folder and return them in dict"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.proj... | stack_v2_sparse_classes_36k_train_034060 | 13,670 | no_license | [
{
"docstring": "Retrieve project for current folder :return:",
"name": "retrieve_project",
"signature": "def retrieve_project(self)"
},
{
"docstring": "Retrieve children of Folder and return them in dict",
"name": "get_tree_children",
"signature": "def get_tree_children(self, role)"
}
... | 2 | stack_v2_sparse_classes_30k_train_002031 | Implement the Python class `Folders` described below.
Class description:
Implement the Folders class.
Method signatures and docstrings:
- def retrieve_project(self): Retrieve project for current folder :return:
- def get_tree_children(self, role): Retrieve children of Folder and return them in dict | Implement the Python class `Folders` described below.
Class description:
Implement the Folders class.
Method signatures and docstrings:
- def retrieve_project(self): Retrieve project for current folder :return:
- def get_tree_children(self, role): Retrieve children of Folder and return them in dict
<|skeleton|>
clas... | cd19e3168b4661312efdc80b5b7c006a70b8004b | <|skeleton|>
class Folders:
def retrieve_project(self):
"""Retrieve project for current folder :return:"""
<|body_0|>
def get_tree_children(self, role):
"""Retrieve children of Folder and return them in dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Folders:
def retrieve_project(self):
"""Retrieve project for current folder :return:"""
if self.project:
return self.project
parent_folder = self.parent_folder
return parent_folder.retrieve_project()
def get_tree_children(self, role):
"""Retrieve childr... | the_stack_v2_python_sparse | idarling_management/idarling_management/IDArling/models.py | saidelike/IDArling-1 | train | 0 | |
77375abd37e709f5e7bee16d367879f2529a2ca8 | [
"if root == None:\n return []\nleft = []\nright = []\nif root.left != None:\n left = self.inorderTraversal(root.left)\nif root.right != None:\n right = self.inorderTraversal(root.right)\nreturn left + [root.val] + right",
"data = self.inorderTraversal(root)\nl = 0\nr = len(data) - 1\nwhile r - l + 1 > k:... | <|body_start_0|>
if root == None:
return []
left = []
right = []
if root.left != None:
left = self.inorderTraversal(root.left)
if root.right != None:
right = self.inorderTraversal(root.right)
return left + [root.val] + right
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def closestKValues(self, root, target, k):
""":type root: TreeNode :type target: float :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_034061 | 1,047 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :type target: float :type k: int :rtype: List[int]",
"name": "closestKValues",
"signature": "def closestKValues(sel... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def closestKValues(self, root, target, k): :type root: TreeNode :type target: float :type k: int :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def closestKValues(self, root, target, k): :type root: TreeNode :type target: float :type k: int :rtype... | ef8c9422c481aa3c482933318c785ad28dd7703e | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def closestKValues(self, root, target, k):
""":type root: TreeNode :type target: float :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
if root == None:
return []
left = []
right = []
if root.left != None:
left = self.inorderTraversal(root.left)
if root.right != None:
righ... | the_stack_v2_python_sparse | python/closest_binary_search_tree_value_II.py | pzmrzy/LeetCode | train | 2 | |
c8d2eaf019620e142bdf6922820d2d2048ab44c8 | [
"with shelve.open(Constants.SONAR_DB_PATH) as db:\n tools = db['tool']\n try:\n _dict = tools[tool_name]\n except KeyError:\n _dict = {'versions': [], 'executable': {}, 'script': {}}\n if version in _dict['versions']:\n logger.error(\"%s already exists. Use 'edit' to modify existing... | <|body_start_0|>
with shelve.open(Constants.SONAR_DB_PATH) as db:
tools = db['tool']
try:
_dict = tools[tool_name]
except KeyError:
_dict = {'versions': [], 'executable': {}, 'script': {}}
if version in _dict['versions']:
... | Manage the tools in the database | Tool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tool:
"""Manage the tools in the database"""
def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
"""Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_ex... | stack_v2_sparse_classes_36k_train_034062 | 22,434 | permissive | [
{
"docstring": "Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name of HLS tool executable. None if not applicable sim_exe (str): Name of simulation tool executable. None if not ... | 6 | stack_v2_sparse_classes_30k_val_000458 | Implement the Python class `Tool` described below.
Class description:
Manage the tools in the database
Method signatures and docstrings:
- def add(tool_name, version, cad_exe, hls_exe, sim_exe, script): Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): N... | Implement the Python class `Tool` described below.
Class description:
Manage the tools in the database
Method signatures and docstrings:
- def add(tool_name, version, cad_exe, hls_exe, sim_exe, script): Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): N... | 99de16dd16d0aa77734584e67263c78a37abef86 | <|skeleton|>
class Tool:
"""Manage the tools in the database"""
def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
"""Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tool:
"""Manage the tools in the database"""
def add(tool_name, version, cad_exe, hls_exe, sim_exe, script):
"""Add a new tool to the database Args: tool_name (str): Name of the tool version (str): Tool version cad_exe (str): Name of CAD tool executable. None if not applicable hls_exe (str): Name... | the_stack_v2_python_sparse | sonar/database.py | Zyk-Hyphen/sonar | train | 0 |
dfbe468f1f1f80f033baa04b32ac49a978d7d13f | [
"url = self._base_url.format(station_id=station_id)\nfile = download_file(url, settings=self.sr.stations.settings, ttl=CacheExpiry.FIVE_MINUTES)\ndf = pl.read_csv(source=file, separator=',', has_header=False, infer_schema_length=0, storage_options={'compression': 'gzip'})\ndf = df.rename(mapping={'column_1': Column... | <|body_start_0|>
url = self._base_url.format(station_id=station_id)
file = download_file(url, settings=self.sr.stations.settings, ttl=CacheExpiry.FIVE_MINUTES)
df = pl.read_csv(source=file, separator=',', has_header=False, infer_schema_length=0, storage_options={'compression': 'gzip'})
d... | NoaaGhcnValues | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoaaGhcnValues:
def _collect_station_parameter(self, station_id: str, parameter, dataset) -> pl.DataFrame:
"""Collection method for NOAA GHCN data. Parameter and dataset can be ignored as data is provided as a whole. :param station_id: station id of the station being queried :param param... | stack_v2_sparse_classes_36k_train_034063 | 8,053 | permissive | [
{
"docstring": "Collection method for NOAA GHCN data. Parameter and dataset can be ignored as data is provided as a whole. :param station_id: station id of the station being queried :param parameter: parameter being queried :param dataset: dataset being queried :return: dataframe with read data",
"name": "_... | 2 | null | Implement the Python class `NoaaGhcnValues` described below.
Class description:
Implement the NoaaGhcnValues class.
Method signatures and docstrings:
- def _collect_station_parameter(self, station_id: str, parameter, dataset) -> pl.DataFrame: Collection method for NOAA GHCN data. Parameter and dataset can be ignored ... | Implement the Python class `NoaaGhcnValues` described below.
Class description:
Implement the NoaaGhcnValues class.
Method signatures and docstrings:
- def _collect_station_parameter(self, station_id: str, parameter, dataset) -> pl.DataFrame: Collection method for NOAA GHCN data. Parameter and dataset can be ignored ... | 448fbd56b67978cf8f4215dedc02a11b89f66b01 | <|skeleton|>
class NoaaGhcnValues:
def _collect_station_parameter(self, station_id: str, parameter, dataset) -> pl.DataFrame:
"""Collection method for NOAA GHCN data. Parameter and dataset can be ignored as data is provided as a whole. :param station_id: station id of the station being queried :param param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoaaGhcnValues:
def _collect_station_parameter(self, station_id: str, parameter, dataset) -> pl.DataFrame:
"""Collection method for NOAA GHCN data. Parameter and dataset can be ignored as data is provided as a whole. :param station_id: station id of the station being queried :param parameter: paramete... | the_stack_v2_python_sparse | wetterdienst/provider/noaa/ghcn/api.py | earthobservations/wetterdienst | train | 283 | |
c8d440779e232d56375599b688c7b0d572231148 | [
"self.create_pst = create_pst\nself.option_flags = option_flags\nself.pst_name_prefix = pst_name_prefix\nself.pst_password = pst_password\nself.pst_size_threshold = pst_size_threshold",
"if dictionary is None:\n return None\ncreate_pst = dictionary.get('createPst')\noption_flags = dictionary.get('optionFlags')... | <|body_start_0|>
self.create_pst = create_pst
self.option_flags = option_flags
self.pst_name_prefix = pst_name_prefix
self.pst_password = pst_password
self.pst_size_threshold = pst_size_threshold
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return N... | Implementation of the 'EwsToPstConversionParams' model. TODO: type description here. Attributes: create_pst (bool): Create Msg files or Pst. false value indicates only create msg files. Default value is true. option_flags (int): ConvertEwsToPst flags of type ConvertEwsToPSTOptionFlags. pst_name_prefix (string): Name pr... | EwsToPstConversionParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EwsToPstConversionParams:
"""Implementation of the 'EwsToPstConversionParams' model. TODO: type description here. Attributes: create_pst (bool): Create Msg files or Pst. false value indicates only create msg files. Default value is true. option_flags (int): ConvertEwsToPst flags of type ConvertEw... | stack_v2_sparse_classes_36k_train_034064 | 2,573 | permissive | [
{
"docstring": "Constructor for the EwsToPstConversionParams class",
"name": "__init__",
"signature": "def __init__(self, create_pst=None, option_flags=None, pst_name_prefix=None, pst_password=None, pst_size_threshold=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary ... | 2 | stack_v2_sparse_classes_30k_train_004915 | Implement the Python class `EwsToPstConversionParams` described below.
Class description:
Implementation of the 'EwsToPstConversionParams' model. TODO: type description here. Attributes: create_pst (bool): Create Msg files or Pst. false value indicates only create msg files. Default value is true. option_flags (int): ... | Implement the Python class `EwsToPstConversionParams` described below.
Class description:
Implementation of the 'EwsToPstConversionParams' model. TODO: type description here. Attributes: create_pst (bool): Create Msg files or Pst. false value indicates only create msg files. Default value is true. option_flags (int): ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class EwsToPstConversionParams:
"""Implementation of the 'EwsToPstConversionParams' model. TODO: type description here. Attributes: create_pst (bool): Create Msg files or Pst. false value indicates only create msg files. Default value is true. option_flags (int): ConvertEwsToPst flags of type ConvertEw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EwsToPstConversionParams:
"""Implementation of the 'EwsToPstConversionParams' model. TODO: type description here. Attributes: create_pst (bool): Create Msg files or Pst. false value indicates only create msg files. Default value is true. option_flags (int): ConvertEwsToPst flags of type ConvertEwsToPSTOptionF... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ews_to_pst_conversion_params.py | cohesity/management-sdk-python | train | 24 |
9e69f1f4524c896ea7ca9842b32f0283c067e446 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('h1.entry-title').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = self.absolute_url(soup.select_one('div.elementor-image img')['data-src'])\nlogger.info('Novel co... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('h1.entry-title').text.strip()
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = self.absolute_url(soup.select_one('div.elementor... | ReincarnationPalace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReincarnationPalace:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_034065 | 2,691 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | stack_v2_sparse_classes_30k_train_010545 | Implement the Python class `ReincarnationPalace` described below.
Class description:
Implement the ReincarnationPalace class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as cle... | Implement the Python class `ReincarnationPalace` described below.
Class description:
Implement the ReincarnationPalace class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return as cle... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class ReincarnationPalace:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReincarnationPalace:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('h1.entry-title').text.strip()
logger.info('Novel title: %s', self... | the_stack_v2_python_sparse | lncrawl/sources/reincarnationpalace.py | NNTin/lightnovel-crawler | train | 2 | |
d14db89feb972db40fbd185e4d9afebbd4bd9ec5 | [
"self.object_prefix = object_prefix\nself.region = region\nself.s3_bucket = s3_bucket",
"if dictionary is None:\n return None\nobject_prefix = dictionary.get('objectPrefix')\nregion = cohesity_management_sdk.models.entity_proto.EntityProto.from_dictionary(dictionary.get('region')) if dictionary.get('region') e... | <|body_start_0|>
self.object_prefix = object_prefix
self.region = region
self.s3_bucket = s3_bucket
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
object_prefix = dictionary.get('objectPrefix')
region = cohesity_management_sdk.models.entit... | Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". region (EntityProto): Target Region in which recovery should hap... | RestoreS3Params_NewLocationParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreS3Params_NewLocationParams:
"""Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". reg... | stack_v2_sparse_classes_36k_train_034066 | 2,258 | permissive | [
{
"docstring": "Constructor for the RestoreS3Params_NewLocationParams class",
"name": "__init__",
"signature": "def __init__(self, object_prefix=None, region=None, s3_bucket=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary ... | 2 | null | Implement the Python class `RestoreS3Params_NewLocationParams` described below.
Class description:
Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the r... | Implement the Python class `RestoreS3Params_NewLocationParams` described below.
Class description:
Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the r... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreS3Params_NewLocationParams:
"""Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". reg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreS3Params_NewLocationParams:
"""Implementation of the 'RestoreS3Params_NewLocationParams' model. Message specifying new location details, should be set only when is_original_location is false. Attributes: object_prefix (string): Object prefix for the recovered objects. E.g. "/", "/a/b". region (EntityPr... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_s3_params_new_location_params.py | cohesity/management-sdk-python | train | 24 |
a982c8780d821868cc20216307e8984210d86237 | [
"m = 0\nfor i in range(len(matrix)):\n for j in range(len(matrix[i])):\n matrix[i][j] = int(matrix[i][j])\n if i != 0 and matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\nfor row in matrix:\n m = max(m, self.largestRectangleArea(row))\nreturn m",
"stack = []\nheight.append(0)\... | <|body_start_0|>
m = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if i != 0 and matrix[i][j] == 1:
matrix[i][j] += matrix[i - 1][j]
for row in matrix:
m = max(m, self.la... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = 0
for... | stack_v2_sparse_classes_36k_train_034067 | 1,154 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011148 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
- def largestRectangleArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class So... | cb70fc9ddc410923cc1dae6015a821d4e52c1c14 | <|skeleton|>
class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
m = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if i != 0 and matrix[i][j] == 1:
... | the_stack_v2_python_sparse | 85Maximal Rectangle.py | zingzheng/LeetCode_py | train | 0 | |
759dece2be9b8ec507e6c714138fa459efdb2f44 | [
"if n < 0:\n return 0\nif n == 0 or n == 1:\n return n\nelse:\n return self.nth_fibonacci(n - 1) + self.nth_fibonacci(n - 2)",
"result = []\nif n < 1:\n return result\narr = [0, 1]\nfor i in range(2, n):\n nextval = arr[i - 1] + arr[i - 2]\n if nextval > n:\n return arr\n else:\n ... | <|body_start_0|>
if n < 0:
return 0
if n == 0 or n == 1:
return n
else:
return self.nth_fibonacci(n - 1) + self.nth_fibonacci(n - 2)
<|end_body_0|>
<|body_start_1|>
result = []
if n < 1:
return result
arr = [0, 1]
f... | https://projecteuler.net/problem=2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://projecteuler.net/problem=2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."""
def nth_fibonacci(self, n):
"""Find the nth fibonacci number in the sequence."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_034068 | 1,258 | no_license | [
{
"docstring": "Find the nth fibonacci number in the sequence.",
"name": "nth_fibonacci",
"signature": "def nth_fibonacci(self, n)"
},
{
"docstring": "Given a positive integer, return a list of numbers in the fibonacci sequence less than the number.",
"name": "show_fibs_until",
"signatur... | 2 | stack_v2_sparse_classes_30k_val_000711 | Implement the Python class `Solution` described below.
Class description:
https://projecteuler.net/problem=2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Method signatures and docstrings:
- def nth_fibonacci(self, n): Find the nth f... | Implement the Python class `Solution` described below.
Class description:
https://projecteuler.net/problem=2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Method signatures and docstrings:
- def nth_fibonacci(self, n): Find the nth f... | acad7283f4af301539c621b4b50268208509d38f | <|skeleton|>
class Solution:
"""https://projecteuler.net/problem=2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."""
def nth_fibonacci(self, n):
"""Find the nth fibonacci number in the sequence."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://projecteuler.net/problem=2 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."""
def nth_fibonacci(self, n):
"""Find the nth fibonacci number in the sequence."""
if n < 0:
retu... | the_stack_v2_python_sparse | euler/multiples.py | arijort/prep | train | 2 |
fc2aeabca5ab13924be1b872d7ec6d03e207b1df | [
"super(GaussianDist, self).__init__(input_size=input_size, output_size=output_size, hidden_sizes=hidden_sizes, hidden_activation=hidden_activation, use_output_layer=False)\nself.std_activation = std_activation\nself.mean_activation = mean_activation\nself.log_std_min = log_std_min\nself.log_std_max = log_std_max\ni... | <|body_start_0|>
super(GaussianDist, self).__init__(input_size=input_size, output_size=output_size, hidden_sizes=hidden_sizes, hidden_activation=hidden_activation, use_output_layer=False)
self.std_activation = std_activation
self.mean_activation = mean_activation
self.log_std_min = log_s... | Multilayer perceptron with Gaussian distribution output. the Mean Attributes: mean_activation (function): bounding function for mean log_std_min (float): lower bound of log std log_std_max (float): upper bound of log std mean_layer (nn.Linear): output layer for mean log_std_layer (nn.Linear): output layer for log std | GaussianDist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianDist:
"""Multilayer perceptron with Gaussian distribution output. the Mean Attributes: mean_activation (function): bounding function for mean log_std_min (float): lower bound of log std log_std_max (float): upper bound of log std mean_layer (nn.Linear): output layer for mean log_std_layer... | stack_v2_sparse_classes_36k_train_034069 | 10,144 | no_license | [
{
"docstring": "Initialize If std is not None, then use fixed std value given by argument std, otherwise use std layer",
"name": "__init__",
"signature": "def __init__(self, input_size, output_size, hidden_sizes, hidden_activation=torch.relu, mean_activation=torch.tanh, std_activation=torch.tanh, log_st... | 3 | null | Implement the Python class `GaussianDist` described below.
Class description:
Multilayer perceptron with Gaussian distribution output. the Mean Attributes: mean_activation (function): bounding function for mean log_std_min (float): lower bound of log std log_std_max (float): upper bound of log std mean_layer (nn.Linea... | Implement the Python class `GaussianDist` described below.
Class description:
Multilayer perceptron with Gaussian distribution output. the Mean Attributes: mean_activation (function): bounding function for mean log_std_min (float): lower bound of log std log_std_max (float): upper bound of log std mean_layer (nn.Linea... | 2d70d4792e78ceefd4626302fa85e7774e2ff250 | <|skeleton|>
class GaussianDist:
"""Multilayer perceptron with Gaussian distribution output. the Mean Attributes: mean_activation (function): bounding function for mean log_std_min (float): lower bound of log std log_std_max (float): upper bound of log std mean_layer (nn.Linear): output layer for mean log_std_layer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianDist:
"""Multilayer perceptron with Gaussian distribution output. the Mean Attributes: mean_activation (function): bounding function for mean log_std_min (float): lower bound of log std log_std_max (float): upper bound of log std mean_layer (nn.Linear): output layer for mean log_std_layer (nn.Linear):... | the_stack_v2_python_sparse | src/SDRL_Project/learning_agents/architectures/mlp.py | sbhambr1/symbolic_planning_and_rl | train | 0 |
8b62b0a021f74a123bd36d34652c09d7d823f3a2 | [
"self.poscar = vasp_io.POSCAR(poscar)\nself.cell_recip = self.poscar.cell[1]\nself.cell = utils.cell_to_spgcell(self.poscar.cell, self.poscar.atom)\nself.cell_type = [None, None]",
"deltax = 2 * krange[0] / (npoint[0] - 1)\ndeltay = 2 * krange[1] / (npoint[1] - 1)\nX, Y = np.mgrid[-krange[0]:krange[0] + deltax * ... | <|body_start_0|>
self.poscar = vasp_io.POSCAR(poscar)
self.cell_recip = self.poscar.cell[1]
self.cell = utils.cell_to_spgcell(self.poscar.cell, self.poscar.atom)
self.cell_type = [None, None]
<|end_body_0|>
<|body_start_1|>
deltax = 2 * krange[0] / (npoint[0] - 1)
deltay... | main | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class main:
def __init__(self, poscar='POSCAR'):
"""Get POSCAR file and return a POSCAR object"""
<|body_0|>
def get_2D_kmesh(self, origin=[0, 0, 0], krange=[0.1, 0.1], plane='xy', npoint=[11, 11]):
"""Get a rectangular k-mesh around a k-point on a plane Attribute: origin ... | stack_v2_sparse_classes_36k_train_034070 | 3,364 | permissive | [
{
"docstring": "Get POSCAR file and return a POSCAR object",
"name": "__init__",
"signature": "def __init__(self, poscar='POSCAR')"
},
{
"docstring": "Get a rectangular k-mesh around a k-point on a plane Attribute: origin : k-point (fractional, reciprocal) coordinate considered at the center of ... | 2 | stack_v2_sparse_classes_30k_train_006863 | Implement the Python class `main` described below.
Class description:
Implement the main class.
Method signatures and docstrings:
- def __init__(self, poscar='POSCAR'): Get POSCAR file and return a POSCAR object
- def get_2D_kmesh(self, origin=[0, 0, 0], krange=[0.1, 0.1], plane='xy', npoint=[11, 11]): Get a rectangu... | Implement the Python class `main` described below.
Class description:
Implement the main class.
Method signatures and docstrings:
- def __init__(self, poscar='POSCAR'): Get POSCAR file and return a POSCAR object
- def get_2D_kmesh(self, origin=[0, 0, 0], krange=[0.1, 0.1], plane='xy', npoint=[11, 11]): Get a rectangu... | 42945ee15465caa6fad1983597e23beac78b774d | <|skeleton|>
class main:
def __init__(self, poscar='POSCAR'):
"""Get POSCAR file and return a POSCAR object"""
<|body_0|>
def get_2D_kmesh(self, origin=[0, 0, 0], krange=[0.1, 0.1], plane='xy', npoint=[11, 11]):
"""Get a rectangular k-mesh around a k-point on a plane Attribute: origin ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class main:
def __init__(self, poscar='POSCAR'):
"""Get POSCAR file and return a POSCAR object"""
self.poscar = vasp_io.POSCAR(poscar)
self.cell_recip = self.poscar.cell[1]
self.cell = utils.cell_to_spgcell(self.poscar.cell, self.poscar.atom)
self.cell_type = [None, None]
... | the_stack_v2_python_sparse | mcu/vasp/poscar.py | hungpham2017/mcu | train | 44 | |
03152315708b19812c7af0b0f0809de203609db1 | [
"if othermap is not None:\n assert isinstance(othermap, PrefixMap)\n self._map = deepcopy(othermap._map)\nself._map = dict()",
"assert isinstance(name, unicode)\nfor key in prefixes(name):\n if key not in self._map:\n self._map[key] = set()\n self._map[key].add(value)",
"assert isinstance(pre... | <|body_start_0|>
if othermap is not None:
assert isinstance(othermap, PrefixMap)
self._map = deepcopy(othermap._map)
self._map = dict()
<|end_body_0|>
<|body_start_1|>
assert isinstance(name, unicode)
for key in prefixes(name):
if key not in self._map... | Map designed to store and query unique objects by prefixes. | PrefixMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrefixMap:
"""Map designed to store and query unique objects by prefixes."""
def __init__(self, othermap=None):
"""If `othermap` is none, construct a copy. Otherwise initialize an empty instance."""
<|body_0|>
def add(self, name, value):
"""Add (name, value) pair... | stack_v2_sparse_classes_36k_train_034071 | 1,484 | no_license | [
{
"docstring": "If `othermap` is none, construct a copy. Otherwise initialize an empty instance.",
"name": "__init__",
"signature": "def __init__(self, othermap=None)"
},
{
"docstring": "Add (name, value) pair to the instance.",
"name": "add",
"signature": "def add(self, name, value)"
... | 4 | stack_v2_sparse_classes_30k_train_017113 | Implement the Python class `PrefixMap` described below.
Class description:
Map designed to store and query unique objects by prefixes.
Method signatures and docstrings:
- def __init__(self, othermap=None): If `othermap` is none, construct a copy. Otherwise initialize an empty instance.
- def add(self, name, value): A... | Implement the Python class `PrefixMap` described below.
Class description:
Map designed to store and query unique objects by prefixes.
Method signatures and docstrings:
- def __init__(self, othermap=None): If `othermap` is none, construct a copy. Otherwise initialize an empty instance.
- def add(self, name, value): A... | a823f05c8db3f7d7712075bde54c0d0d4a8bc2c5 | <|skeleton|>
class PrefixMap:
"""Map designed to store and query unique objects by prefixes."""
def __init__(self, othermap=None):
"""If `othermap` is none, construct a copy. Otherwise initialize an empty instance."""
<|body_0|>
def add(self, name, value):
"""Add (name, value) pair... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrefixMap:
"""Map designed to store and query unique objects by prefixes."""
def __init__(self, othermap=None):
"""If `othermap` is none, construct a copy. Otherwise initialize an empty instance."""
if othermap is not None:
assert isinstance(othermap, PrefixMap)
se... | the_stack_v2_python_sparse | hsm/data/prefixmap.py | AlwaysTraining/patnlp-hsm | train | 0 |
e55bfa9c4d6a25e24dfde7a4d9ee0f3718b846d0 | [
"status, error_msg, conn, trans_obj, session_obj = args\nif error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:\n return make_json_response(success=0, errormsg=error_msg, info='DATAGRID_TRANSACTION_REQUIRED', status=404)\ncolumn_list = []\nif status and conn is not None and (trans_obj is not None) and (session_obj is not... | <|body_start_0|>
status, error_msg, conn, trans_obj, session_obj = args
if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
return make_json_response(success=0, errormsg=error_msg, info='DATAGRID_TRANSACTION_REQUIRED', status=404)
column_list = []
if status and conn is not None and... | FilterDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterDialog:
def get(*args):
"""To fetch the current sorted columns"""
<|body_0|>
def save(*args, **kwargs):
"""To save the sorted columns"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
status, error_msg, conn, trans_obj, session_obj = args
... | stack_v2_sparse_classes_36k_train_034072 | 3,733 | permissive | [
{
"docstring": "To fetch the current sorted columns",
"name": "get",
"signature": "def get(*args)"
},
{
"docstring": "To save the sorted columns",
"name": "save",
"signature": "def save(*args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020887 | Implement the Python class `FilterDialog` described below.
Class description:
Implement the FilterDialog class.
Method signatures and docstrings:
- def get(*args): To fetch the current sorted columns
- def save(*args, **kwargs): To save the sorted columns | Implement the Python class `FilterDialog` described below.
Class description:
Implement the FilterDialog class.
Method signatures and docstrings:
- def get(*args): To fetch the current sorted columns
- def save(*args, **kwargs): To save the sorted columns
<|skeleton|>
class FilterDialog:
def get(*args):
... | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | <|skeleton|>
class FilterDialog:
def get(*args):
"""To fetch the current sorted columns"""
<|body_0|>
def save(*args, **kwargs):
"""To save the sorted columns"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterDialog:
def get(*args):
"""To fetch the current sorted columns"""
status, error_msg, conn, trans_obj, session_obj = args
if error_msg == ERROR_MSG_TRANS_ID_NOT_FOUND:
return make_json_response(success=0, errormsg=error_msg, info='DATAGRID_TRANSACTION_REQUIRED', status... | the_stack_v2_python_sparse | _MY_ORGS/Web-Dev-Collaborative/blog-research/database/pg-admin/web/pgadmin/tools/sqleditor/utils/filter_dialog.py | bgoonz/UsefulResourceRepo2.0 | train | 10 | |
0983b5ad2a06663f2ec3763ea09f3581fe003e2b | [
"if n == 2 or n == 3:\n return True\nif n % 6 != 1 and n % 6 != 5:\n return False\nsqrt_n = int(math.sqrt(n)) + 1\nindex = 5\nwhile index < sqrt_n:\n if n % index == 0 or n % (index + 2) == 0:\n return False\n index += 6\nreturn True",
"sqrt_n = int(math.sqrt(n)) + 1\nfor i in range(2, sqrt_n):... | <|body_start_0|>
if n == 2 or n == 3:
return True
if n % 6 != 1 and n % 6 != 5:
return False
sqrt_n = int(math.sqrt(n)) + 1
index = 5
while index < sqrt_n:
if n % index == 0 or n % (index + 2) == 0:
return False
inde... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _is_prime_bad2(self, n):
"""# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两... | stack_v2_sparse_classes_36k_train_034073 | 2,539 | no_license | [
{
"docstring": "# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两侧的数为6x+2,6x+3,6x+4,由于2(3x+1),3(2x+1),2(3x+2),所以它们一... | 4 | stack_v2_sparse_classes_30k_train_001315 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _is_prime_bad2(self, n): # Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _is_prime_bad2(self, n): # Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥... | 3c9e54680cefd51c8f56fa12eb27276787de3a2a | <|skeleton|>
class Solution:
def _is_prime_bad2(self, n):
"""# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _is_prime_bad2(self, n):
"""# Better than _is_prime_bad1 but still bad. # Reference: [判断一个数是否为质数/素数——从普通判断算法到高效判断算法思路](blog.csdn.net/huang_miao_xin/article/details/51331710) 令x≥1,将大于等于5的自然数表示如下: 6x-1, 6x, 6x+1, 6x+2, 6x+3, 6x+4, 6x+5, 6(x+1), 6(x+1)+1 ··· 可以看到,不在6的倍数两侧,即6x两侧的数为6x+2,6x+3,... | the_stack_v2_python_sparse | lxw/num204/num204.py | We-Hack/LeetCode | train | 3 | |
885528bbd45f9e7fdc481b7a529841bf8339c662 | [
"self.url = url\nself.repo = repo\nself.name = cookbook_name\nself.version = version\nself.manager = who",
"folder = './cookbooks/'\nmsg = 'En el getCookbook. \\n '\nset_info_log('url: ' + self.url + '. name: ' + folder + self.name)\nif self.repo == 'svn':\n try:\n Client().checkout(self.url, folder + s... | <|body_start_0|>
self.url = url
self.repo = repo
self.name = cookbook_name
self.version = version
self.manager = who
<|end_body_0|>
<|body_start_1|>
folder = './cookbooks/'
msg = 'En el getCookbook. \n '
set_info_log('url: ' + self.url + '. name: ' + fold... | Download | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Download:
def __init__(self, url, repo, cookbook_name, version, who):
"""Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None i... | stack_v2_sparse_classes_36k_train_034074 | 3,001 | no_license | [
{
"docstring": "Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None if all OK or an error on failure",
"name": "__init__",
"signature": "def _... | 3 | stack_v2_sparse_classes_30k_train_019327 | Implement the Python class `Download` described below.
Class description:
Implement the Download class.
Method signatures and docstrings:
- def __init__(self, url, repo, cookbook_name, version, who): Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: softwar... | Implement the Python class `Download` described below.
Class description:
Implement the Download class.
Method signatures and docstrings:
- def __init__(self, url, repo, cookbook_name, version, who): Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: softwar... | 34e1cb245b88789e779282db88108dd512e24bac | <|skeleton|>
class Download:
def __init__(self, url, repo, cookbook_name, version, who):
"""Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Download:
def __init__(self, url, repo, cookbook_name, version, who):
"""Initial parameters @param url: The url of the repository @param repo: kind os repository @param cookbook_name: software name @param version: software version @param who: configuration management type @return: None if all OK or an... | the_stack_v2_python_sparse | recipes/download.py | telefonicaid/fiware-uploadrecipes | train | 0 | |
34b54ca5614d3efaafe4dcd8703581cfa3a061bb | [
"super(Pan, self).__init__(image=Pan.pan_image, x=games.mouse.x, bottom=games.screen.height)\nself.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width - 10)\ngames.screen.add(self.score)\nself.player_level = games.Text(value=Chef.level, size=25, color=color.black, top=5, right=20... | <|body_start_0|>
super(Pan, self).__init__(image=Pan.pan_image, x=games.mouse.x, bottom=games.screen.height)
self.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width - 10)
games.screen.add(self.score)
self.player_level = games.Text(value=Chef.level, si... | Pan to catch pizza | Pan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pan:
"""Pan to catch pizza"""
def __init__(self):
"""Initialize Pan and create text counter"""
<|body_0|>
def update(self):
"""Move object to mouse position"""
<|body_1|>
def check_catch(self):
"""Check if pizza is catched"""
<|body_2... | stack_v2_sparse_classes_36k_train_034075 | 4,179 | no_license | [
{
"docstring": "Initialize Pan and create text counter",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Move object to mouse position",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Check if pizza is catched",
"name": "check_ca... | 3 | stack_v2_sparse_classes_30k_train_002189 | Implement the Python class `Pan` described below.
Class description:
Pan to catch pizza
Method signatures and docstrings:
- def __init__(self): Initialize Pan and create text counter
- def update(self): Move object to mouse position
- def check_catch(self): Check if pizza is catched | Implement the Python class `Pan` described below.
Class description:
Pan to catch pizza
Method signatures and docstrings:
- def __init__(self): Initialize Pan and create text counter
- def update(self): Move object to mouse position
- def check_catch(self): Check if pizza is catched
<|skeleton|>
class Pan:
"""Pa... | 19343c985f368770dc01ce415506506d62a23285 | <|skeleton|>
class Pan:
"""Pan to catch pizza"""
def __init__(self):
"""Initialize Pan and create text counter"""
<|body_0|>
def update(self):
"""Move object to mouse position"""
<|body_1|>
def check_catch(self):
"""Check if pizza is catched"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pan:
"""Pan to catch pizza"""
def __init__(self):
"""Initialize Pan and create text counter"""
super(Pan, self).__init__(image=Pan.pan_image, x=games.mouse.x, bottom=games.screen.height)
self.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width -... | the_stack_v2_python_sparse | graphics/pizza_panic.py | gofr1/python-learning | train | 0 |
dc4a7362cfdf2824ed20c3b7b15833817eea566e | [
"def traversal(node):\n if node is None:\n self.res += '-,'\n return\n self.res += str(node.val) + ','\n traversal(node.left)\n traversal(node.right)\nself.res = ''\ntraversal(root)\nreturn self.res[0:len(self.res) - 1]",
"def traversal():\n if self.data[self.index] == '-':\n s... | <|body_start_0|>
def traversal(node):
if node is None:
self.res += '-,'
return
self.res += str(node.val) + ','
traversal(node.left)
traversal(node.right)
self.res = ''
traversal(root)
return self.res[0:len(se... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def traversal(... | stack_v2_sparse_classes_36k_train_034076 | 2,589 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_004830 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 9b5e431773a9d50d073d7555472970cc06e6ca4d | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def traversal(node):
if node is None:
self.res += '-,'
return
self.res += str(node.val) + ','
traversal(node.left)
travers... | the_stack_v2_python_sparse | design/449_serialize_deserialize_bt.py | maximelearning/My-Leetcode-Solutions | train | 0 | |
f284244af916d2f8b98ea5b9ea686540ee0f6726 | [
"super().__init__(product_code, description, market_price, rental_price)\nif 'brand' in kwargs:\n self.brand = kwargs['brand']\nif 'voltage' in kwargs:\n self.voltage = kwargs['voltage']",
"output_dict = super().return_as_dictionary()\noutput_dict['brand'] = self.brand\noutput_dict['voltage'] = self.voltage... | <|body_start_0|>
super().__init__(product_code, description, market_price, rental_price)
if 'brand' in kwargs:
self.brand = kwargs['brand']
if 'voltage' in kwargs:
self.voltage = kwargs['voltage']
<|end_body_0|>
<|body_start_1|>
output_dict = super().return_as_di... | Class for electric appliances | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""Class for electric appliances"""
def __init__(self, product_code, description, market_price, rental_price, **kwargs):
"""Initializes electric appliances class"""
<|body_0|>
def return_as_dictionary(self):
"""Returns several attributes of di... | stack_v2_sparse_classes_36k_train_034077 | 1,034 | no_license | [
{
"docstring": "Initializes electric appliances class",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, **kwargs)"
},
{
"docstring": "Returns several attributes of dictionary class",
"name": "return_as_dictionary",
"signature": ... | 2 | null | Implement the Python class `ElectricAppliances` described below.
Class description:
Class for electric appliances
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, **kwargs): Initializes electric appliances class
- def return_as_dictionary(self): Returns sev... | Implement the Python class `ElectricAppliances` described below.
Class description:
Class for electric appliances
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, **kwargs): Initializes electric appliances class
- def return_as_dictionary(self): Returns sev... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""Class for electric appliances"""
def __init__(self, product_code, description, market_price, rental_price, **kwargs):
"""Initializes electric appliances class"""
<|body_0|>
def return_as_dictionary(self):
"""Returns several attributes of di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""Class for electric appliances"""
def __init__(self, product_code, description, market_price, rental_price, **kwargs):
"""Initializes electric appliances class"""
super().__init__(product_code, description, market_price, rental_price)
if 'brand' in kwargs:
... | the_stack_v2_python_sparse | students/amirg/lesson01/inventory_management/electric_appliances_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
7de47bc8cb98e55537e60f11463d47bed1ed7b5c | [
"product = products_page\nproduct.add_product(product_name, product_tag, product_model)\ntime.sleep(5)\nassert products_success in product._success_alert()\ntime.sleep(3)",
"product = ProductsPage(chosen_browser)\nproduct.find_product(product_name)\nproduct.edit_product_min_quantity(min_quantity)\ntime.sleep(5)\n... | <|body_start_0|>
product = products_page
product.add_product(product_name, product_tag, product_model)
time.sleep(5)
assert products_success in product._success_alert()
time.sleep(3)
<|end_body_0|>
<|body_start_1|>
product = ProductsPage(chosen_browser)
product.f... | Class for Products Page positive tests (add, edit, delete a product) | TestProductsPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProductsPage:
"""Class for Products Page positive tests (add, edit, delete a product)"""
def test_add_product(self, products_page, products_success, product_name, product_tag, product_model):
"""Checks adding product at product page :param chosen_browser: :return: asserts if got ... | stack_v2_sparse_classes_36k_train_034078 | 2,184 | no_license | [
{
"docstring": "Checks adding product at product page :param chosen_browser: :return: asserts if got success alert",
"name": "test_add_product",
"signature": "def test_add_product(self, products_page, products_success, product_name, product_tag, product_model)"
},
{
"docstring": "Checks editing ... | 3 | null | Implement the Python class `TestProductsPage` described below.
Class description:
Class for Products Page positive tests (add, edit, delete a product)
Method signatures and docstrings:
- def test_add_product(self, products_page, products_success, product_name, product_tag, product_model): Checks adding product at pro... | Implement the Python class `TestProductsPage` described below.
Class description:
Class for Products Page positive tests (add, edit, delete a product)
Method signatures and docstrings:
- def test_add_product(self, products_page, products_success, product_name, product_tag, product_model): Checks adding product at pro... | 228e53aee152d488b75d72de9c4add315c414409 | <|skeleton|>
class TestProductsPage:
"""Class for Products Page positive tests (add, edit, delete a product)"""
def test_add_product(self, products_page, products_success, product_name, product_tag, product_model):
"""Checks adding product at product page :param chosen_browser: :return: asserts if got ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProductsPage:
"""Class for Products Page positive tests (add, edit, delete a product)"""
def test_add_product(self, products_page, products_success, product_name, product_tag, product_model):
"""Checks adding product at product page :param chosen_browser: :return: asserts if got success alert... | the_stack_v2_python_sparse | selenium_opencart_tests/test_products_page.py | bronzehat/otus_auto_qa | train | 0 |
b19c09ecbae4596300f1303b0555dbbc87710b01 | [
"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!')",
"conte... | <|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... | Missing associated documentation comment in .proto file. | LanguageServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_all(self, request, context):
"""Missing associated documentation ... | stack_v2_sparse_classes_36k_train_034079 | 10,761 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "table",
"signature": "def table(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_all",
"signature": "def get_all(self, request, context)"... | 6 | stack_v2_sparse_classes_30k_train_014783 | Implement the Python class `LanguageServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def table(self, request, context): Missing associated documentation comment in .proto file.
- def get_all(self, request, context): Missing asso... | Implement the Python class `LanguageServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def table(self, request, context): Missing associated documentation comment in .proto file.
- def get_all(self, request, context): Missing asso... | 47d57bda959afa0b53d65e996b08e2f3b650c1a8 | <|skeleton|>
class LanguageServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_all(self, request, context):
"""Missing associated documentation ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageServicer:
"""Missing associated documentation comment in .proto file."""
def table(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | pix/resources_client/protos/language_pb2_grpc.py | thecodeworkers/testing-clients | train | 0 |
7fa40d957c829055b51264661f73b6ec88a2500d | [
"if not prices:\n return 0\nn, i, profit = (len(prices), 0, 0)\nvalley, peak = (prices[0], prices[0])\nwhile i < n - 1:\n while i < n - 1 and prices[i] >= prices[i + 1]:\n i += 1\n valley = prices[i]\n while i < n - 1 and prices[i] <= prices[i + 1]:\n i += 1\n peak = prices[i]\n prof... | <|body_start_0|>
if not prices:
return 0
n, i, profit = (len(prices), 0, 0)
valley, peak = (prices[0], prices[0])
while i < n - 1:
while i < n - 1 and prices[i] >= prices[i + 1]:
i += 1
valley = prices[i]
while i < n - 1 and... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: list) -> int:
"""峰谷法 连续的波谷和波锋之差相加,就是最大利润"""
<|body_0|>
def maxProfit_1(self, prices: list) -> int:
"""只要后一天的价格比前一天大,就卖出,增加利润"""
<|body_1|>
def maxProfit_2(self, prices: list) -> int:
"""动态规划 此题就是k=无穷大的情况,即不限制... | stack_v2_sparse_classes_36k_train_034080 | 2,551 | no_license | [
{
"docstring": "峰谷法 连续的波谷和波锋之差相加,就是最大利润",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: list) -> int"
},
{
"docstring": "只要后一天的价格比前一天大,就卖出,增加利润",
"name": "maxProfit_1",
"signature": "def maxProfit_1(self, prices: list) -> int"
},
{
"docstring": "动态规划 此题就是k=无穷大的情况... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: list) -> int: 峰谷法 连续的波谷和波锋之差相加,就是最大利润
- def maxProfit_1(self, prices: list) -> int: 只要后一天的价格比前一天大,就卖出,增加利润
- def maxProfit_2(self, prices: list) -> in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: list) -> int: 峰谷法 连续的波谷和波锋之差相加,就是最大利润
- def maxProfit_1(self, prices: list) -> int: 只要后一天的价格比前一天大,就卖出,增加利润
- def maxProfit_2(self, prices: list) -> in... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def maxProfit(self, prices: list) -> int:
"""峰谷法 连续的波谷和波锋之差相加,就是最大利润"""
<|body_0|>
def maxProfit_1(self, prices: list) -> int:
"""只要后一天的价格比前一天大,就卖出,增加利润"""
<|body_1|>
def maxProfit_2(self, prices: list) -> int:
"""动态规划 此题就是k=无穷大的情况,即不限制... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: list) -> int:
"""峰谷法 连续的波谷和波锋之差相加,就是最大利润"""
if not prices:
return 0
n, i, profit = (len(prices), 0, 0)
valley, peak = (prices[0], prices[0])
while i < n - 1:
while i < n - 1 and prices[i] >= prices[i + 1]:
... | the_stack_v2_python_sparse | algorithm/leetcode/dp/09-买卖股票的最佳时机Ⅱ.py | lxconfig/UbuntuCode_bak | train | 0 | |
7f2afa923309d8e0e28db397392ca0a3239cdf3b | [
"if p.val < root.val and q.val < root.val:\n return self.lowestCommonAncestor(root.left, p, q)\nif p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right, p, q)\nreturn root",
"if max(p.val, q.val) < root.val:\n return self.lowestCommonAncestor(root.left, p, q)\nif root.val ... | <|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
<|end_body_0|>
<|body_start_1|>
if max(p.val, q.v... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/16/2021 00:06"""
<|body_0|>
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/21/2022 15:00"""
<|bo... | stack_v2_sparse_classes_36k_train_034081 | 2,517 | no_license | [
{
"docstring": "08/16/2021 00:06",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "08/21/2022 15:00",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self... | 2 | stack_v2_sparse_classes_30k_train_006647 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 08/16/2021 00:06
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 08/16/2021 00:06
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/16/2021 00:06"""
<|body_0|>
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/21/2022 15:00"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""08/16/2021 00:06"""
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
r... | the_stack_v2_python_sparse | leetcode/solved/235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree/solution.py | sungminoh/algorithms | train | 0 | |
38d3fb1b28d9c6d9d5ebe8e0d1e78c4b29730b71 | [
"self.credentials = credentials\nself.host_address = host_address\nself.host_type = host_type",
"if dictionary is None:\n return None\ncredentials = cohesity_management_sdk.models.credentials.Credentials.from_dictionary(dictionary.get('credentials')) if dictionary.get('credentials') else None\nhost_address = d... | <|body_start_0|>
self.credentials = credentials
self.host_address = host_address
self.host_type = host_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
credentials = cohesity_management_sdk.models.credentials.Credentials.from_dictionary(diction... | Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access to the remote host. So only username field MUST be s... | RemoteHostConnectorParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteHostConnectorParams:
"""Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access... | stack_v2_sparse_classes_36k_train_034082 | 2,331 | permissive | [
{
"docstring": "Constructor for the RemoteHostConnectorParams class",
"name": "__init__",
"signature": "def __init__(self, credentials=None, host_address=None, host_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repr... | 2 | null | Implement the Python class `RemoteHostConnectorParams` described below.
Class description:
Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that ... | Implement the Python class `RemoteHostConnectorParams` described below.
Class description:
Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RemoteHostConnectorParams:
"""Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteHostConnectorParams:
"""Implementation of the 'RemoteHostConnectorParams' model. TODO: type description here. Attributes: credentials (Credentials): Credentials that will be used to login to the remote host. For env of type kLinux, it is expected that user has setup the password-less access to the remot... | the_stack_v2_python_sparse | cohesity_management_sdk/models/remote_host_connector_params.py | cohesity/management-sdk-python | train | 24 |
ae3826aa28b843ff64d213e55a0ec78baab0142a | [
"l_app = get_app(name)\nif not len(l_app):\n d_msg = {'error': 'name {} is not found.'.format(name)}\n return (d_msg, 404)\nreturn l_app[0]",
"b_ret, s_msg = delete_app(name)\nif not b_ret:\n d_msg = {'error': s_msg}\n return (d_msg, 404)\nreturn (None, 204)"
] | <|body_start_0|>
l_app = get_app(name)
if not len(l_app):
d_msg = {'error': 'name {} is not found.'.format(name)}
return (d_msg, 404)
return l_app[0]
<|end_body_0|>
<|body_start_1|>
b_ret, s_msg = delete_app(name)
if not b_ret:
d_msg = {'error... | AppItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppItem:
def get(self, name):
"""Returns the app information."""
<|body_0|>
def delete(self, name):
"""Deletes the app."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l_app = get_app(name)
if not len(l_app):
d_msg = {'error': 'n... | stack_v2_sparse_classes_36k_train_034083 | 3,345 | permissive | [
{
"docstring": "Returns the app information.",
"name": "get",
"signature": "def get(self, name)"
},
{
"docstring": "Deletes the app.",
"name": "delete",
"signature": "def delete(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000124 | Implement the Python class `AppItem` described below.
Class description:
Implement the AppItem class.
Method signatures and docstrings:
- def get(self, name): Returns the app information.
- def delete(self, name): Deletes the app. | Implement the Python class `AppItem` described below.
Class description:
Implement the AppItem class.
Method signatures and docstrings:
- def get(self, name): Returns the app information.
- def delete(self, name): Deletes the app.
<|skeleton|>
class AppItem:
def get(self, name):
"""Returns the app infor... | 65d01799296fce043e87ba58106f8fa8c1d8aa98 | <|skeleton|>
class AppItem:
def get(self, name):
"""Returns the app information."""
<|body_0|>
def delete(self, name):
"""Deletes the app."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppItem:
def get(self, name):
"""Returns the app information."""
l_app = get_app(name)
if not len(l_app):
d_msg = {'error': 'name {} is not found.'.format(name)}
return (d_msg, 404)
return l_app[0]
def delete(self, name):
"""Deletes the app.... | the_stack_v2_python_sparse | pengrixio/api/app/endpoints/route.py | iorchard/pengrixio | train | 0 | |
185cdd1cf1d7e1babf6dacc92f17bf2aeabf1d86 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CustomTaskExtension()",
"from ..custom_callout_extension import CustomCalloutExtension\nfrom ..custom_extension_callback_configuration import CustomExtensionCallbackConfiguration\nfrom ..user import User\nfrom ..custom_callout_extensio... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CustomTaskExtension()
<|end_body_0|>
<|body_start_1|>
from ..custom_callout_extension import CustomCalloutExtension
from ..custom_extension_callback_configuration import CustomExtensionC... | CustomTaskExtension | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomTaskExtension:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomTaskExtension:
"""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 ob... | stack_v2_sparse_classes_36k_train_034084 | 4,137 | 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: CustomTaskExtension",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `CustomTaskExtension` described below.
Class description:
Implement the CustomTaskExtension class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomTaskExtension: Creates a new instance of the appropriate class based on d... | Implement the Python class `CustomTaskExtension` described below.
Class description:
Implement the CustomTaskExtension class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomTaskExtension: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CustomTaskExtension:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomTaskExtension:
"""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 ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomTaskExtension:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CustomTaskExtension:
"""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: ... | the_stack_v2_python_sparse | msgraph/generated/models/identity_governance/custom_task_extension.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0b5c0809a77cd251d9d070b66d6ccc7a2ffabe34 | [
"dummy = ListNode(0)\ndummy.next = head\ncur = dummy\ni = 0\nwhile True:\n if i == m - 1:\n prev = cur\n if i == n:\n last = cur\n p = prev.next\n prev.next = last\n end = last.next\n next = end\n while p != end:\n tmp = p.next\n p.next = ... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
cur = dummy
i = 0
while True:
if i == m - 1:
prev = cur
if i == n:
last = cur
p = prev.next
prev.next = last
end = last.n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode:
"""1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转"""
<|body_0|>
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
"""2. 到 m 个节点,依次将后面节点插到前面"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_034085 | 2,075 | no_license | [
{
"docstring": "1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转",
"name": "reverseBetween_1",
"signature": "def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode"
},
{
"docstring": "2. 到 m 个节点,依次将后面节点插到前面",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head: ListNode, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode: 1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转
- def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 2. ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode: 1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转
- def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: 2. ... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode:
"""1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转"""
<|body_0|>
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
"""2. 到 m 个节点,依次将后面节点插到前面"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseBetween_1(self, head: ListNode, m: int, n: int) -> ListNode:
"""1. 找到并记录第 m-1 和 第 n 个节点,然后开始逆转"""
dummy = ListNode(0)
dummy.next = head
cur = dummy
i = 0
while True:
if i == m - 1:
prev = cur
if i == n... | the_stack_v2_python_sparse | .leetcode/92.反转链表-ii.py | xiaoruijiang/algorithm | train | 0 | |
8df8a6ba27994cd0b35181c410b75387db9d1e42 | [
"self.limit = limit\nself.wait_time = wait_time\nsuper().__init__(*args)\nfor item in self:\n if not isinstance(item, threading.Thread):\n raise TypeError(f\"Cannot add '{type(item)}' to ThreadList\")",
"cnt = 0\nfor item in self[:]:\n if item.is_alive():\n cnt += 1\n else:\n self.re... | <|body_start_0|>
self.limit = limit
self.wait_time = wait_time
super().__init__(*args)
for item in self:
if not isinstance(item, threading.Thread):
raise TypeError(f"Cannot add '{type(item)}' to ThreadList")
<|end_body_0|>
<|body_start_1|>
cnt = 0
... | A simple threadpool class to limit the number of simultaneous threads. Any threading.Thread object can be added to the pool using the append() method. If the maximum number of simultaneous threads has not been reached, the Thread object will be started immediately; if not, the append() call will block until the thread ... | ThreadList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadList:
"""A simple threadpool class to limit the number of simultaneous threads. Any threading.Thread object can be added to the pool using the append() method. If the maximum number of simultaneous threads has not been reached, the Thread object will be started immediately; if not, the appe... | stack_v2_sparse_classes_36k_train_034086 | 6,987 | permissive | [
{
"docstring": "Initializer. :param limit: the number of simultaneous threads :param wait_time: how long to wait if active threads exceeds limit",
"name": "__init__",
"signature": "def __init__(self, limit: int=128, wait_time: float=2, *args) -> None"
},
{
"docstring": "Return the number of aliv... | 3 | null | Implement the Python class `ThreadList` described below.
Class description:
A simple threadpool class to limit the number of simultaneous threads. Any threading.Thread object can be added to the pool using the append() method. If the maximum number of simultaneous threads has not been reached, the Thread object will b... | Implement the Python class `ThreadList` described below.
Class description:
A simple threadpool class to limit the number of simultaneous threads. Any threading.Thread object can be added to the pool using the append() method. If the maximum number of simultaneous threads has not been reached, the Thread object will b... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class ThreadList:
"""A simple threadpool class to limit the number of simultaneous threads. Any threading.Thread object can be added to the pool using the append() method. If the maximum number of simultaneous threads has not been reached, the Thread object will be started immediately; if not, the appe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadList:
"""A simple threadpool class to limit the number of simultaneous threads. Any threading.Thread object can be added to the pool using the append() method. If the maximum number of simultaneous threads has not been reached, the Thread object will be started immediately; if not, the append() call wil... | the_stack_v2_python_sparse | pywikibot/tools/threading.py | wikimedia/pywikibot | train | 432 |
5b4aec72b768dc96f5310aea98c1d8e0897e3970 | [
"super().__init__()\nself.dropout_rate = dropout_rate\nself.prenet = nn.LayerList()\nfor layer in six.moves.range(n_layers):\n n_inputs = idim if layer == 0 else n_units\n self.prenet.append(nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU()))",
"for i in six.moves.range(len(self.prenet)):\n x = F.dro... | <|body_start_0|>
super().__init__()
self.dropout_rate = dropout_rate
self.prenet = nn.LayerList()
for layer in six.moves.range(n_layers):
n_inputs = idim if layer == 0 else n_units
self.prenet.append(nn.Sequential(nn.Linear(n_inputs, n_units), nn.ReLU()))
<|end_bo... | Prenet module for decoder of Spectrogram prediction network. This is a module of Prenet in the decoder of Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of inputs before input to auto-regressive... | Prenet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Prenet:
"""Prenet module for decoder of Spectrogram prediction network. This is a module of Prenet in the decoder of Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of inpu... | stack_v2_sparse_classes_36k_train_034087 | 6,559 | permissive | [
{
"docstring": "Initialize prenet module. Parameters ---------- idim : int Dimension of the inputs. odim : int Dimension of the outputs. n_layers : int, optional The number of prenet layers. n_units : int, optional The number of prenet units.",
"name": "__init__",
"signature": "def __init__(self, idim, ... | 2 | null | Implement the Python class `Prenet` described below.
Class description:
Prenet module for decoder of Spectrogram prediction network. This is a module of Prenet in the decoder of Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prene... | Implement the Python class `Prenet` described below.
Class description:
Prenet module for decoder of Spectrogram prediction network. This is a module of Prenet in the decoder of Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prene... | 8705a2a8405e3c63f2174d69880d2b5525a6c9fd | <|skeleton|>
class Prenet:
"""Prenet module for decoder of Spectrogram prediction network. This is a module of Prenet in the decoder of Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Prenet:
"""Prenet module for decoder of Spectrogram prediction network. This is a module of Prenet in the decoder of Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Prenet preforms nonlinear conversion of inputs before inp... | the_stack_v2_python_sparse | parakeet/modules/tacotron2/decoder.py | PaddlePaddle/Parakeet | train | 609 |
7d33af08075958ab5704a7411bf3e956b55bdcd6 | [
"self.scanning_enabled = scanning_enabled\nself.advertising_enabled = advertising_enabled\nself.uuid = uuid\nself.major_minor_assignment_mode = major_minor_assignment_mode\nself.major = major\nself.minor = minor",
"if dictionary is None:\n return None\nscanning_enabled = dictionary.get('scanningEnabled')\nadve... | <|body_start_0|>
self.scanning_enabled = scanning_enabled
self.advertising_enabled = advertising_enabled
self.uuid = uuid
self.major_minor_assignment_mode = major_minor_assignment_mode
self.major = major
self.minor = minor
<|end_body_0|>
<|body_start_1|>
if dicti... | Implementation of the 'updateNetworkBluetoothSettings' model. TODO: type model description here. Attributes: scanning_enabled (bool): Whether APs will scan for Bluetooth enabled clients. (true, false) advertising_enabled (bool): Whether APs will advertise beacons. (true, false) uuid (string): The UUID to be used in the... | UpdateNetworkBluetoothSettingsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkBluetoothSettingsModel:
"""Implementation of the 'updateNetworkBluetoothSettings' model. TODO: type model description here. Attributes: scanning_enabled (bool): Whether APs will scan for Bluetooth enabled clients. (true, false) advertising_enabled (bool): Whether APs will advertise b... | stack_v2_sparse_classes_36k_train_034088 | 3,237 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkBluetoothSettingsModel class",
"name": "__init__",
"signature": "def __init__(self, scanning_enabled=None, advertising_enabled=None, uuid=None, major_minor_assignment_mode=None, major=None, minor=None)"
},
{
"docstring": "Creates an instance of th... | 2 | null | Implement the Python class `UpdateNetworkBluetoothSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkBluetoothSettings' model. TODO: type model description here. Attributes: scanning_enabled (bool): Whether APs will scan for Bluetooth enabled clients. (true, false) advertising_enabl... | Implement the Python class `UpdateNetworkBluetoothSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkBluetoothSettings' model. TODO: type model description here. Attributes: scanning_enabled (bool): Whether APs will scan for Bluetooth enabled clients. (true, false) advertising_enabl... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkBluetoothSettingsModel:
"""Implementation of the 'updateNetworkBluetoothSettings' model. TODO: type model description here. Attributes: scanning_enabled (bool): Whether APs will scan for Bluetooth enabled clients. (true, false) advertising_enabled (bool): Whether APs will advertise b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateNetworkBluetoothSettingsModel:
"""Implementation of the 'updateNetworkBluetoothSettings' model. TODO: type model description here. Attributes: scanning_enabled (bool): Whether APs will scan for Bluetooth enabled clients. (true, false) advertising_enabled (bool): Whether APs will advertise beacons. (true... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_bluetooth_settings_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
c3ee8a38a79865f238b73b5f83c3a60b50f50629 | [
"assert html_tag in ('li', 'div', 'span', None)\nself.html_tag = html_tag\nself.prefix_label = prefix_label\nself.with_label = with_label\nself.class_ = class_",
"if self.with_label:\n if self.prefix_label:\n return '%s: %s' % (subfield.label, subfield())\n else:\n return '%s %s' % (subfield()... | <|body_start_0|>
assert html_tag in ('li', 'div', 'span', None)
self.html_tag = html_tag
self.prefix_label = prefix_label
self.with_label = with_label
self.class_ = class_
<|end_body_0|>
<|body_start_1|>
if self.with_label:
if self.prefix_label:
... | Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed. | ListItemWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListItemWidget:
"""Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed."""
def __init__(self, html_tag='li', with_label=True, prefix_labe... | stack_v2_sparse_classes_36k_train_034089 | 15,429 | no_license | [
{
"docstring": "Initialize list item with html tag. :param html_tag: name of html tag can be 'li', 'div', or 'span'.",
"name": "__init__",
"signature": "def __init__(self, html_tag='li', with_label=True, prefix_label=True, class_=None)"
},
{
"docstring": "Render subfield.",
"name": "render_s... | 5 | null | Implement the Python class `ListItemWidget` described below.
Class description:
Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed.
Method signatures and docstrin... | Implement the Python class `ListItemWidget` described below.
Class description:
Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed.
Method signatures and docstrin... | 90032ba4825c6c4dda78c9c2b1d3edf18692b9dc | <|skeleton|>
class ListItemWidget:
"""Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed."""
def __init__(self, html_tag='li', with_label=True, prefix_labe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListItemWidget:
"""Render each subfield in a ExtendedListWidget as a list element. If `with_label` is set, the fields label will be rendered. If `prefix_label` is set, the label will be prefixed, otherwise it will be suffixed."""
def __init__(self, html_tag='li', with_label=True, prefix_label=True, class... | the_stack_v2_python_sparse | inspirehep/modules/forms/field_widgets.py | spirosdelviniotis/inspire-next | train | 1 |
7f391a99f1ea4548114aa463c62c70c7f7cce375 | [
"lfdo = tree_string_to_LFDO(g_tree_string)\nfor N in (1, 5, 10):\n lfdn_a = LFDO_to_LFDN(lfdo, N)\n lfdm = LFDO_to_LFDM(lfdo, N)\n lfdn_b = LFDM_to_LFDN(lfdm)\n self.assertTrue(np.allclose(lfdn_a.M, lfdn_b.M))",
"lfdo = tree_string_to_LFDO(g_tree_string)\nN = 1\nlfdn = LFDO_to_LFDN(lfdo, N)\nHDH = Mat... | <|body_start_0|>
lfdo = tree_string_to_LFDO(g_tree_string)
for N in (1, 5, 10):
lfdn_a = LFDO_to_LFDN(lfdo, N)
lfdm = LFDO_to_LFDM(lfdo, N)
lfdn_b = LFDM_to_LFDN(lfdm)
self.assertTrue(np.allclose(lfdn_a.M, lfdn_b.M))
<|end_body_0|>
<|body_start_1|>
... | ProofDecorationTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProofDecorationTest:
def test_lfdn_shortcut(self):
"""Check two ways of constructing blocks of a matrix. The matrix in question is the centered finitely extended matrix. One way is to construct the whole matrix and then take blocks. The other way is to construct the blocks more directly.... | stack_v2_sparse_classes_36k_train_034090 | 7,534 | no_license | [
{
"docstring": "Check two ways of constructing blocks of a matrix. The matrix in question is the centered finitely extended matrix. One way is to construct the whole matrix and then take blocks. The other way is to construct the blocks more directly.",
"name": "test_lfdn_shortcut",
"signature": "def tes... | 4 | null | Implement the Python class `ProofDecorationTest` described below.
Class description:
Implement the ProofDecorationTest class.
Method signatures and docstrings:
- def test_lfdn_shortcut(self): Check two ways of constructing blocks of a matrix. The matrix in question is the centered finitely extended matrix. One way is... | Implement the Python class `ProofDecorationTest` described below.
Class description:
Implement the ProofDecorationTest class.
Method signatures and docstrings:
- def test_lfdn_shortcut(self): Check two ways of constructing blocks of a matrix. The matrix in question is the centered finitely extended matrix. One way is... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class ProofDecorationTest:
def test_lfdn_shortcut(self):
"""Check two ways of constructing blocks of a matrix. The matrix in question is the centered finitely extended matrix. One way is to construct the whole matrix and then take blocks. The other way is to construct the blocks more directly.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProofDecorationTest:
def test_lfdn_shortcut(self):
"""Check two ways of constructing blocks of a matrix. The matrix in question is the centered finitely extended matrix. One way is to construct the whole matrix and then take blocks. The other way is to construct the blocks more directly."""
lf... | the_stack_v2_python_sparse | ProofDecoration.py | argriffing/xgcode | train | 1 | |
6f4776aea2e74bc9b2d08fe274b50b54baaeedbb | [
"self.eps = eps\nself.beta = beta\nself.r = r",
"assert atlases_prob.get_shape().as_list()[-1] == 2, 'Only applicable to binary segmentation in current version!'\nassert atlases_prob.get_shape().as_list()[-2] == 1, 'Only applicable to single-atlas segmentation in current version!'\natlases_prob = tf.clip_by_value... | <|body_start_0|>
self.eps = eps
self.beta = beta
self.r = r
<|end_body_0|>
<|body_start_1|>
assert atlases_prob.get_shape().as_list()[-1] == 2, 'Only applicable to binary segmentation in current version!'
assert atlases_prob.get_shape().as_list()[-2] == 1, 'Only applicable to si... | Compute the KL-divergence loss between the true posterior and approximate posterior, only applicable to binary and single-atlas segmentation currently. Todo: Generalise the class to multi-class and multi-atlas segmentation. | KLDivergenceLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KLDivergenceLoss:
"""Compute the KL-divergence loss between the true posterior and approximate posterior, only applicable to binary and single-atlas segmentation currently. Todo: Generalise the class to multi-class and multi-atlas segmentation."""
def __init__(self, eps=1e-10, beta=0.5, r=2,... | stack_v2_sparse_classes_36k_train_034091 | 35,006 | permissive | [
{
"docstring": "Initialization. :param eps: epsilon for probability truncation :param beta: parameter to control the weight distribution :param r: radius of the cube-shaped neighbourhood",
"name": "__init__",
"signature": "def __init__(self, eps=1e-10, beta=0.5, r=2, **kwargs)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_003155 | Implement the Python class `KLDivergenceLoss` described below.
Class description:
Compute the KL-divergence loss between the true posterior and approximate posterior, only applicable to binary and single-atlas segmentation currently. Todo: Generalise the class to multi-class and multi-atlas segmentation.
Method signa... | Implement the Python class `KLDivergenceLoss` described below.
Class description:
Compute the KL-divergence loss between the true posterior and approximate posterior, only applicable to binary and single-atlas segmentation currently. Todo: Generalise the class to multi-class and multi-atlas segmentation.
Method signa... | c08d5df14b4a9c4a98c66973ff4950aba7f416e4 | <|skeleton|>
class KLDivergenceLoss:
"""Compute the KL-divergence loss between the true posterior and approximate posterior, only applicable to binary and single-atlas segmentation currently. Todo: Generalise the class to multi-class and multi-atlas segmentation."""
def __init__(self, eps=1e-10, beta=0.5, r=2,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KLDivergenceLoss:
"""Compute the KL-divergence loss between the true posterior and approximate posterior, only applicable to binary and single-atlas segmentation currently. Todo: Generalise the class to multi-class and multi-atlas segmentation."""
def __init__(self, eps=1e-10, beta=0.5, r=2, **kwargs):
... | the_stack_v2_python_sparse | src_2d/core/losses_2d.py | Felix660/MvMM-RegNet | train | 0 |
20e7991f4068a4b7c31b61b3a22a35b4a3a510be | [
"super().__init__()\nif residuals is not None:\n residuals = residuals.lower()\nself.residuals = residuals\nself.body = nn.Sequential(nn.Linear(features_in, features_out, bias=False), norm_factory(features_out), activation_factory())",
"if self.residuals is None:\n return self.body(x)\nif self.residuals == ... | <|body_start_0|>
super().__init__()
if residuals is not None:
residuals = residuals.lower()
self.residuals = residuals
self.body = nn.Sequential(nn.Linear(features_in, features_out, bias=False), norm_factory(features_out), activation_factory())
<|end_body_0|>
<|body_start_1|... | A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor. | MLPBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The numbe... | stack_v2_sparse_classes_36k_train_034092 | 9,125 | permissive | [
{
"docstring": "Args: features_in: The number of features of the block input. features_out: The number of features of the block output. activation_factory: A factory functional to create the activation layers in the block. norm_factory: A factory functional to create the normalization layers used in the block. ... | 2 | stack_v2_sparse_classes_30k_train_000083 | Implement the Python class `MLPBlock` described below.
Class description:
A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor.
Method signatures and docstrings:
- def __init__(self, features_in, features_out, activation_factory, no... | Implement the Python class `MLPBlock` described below.
Class description:
A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor.
Method signatures and docstrings:
- def __init__(self, features_in, features_out, activation_factory, no... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The numbe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The number of features... | the_stack_v2_python_sparse | quantnn/models/pytorch/fully_connected.py | simonpf/quantnn | train | 7 |
5b48611374365147ee87cc81424241d577ac2f85 | [
"logger.debug('Initializing xform: log: %s phys: %s', str(log_rect), str(phys_rect))\nself.log_rect = log_rect\nself.phys_rect = phys_rect\nself._w_log = self.log_rect.SignedWidth()\nself._h_log = self.log_rect.SignedHeight()\nself._w_phys = self.phys_rect.SignedWidth()\nself._h_phys = self.phys_rect.SignedHeight()... | <|body_start_0|>
logger.debug('Initializing xform: log: %s phys: %s', str(log_rect), str(phys_rect))
self.log_rect = log_rect
self.phys_rect = phys_rect
self._w_log = self.log_rect.SignedWidth()
self._h_log = self.log_rect.SignedHeight()
self._w_phys = self.phys_rect.Sign... | Well-known graphics window <-> viewport transformation. Many explanations on the web, one is: http://www.siggraph.org/education/materials/HyperGraph/viewing/ view2d/pwint.htm Window (here 'logical') is the projection space, viewport ('physical') is tilepixel space. | WindowViewportMapping | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowViewportMapping:
"""Well-known graphics window <-> viewport transformation. Many explanations on the web, one is: http://www.siggraph.org/education/materials/HyperGraph/viewing/ view2d/pwint.htm Window (here 'logical') is the projection space, viewport ('physical') is tilepixel space."""
... | stack_v2_sparse_classes_36k_train_034093 | 3,683 | permissive | [
{
"docstring": "Initialization. The corners of <log_rect> and <phys_rect> have to correspond. Args: log_rect: the logical rectangle, the 'window'. phys_rect: the physical rectangle, the 'viewport' or 'device'.",
"name": "__init__",
"signature": "def __init__(self, log_rect, phys_rect)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_007080 | Implement the Python class `WindowViewportMapping` described below.
Class description:
Well-known graphics window <-> viewport transformation. Many explanations on the web, one is: http://www.siggraph.org/education/materials/HyperGraph/viewing/ view2d/pwint.htm Window (here 'logical') is the projection space, viewport... | Implement the Python class `WindowViewportMapping` described below.
Class description:
Well-known graphics window <-> viewport transformation. Many explanations on the web, one is: http://www.siggraph.org/education/materials/HyperGraph/viewing/ view2d/pwint.htm Window (here 'logical') is the projection space, viewport... | bb46deb53a4871518b33d788c5d18d4342c41657 | <|skeleton|>
class WindowViewportMapping:
"""Well-known graphics window <-> viewport transformation. Many explanations on the web, one is: http://www.siggraph.org/education/materials/HyperGraph/viewing/ view2d/pwint.htm Window (here 'logical') is the projection space, viewport ('physical') is tilepixel space."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowViewportMapping:
"""Well-known graphics window <-> viewport transformation. Many explanations on the web, one is: http://www.siggraph.org/education/materials/HyperGraph/viewing/ view2d/pwint.htm Window (here 'logical') is the projection space, viewport ('physical') is tilepixel space."""
def __init... | the_stack_v2_python_sparse | earth_enterprise/src/server/wsgi/wms/ogc/common/xform.py | mylxiaoyi/earthenterprise | train | 2 |
21f7e3d698c72ba04caf2411139d778a2b7ba2bb | [
"super(routing_table, self).__init__(fpath, threadlock)\nself.tag = 'routing_table'\nself.cfg = {}\nself.ipv4_syntax = {'destination': {'T': str, 'D': '192.168.0.0', 'M': True, 'S': None, 'V': [ml_check.validate_ipv4]}, 'prefix': {'T': int, 'D': 24, 'M': True, 'S': None, 'V': [ml_check.validate_ipv4_prefix]}, 'gate... | <|body_start_0|>
super(routing_table, self).__init__(fpath, threadlock)
self.tag = 'routing_table'
self.cfg = {}
self.ipv4_syntax = {'destination': {'T': str, 'D': '192.168.0.0', 'M': True, 'S': None, 'V': [ml_check.validate_ipv4]}, 'prefix': {'T': int, 'D': 24, 'M': True, 'S': None, 'V'... | Routing Table | routing_table | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class routing_table:
"""Routing Table"""
def __init__(self, fpath=os.path.join(ml_system.CFG_PATH, 'routing_table.txt'), threadlock=None):
"""init config"""
<|body_0|>
def do_set(self):
"""real task"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
supe... | stack_v2_sparse_classes_36k_train_034094 | 3,706 | no_license | [
{
"docstring": "init config",
"name": "__init__",
"signature": "def __init__(self, fpath=os.path.join(ml_system.CFG_PATH, 'routing_table.txt'), threadlock=None)"
},
{
"docstring": "real task",
"name": "do_set",
"signature": "def do_set(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016820 | Implement the Python class `routing_table` described below.
Class description:
Routing Table
Method signatures and docstrings:
- def __init__(self, fpath=os.path.join(ml_system.CFG_PATH, 'routing_table.txt'), threadlock=None): init config
- def do_set(self): real task | Implement the Python class `routing_table` described below.
Class description:
Routing Table
Method signatures and docstrings:
- def __init__(self, fpath=os.path.join(ml_system.CFG_PATH, 'routing_table.txt'), threadlock=None): init config
- def do_set(self): real task
<|skeleton|>
class routing_table:
"""Routing... | 12a25d06c8ea7971267aca43a63aafb71b29a3f1 | <|skeleton|>
class routing_table:
"""Routing Table"""
def __init__(self, fpath=os.path.join(ml_system.CFG_PATH, 'routing_table.txt'), threadlock=None):
"""init config"""
<|body_0|>
def do_set(self):
"""real task"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class routing_table:
"""Routing Table"""
def __init__(self, fpath=os.path.join(ml_system.CFG_PATH, 'routing_table.txt'), threadlock=None):
"""init config"""
super(routing_table, self).__init__(fpath, threadlock)
self.tag = 'routing_table'
self.cfg = {}
self.ipv4_syntax =... | the_stack_v2_python_sparse | ml_w_routing_table.py | poyhsiao/betapyweb-middleware | train | 0 |
b97c5d03774577aabae46632a1a9428a132df0c7 | [
"books = BookInfo.objects.all()\nbooks_li = []\nfor book in books:\n data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else ''}\n books_li.append(data)\nreturn JsonResponse(books_li, safe=False)",
... | <|body_start_0|>
books = BookInfo.objects.all()
books_li = []
for book in books:
data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else ''}
books_li.append(data)... | BookListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookListView:
def get(self, request):
"""获取所有图书信息"""
<|body_0|>
def post(self, request):
"""新建一本图书信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
books = BookInfo.objects.all()
books_li = []
for book in books:
data = {... | stack_v2_sparse_classes_36k_train_034095 | 4,373 | no_license | [
{
"docstring": "获取所有图书信息",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新建一本图书信息",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000075 | Implement the Python class `BookListView` described below.
Class description:
Implement the BookListView class.
Method signatures and docstrings:
- def get(self, request): 获取所有图书信息
- def post(self, request): 新建一本图书信息 | Implement the Python class `BookListView` described below.
Class description:
Implement the BookListView class.
Method signatures and docstrings:
- def get(self, request): 获取所有图书信息
- def post(self, request): 新建一本图书信息
<|skeleton|>
class BookListView:
def get(self, request):
"""获取所有图书信息"""
<|body_... | f8ec0bec399253e481e16443ba9a3e45e61486f4 | <|skeleton|>
class BookListView:
def get(self, request):
"""获取所有图书信息"""
<|body_0|>
def post(self, request):
"""新建一本图书信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookListView:
def get(self, request):
"""获取所有图书信息"""
books = BookInfo.objects.all()
books_li = []
for book in books:
data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if... | the_stack_v2_python_sparse | drf_demo/booktest/views-01-Django自定义RestAPI接口.py | cz495969281/2019_- | train | 0 | |
89f507bc0e205ae3fc33ab4b8d80c3be9424c360 | [
"super(MidasNet_ASPP, self).__init__()\nuse_pretrained = False if path else True\nself.pretrained, self.scratch = _make_encoder('resnext101_wsl_aspp', features, use_pretrained)\nself.scratch.refinenet4 = FeatureFusionBlock(features)\nself.scratch.refinenet3 = FeatureFusionBlock(features)\nself.scratch.refinenet2 = ... | <|body_start_0|>
super(MidasNet_ASPP, self).__init__()
use_pretrained = False if path else True
self.pretrained, self.scratch = _make_encoder('resnext101_wsl_aspp', features, use_pretrained)
self.scratch.refinenet4 = FeatureFusionBlock(features)
self.scratch.refinenet3 = FeatureF... | Network for monocular depth estimation. | MidasNet_ASPP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidasNet_ASPP:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone netw... | stack_v2_sparse_classes_36k_train_034096 | 13,019 | permissive | [
{
"docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50",
"name": "__init__",
"signature": "def __init__(self, path=None, features=... | 2 | stack_v2_sparse_classes_30k_train_004442 | Implement the Python class `MidasNet_ASPP` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features.... | Implement the Python class `MidasNet_ASPP` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features.... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class MidasNet_ASPP:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone netw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MidasNet_ASPP:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encod... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/midas_net.py | kcyu2014/nas-landmarkreg | train | 10 |
4cd4203af612c4f2688395919f70e2a827d9fe76 | [
"if source is None:\n raise ValueError('source cannot be empty')\nself.allowed = load_passwords(source)\nself.algo = algo\nself.auth_header_prefix = 'Basic'",
"if not auth_header:\n raise falcon.HTTPUnauthorized(title='401 Unauthorized', description='Missing Authorization Header')\nparts = auth_header.split... | <|body_start_0|>
if source is None:
raise ValueError('source cannot be empty')
self.allowed = load_passwords(source)
self.algo = algo
self.auth_header_prefix = 'Basic'
<|end_body_0|>
<|body_start_1|>
if not auth_header:
raise falcon.HTTPUnauthorized(title... | Authentification. The name and secret comes from a file. The file must store encrypted password. | AuthMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthMiddleware:
"""Authentification. The name and secret comes from a file. The file must store encrypted password."""
def __init__(self, source, algo='sha224'):
"""@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords"""
... | stack_v2_sparse_classes_36k_train_034097 | 3,541 | permissive | [
{
"docstring": "@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords",
"name": "__init__",
"signature": "def __init__(self, source, algo='sha224')"
},
{
"docstring": "Parses and returns Auth token from the request header. Raises `falcon.HTTP... | 4 | null | Implement the Python class `AuthMiddleware` described below.
Class description:
Authentification. The name and secret comes from a file. The file must store encrypted password.
Method signatures and docstrings:
- def __init__(self, source, algo='sha224'): @param source filename or dataframe for encrypted password @pa... | Implement the Python class `AuthMiddleware` described below.
Class description:
Authentification. The name and secret comes from a file. The file must store encrypted password.
Method signatures and docstrings:
- def __init__(self, source, algo='sha224'): @param source filename or dataframe for encrypted password @pa... | def172965eb197d8ab7f812c3f5f5ce129593cef | <|skeleton|>
class AuthMiddleware:
"""Authentification. The name and secret comes from a file. The file must store encrypted password."""
def __init__(self, source, algo='sha224'):
"""@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthMiddleware:
"""Authentification. The name and secret comes from a file. The file must store encrypted password."""
def __init__(self, source, algo='sha224'):
"""@param source filename or dataframe for encrypted password @param algo algorithm used to hash the passwords"""
if source is ... | the_stack_v2_python_sparse | src/lightmlrestapi/mlapp/authfiction.py | sdpython/lightmlrestapi | train | 0 |
fe1a15bdd485b7ce09a64646d007ae0154748c2d | [
"try:\n return base64.b64encode(pickle.dumps(obj)).decode()\nexcept pickle.PicklingError:\n pass",
"try:\n return pickle.loads(base64.b64decode(obj_str.encode()))\nexcept pickle.UnpicklingError:\n pass"
] | <|body_start_0|>
try:
return base64.b64encode(pickle.dumps(obj)).decode()
except pickle.PicklingError:
pass
<|end_body_0|>
<|body_start_1|>
try:
return pickle.loads(base64.b64decode(obj_str.encode()))
except pickle.UnpicklingError:
pass
<|... | transform object and string | ObjectTransform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectTransform:
"""transform object and string"""
def pickle_dumps_to_str(cls, obj):
"""from object to str"""
<|body_0|>
def pickle_loads_from_str(cls, obj_str):
"""from str to object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_034098 | 1,183 | permissive | [
{
"docstring": "from object to str",
"name": "pickle_dumps_to_str",
"signature": "def pickle_dumps_to_str(cls, obj)"
},
{
"docstring": "from str to object",
"name": "pickle_loads_from_str",
"signature": "def pickle_loads_from_str(cls, obj_str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013741 | Implement the Python class `ObjectTransform` described below.
Class description:
transform object and string
Method signatures and docstrings:
- def pickle_dumps_to_str(cls, obj): from object to str
- def pickle_loads_from_str(cls, obj_str): from str to object | Implement the Python class `ObjectTransform` described below.
Class description:
transform object and string
Method signatures and docstrings:
- def pickle_dumps_to_str(cls, obj): from object to str
- def pickle_loads_from_str(cls, obj_str): from str to object
<|skeleton|>
class ObjectTransform:
"""transform obj... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class ObjectTransform:
"""transform object and string"""
def pickle_dumps_to_str(cls, obj):
"""from object to str"""
<|body_0|>
def pickle_loads_from_str(cls, obj_str):
"""from str to object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectTransform:
"""transform object and string"""
def pickle_dumps_to_str(cls, obj):
"""from object to str"""
try:
return base64.b64encode(pickle.dumps(obj)).decode()
except pickle.PicklingError:
pass
def pickle_loads_from_str(cls, obj_str):
"... | the_stack_v2_python_sparse | ST_DM/KDD2021-MSTPAC/code/MST-PAC/utils/object_transform.py | sserdoubleh/Research | train | 10 |
a3f5f64372a07ddced41b70917651745d96ad864 | [
"dr = login_domain\nself.arn = resnodeaction.Add_Res_Node(dr)\nself.srmpg = sys_regionMgrPage.SysRegionMgrPage(dr)\np_data = datainfo.get_xls_to_dict('res_node_data.xlsx', 'endpoint')['创建vmware-endpoint']\nself.arn.delete_endpoint(p_data['regionname'], p_data['nodename'], p_data['servicename'])\ntime.sleep(globalpa... | <|body_start_0|>
dr = login_domain
self.arn = resnodeaction.Add_Res_Node(dr)
self.srmpg = sys_regionMgrPage.SysRegionMgrPage(dr)
p_data = datainfo.get_xls_to_dict('res_node_data.xlsx', 'endpoint')['创建vmware-endpoint']
self.arn.delete_endpoint(p_data['regionname'], p_data['nodenam... | 测试删除Endpoint | TestDeleteEndpoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDeleteEndpoint:
"""测试删除Endpoint"""
def test_delete_vmware_endpoint(self, login_domain):
"""测试删除vmware,endpoint :return:"""
<|body_0|>
def test_delete_openstack_endpoint(self, login_domain):
"""测试删除openstack,endpoint :return:"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_034099 | 2,397 | no_license | [
{
"docstring": "测试删除vmware,endpoint :return:",
"name": "test_delete_vmware_endpoint",
"signature": "def test_delete_vmware_endpoint(self, login_domain)"
},
{
"docstring": "测试删除openstack,endpoint :return:",
"name": "test_delete_openstack_endpoint",
"signature": "def test_delete_openstack_... | 2 | null | Implement the Python class `TestDeleteEndpoint` described below.
Class description:
测试删除Endpoint
Method signatures and docstrings:
- def test_delete_vmware_endpoint(self, login_domain): 测试删除vmware,endpoint :return:
- def test_delete_openstack_endpoint(self, login_domain): 测试删除openstack,endpoint :return: | Implement the Python class `TestDeleteEndpoint` described below.
Class description:
测试删除Endpoint
Method signatures and docstrings:
- def test_delete_vmware_endpoint(self, login_domain): 测试删除vmware,endpoint :return:
- def test_delete_openstack_endpoint(self, login_domain): 测试删除openstack,endpoint :return:
<|skeleton|>... | 7997338cd1038512be5cc0ad6fb60054896d0c59 | <|skeleton|>
class TestDeleteEndpoint:
"""测试删除Endpoint"""
def test_delete_vmware_endpoint(self, login_domain):
"""测试删除vmware,endpoint :return:"""
<|body_0|>
def test_delete_openstack_endpoint(self, login_domain):
"""测试删除openstack,endpoint :return:"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDeleteEndpoint:
"""测试删除Endpoint"""
def test_delete_vmware_endpoint(self, login_domain):
"""测试删除vmware,endpoint :return:"""
dr = login_domain
self.arn = resnodeaction.Add_Res_Node(dr)
self.srmpg = sys_regionMgrPage.SysRegionMgrPage(dr)
p_data = datainfo.get_xls_... | the_stack_v2_python_sparse | testcase/test_17_delete_endpoint.py | woozs/ui_auto_test | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.