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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2fbebc64a3053f3ad34878e8a60c5550b4b6ba6 | [
"self.checkpoint_dir = os.path.dirname(__file__) + '/checkpoint'\nself.num_pipeline = None\nself.cat_pipeline = None\nself.log_reg = None",
"data = feed['data_path'] + '/data.csv'\ndata = pd.read_csv(data)\nlabeldata = data['ArrDel15']\ndata = data.drop(['ArrDel15'], axis=1)\nallfeatures = list(data.columns.value... | <|body_start_0|>
self.checkpoint_dir = os.path.dirname(__file__) + '/checkpoint'
self.num_pipeline = None
self.cat_pipeline = None
self.log_reg = None
<|end_body_0|>
<|body_start_1|>
data = feed['data_path'] + '/data.csv'
data = pd.read_csv(data)
labeldata = data... | sesese | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sesese:
def __init__(self):
""":param feed:"""
<|body_0|>
def train(self, feed={}):
""":param feed: :return:"""
<|body_1|>
def predict(self, feed={}):
""":param feed: :return:"""
<|body_2|>
def load_model(self):
""":param fee... | stack_v2_sparse_classes_36k_train_015700 | 3,915 | no_license | [
{
"docstring": ":param feed:",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param feed: :return:",
"name": "train",
"signature": "def train(self, feed={})"
},
{
"docstring": ":param feed: :return:",
"name": "predict",
"signature": "def predict... | 4 | stack_v2_sparse_classes_30k_train_017077 | Implement the Python class `sesese` described below.
Class description:
Implement the sesese class.
Method signatures and docstrings:
- def __init__(self): :param feed:
- def train(self, feed={}): :param feed: :return:
- def predict(self, feed={}): :param feed: :return:
- def load_model(self): :param feed: :return: | Implement the Python class `sesese` described below.
Class description:
Implement the sesese class.
Method signatures and docstrings:
- def __init__(self): :param feed:
- def train(self, feed={}): :param feed: :return:
- def predict(self, feed={}): :param feed: :return:
- def load_model(self): :param feed: :return:
... | 26ccff6c2f1ed3a8ba00a2c256aaa0199197b175 | <|skeleton|>
class sesese:
def __init__(self):
""":param feed:"""
<|body_0|>
def train(self, feed={}):
""":param feed: :return:"""
<|body_1|>
def predict(self, feed={}):
""":param feed: :return:"""
<|body_2|>
def load_model(self):
""":param fee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sesese:
def __init__(self):
""":param feed:"""
self.checkpoint_dir = os.path.dirname(__file__) + '/checkpoint'
self.num_pipeline = None
self.cat_pipeline = None
self.log_reg = None
def train(self, feed={}):
""":param feed: :return:"""
data = feed['d... | the_stack_v2_python_sparse | pyserver/functions/zhaofengli-mmm/modules/zhaofengli/sesese/src/.ipynb_checkpoints/main-checkpoint.py | StevenXue/mo | train | 0 | |
45c282e5451e9b9c2e4ffd94629784853dfa1c92 | [
"log.debug('GET request from user %s for stage plan list' % request.user)\nproj = Project.objects.get(project_number=project_number)\nwbs = WorkItem.objects.get(id=wbs_id)\nif not check_project_read_acl(proj, request.user):\n log.debug('Refusing GET request for project list %s from user %s' % (project_number, re... | <|body_start_0|>
log.debug('GET request from user %s for stage plan list' % request.user)
proj = Project.objects.get(project_number=project_number)
wbs = WorkItem.objects.get(id=wbs_id)
if not check_project_read_acl(proj, request.user):
log.debug('Refusing GET request for pro... | URL: /api/engineeringdays/%project_number%/%wbs_id%/ VERBS: GET, POST Returns a list of EngineeringDays associated with a Work Item, also adds a new EngineeringDay to the WorkItem | EngineeringDayWBSListHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EngineeringDayWBSListHandler:
"""URL: /api/engineeringdays/%project_number%/%wbs_id%/ VERBS: GET, POST Returns a list of EngineeringDays associated with a Work Item, also adds a new EngineeringDay to the WorkItem"""
def read(self, request, project_number):
"""Return a list of enginee... | stack_v2_sparse_classes_36k_train_015701 | 19,350 | no_license | [
{
"docstring": "Return a list of engineering days associated with a work item",
"name": "read",
"signature": "def read(self, request, project_number)"
},
{
"docstring": "Create a new Engineering Day",
"name": "create",
"signature": "def create(self, request, project_number, wbs_id)"
}
... | 2 | stack_v2_sparse_classes_30k_train_015773 | Implement the Python class `EngineeringDayWBSListHandler` described below.
Class description:
URL: /api/engineeringdays/%project_number%/%wbs_id%/ VERBS: GET, POST Returns a list of EngineeringDays associated with a Work Item, also adds a new EngineeringDay to the WorkItem
Method signatures and docstrings:
- def read... | Implement the Python class `EngineeringDayWBSListHandler` described below.
Class description:
URL: /api/engineeringdays/%project_number%/%wbs_id%/ VERBS: GET, POST Returns a list of EngineeringDays associated with a Work Item, also adds a new EngineeringDay to the WorkItem
Method signatures and docstrings:
- def read... | 106a96307612318fb66246486e7226069e5508ac | <|skeleton|>
class EngineeringDayWBSListHandler:
"""URL: /api/engineeringdays/%project_number%/%wbs_id%/ VERBS: GET, POST Returns a list of EngineeringDays associated with a Work Item, also adds a new EngineeringDay to the WorkItem"""
def read(self, request, project_number):
"""Return a list of enginee... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EngineeringDayWBSListHandler:
"""URL: /api/engineeringdays/%project_number%/%wbs_id%/ VERBS: GET, POST Returns a list of EngineeringDays associated with a Work Item, also adds a new EngineeringDay to the WorkItem"""
def read(self, request, project_number):
"""Return a list of engineering days ass... | the_stack_v2_python_sparse | branches/rest-api-branch/django-project-management/wbs/api_views.py | NhaTrang/django-project-management | train | 0 |
0e3e990c6f04b52c11e4cb6e67d82ed96b03b7ae | [
"if m <= 0:\n nums1[:] = nums2[:]\n return\ncurrent = 0\nfor i in range(n):\n for j in range(current, m):\n if nums2[i] >= nums1[m - 1]:\n nums1[m] = nums2[i]\n m += 1\n break\n if nums2[i] <= nums1[j]:\n nums1.insert(j, nums2[i])\n curre... | <|body_start_0|>
if m <= 0:
nums1[:] = nums2[:]
return
current = 0
for i in range(n):
for j in range(current, m):
if nums2[i] >= nums1[m - 1]:
nums1[m] = nums2[i]
m += 1
break
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge1(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1, m, nums2, n):
""":type nums1: List[int... | stack_v2_sparse_classes_36k_train_015702 | 1,307 | permissive | [
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.",
"name": "merge1",
"signature": "def merge1(self, nums1, m, nums2, n)"
},
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: ... | 2 | stack_v2_sparse_classes_30k_train_001866 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead.
... | 03876232521a20d32f8fa4e7d6d19cf208739a79 | <|skeleton|>
class Solution:
def merge1(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1, m, nums2, n):
""":type nums1: List[int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge1(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead."""
if m <= 0:
nums1[:] = nums2[:]
return
current = 0
for i in r... | the_stack_v2_python_sparse | Python/merge-sorted-array.py | coolryze/LeetCode | train | 4 | |
2cc168b86c888d42b6a77bb6ae18d5305a8746a9 | [
"response = super().get(request, *args, **kwargs)\nself.object.increase_views()\nreturn response",
"if self.object.category:\n return '%s_%s' % (self.object.title, self.object.category.name)\nreturn '%s' % self.object.title",
"post = super().get_object(queryset=queryset)\nmd = markdown.Markdown(extensions=['... | <|body_start_0|>
response = super().get(request, *args, **kwargs)
self.object.increase_views()
return response
<|end_body_0|>
<|body_start_1|>
if self.object.category:
return '%s_%s' % (self.object.title, self.object.category.name)
return '%s' % self.object.title
<|e... | DetailView方法顺序: get get_object get_ocntext_data get_hadline | PostDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostDetailView:
"""DetailView方法顺序: get get_object get_ocntext_data get_hadline"""
def get(self, request, *args, **kwargs):
"""每次被请求的post,点击量+1"""
<|body_0|>
def get_headline(self):
"""设置行头"""
<|body_1|>
def get_object(self, queryset=None):
""... | stack_v2_sparse_classes_36k_train_015703 | 8,828 | no_license | [
{
"docstring": "每次被请求的post,点击量+1",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "设置行头",
"name": "get_headline",
"signature": "def get_headline(self)"
},
{
"docstring": "获取对象(不是queryset) 使用markdown封装成html 增加toc",
"name": "get_object",... | 4 | stack_v2_sparse_classes_30k_train_014941 | Implement the Python class `PostDetailView` described below.
Class description:
DetailView方法顺序: get get_object get_ocntext_data get_hadline
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 每次被请求的post,点击量+1
- def get_headline(self): 设置行头
- def get_object(self, queryset=None): 获取对象(不是queryse... | Implement the Python class `PostDetailView` described below.
Class description:
DetailView方法顺序: get get_object get_ocntext_data get_hadline
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 每次被请求的post,点击量+1
- def get_headline(self): 设置行头
- def get_object(self, queryset=None): 获取对象(不是queryse... | 53f395f1d2ad2e4cea1fe38b99db705bb7fb352e | <|skeleton|>
class PostDetailView:
"""DetailView方法顺序: get get_object get_ocntext_data get_hadline"""
def get(self, request, *args, **kwargs):
"""每次被请求的post,点击量+1"""
<|body_0|>
def get_headline(self):
"""设置行头"""
<|body_1|>
def get_object(self, queryset=None):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostDetailView:
"""DetailView方法顺序: get get_object get_ocntext_data get_hadline"""
def get(self, request, *args, **kwargs):
"""每次被请求的post,点击量+1"""
response = super().get(request, *args, **kwargs)
self.object.increase_views()
return response
def get_headline(self):
... | the_stack_v2_python_sparse | blog/views.py | lianchonghui/django-blog | train | 1 |
cf2f466d601f487ea693148c9793467a296ee6a7 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DelegatedAdminAccessAssignment()",
"from .delegated_admin_access_assignment_status import DelegatedAdminAccessAssignmentStatus\nfrom .delegated_admin_access_container import DelegatedAdminAccessContainer\nfrom .delegated_admin_access_d... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DelegatedAdminAccessAssignment()
<|end_body_0|>
<|body_start_1|>
from .delegated_admin_access_assignment_status import DelegatedAdminAccessAssignmentStatus
from .delegated_admin_access_c... | DelegatedAdminAccessAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelegatedAdminAccessAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_36k_train_015704 | 4,301 | 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: DelegatedAdminAccessAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_from_di... | 3 | stack_v2_sparse_classes_30k_train_021027 | Implement the Python class `DelegatedAdminAccessAssignment` described below.
Class description:
Implement the DelegatedAdminAccessAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment: Creates a new instance of... | Implement the Python class `DelegatedAdminAccessAssignment` described below.
Class description:
Implement the DelegatedAdminAccessAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DelegatedAdminAccessAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelegatedAdminAccessAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DelegatedAdminAccessAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | the_stack_v2_python_sparse | msgraph/generated/models/delegated_admin_access_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a132ab0038f7687de592c9afcaed043005b828d9 | [
"self.view = view\nself.args = args\nself.kwargs = kwargs",
"if 'request' in context:\n request = context['request']\n view = urls.get_callable(Variable(self.view).resolve(context))\n args = [Variable(arg).resolve(context) for arg in self.args]\n kwargs = {key: Variable(value).resolve(context) for key... | <|body_start_0|>
self.view = view
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
if 'request' in context:
request = context['request']
view = urls.get_callable(Variable(self.view).resolve(context))
args = [Variable(arg).resolve(... | Insérer le contenu d'une vue Django dans un template Insertion par chemin complet de fonction La vue peut renvoyer une HttpReponse ou une chaîne de caractères. (Code basé sur un snippet de James G. Pearce, 17 juin 2009) | ViewFuncNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewFuncNode:
"""Insérer le contenu d'une vue Django dans un template Insertion par chemin complet de fonction La vue peut renvoyer une HttpReponse ou une chaîne de caractères. (Code basé sur un snippet de James G. Pearce, 17 juin 2009)"""
def __init__(self, view, args, kwargs):
"""I... | stack_v2_sparse_classes_36k_train_015705 | 5,870 | no_license | [
{
"docstring": "Initialiser le nœud",
"name": "__init__",
"signature": "def __init__(self, view, args, kwargs)"
},
{
"docstring": "Effectuer le rendu du nœud",
"name": "render",
"signature": "def render(self, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018201 | Implement the Python class `ViewFuncNode` described below.
Class description:
Insérer le contenu d'une vue Django dans un template Insertion par chemin complet de fonction La vue peut renvoyer une HttpReponse ou une chaîne de caractères. (Code basé sur un snippet de James G. Pearce, 17 juin 2009)
Method signatures an... | Implement the Python class `ViewFuncNode` described below.
Class description:
Insérer le contenu d'une vue Django dans un template Insertion par chemin complet de fonction La vue peut renvoyer une HttpReponse ou une chaîne de caractères. (Code basé sur un snippet de James G. Pearce, 17 juin 2009)
Method signatures an... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class ViewFuncNode:
"""Insérer le contenu d'une vue Django dans un template Insertion par chemin complet de fonction La vue peut renvoyer une HttpReponse ou une chaîne de caractères. (Code basé sur un snippet de James G. Pearce, 17 juin 2009)"""
def __init__(self, view, args, kwargs):
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewFuncNode:
"""Insérer le contenu d'une vue Django dans un template Insertion par chemin complet de fonction La vue peut renvoyer une HttpReponse ou une chaîne de caractères. (Code basé sur un snippet de James G. Pearce, 17 juin 2009)"""
def __init__(self, view, args, kwargs):
"""Initialiser le... | the_stack_v2_python_sparse | scoop/core/templatetags/panels.py | artscoop/scoop | train | 0 |
797396cbcabbfb6377eab4b54ca47b4f4e0bef85 | [
"self.fail_enabled = kwargs.get('fail_enabled', True)\nself.fail_msg = kwargs.get('fail_msg', 'Method returned invalid output.')\nself.fail_on = kwargs.get('fail_on', [])\nself.fail_msg_property = kwargs.get('fail_msg_property')\nself.write_output = kwargs.get('write_output', True)",
"def fail(app, *args, **kwarg... | <|body_start_0|>
self.fail_enabled = kwargs.get('fail_enabled', True)
self.fail_msg = kwargs.get('fail_msg', 'Method returned invalid output.')
self.fail_on = kwargs.get('fail_on', [])
self.fail_msg_property = kwargs.get('fail_msg_property')
self.write_output = kwargs.get('write_... | Fail App if return value (output) value conditions are met. This decorator allows for the App to exit on conditions defined in the function parameters. .. code-block:: python :linenos: :lineno-start: 1 @FailOnOutput( fail_on=['false'], fail_msg='Operation returned a value of "false".' ) def my_method(data): return data... | FailOnOutput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FailOnOutput:
"""Fail App if return value (output) value conditions are met. This decorator allows for the App to exit on conditions defined in the function parameters. .. code-block:: python :linenos: :lineno-start: 1 @FailOnOutput( fail_on=['false'], fail_msg='Operation returned a value of "fal... | stack_v2_sparse_classes_36k_train_015706 | 4,436 | permissive | [
{
"docstring": "Initialize Class properties.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Implement __call__ function for decorator. Args: wrapped (callable): The wrapped function which in turns needs to be called by your wrapper function. instance (App): ... | 3 | stack_v2_sparse_classes_30k_train_004736 | Implement the Python class `FailOnOutput` described below.
Class description:
Fail App if return value (output) value conditions are met. This decorator allows for the App to exit on conditions defined in the function parameters. .. code-block:: python :linenos: :lineno-start: 1 @FailOnOutput( fail_on=['false'], fail_... | Implement the Python class `FailOnOutput` described below.
Class description:
Fail App if return value (output) value conditions are met. This decorator allows for the App to exit on conditions defined in the function parameters. .. code-block:: python :linenos: :lineno-start: 1 @FailOnOutput( fail_on=['false'], fail_... | 7cf04fec048fadc71ff851970045b8a587269ccf | <|skeleton|>
class FailOnOutput:
"""Fail App if return value (output) value conditions are met. This decorator allows for the App to exit on conditions defined in the function parameters. .. code-block:: python :linenos: :lineno-start: 1 @FailOnOutput( fail_on=['false'], fail_msg='Operation returned a value of "fal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FailOnOutput:
"""Fail App if return value (output) value conditions are met. This decorator allows for the App to exit on conditions defined in the function parameters. .. code-block:: python :linenos: :lineno-start: 1 @FailOnOutput( fail_on=['false'], fail_msg='Operation returned a value of "false".' ) def m... | the_stack_v2_python_sparse | tcex/decorators/fail_on_output.py | TpyoKnig/tcex | train | 0 |
5ba373ddc47ab472f5b2a9506a1a945bdc0f5612 | [
"self.color_array = color_array / 255.0\nself.n = len(self.color_array)\nself.base = np.arange(0, self.n)",
"cx = np.clip(xs * self.n, 0, self.n)\nr = np.interp(cx, self.base, self.color_array[:, 0])\ng = np.interp(cx, self.base, self.color_array[:, 1])\nb = np.interp(cx, self.base, self.color_array[:, 2])\nretur... | <|body_start_0|>
self.color_array = color_array / 255.0
self.n = len(self.color_array)
self.base = np.arange(0, self.n)
<|end_body_0|>
<|body_start_1|>
cx = np.clip(xs * self.n, 0, self.n)
r = np.interp(cx, self.base, self.color_array[:, 0])
g = np.interp(cx, self.base, ... | ColorGradient | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorGradient:
def __init__(self, color_array):
"""Create a color gradient from an array of RGB integer tuples"""
<|body_0|>
def __call__(self, xs):
"""Given a floating point value in [0,1], return the RGB color as an floating point triple."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_015707 | 6,408 | permissive | [
{
"docstring": "Create a color gradient from an array of RGB integer tuples",
"name": "__init__",
"signature": "def __init__(self, color_array)"
},
{
"docstring": "Given a floating point value in [0,1], return the RGB color as an floating point triple.",
"name": "__call__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_009750 | Implement the Python class `ColorGradient` described below.
Class description:
Implement the ColorGradient class.
Method signatures and docstrings:
- def __init__(self, color_array): Create a color gradient from an array of RGB integer tuples
- def __call__(self, xs): Given a floating point value in [0,1], return the... | Implement the Python class `ColorGradient` described below.
Class description:
Implement the ColorGradient class.
Method signatures and docstrings:
- def __init__(self, color_array): Create a color gradient from an array of RGB integer tuples
- def __call__(self, xs): Given a floating point value in [0,1], return the... | 5925d156c4ab41157884ec656fea21f4894df45a | <|skeleton|>
class ColorGradient:
def __init__(self, color_array):
"""Create a color gradient from an array of RGB integer tuples"""
<|body_0|>
def __call__(self, xs):
"""Given a floating point value in [0,1], return the RGB color as an floating point triple."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorGradient:
def __init__(self, color_array):
"""Create a color gradient from an array of RGB integer tuples"""
self.color_array = color_array / 255.0
self.n = len(self.color_array)
self.base = np.arange(0, self.n)
def __call__(self, xs):
"""Given a floating poin... | the_stack_v2_python_sparse | pyspheregl/utils/graphics_utils.py | johnhw/pyspheregl | train | 1 | |
179e660a65f2873512f756f008d2c20c0eecca84 | [
"args = args.split()\nif _debug:\n TestConsoleCmd._debug('do_test %r', args)\ndate_string, time_string = args\ntest_date = Date(date_string).value\ntest_time = Time(time_string).value\nv, t = test_schedule._task.eval(test_date, test_time)\nprint(test_schedule.objectName + ', ' + repr(v and v.value) + ' until ' +... | <|body_start_0|>
args = args.split()
if _debug:
TestConsoleCmd._debug('do_test %r', args)
date_string, time_string = args
test_date = Date(date_string).value
test_time = Time(time_string).value
v, t = test_schedule._task.eval(test_date, test_time)
prin... | TestConsoleCmd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConsoleCmd:
def do_test(self, args):
"""test <date> <time>"""
<|body_0|>
def do_except(self, args):
"""except <date> <start> <stop>"""
<|body_1|>
def do_now(self, args):
"""now"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015708 | 5,647 | permissive | [
{
"docstring": "test <date> <time>",
"name": "do_test",
"signature": "def do_test(self, args)"
},
{
"docstring": "except <date> <start> <stop>",
"name": "do_except",
"signature": "def do_except(self, args)"
},
{
"docstring": "now",
"name": "do_now",
"signature": "def do_n... | 3 | null | Implement the Python class `TestConsoleCmd` described below.
Class description:
Implement the TestConsoleCmd class.
Method signatures and docstrings:
- def do_test(self, args): test <date> <time>
- def do_except(self, args): except <date> <start> <stop>
- def do_now(self, args): now | Implement the Python class `TestConsoleCmd` described below.
Class description:
Implement the TestConsoleCmd class.
Method signatures and docstrings:
- def do_test(self, args): test <date> <time>
- def do_except(self, args): except <date> <start> <stop>
- def do_now(self, args): now
<|skeleton|>
class TestConsoleCmd... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class TestConsoleCmd:
def do_test(self, args):
"""test <date> <time>"""
<|body_0|>
def do_except(self, args):
"""except <date> <start> <stop>"""
<|body_1|>
def do_now(self, args):
"""now"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestConsoleCmd:
def do_test(self, args):
"""test <date> <time>"""
args = args.split()
if _debug:
TestConsoleCmd._debug('do_test %r', args)
date_string, time_string = args
test_date = Date(date_string).value
test_time = Time(time_string).value
... | the_stack_v2_python_sparse | samples/LocalScheduleObject2.py | JoelBender/bacpypes | train | 284 | |
7d5b8f28ccd51bc719d9fa6f2dd20bd5ff31892f | [
"super(DefaultNBitConvWeightsQuantizer, self).__init__(num_bits=num_bits_weight, per_axis=True, symmetric=True, narrow_range=True)\nself._num_bits_weight = num_bits_weight\nself._num_bits_activation = num_bits_activation",
"min_weight = layer.add_weight(name + '_min', shape=(tensor_shape[-1],), initializer=tf.ker... | <|body_start_0|>
super(DefaultNBitConvWeightsQuantizer, self).__init__(num_bits=num_bits_weight, per_axis=True, symmetric=True, narrow_range=True)
self._num_bits_weight = num_bits_weight
self._num_bits_activation = num_bits_activation
<|end_body_0|>
<|body_start_1|>
min_weight = layer.a... | Quantizer for handling weights in Conv2D/DepthwiseConv2D layers. | DefaultNBitConvWeightsQuantizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultNBitConvWeightsQuantizer:
"""Quantizer for handling weights in Conv2D/DepthwiseConv2D layers."""
def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8):
"""Construct LastValueQuantizer with params specific for TFLite Convs."""
<|body_0|>
def build(... | stack_v2_sparse_classes_36k_train_015709 | 13,651 | permissive | [
{
"docstring": "Construct LastValueQuantizer with params specific for TFLite Convs.",
"name": "__init__",
"signature": "def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8)"
},
{
"docstring": "Build min/max quantization variables.",
"name": "build",
"signature": "def bu... | 2 | null | Implement the Python class `DefaultNBitConvWeightsQuantizer` described below.
Class description:
Quantizer for handling weights in Conv2D/DepthwiseConv2D layers.
Method signatures and docstrings:
- def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8): Construct LastValueQuantizer with params specifi... | Implement the Python class `DefaultNBitConvWeightsQuantizer` described below.
Class description:
Quantizer for handling weights in Conv2D/DepthwiseConv2D layers.
Method signatures and docstrings:
- def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8): Construct LastValueQuantizer with params specifi... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class DefaultNBitConvWeightsQuantizer:
"""Quantizer for handling weights in Conv2D/DepthwiseConv2D layers."""
def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8):
"""Construct LastValueQuantizer with params specific for TFLite Convs."""
<|body_0|>
def build(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultNBitConvWeightsQuantizer:
"""Quantizer for handling weights in Conv2D/DepthwiseConv2D layers."""
def __init__(self, num_bits_weight: int=8, num_bits_activation: int=8):
"""Construct LastValueQuantizer with params specific for TFLite Convs."""
super(DefaultNBitConvWeightsQuantizer, ... | the_stack_v2_python_sparse | official/projects/qat/vision/n_bit/configs.py | jianzhnie/models | train | 2 |
007f271b1af9d2c87d7923ea577f3490c36e596f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Shift()",
"from .change_tracked_entity import ChangeTrackedEntity\nfrom .shift_item import ShiftItem\nfrom .change_tracked_entity import ChangeTrackedEntity\nfrom .shift_item import ShiftItem\nfields: Dict[str, Callable[[Any], None]] =... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Shift()
<|end_body_0|>
<|body_start_1|>
from .change_tracked_entity import ChangeTrackedEntity
from .shift_item import ShiftItem
from .change_tracked_entity import ChangeTrackedE... | Shift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Shift:
"""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: Shift"""
... | stack_v2_sparse_classes_36k_train_015710 | 3,080 | 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: Shift",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(parse_n... | 3 | null | Implement the Python class `Shift` described below.
Class description:
Implement the Shift class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Shift: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | Implement the Python class `Shift` described below.
Class description:
Implement the Shift class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Shift: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Shift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Shift:
"""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: Shift"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Shift:
"""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: Shift"""
if not pars... | the_stack_v2_python_sparse | msgraph/generated/models/shift.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a8edee3e2f6ead518f7ea331bfbecf00d6c6f145 | [
"self.tokenizer = Tokenizer(oov_token='oovtok', lower=False)\nself.enc2targs = {}\nself.targ2int = {}\nself.train_dir = train_dir\nself.min_examples_per_targ = min_examples_per_targ\nself.n_x_cuis = None if n_x_cuis == 'all' else int(n_x_cuis)\nself.n_y_cuis = None if n_y_cuis == 'all' else int(n_y_cuis)\nself.inde... | <|body_start_0|>
self.tokenizer = Tokenizer(oov_token='oovtok', lower=False)
self.enc2targs = {}
self.targ2int = {}
self.train_dir = train_dir
self.min_examples_per_targ = min_examples_per_targ
self.n_x_cuis = None if n_x_cuis == 'all' else int(n_x_cuis)
self.n_y_... | Make x and y from raw data | DatasetProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetProvider:
"""Make x and y from raw data"""
def __init__(self, train_dir, model_dir, n_x_cuis, n_y_cuis, min_examples_per_targ):
"""Constructor"""
<|body_0|>
def index(self):
"""Process discharge summaries (prediction targets)"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_015711 | 4,361 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, train_dir, model_dir, n_x_cuis, n_y_cuis, min_examples_per_targ)"
},
{
"docstring": "Process discharge summaries (prediction targets)",
"name": "index",
"signature": "def index(self)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_011286 | Implement the Python class `DatasetProvider` described below.
Class description:
Make x and y from raw data
Method signatures and docstrings:
- def __init__(self, train_dir, model_dir, n_x_cuis, n_y_cuis, min_examples_per_targ): Constructor
- def index(self): Process discharge summaries (prediction targets)
- def loa... | Implement the Python class `DatasetProvider` described below.
Class description:
Make x and y from raw data
Method signatures and docstrings:
- def __init__(self, train_dir, model_dir, n_x_cuis, n_y_cuis, min_examples_per_targ): Constructor
- def index(self): Process discharge summaries (prediction targets)
- def loa... | 4fcb7aa9c5f7ed41277f6b369aff3b36ad47a118 | <|skeleton|>
class DatasetProvider:
"""Make x and y from raw data"""
def __init__(self, train_dir, model_dir, n_x_cuis, n_y_cuis, min_examples_per_targ):
"""Constructor"""
<|body_0|>
def index(self):
"""Process discharge summaries (prediction targets)"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatasetProvider:
"""Make x and y from raw data"""
def __init__(self, train_dir, model_dir, n_x_cuis, n_y_cuis, min_examples_per_targ):
"""Constructor"""
self.tokenizer = Tokenizer(oov_token='oovtok', lower=False)
self.enc2targs = {}
self.targ2int = {}
self.train_di... | the_stack_v2_python_sparse | Archive/MultLabel/dataset.py | dmitriydligach/Universal | train | 1 |
ecaa9fea4a1ebdc64aff0d980940e406e889d077 | [
"length = len(a)\ntotal = sum(a)\nmaximum = curr = sum((i * v for i, v in enumerate(a)))\nfor i in range(1, length):\n curr = curr - total + length * a[i - 1]\n maximum = max(maximum, curr)\nreturn maximum",
"def rotation(l):\n total = 0\n for i, v in enumerate(l):\n total += i * v\n return ... | <|body_start_0|>
length = len(a)
total = sum(a)
maximum = curr = sum((i * v for i, v in enumerate(a)))
for i in range(1, length):
curr = curr - total + length * a[i - 1]
maximum = max(maximum, curr)
return maximum
<|end_body_0|>
<|body_start_1|>
d... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxRotateFunction(self, a: List[int]) -> int:
"""Math solution f(n + 1) = f(n) - sum(a) + len(a) * a[n - 1] Time: O(n) Space: O(1)"""
<|body_0|>
def maxRotateFunction2(self, a: List[int]) -> int:
"""Brute-force solution Try every possible combination an... | stack_v2_sparse_classes_36k_train_015712 | 1,125 | no_license | [
{
"docstring": "Math solution f(n + 1) = f(n) - sum(a) + len(a) * a[n - 1] Time: O(n) Space: O(1)",
"name": "maxRotateFunction",
"signature": "def maxRotateFunction(self, a: List[int]) -> int"
},
{
"docstring": "Brute-force solution Try every possible combination and calculate rotation. Time: O(... | 2 | stack_v2_sparse_classes_30k_train_012074 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxRotateFunction(self, a: List[int]) -> int: Math solution f(n + 1) = f(n) - sum(a) + len(a) * a[n - 1] Time: O(n) Space: O(1)
- def maxRotateFunction2(self, a: List[int]) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxRotateFunction(self, a: List[int]) -> int: Math solution f(n + 1) = f(n) - sum(a) + len(a) * a[n - 1] Time: O(n) Space: O(1)
- def maxRotateFunction2(self, a: List[int]) -... | c14d8829c95f61ff6691816e8c0de76b9319f389 | <|skeleton|>
class Solution:
def maxRotateFunction(self, a: List[int]) -> int:
"""Math solution f(n + 1) = f(n) - sum(a) + len(a) * a[n - 1] Time: O(n) Space: O(1)"""
<|body_0|>
def maxRotateFunction2(self, a: List[int]) -> int:
"""Brute-force solution Try every possible combination an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxRotateFunction(self, a: List[int]) -> int:
"""Math solution f(n + 1) = f(n) - sum(a) + len(a) * a[n - 1] Time: O(n) Space: O(1)"""
length = len(a)
total = sum(a)
maximum = curr = sum((i * v for i, v in enumerate(a)))
for i in range(1, length):
... | the_stack_v2_python_sparse | medium/rotate-function/solution.py | hsuanhauliu/leetcode-solutions | train | 0 | |
703781930dcd920f31014d40a52c1404e13bde0d | [
"if not re.match('^1[3-9]\\\\d{9}$', value):\n raise serializers.ValidationError('手机号码格式出错')\nreturn value",
"if value != 'true':\n raise serializers.ValidationError('请同意用户协议')\nreturn value",
"if data['password'] != data['password2']:\n raise serializers.ValidationError('两次密码输入不正确')\nredis_ok = get_re... | <|body_start_0|>
if not re.match('^1[3-9]\\d{9}$', value):
raise serializers.ValidationError('手机号码格式出错')
return value
<|end_body_0|>
<|body_start_1|>
if value != 'true':
raise serializers.ValidationError('请同意用户协议')
return value
<|end_body_1|>
<|body_start_2|>
... | 用户注册创建用户序列化器 | CreateUserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateUserSerializer:
"""用户注册创建用户序列化器"""
def validate_mobile(self, value):
"""校验手机号码"""
<|body_0|>
def validate_allow(self, value):
"""检验用户是否同意协议"""
<|body_1|>
def validate(self, data):
"""判断密码"""
<|body_2|>
def create(self, vali... | stack_v2_sparse_classes_36k_train_015713 | 5,970 | no_license | [
{
"docstring": "校验手机号码",
"name": "validate_mobile",
"signature": "def validate_mobile(self, value)"
},
{
"docstring": "检验用户是否同意协议",
"name": "validate_allow",
"signature": "def validate_allow(self, value)"
},
{
"docstring": "判断密码",
"name": "validate",
"signature": "def val... | 4 | stack_v2_sparse_classes_30k_train_003455 | Implement the Python class `CreateUserSerializer` described below.
Class description:
用户注册创建用户序列化器
Method signatures and docstrings:
- def validate_mobile(self, value): 校验手机号码
- def validate_allow(self, value): 检验用户是否同意协议
- def validate(self, data): 判断密码
- def create(self, validated_data): 创建用户 | Implement the Python class `CreateUserSerializer` described below.
Class description:
用户注册创建用户序列化器
Method signatures and docstrings:
- def validate_mobile(self, value): 校验手机号码
- def validate_allow(self, value): 检验用户是否同意协议
- def validate(self, data): 判断密码
- def create(self, validated_data): 创建用户
<|skeleton|>
class Cr... | 2f3ae26b64887b19d97679ef16af6be8019e1ea3 | <|skeleton|>
class CreateUserSerializer:
"""用户注册创建用户序列化器"""
def validate_mobile(self, value):
"""校验手机号码"""
<|body_0|>
def validate_allow(self, value):
"""检验用户是否同意协议"""
<|body_1|>
def validate(self, data):
"""判断密码"""
<|body_2|>
def create(self, vali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateUserSerializer:
"""用户注册创建用户序列化器"""
def validate_mobile(self, value):
"""校验手机号码"""
if not re.match('^1[3-9]\\d{9}$', value):
raise serializers.ValidationError('手机号码格式出错')
return value
def validate_allow(self, value):
"""检验用户是否同意协议"""
if value ... | the_stack_v2_python_sparse | apps/users/serializers.py | aglyun/django | train | 1 |
bb0c5155111e0c6ad0be0dcc95af68e9fde7e24b | [
"response = self.client.get(reverse('education:states'))\nself.assertEqual(response.status_code, 200)\nself.assertEqual(response.context.get('states').count(), 0)\nself.assertContains(response, 'No Data Available')\nself.assertNotContains(response, 'Number of Public High Schools')",
"create_states()\nresponse = s... | <|body_start_0|>
response = self.client.get(reverse('education:states'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context.get('states').count(), 0)
self.assertContains(response, 'No Data Available')
self.assertNotContains(response, 'Number of Public H... | EducationStatesViewTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationStatesViewTest:
def test_no_data(self):
"""Make sure the page renders and gives an error message if no data is available."""
<|body_0|>
def test_with_data(self):
"""Make sure page renders when state database is filled."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_015714 | 9,266 | no_license | [
{
"docstring": "Make sure the page renders and gives an error message if no data is available.",
"name": "test_no_data",
"signature": "def test_no_data(self)"
},
{
"docstring": "Make sure page renders when state database is filled.",
"name": "test_with_data",
"signature": "def test_with_... | 2 | stack_v2_sparse_classes_30k_train_002998 | Implement the Python class `EducationStatesViewTest` described below.
Class description:
Implement the EducationStatesViewTest class.
Method signatures and docstrings:
- def test_no_data(self): Make sure the page renders and gives an error message if no data is available.
- def test_with_data(self): Make sure page re... | Implement the Python class `EducationStatesViewTest` described below.
Class description:
Implement the EducationStatesViewTest class.
Method signatures and docstrings:
- def test_no_data(self): Make sure the page renders and gives an error message if no data is available.
- def test_with_data(self): Make sure page re... | 2a8e2dc4e9b3cb92d4d437b37e61940a9486b81f | <|skeleton|>
class EducationStatesViewTest:
def test_no_data(self):
"""Make sure the page renders and gives an error message if no data is available."""
<|body_0|>
def test_with_data(self):
"""Make sure page renders when state database is filled."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationStatesViewTest:
def test_no_data(self):
"""Make sure the page renders and gives an error message if no data is available."""
response = self.client.get(reverse('education:states'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context.get('state... | the_stack_v2_python_sparse | education/tests.py | smeds1/mysite | train | 1 | |
c9a743956d8b97db6bdc1d4c6605347d3a679272 | [
"feedback = {'permission': True}\ntry:\n task_id = request.GET.get('task_id', None)\n if task_id is None:\n feedback['data'] = ErrorCode.parameter_missing('task_id')\n raise natrix_exception.ParameterMissingException(parameter='task_id')\n try:\n uuid.UUID(hex=task_id)\n task = ... | <|body_start_0|>
feedback = {'permission': True}
try:
task_id = request.GET.get('task_id', None)
if task_id is None:
feedback['data'] = ErrorCode.parameter_missing('task_id')
raise natrix_exception.ParameterMissingException(parameter='task_id')
... | Instant Task Info API mehtod: - GET get instant task information - POST create instant task | InstantTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstantTask:
"""Instant Task Info API mehtod: - GET get instant task information - POST create instant task"""
def get(self, request):
"""GET method Get an instant task information. :param request: :return:"""
<|body_0|>
def post(self, request, format=None):
"""C... | stack_v2_sparse_classes_36k_train_015715 | 10,343 | permissive | [
{
"docstring": "GET method Get an instant task information. :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create an instant task :param request: :param format: :return:",
"name": "post",
"signature": "def post(self, request, format=Non... | 2 | stack_v2_sparse_classes_30k_train_017639 | Implement the Python class `InstantTask` described below.
Class description:
Instant Task Info API mehtod: - GET get instant task information - POST create instant task
Method signatures and docstrings:
- def get(self, request): GET method Get an instant task information. :param request: :return:
- def post(self, req... | Implement the Python class `InstantTask` described below.
Class description:
Instant Task Info API mehtod: - GET get instant task information - POST create instant task
Method signatures and docstrings:
- def get(self, request): GET method Get an instant task information. :param request: :return:
- def post(self, req... | 8b97efdc9287645ea6b99dcf3a99fbe3f6ba6862 | <|skeleton|>
class InstantTask:
"""Instant Task Info API mehtod: - GET get instant task information - POST create instant task"""
def get(self, request):
"""GET method Get an instant task information. :param request: :return:"""
<|body_0|>
def post(self, request, format=None):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstantTask:
"""Instant Task Info API mehtod: - GET get instant task information - POST create instant task"""
def get(self, request):
"""GET method Get an instant task information. :param request: :return:"""
feedback = {'permission': True}
try:
task_id = request.GET.... | the_stack_v2_python_sparse | benchmark/views/instant_views.py | creditease-natrix/natrix | train | 4 |
2cb80e1bcc8046168061edb78acc8389fb88c62e | [
"assert isinstance(stabilize, bool), '\"stabilize\" should be a bool value.'\nassert mode in ['mean', 'sum'], '\"mode\" should be either \"mean\" or \"sum\".'\nself.stabilize = stabilize\nself.mode = mode",
"if mask is None:\n if self.mode == 'mean':\n if self.stabilize:\n return T.mean(T.nne... | <|body_start_0|>
assert isinstance(stabilize, bool), '"stabilize" should be a bool value.'
assert mode in ['mean', 'sum'], '"mode" should be either "mean" or "sum".'
self.stabilize = stabilize
self.mode = mode
<|end_body_0|>
<|body_start_1|>
if mask is None:
if self.... | CategoricalCrossentropy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoricalCrossentropy:
def __init__(self, stabilize=False, mode='mean'):
"""This function initializes the class. Parameters ---------- stabilize: bool, default: False a bool value to use stabilization or not. if yes, input_ions are clipped to small, nonnegative values to prevent NaNs. ... | stack_v2_sparse_classes_36k_train_015716 | 19,014 | permissive | [
{
"docstring": "This function initializes the class. Parameters ---------- stabilize: bool, default: False a bool value to use stabilization or not. if yes, input_ions are clipped to small, nonnegative values to prevent NaNs. the input_ion slightly ignores the probability distribution assumtion of sum = 1. for ... | 2 | null | Implement the Python class `CategoricalCrossentropy` described below.
Class description:
Implement the CategoricalCrossentropy class.
Method signatures and docstrings:
- def __init__(self, stabilize=False, mode='mean'): This function initializes the class. Parameters ---------- stabilize: bool, default: False a bool ... | Implement the Python class `CategoricalCrossentropy` described below.
Class description:
Implement the CategoricalCrossentropy class.
Method signatures and docstrings:
- def __init__(self, stabilize=False, mode='mean'): This function initializes the class. Parameters ---------- stabilize: bool, default: False a bool ... | 7585261dd1b1c6c99dada5d2d1aabf482e89e880 | <|skeleton|>
class CategoricalCrossentropy:
def __init__(self, stabilize=False, mode='mean'):
"""This function initializes the class. Parameters ---------- stabilize: bool, default: False a bool value to use stabilization or not. if yes, input_ions are clipped to small, nonnegative values to prevent NaNs. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoricalCrossentropy:
def __init__(self, stabilize=False, mode='mean'):
"""This function initializes the class. Parameters ---------- stabilize: bool, default: False a bool value to use stabilization or not. if yes, input_ions are clipped to small, nonnegative values to prevent NaNs. the input_ion ... | the_stack_v2_python_sparse | lemontree/objectives.py | khshim/lemontree | train | 3 | |
bd771c814da2ec9ba4337f24a133ee01a51fccb8 | [
"params = Parameters.instance().place_params\ntransmission = params['place_transmission']\nplace_idx = place.place_type.value - 1\ntry:\n num_groups = params['mean_group_size'][place_idx]\nexcept IndexError:\n num_groups = 1\nplace_inf = 0 if hasattr(infector.microcell, 'closure_start_time') and infector.is_p... | <|body_start_0|>
params = Parameters.instance().place_params
transmission = params['place_transmission']
place_idx = place.place_type.value - 1
try:
num_groups = params['mean_group_size'][place_idx]
except IndexError:
num_groups = 1
place_inf = 0 i... | Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places. | PlaceInfection | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaceInfection:
"""Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places."""
def place_inf(place, infector, time: float):
"""Calculate the infectiousness of a place. Does not include interventions such as isolation, or... | stack_v2_sparse_classes_36k_train_015717 | 6,023 | permissive | [
{
"docstring": "Calculate the infectiousness of a place. Does not include interventions such as isolation, or whether individual is a carehome resident. Does not yet differentiate between places as we have not decided which places to implement, and what transmission to give them. Parameters ---------- place : P... | 3 | stack_v2_sparse_classes_30k_test_000735 | Implement the Python class `PlaceInfection` described below.
Class description:
Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places.
Method signatures and docstrings:
- def place_inf(place, infector, time: float): Calculate the infectiousness of a pl... | Implement the Python class `PlaceInfection` described below.
Class description:
Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places.
Method signatures and docstrings:
- def place_inf(place, infector, time: float): Calculate the infectiousness of a pl... | c11de122c6bfdf9103162e4045758808da5df322 | <|skeleton|>
class PlaceInfection:
"""Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places."""
def place_inf(place, infector, time: float):
"""Calculate the infectiousness of a place. Does not include interventions such as isolation, or... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaceInfection:
"""Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, within places."""
def place_inf(place, infector, time: float):
"""Calculate the infectiousness of a place. Does not include interventions such as isolation, or whether indi... | the_stack_v2_python_sparse | pyEpiabm/pyEpiabm/property/place_foi.py | SABS-R3-Epidemiology/epiabm | train | 21 |
2714c0d5ae97ce28f3aeb2cc285d00f9ebf5c8ed | [
"data = simplejson.dumps(context)\nresponse_kwargs['content_type'] = 'application/json'\nreturn HttpResponse(data, **response_kwargs)",
"response = super(AjaxFormResponseMixin, self).form_invalid(form)\nif self.request.is_ajax():\n return self.render_to_json_response(form.errors, status=400)\nelse:\n return... | <|body_start_0|>
data = simplejson.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
<|end_body_0|>
<|body_start_1|>
response = super(AjaxFormResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
... | Mixin that renders the response in Json for build-in class-based views. | AjaxFormResponseMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AjaxFormResponseMixin:
"""Mixin that renders the response in Json for build-in class-based views."""
def render_to_json_response(self, context, **response_kwargs):
"""Kwargs: context: the context object to render in json response_kwargs: keyword arguments to put in HttpResponse Retur... | stack_v2_sparse_classes_36k_train_015718 | 2,341 | no_license | [
{
"docstring": "Kwargs: context: the context object to render in json response_kwargs: keyword arguments to put in HttpResponse Returns: HttpResponse.",
"name": "render_to_json_response",
"signature": "def render_to_json_response(self, context, **response_kwargs)"
},
{
"docstring": "Method that ... | 3 | stack_v2_sparse_classes_30k_train_002854 | Implement the Python class `AjaxFormResponseMixin` described below.
Class description:
Mixin that renders the response in Json for build-in class-based views.
Method signatures and docstrings:
- def render_to_json_response(self, context, **response_kwargs): Kwargs: context: the context object to render in json respon... | Implement the Python class `AjaxFormResponseMixin` described below.
Class description:
Mixin that renders the response in Json for build-in class-based views.
Method signatures and docstrings:
- def render_to_json_response(self, context, **response_kwargs): Kwargs: context: the context object to render in json respon... | 027a07ebcbbd61fbdf04006611d860566eb46b93 | <|skeleton|>
class AjaxFormResponseMixin:
"""Mixin that renders the response in Json for build-in class-based views."""
def render_to_json_response(self, context, **response_kwargs):
"""Kwargs: context: the context object to render in json response_kwargs: keyword arguments to put in HttpResponse Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AjaxFormResponseMixin:
"""Mixin that renders the response in Json for build-in class-based views."""
def render_to_json_response(self, context, **response_kwargs):
"""Kwargs: context: the context object to render in json response_kwargs: keyword arguments to put in HttpResponse Returns: HttpRespo... | the_stack_v2_python_sparse | spin_base/mixin/json.py | Loki88/django-Spin | train | 0 |
c76478b5fe70b86663e7228ce7250319fae61f16 | [
"\"\"\"\n self.arr = []\n for i in xrange(0, len(A), 2):\n num = A[i]\n val = A[i + 1]\n for j in xrange(num):\n self.arr.append(val)\n self.index = -1\n \"\"\"\nself.arr = A\nself.index = 0\nself.pos = 0",
"\"\"\"\n # ans1\n ... | <|body_start_0|>
"""
self.arr = []
for i in xrange(0, len(A), 2):
num = A[i]
val = A[i + 1]
for j in xrange(num):
self.arr.append(val)
self.index = -1
"""
s... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
self.arr = []
for i in xrange(0, len(A), 2):
... | stack_v2_sparse_classes_36k_train_015719 | 1,159 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013613 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 992bb618b605c3345318a0eeb2d2df4d11f6a2d5 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
"""
self.arr = []
for i in xrange(0, len(A), 2):
num = A[i]
val = A[i + 1]
for j in xrange(num):
self.arr.append(val)... | the_stack_v2_python_sparse | leetcode/900. RLE Iterator.py | gsrr/leetcode | train | 0 | |
01cf05a89820cee3873a3e6beebdf1f591a003c9 | [
"super().__init__()\nself.h_size = h_size\nself.h_size_inner = h_size_inner\nself.encoder_activation = encoder_activation\nself.preembed_size = preembed_size\nself.input_size = input_size\nself.rnn_type = rnn_type\nself.depth = depth\nself.dropout = dropout\nself.node_fdim = node_fdim\nself._build_layers()",
"enc... | <|body_start_0|>
super().__init__()
self.h_size = h_size
self.h_size_inner = h_size_inner
self.encoder_activation = encoder_activation
self.preembed_size = preembed_size
self.input_size = input_size
self.rnn_type = rnn_type
self.depth = depth
self.... | MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings. | MPNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPNEncoder:
"""MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings."""
def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: int, h_size_inner: int=None, preembed_size: int=None, depth: int=3, dr... | stack_v2_sparse_classes_36k_train_015720 | 31,930 | permissive | [
{
"docstring": "Parameters ---------- rnn_type: str, Type of RNN used (gru/lstm) input_size: int, Input size node_fdim: int, Number of node features h_size: int, Hidden state size depth: int, Number of time steps in the RNN",
"name": "__init__",
"signature": "def __init__(self, rnn_type: str, input_size... | 3 | stack_v2_sparse_classes_30k_train_003822 | Implement the Python class `MPNEncoder` described below.
Class description:
MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings.
Method signatures and docstrings:
- def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: in... | Implement the Python class `MPNEncoder` described below.
Class description:
MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings.
Method signatures and docstrings:
- def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: in... | 8480822d0d8ad74e46edf693ad1cdc787291f422 | <|skeleton|>
class MPNEncoder:
"""MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings."""
def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: int, h_size_inner: int=None, preembed_size: int=None, depth: int=3, dr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPNEncoder:
"""MessagePassing Network based encoder. Messages are updated using an RNN and the final message is used to update atom embeddings."""
def __init__(self, rnn_type: str, input_size: int, node_fdim: int, h_size: int, h_size_inner: int=None, preembed_size: int=None, depth: int=3, dropout: float=... | the_stack_v2_python_sparse | rxnebm/model/G2E.py | rnaimehaom/rxn-ebm | train | 0 |
3f91ae119f3b9f7d2febb4f9e381aad24f26cb3a | [
"if isinstance(other, OperationRetry):\n return self.run_at < other.run_at\nelif isinstance(other, datetime.datetime):\n return self.run_at < other\nreturn NotImplemented",
"if isinstance(self.operation, BulkWriterCreateOperation):\n bulk_writer.create(reference=self.operation.reference, document_data=se... | <|body_start_0|>
if isinstance(other, OperationRetry):
return self.run_at < other.run_at
elif isinstance(other, datetime.datetime):
return self.run_at < other
return NotImplemented
<|end_body_0|>
<|body_start_1|>
if isinstance(self.operation, BulkWriterCreateOper... | Parent class for both the @dataclass and old-style `OperationRetry` classes. Methods on this class be moved directly to `OperationRetry` when support for Python 3.6 is dropped and `dataclasses` becomes universal. | BaseOperationRetry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseOperationRetry:
"""Parent class for both the @dataclass and old-style `OperationRetry` classes. Methods on this class be moved directly to `OperationRetry` when support for Python 3.6 is dropped and `dataclasses` becomes universal."""
def __lt__(self, other: 'OperationRetry'):
""... | stack_v2_sparse_classes_36k_train_015721 | 34,754 | permissive | [
{
"docstring": "Allows use of `bisect` to maintain a sorted list of `OperationRetry` instances, which in turn allows us to cheaply grab all that are ready to run.",
"name": "__lt__",
"signature": "def __lt__(self, other: 'OperationRetry')"
},
{
"docstring": "Call this after waiting any necessary... | 2 | stack_v2_sparse_classes_30k_train_017117 | Implement the Python class `BaseOperationRetry` described below.
Class description:
Parent class for both the @dataclass and old-style `OperationRetry` classes. Methods on this class be moved directly to `OperationRetry` when support for Python 3.6 is dropped and `dataclasses` becomes universal.
Method signatures and... | Implement the Python class `BaseOperationRetry` described below.
Class description:
Parent class for both the @dataclass and old-style `OperationRetry` classes. Methods on this class be moved directly to `OperationRetry` when support for Python 3.6 is dropped and `dataclasses` becomes universal.
Method signatures and... | ccadec5eba81c20618a94c0e4a23f07dfb7c1ea7 | <|skeleton|>
class BaseOperationRetry:
"""Parent class for both the @dataclass and old-style `OperationRetry` classes. Methods on this class be moved directly to `OperationRetry` when support for Python 3.6 is dropped and `dataclasses` becomes universal."""
def __lt__(self, other: 'OperationRetry'):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseOperationRetry:
"""Parent class for both the @dataclass and old-style `OperationRetry` classes. Methods on this class be moved directly to `OperationRetry` when support for Python 3.6 is dropped and `dataclasses` becomes universal."""
def __lt__(self, other: 'OperationRetry'):
"""Allows use o... | the_stack_v2_python_sparse | google/cloud/firestore_v1/bulk_writer.py | googleapis/python-firestore | train | 203 |
904435b8f270fdb7b191e6039da47ce9da99be0f | [
"super().__init__(features_to_sample, **kwargs)\nself.sample_size = tuple(sample_size)\nself.stride = tuple(stride)\nif not all((value > 0 for value in self.sample_size + self.stride)):\n raise ValueError('Both sample_size and stride should have only positive values')",
"rows = np.arange(0, image_shape[0] - se... | <|body_start_0|>
super().__init__(features_to_sample, **kwargs)
self.sample_size = tuple(sample_size)
self.stride = tuple(stride)
if not all((value > 0 for value in self.sample_size + self.stride)):
raise ValueError('Both sample_size and stride should have only positive value... | A task to sample blocks of a given size in a regular grid. This task doesn't use any randomness and always produces the same results. | GridSamplingTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridSamplingTask:
"""A task to sample blocks of a given size in a regular grid. This task doesn't use any randomness and always produces the same results."""
def __init__(self, features_to_sample: FeaturesSpecification, sample_size: tuple[int, int]=(1, 1), stride: tuple[int, int]=(1, 1), **k... | stack_v2_sparse_classes_36k_train_015722 | 17,895 | permissive | [
{
"docstring": ":param features_to_sample: Features that will be spatially sampled according to given sampling parameters. :param sample_size: A tuple describing a size of sampled blocks. The size is defined as a tuple of number of rows and number of columns. :param stride: A tuple describing a distance between... | 3 | stack_v2_sparse_classes_30k_train_004360 | Implement the Python class `GridSamplingTask` described below.
Class description:
A task to sample blocks of a given size in a regular grid. This task doesn't use any randomness and always produces the same results.
Method signatures and docstrings:
- def __init__(self, features_to_sample: FeaturesSpecification, samp... | Implement the Python class `GridSamplingTask` described below.
Class description:
A task to sample blocks of a given size in a regular grid. This task doesn't use any randomness and always produces the same results.
Method signatures and docstrings:
- def __init__(self, features_to_sample: FeaturesSpecification, samp... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class GridSamplingTask:
"""A task to sample blocks of a given size in a regular grid. This task doesn't use any randomness and always produces the same results."""
def __init__(self, features_to_sample: FeaturesSpecification, sample_size: tuple[int, int]=(1, 1), stride: tuple[int, int]=(1, 1), **k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridSamplingTask:
"""A task to sample blocks of a given size in a regular grid. This task doesn't use any randomness and always produces the same results."""
def __init__(self, features_to_sample: FeaturesSpecification, sample_size: tuple[int, int]=(1, 1), stride: tuple[int, int]=(1, 1), **kwargs: Any):
... | the_stack_v2_python_sparse | ml_tools/eolearn/ml_tools/sampling.py | sentinel-hub/eo-learn | train | 1,072 |
f2f7ba8d94ef1484e08607c079a43799bd3d7aba | [
"self.mav_con = mavutil.mavlink_connection(device, input=True)\nmavutil.set_dialect('ardupilotmega')\nself.mav_con.wait_heartbeat()\nself.fence_loader = mavwp.MAVFenceLoader(self.mav_con.target_system, self.mav_con.target_component)\nself.fence_enable = False",
"self.mav_con.mav.param_set_send(self.mav_con.target... | <|body_start_0|>
self.mav_con = mavutil.mavlink_connection(device, input=True)
mavutil.set_dialect('ardupilotmega')
self.mav_con.wait_heartbeat()
self.fence_loader = mavwp.MAVFenceLoader(self.mav_con.target_system, self.mav_con.target_component)
self.fence_enable = False
<|end_bo... | Creates a link to the ArduPilot using MAVLink. | MavlinkClient | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MavlinkClient:
"""Creates a link to the ArduPilot using MAVLink."""
def __init__(self, device: str='udpin:127.0.0.1:14551') -> None:
"""Create a new MAVLink connection. Add a connection and wait for a heartbeat to fetch target system and target component. Args: - device: A string def... | stack_v2_sparse_classes_36k_train_015723 | 4,225 | permissive | [
{
"docstring": "Create a new MAVLink connection. Add a connection and wait for a heartbeat to fetch target system and target component. Args: - device: A string defining how to connect to the desired MAVLink-enabled device. See: https://github.com/ArduPilot/pymavlink/blob/fe0651f9be6d1efeaed3d4e53ef5ea533ee64c5... | 3 | stack_v2_sparse_classes_30k_train_009355 | Implement the Python class `MavlinkClient` described below.
Class description:
Creates a link to the ArduPilot using MAVLink.
Method signatures and docstrings:
- def __init__(self, device: str='udpin:127.0.0.1:14551') -> None: Create a new MAVLink connection. Add a connection and wait for a heartbeat to fetch target ... | Implement the Python class `MavlinkClient` described below.
Class description:
Creates a link to the ArduPilot using MAVLink.
Method signatures and docstrings:
- def __init__(self, device: str='udpin:127.0.0.1:14551') -> None: Create a new MAVLink connection. Add a connection and wait for a heartbeat to fetch target ... | bbb5aec826aff065eab44f07410377f515dea133 | <|skeleton|>
class MavlinkClient:
"""Creates a link to the ArduPilot using MAVLink."""
def __init__(self, device: str='udpin:127.0.0.1:14551') -> None:
"""Create a new MAVLink connection. Add a connection and wait for a heartbeat to fetch target system and target component. Args: - device: A string def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MavlinkClient:
"""Creates a link to the ArduPilot using MAVLink."""
def __init__(self, device: str='udpin:127.0.0.1:14551') -> None:
"""Create a new MAVLink connection. Add a connection and wait for a heartbeat to fetch target system and target component. Args: - device: A string defining how to ... | the_stack_v2_python_sparse | src/mavlink_client.py | OmarTheMostWanted/Autark-Zero | train | 0 |
9494ac3e932aa857c3c41777f9c685946c39044e | [
"lines = open(track + '.log').readlines()\nstarted = 'not started'\nif len(lines) < 1:\n return ('FAIL', started)\nx = re.search('# job started at ([^-]*) on', lines[1])\nif x:\n started = x.groups()[1]\nx = re.search('# job finished in (\\\\d+) seconds at ([^-]*) -- ', lines[-1])\nif not x:\n return ('FAI... | <|body_start_0|>
lines = open(track + '.log').readlines()
started = 'not started'
if len(lines) < 1:
return ('FAIL', started)
x = re.search('# job started at ([^-]*) on', lines[1])
if x:
started = x.groups()[1]
x = re.search('# job finished in (\\d... | PipelineStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineStatus:
def testCompletion(self, track):
"""check if pipeline completed successfully."""
<|body_0|>
def testReport(self, track):
"""check if report completed successfully."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lines = open(track + ... | stack_v2_sparse_classes_36k_train_015724 | 5,397 | no_license | [
{
"docstring": "check if pipeline completed successfully.",
"name": "testCompletion",
"signature": "def testCompletion(self, track)"
},
{
"docstring": "check if report completed successfully.",
"name": "testReport",
"signature": "def testReport(self, track)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007862 | Implement the Python class `PipelineStatus` described below.
Class description:
Implement the PipelineStatus class.
Method signatures and docstrings:
- def testCompletion(self, track): check if pipeline completed successfully.
- def testReport(self, track): check if report completed successfully. | Implement the Python class `PipelineStatus` described below.
Class description:
Implement the PipelineStatus class.
Method signatures and docstrings:
- def testCompletion(self, track): check if pipeline completed successfully.
- def testReport(self, track): check if report completed successfully.
<|skeleton|>
class ... | 01758b19aa1b0883f0e648f495b570f1b6159be4 | <|skeleton|>
class PipelineStatus:
def testCompletion(self, track):
"""check if pipeline completed successfully."""
<|body_0|>
def testReport(self, track):
"""check if report completed successfully."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelineStatus:
def testCompletion(self, track):
"""check if pipeline completed successfully."""
lines = open(track + '.log').readlines()
started = 'not started'
if len(lines) < 1:
return ('FAIL', started)
x = re.search('# job started at ([^-]*) on', lines[1... | the_stack_v2_python_sparse | CGATPipelines/pipeline_docs/pipeline_testing/trackers/TestingReport.py | yangjl/cgat | train | 0 | |
0c722c452f49711c95ad9b7da28ed85b72f8d25f | [
"self.stack = list()\nself.it = root\nif not self.it:\n return\nwhile self.it.left:\n self.stack.append(self.it)\n self.it = self.it.left",
"if not self.it:\n return False\nelse:\n return True",
"result = self.it.val\nif self.it.right:\n jt = self.it.right\n while jt.left:\n self.sta... | <|body_start_0|>
self.stack = list()
self.it = root
if not self.it:
return
while self.it.left:
self.stack.append(self.it)
self.it = self.it.left
<|end_body_0|>
<|body_start_1|>
if not self.it:
return False
else:
... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.stack = list()
... | stack_v2_sparse_classes_36k_train_015725 | 1,144 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasNext(self)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
}
] | 3 | null | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int
<|skeleton|>
class BSTIterator:
def __init__(self, root... | 78ed11f34fd03e9a188c9c6cb352e883016d05d9 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.stack = list()
self.it = root
if not self.it:
return
while self.it.left:
self.stack.append(self.it)
self.it = self.it.left
def hasNext(self):
""":rtyp... | the_stack_v2_python_sparse | 173_binary_search_tree_iterator.py | 26XINXIN/leetcode | train | 0 | |
fc15c9333383ddced192fb800d7d2abd6a7ee459 | [
"if len(nums) < 3:\n return []\nnums.sort()\nres = set()\nfor i, v in enumerate(nums[:-2]):\n if i >= 1 and v == nums[i - 1]:\n continue\n d = {}\n for x in nums[i + 1:]:\n if x not in d:\n d[-v - x] = 1\n else:\n res.add((v, -v - x, x))\nreturn list(map(list, ... | <|body_start_0|>
if len(nums) < 3:
return []
nums.sort()
res = set()
for i, v in enumerate(nums[:-2]):
if i >= 1 and v == nums[i - 1]:
continue
d = {}
for x in nums[i + 1:]:
if x not in d:
... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def threeSum2(self, nums):
"""用map或者set的方式 :param nums: :return:"""
<|body_0|>
def threeSum(self, nums):
"""思路是两重循环 :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 3:
... | stack_v2_sparse_classes_36k_train_015726 | 3,761 | no_license | [
{
"docstring": "用map或者set的方式 :param nums: :return:",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
},
{
"docstring": "思路是两重循环 :type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000804 | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def threeSum2(self, nums): 用map或者set的方式 :param nums: :return:
- def threeSum(self, nums): 思路是两重循环 :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def threeSum2(self, nums): 用map或者set的方式 :param nums: :return:
- def threeSum(self, nums): 思路是两重循环 :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution2:
... | aa285d16bc96d30a632fae5c7578d0e7a5f51e7c | <|skeleton|>
class Solution2:
def threeSum2(self, nums):
"""用map或者set的方式 :param nums: :return:"""
<|body_0|>
def threeSum(self, nums):
"""思路是两重循环 :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution2:
def threeSum2(self, nums):
"""用map或者set的方式 :param nums: :return:"""
if len(nums) < 3:
return []
nums.sort()
res = set()
for i, v in enumerate(nums[:-2]):
if i >= 1 and v == nums[i - 1]:
continue
d = {}
... | the_stack_v2_python_sparse | package_1_100/package_1_20/15.3Sum.py | morindaz/leecode_morindaz | train | 4 | |
93c833ed5e10ebb8f0f93898520a2a6947f49c32 | [
"if key == 'log_line':\n time_elements_structure = self._GetValueFromStructure(structure, 'timestamp')\n body = self._GetValueFromStructure(structure, 'body', default_value='')\n body = body.strip()\n try:\n body_structure = self._KEY_VALUE_DICT.parseString(body)\n process_identifier = sel... | <|body_start_0|>
if key == 'log_line':
time_elements_structure = self._GetValueFromStructure(structure, 'timestamp')
body = self._GetValueFromStructure(structure, 'body', default_value='')
body = body.strip()
try:
body_structure = self._KEY_VALUE_D... | Text parser plugin for SELinux audit log (audit.log) files. | SELinuxTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SELinuxTextPlugin:
"""Text parser plugin for SELinux audit log (audit.log) files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s... | stack_v2_sparse_classes_36k_train_015727 | 5,812 | permissive | [
{
"docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru... | 3 | null | Implement the Python class `SELinuxTextPlugin` described below.
Class description:
Text parser plugin for SELinux audit log (audit.log) files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates int... | Implement the Python class `SELinuxTextPlugin` described below.
Class description:
Text parser plugin for SELinux audit log (audit.log) files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates int... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class SELinuxTextPlugin:
"""Text parser plugin for SELinux audit log (audit.log) files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SELinuxTextPlugin:
"""Text parser plugin for SELinux audit log (audit.log) files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and df... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/selinux.py | log2timeline/plaso | train | 1,506 |
62e1b3920cfb42c82371c959dcab2fee493d3d9a | [
"self.n_rows = n_rows\nself.n_cols = n_cols\nself.num = []\nfor i in range(n_rows):\n self.num.append([0] * n_cols)",
"sum_num = sum((sum(i) for i in self.num))\nif sum_num == self.n_rows * self.n_cols:\n return\nimport random\nwhile True:\n x = random.randint(0, self.n_rows - 1)\n y = random.randint(... | <|body_start_0|>
self.n_rows = n_rows
self.n_cols = n_cols
self.num = []
for i in range(n_rows):
self.num.append([0] * n_cols)
<|end_body_0|>
<|body_start_1|>
sum_num = sum((sum(i) for i in self.num))
if sum_num == self.n_rows * self.n_cols:
retur... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def __init__(self, n_rows, n_cols):
""":type n_rows: int :type n_cols: int"""
<|body_0|>
def flip(self):
""":rtype: List[int]"""
<|body_1|>
def reset(self):
""":rtype: None"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015728 | 1,777 | no_license | [
{
"docstring": ":type n_rows: int :type n_cols: int",
"name": "__init__",
"signature": "def __init__(self, n_rows, n_cols)"
},
{
"docstring": ":rtype: List[int]",
"name": "flip",
"signature": "def flip(self)"
},
{
"docstring": ":rtype: None",
"name": "reset",
"signature":... | 3 | stack_v2_sparse_classes_30k_test_000534 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, n_rows, n_cols): :type n_rows: int :type n_cols: int
- def flip(self): :rtype: List[int]
- def reset(self): :rtype: None | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, n_rows, n_cols): :type n_rows: int :type n_cols: int
- def flip(self): :rtype: List[int]
- def reset(self): :rtype: None
<|skeleton|>
class Solution1:
... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class Solution1:
def __init__(self, n_rows, n_cols):
""":type n_rows: int :type n_cols: int"""
<|body_0|>
def flip(self):
""":rtype: List[int]"""
<|body_1|>
def reset(self):
""":rtype: None"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def __init__(self, n_rows, n_cols):
""":type n_rows: int :type n_cols: int"""
self.n_rows = n_rows
self.n_cols = n_cols
self.num = []
for i in range(n_rows):
self.num.append([0] * n_cols)
def flip(self):
""":rtype: List[int]"""
... | the_stack_v2_python_sparse | 2019/sampling/random_flip_matrix_519.py | yehongyu/acode | train | 0 | |
af9a7d269cd5f5586ca02f0f256eb254c56bfce7 | [
"if not self.is_visible(source, overrides):\n return\ntag = self.get_property('tag', source, overrides)\nshow_line = self.get_property('show_line', source, overrides)\nshow_labels = self.get_property('show_labels', source, overrides)\nshow_major_ticks = self.get_property('show_major_ticks', source, overrides)\ns... | <|body_start_0|>
if not self.is_visible(source, overrides):
return
tag = self.get_property('tag', source, overrides)
show_line = self.get_property('show_line', source, overrides)
show_labels = self.get_property('show_labels', source, overrides)
show_major_ticks = self... | Radial axis is a standard type of axis used for polar plots. By default the axis is drawn as a circle or arc line with ticks and labels facing out. The ticks are expected to be provided as absolute angle values in the units specified by the 'units' property. Properties: radius: int, float or callable Specifies the axis... | RadialAxis | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadialAxis:
"""Radial axis is a standard type of axis used for polar plots. By default the axis is drawn as a circle or arc line with ticks and labels facing out. The ticks are expected to be provided as absolute angle values in the units specified by the 'units' property. Properties: radius: int... | stack_v2_sparse_classes_36k_train_015729 | 29,078 | permissive | [
{
"docstring": "Uses given canvas to draw the axis.",
"name": "draw",
"signature": "def draw(self, canvas, source=UNDEF, **overrides)"
},
{
"docstring": "Draws axis major ticks.",
"name": "_draw_major_ticks",
"signature": "def _draw_major_ticks(self, canvas, source, overrides)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_020583 | Implement the Python class `RadialAxis` described below.
Class description:
Radial axis is a standard type of axis used for polar plots. By default the axis is drawn as a circle or arc line with ticks and labels facing out. The ticks are expected to be provided as absolute angle values in the units specified by the 'u... | Implement the Python class `RadialAxis` described below.
Class description:
Radial axis is a standard type of axis used for polar plots. By default the axis is drawn as a circle or arc line with ticks and labels facing out. The ticks are expected to be provided as absolute angle values in the units specified by the 'u... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class RadialAxis:
"""Radial axis is a standard type of axis used for polar plots. By default the axis is drawn as a circle or arc line with ticks and labels facing out. The ticks are expected to be provided as absolute angle values in the units specified by the 'units' property. Properties: radius: int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RadialAxis:
"""Radial axis is a standard type of axis used for polar plots. By default the axis is drawn as a circle or arc line with ticks and labels facing out. The ticks are expected to be provided as absolute angle values in the units specified by the 'units' property. Properties: radius: int, float or ca... | the_stack_v2_python_sparse | pero/glyphs/axes.py | xxao/pero | train | 31 |
f748a21c4217748fb2f34586dfe1d6b4312712f6 | [
"if not root:\n return\nself.getMinimumDifferenceRecur(root.left, data)\ndata.append(root.val)\nself.getMinimumDifferenceRecur(root.right, data)",
"data = []\nself.getMinimumDifferenceRecur(root, data)\nmin_diff = float('inf')\nfor i in range(1, len(data)):\n if data[i] - data[i - 1] < min_diff:\n mi... | <|body_start_0|>
if not root:
return
self.getMinimumDifferenceRecur(root.left, data)
data.append(root.val)
self.getMinimumDifferenceRecur(root.right, data)
<|end_body_0|>
<|body_start_1|>
data = []
self.getMinimumDifferenceRecur(root, data)
min_diff =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getMinimumDifferenceRecur(self, root, data):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_015730 | 1,062 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "getMinimumDifferenceRecur",
"signature": "def getMinimumDifferenceRecur(self, root, data)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "getMinimumDifference",
"signature": "def getMinimumDifference(self, root)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMinimumDifferenceRecur(self, root, data): :type root: TreeNode :rtype: int
- def getMinimumDifference(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMinimumDifferenceRecur(self, root, data): :type root: TreeNode :rtype: int
- def getMinimumDifference(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Sol... | 37ece0a8e92a41ced2b4ce0f2d8dda3826b915ae | <|skeleton|>
class Solution:
def getMinimumDifferenceRecur(self, root, data):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getMinimumDifferenceRecur(self, root, data):
""":type root: TreeNode :rtype: int"""
if not root:
return
self.getMinimumDifferenceRecur(root.left, data)
data.append(root.val)
self.getMinimumDifferenceRecur(root.right, data)
def getMinimumDi... | the_stack_v2_python_sparse | Q530MinimumAbsoluteDifferenceinBST.py | ShenTonyM/LeetCode-Learn | train | 0 | |
bb2205351eb15acf3dc138cf0a430aefe50692f6 | [
"self.maxheap = Heap(1)\nself.minheap = Heap(0)\nself.heaps = [self.maxheap, self.minheap]\nself.i = 0",
"i = self.i\nself.heaps[i].insert(num)\nself.heaps[i ^ 1].insert(self.heaps[i].extract())\nself.i ^= 1",
"if self.minheap.count == self.maxheap.count and self.minheap.count > 0:\n maxv = self.minheap.peek... | <|body_start_0|>
self.maxheap = Heap(1)
self.minheap = Heap(0)
self.heaps = [self.maxheap, self.minheap]
self.i = 0
<|end_body_0|>
<|body_start_1|>
i = self.i
self.heaps[i].insert(num)
self.heaps[i ^ 1].insert(self.heaps[i].extract())
self.i ^= 1
<|end_bo... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k_train_015731 | 6,769 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | stack_v2_sparse_classes_30k_train_002432 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | 588a86282b8cc74fa14d810eb3a532c5c3e6de81 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.maxheap = Heap(1)
self.minheap = Heap(0)
self.heaps = [self.maxheap, self.minheap]
self.i = 0
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rty... | the_stack_v2_python_sparse | solutions/FindMedianFromDataStream.py | howardhe0329/leetcode | train | 0 | |
a23f2326af8f11a9ef50ee72a2829c7114627047 | [
"result_list = []\n\ndef _serialize(root):\n if root is None:\n result_list.append('None')\n return\n result_list.append(str(root.val))\n _serialize(root.left)\n _serialize(root.right)\n_serialize(root)\nreturn ','.join(result_list)",
"data_list = data.split(',')\n\ndef _deserialize(data... | <|body_start_0|>
result_list = []
def _serialize(root):
if root is None:
result_list.append('None')
return
result_list.append(str(root.val))
_serialize(root.left)
_serialize(root.right)
_serialize(root)
retu... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_015732 | 3,122 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d99eb75a74e38c91effda81cfc7341679422f005 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result_list = []
def _serialize(root):
if root is None:
result_list.append('None')
return
result_list.append(str(root.val... | the_stack_v2_python_sparse | Python/Serialize_and_Deserialize_Binary_Tree.py | mt3925/leetcode | train | 0 | |
1618db7a2c1c49a22ca485d3e9185b0edac0eccb | [
"if n == 0 or m == 0:\n return 0\ndp = [[1 for _ in range(n)] for _ in range(m)]\nfor i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nreturn dp[-1][-1]",
"if m == 0 or n == 0:\n return 0\npre = [1 for _ in range(n)]\ncur = [1 for _ in range(n)]\nfor i in range(1... | <|body_start_0|>
if n == 0 or m == 0:
return 0
dp = [[1 for _ in range(n)] for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]
<|end_body_0|>
<|body_start_1|>
if m == 0 or... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
"""动态规划: 动态转移方程:dp[i, j] = dp[i - 1, j] + dp[i, j - 1] 初始状态: dp[0, j] = 1 dp[i, 0] = 1 时间复杂度:nm,遍历整个二维数组 空间复杂度:mn,建立一个新的二维数组存储结果 :param m: :param n: :return:"""
<|body_0|>
def uniquePath2_v2(self, m, n):
"""为了优化空间复杂度,我们使用两个n长的数组... | stack_v2_sparse_classes_36k_train_015733 | 2,725 | no_license | [
{
"docstring": "动态规划: 动态转移方程:dp[i, j] = dp[i - 1, j] + dp[i, j - 1] 初始状态: dp[0, j] = 1 dp[i, 0] = 1 时间复杂度:nm,遍历整个二维数组 空间复杂度:mn,建立一个新的二维数组存储结果 :param m: :param n: :return:",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": "为了优化空间复杂度,我们使用两个n长的数组分别表示上面一行pre,和本行cu... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): 动态规划: 动态转移方程:dp[i, j] = dp[i - 1, j] + dp[i, j - 1] 初始状态: dp[0, j] = 1 dp[i, 0] = 1 时间复杂度:nm,遍历整个二维数组 空间复杂度:mn,建立一个新的二维数组存储结果 :param m: :param n: :re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): 动态规划: 动态转移方程:dp[i, j] = dp[i - 1, j] + dp[i, j - 1] 初始状态: dp[0, j] = 1 dp[i, 0] = 1 时间复杂度:nm,遍历整个二维数组 空间复杂度:mn,建立一个新的二维数组存储结果 :param m: :param n: :re... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
"""动态规划: 动态转移方程:dp[i, j] = dp[i - 1, j] + dp[i, j - 1] 初始状态: dp[0, j] = 1 dp[i, 0] = 1 时间复杂度:nm,遍历整个二维数组 空间复杂度:mn,建立一个新的二维数组存储结果 :param m: :param n: :return:"""
<|body_0|>
def uniquePath2_v2(self, m, n):
"""为了优化空间复杂度,我们使用两个n长的数组... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m, n):
"""动态规划: 动态转移方程:dp[i, j] = dp[i - 1, j] + dp[i, j - 1] 初始状态: dp[0, j] = 1 dp[i, 0] = 1 时间复杂度:nm,遍历整个二维数组 空间复杂度:mn,建立一个新的二维数组存储结果 :param m: :param n: :return:"""
if n == 0 or m == 0:
return 0
dp = [[1 for _ in range(n)] for _ in range(m... | the_stack_v2_python_sparse | leetcode/动态规划/62. 不同路径/uniquePaths.py | guohaoyuan/algorithms-for-work | train | 2 | |
fcb3e1b8925804860f0be9613f9c6a4ae48f88a1 | [
"if len(s1) != len(s2):\n return False\nlist1 = list(s1)\nlist2 = list(s2)\nlist1.sort()\nlist2.sort()\nfor i in range(len(list1)):\n if list1[i] != list2[i]:\n return False\nreturn True",
"if len(s1) != len(s2):\n return False\nc1 = [0] * 26\nc2 = [0] * 26\nfor i in range(len(s1)):\n c1[ord(s1... | <|body_start_0|>
if len(s1) != len(s2):
return False
list1 = list(s1)
list2 = list(s2)
list1.sort()
list2.sort()
for i in range(len(list1)):
if list1[i] != list2[i]:
return False
return True
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def anagramSolution(self, s1, s2):
"""排序对比法 思路: 1. 将两个字符串转为list; 2. 堆两个list进行排序; 3. 然后逐一比较对应位置的字符是否相等即可"""
<|body_0|>
def anagramSolution2(self, s1, s2):
"""字符统计对比法(Knowledge) 思路: 1. 创建两个长度位26的数组; 2. 各自统计两个字符串中每个字符出现的次数; 3. 接着对比两个数组即可 PS: ord => python中的一个内... | stack_v2_sparse_classes_36k_train_015734 | 2,988 | no_license | [
{
"docstring": "排序对比法 思路: 1. 将两个字符串转为list; 2. 堆两个list进行排序; 3. 然后逐一比较对应位置的字符是否相等即可",
"name": "anagramSolution",
"signature": "def anagramSolution(self, s1, s2)"
},
{
"docstring": "字符统计对比法(Knowledge) 思路: 1. 创建两个长度位26的数组; 2. 各自统计两个字符串中每个字符出现的次数; 3. 接着对比两个数组即可 PS: ord => python中的一个内置函数,传入一个字符,会返回其对应... | 2 | stack_v2_sparse_classes_30k_train_019031 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def anagramSolution(self, s1, s2): 排序对比法 思路: 1. 将两个字符串转为list; 2. 堆两个list进行排序; 3. 然后逐一比较对应位置的字符是否相等即可
- def anagramSolution2(self, s1, s2): 字符统计对比法(Knowledge) 思路: 1. 创建两个长度位26的数组;... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def anagramSolution(self, s1, s2): 排序对比法 思路: 1. 将两个字符串转为list; 2. 堆两个list进行排序; 3. 然后逐一比较对应位置的字符是否相等即可
- def anagramSolution2(self, s1, s2): 字符统计对比法(Knowledge) 思路: 1. 创建两个长度位26的数组;... | 19ea28c38762c65318275007932786e648a8b415 | <|skeleton|>
class Solution:
def anagramSolution(self, s1, s2):
"""排序对比法 思路: 1. 将两个字符串转为list; 2. 堆两个list进行排序; 3. 然后逐一比较对应位置的字符是否相等即可"""
<|body_0|>
def anagramSolution2(self, s1, s2):
"""字符统计对比法(Knowledge) 思路: 1. 创建两个长度位26的数组; 2. 各自统计两个字符串中每个字符出现的次数; 3. 接着对比两个数组即可 PS: ord => python中的一个内... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def anagramSolution(self, s1, s2):
"""排序对比法 思路: 1. 将两个字符串转为list; 2. 堆两个list进行排序; 3. 然后逐一比较对应位置的字符是否相等即可"""
if len(s1) != len(s2):
return False
list1 = list(s1)
list2 = list(s2)
list1.sort()
list2.sort()
for i in range(len(list1)):
... | the_stack_v2_python_sparse | chapter2/check-out-of-order-string.py | SunnyQjm/algorithm-review | train | 2 | |
b3c2202fb0f69e212d906a31a41bd99815725666 | [
"self.name = 'FaceDataType'\nself.templatesubdivisiontype = 1\nself.drape = drape\nself.verticaldivisions1 = verticaldivisions1\nself.horizontaldivisions1 = horizontaldivisions1\nself.verticaldivisions2 = verticaldivisions2\nself.horizontaldivisions2 = horizontaldivisions2\nself.verticaldivisions3 = verticaldivisio... | <|body_start_0|>
self.name = 'FaceDataType'
self.templatesubdivisiontype = 1
self.drape = drape
self.verticaldivisions1 = verticaldivisions1
self.horizontaldivisions1 = horizontaldivisions1
self.verticaldivisions2 = verticaldivisions2
self.horizontaldivisions2 = h... | Face data type class to create a MODPATH 7 particle location template for input style 2, 3, and 4 on cell faces (templatesubdivisiontype = 2). Parameters ---------- drape : int Drape indicates how particles are treated when starting locations are specified for cells that are dry. If drape is 0, Particles are placed in ... | FaceDataType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceDataType:
"""Face data type class to create a MODPATH 7 particle location template for input style 2, 3, and 4 on cell faces (templatesubdivisiontype = 2). Parameters ---------- drape : int Drape indicates how particles are treated when starting locations are specified for cells that are dry.... | stack_v2_sparse_classes_36k_train_015735 | 35,702 | permissive | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, drape=0, verticaldivisions1=3, horizontaldivisions1=3, verticaldivisions2=3, horizontaldivisions2=3, verticaldivisions3=3, horizontaldivisions3=3, verticaldivisions4=3, horizontaldivisions4=3, rowdivisions5=3, colum... | 2 | stack_v2_sparse_classes_30k_test_000935 | Implement the Python class `FaceDataType` described below.
Class description:
Face data type class to create a MODPATH 7 particle location template for input style 2, 3, and 4 on cell faces (templatesubdivisiontype = 2). Parameters ---------- drape : int Drape indicates how particles are treated when starting location... | Implement the Python class `FaceDataType` described below.
Class description:
Face data type class to create a MODPATH 7 particle location template for input style 2, 3, and 4 on cell faces (templatesubdivisiontype = 2). Parameters ---------- drape : int Drape indicates how particles are treated when starting location... | 7db7869f34b875c9f76d42b7a4801b0c23738448 | <|skeleton|>
class FaceDataType:
"""Face data type class to create a MODPATH 7 particle location template for input style 2, 3, and 4 on cell faces (templatesubdivisiontype = 2). Parameters ---------- drape : int Drape indicates how particles are treated when starting locations are specified for cells that are dry.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceDataType:
"""Face data type class to create a MODPATH 7 particle location template for input style 2, 3, and 4 on cell faces (templatesubdivisiontype = 2). Parameters ---------- drape : int Drape indicates how particles are treated when starting locations are specified for cells that are dry. If drape is ... | the_stack_v2_python_sparse | hataripy/modpath/mp7particledata.py | hatarilabs/hataripy | train | 4 |
ea9855a1fbe8f96781fc4f93c805061ada7f9683 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)\nself.reqparser.add_argument('attribute_id', required=True, type=str, help='Attribute Id missing')",
"args = self.reqparser.parse_args()\nif 'user_id' not in args:\n user = Users.fi... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('user_id', required=False, type=int, store_missing=False)
self.reqparser.add_argument('attribute_id', required=True, type=str, help='Attribute Id missing')
<|end_body_0|>
<|body_start_1|>
args = self.... | Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id. | CheckAlerts | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckAlerts:
"""Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id."""
def __init__(self) -> None:
"""Instantiate req... | stack_v2_sparse_classes_36k_train_015736 | 3,224 | permissive | [
{
"docstring": "Instantiate reqpase.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Check for triggered alerts. :return: On success, an HTTP response with a JSON body content containing the maximum and minimum alerts that have been exceeded with an HTTP status... | 2 | null | Implement the Python class `CheckAlerts` described below.
Class description:
Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id.
Method signatures and ... | Implement the Python class `CheckAlerts` described below.
Class description:
Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id.
Method signatures and ... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class CheckAlerts:
"""Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id."""
def __init__(self) -> None:
"""Instantiate req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckAlerts:
"""Check for alerts that have been triggered. Using a GET request with the following GET query string parameters: * user_id: User Id, If the user Id is not parsed the current user Id is used. * attribute_id: Attribute Id."""
def __init__(self) -> None:
"""Instantiate reqpase."""
... | the_stack_v2_python_sparse | Analytics/resources/alerts/check_alerts.py | thanosbnt/SharingCitiesDashboard | train | 0 |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nmodule_list = adm.get_all_modules()\nreturn module_list",
"adm = ProjectAdministration()\nproposal = Module.from_dict(api.payload)\nprint(proposal)\nif proposal is not None:\n 'Wir verwenden module_name und edv_number des Proposals für die Erzeugung eines Module-Objektes.'\n ... | <|body_start_0|>
adm = ProjectAdministration()
module_list = adm.get_all_modules()
return module_list
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
proposal = Module.from_dict(api.payload)
print(proposal)
if proposal is not None:
'Wir ... | ModuleListOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleListOperations:
def get(self):
"""Auslesen aller Module-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen Module-Objekts"""
<|body_1|>
def put(self):
"""Update eines bestimmten Module-Objekts."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_015737 | 44,493 | no_license | [
{
"docstring": "Auslesen aller Module-Objekte",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Anlegen eines neuen Module-Objekts",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update eines bestimmten Module-Objekts.",
"name": "put",
"s... | 3 | stack_v2_sparse_classes_30k_train_001672 | Implement the Python class `ModuleListOperations` described below.
Class description:
Implement the ModuleListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller Module-Objekte
- def post(self): Anlegen eines neuen Module-Objekts
- def put(self): Update eines bestimmten Module-Objekts. | Implement the Python class `ModuleListOperations` described below.
Class description:
Implement the ModuleListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller Module-Objekte
- def post(self): Anlegen eines neuen Module-Objekts
- def put(self): Update eines bestimmten Module-Objekts.... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ModuleListOperations:
def get(self):
"""Auslesen aller Module-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen Module-Objekts"""
<|body_1|>
def put(self):
"""Update eines bestimmten Module-Objekts."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleListOperations:
def get(self):
"""Auslesen aller Module-Objekte"""
adm = ProjectAdministration()
module_list = adm.get_all_modules()
return module_list
def post(self):
"""Anlegen eines neuen Module-Objekts"""
adm = ProjectAdministration()
prop... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
80383a3477d9e9a6b47db3da75ffb635923c56a6 | [
"size = 20\nmat_a = np.random.rand(size, size)\nmat = np.dot(mat_a, mat_a.T)\nexpected_mat_root = np_power(mat, 0.5)\nmat_root = matrix_functions.matrix_square_root(mat, size)\nself.assertAllCloseAccordingToType(expected_mat_root, mat_root, atol=TOLERANCE, rtol=TOLERANCE)",
"size = 4\nmat_a = np.random.rand(size,... | <|body_start_0|>
size = 20
mat_a = np.random.rand(size, size)
mat = np.dot(mat_a, mat_a.T)
expected_mat_root = np_power(mat, 0.5)
mat_root = matrix_functions.matrix_square_root(mat, size)
self.assertAllCloseAccordingToType(expected_mat_root, mat_root, atol=TOLERANCE, rtol... | MatrixFunctionTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatrixFunctionTests:
def testMatrixSquareRootFunction(self):
"""Tests for matrix square roots."""
<|body_0|>
def testMatrixInversePthRootFunction(self):
"""Tests for matrix inverse pth roots."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = 20... | stack_v2_sparse_classes_36k_train_015738 | 2,000 | permissive | [
{
"docstring": "Tests for matrix square roots.",
"name": "testMatrixSquareRootFunction",
"signature": "def testMatrixSquareRootFunction(self)"
},
{
"docstring": "Tests for matrix inverse pth roots.",
"name": "testMatrixInversePthRootFunction",
"signature": "def testMatrixInversePthRootFu... | 2 | null | Implement the Python class `MatrixFunctionTests` described below.
Class description:
Implement the MatrixFunctionTests class.
Method signatures and docstrings:
- def testMatrixSquareRootFunction(self): Tests for matrix square roots.
- def testMatrixInversePthRootFunction(self): Tests for matrix inverse pth roots. | Implement the Python class `MatrixFunctionTests` described below.
Class description:
Implement the MatrixFunctionTests class.
Method signatures and docstrings:
- def testMatrixSquareRootFunction(self): Tests for matrix square roots.
- def testMatrixInversePthRootFunction(self): Tests for matrix inverse pth roots.
<|... | c00a74b260fcf6ba11199cc4a340c127d6616479 | <|skeleton|>
class MatrixFunctionTests:
def testMatrixSquareRootFunction(self):
"""Tests for matrix square roots."""
<|body_0|>
def testMatrixInversePthRootFunction(self):
"""Tests for matrix inverse pth roots."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatrixFunctionTests:
def testMatrixSquareRootFunction(self):
"""Tests for matrix square roots."""
size = 20
mat_a = np.random.rand(size, size)
mat = np.dot(mat_a, mat_a.T)
expected_mat_root = np_power(mat, 0.5)
mat_root = matrix_functions.matrix_square_root(mat,... | the_stack_v2_python_sparse | lingvo/core/matrix_functions_test.py | tensorflow/lingvo | train | 2,963 | |
8c42522c263eb8d0c4d6be04b4102fab36834681 | [
"try:\n failed_entry = session.query(db.FailedEntry).filter(db.FailedEntry.id == failed_entry_id).one()\nexcept NoResultFound:\n raise NotFoundError('could not find entry with ID %i' % failed_entry_id)\nreturn jsonify(failed_entry.to_dict())",
"try:\n failed_entry = session.query(db.FailedEntry).filter(d... | <|body_start_0|>
try:
failed_entry = session.query(db.FailedEntry).filter(db.FailedEntry.id == failed_entry_id).one()
except NoResultFound:
raise NotFoundError('could not find entry with ID %i' % failed_entry_id)
return jsonify(failed_entry.to_dict())
<|end_body_0|>
<|bo... | RetryFailedID | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetryFailedID:
def get(self, failed_entry_id, session=None):
"""Get failed entry by ID"""
<|body_0|>
def delete(self, failed_entry_id, session=None):
"""Delete failed entry by ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
faile... | stack_v2_sparse_classes_36k_train_015739 | 4,968 | permissive | [
{
"docstring": "Get failed entry by ID",
"name": "get",
"signature": "def get(self, failed_entry_id, session=None)"
},
{
"docstring": "Delete failed entry by ID",
"name": "delete",
"signature": "def delete(self, failed_entry_id, session=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012286 | Implement the Python class `RetryFailedID` described below.
Class description:
Implement the RetryFailedID class.
Method signatures and docstrings:
- def get(self, failed_entry_id, session=None): Get failed entry by ID
- def delete(self, failed_entry_id, session=None): Delete failed entry by ID | Implement the Python class `RetryFailedID` described below.
Class description:
Implement the RetryFailedID class.
Method signatures and docstrings:
- def get(self, failed_entry_id, session=None): Get failed entry by ID
- def delete(self, failed_entry_id, session=None): Delete failed entry by ID
<|skeleton|>
class Re... | 2b7e8314d103c94cf4552bd0152699eeca0ad159 | <|skeleton|>
class RetryFailedID:
def get(self, failed_entry_id, session=None):
"""Get failed entry by ID"""
<|body_0|>
def delete(self, failed_entry_id, session=None):
"""Delete failed entry by ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetryFailedID:
def get(self, failed_entry_id, session=None):
"""Get failed entry by ID"""
try:
failed_entry = session.query(db.FailedEntry).filter(db.FailedEntry.id == failed_entry_id).one()
except NoResultFound:
raise NotFoundError('could not find entry with ID... | the_stack_v2_python_sparse | flexget/components/failed/api.py | BrutuZ/Flexget | train | 1 | |
f8b8e0c3a3f58509196665c6f646096fd5b0e961 | [
"super().__init__(mode, p, p_mode, sample_rate)\nif min_transpose_semitones > max_transpose_semitones:\n raise ValueError('max_transpose_semitones must be > min_transpose_semitones')\nif not sample_rate:\n raise ValueError('sample_rate is invalid.')\nself._sample_rate = sample_rate\nself._fast_shifts = get_fa... | <|body_start_0|>
super().__init__(mode, p, p_mode, sample_rate)
if min_transpose_semitones > max_transpose_semitones:
raise ValueError('max_transpose_semitones must be > min_transpose_semitones')
if not sample_rate:
raise ValueError('sample_rate is invalid.')
self... | Pitch-shift sounds up or down without changing the tempo. | PitchShift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PitchShift:
"""Pitch-shift sounds up or down without changing the tempo."""
def __init__(self, sample_rate: int, min_transpose_semitones: float=-4.0, max_transpose_semitones: float=4.0, mode: str='per_example', p: float=0.5, p_mode: str=None):
""":param sample_rate: :param min_transp... | stack_v2_sparse_classes_36k_train_015740 | 4,239 | permissive | [
{
"docstring": ":param sample_rate: :param min_transpose_semitones: Minimum pitch shift transposition in semitones (default -4.0) :param max_transpose_semitones: Maximum pitch shift transposition in semitones (default +4.0) :param mode: ``per_example``, ``per_channel``, or ``per_batch``. Default ``per_example``... | 3 | stack_v2_sparse_classes_30k_train_009118 | Implement the Python class `PitchShift` described below.
Class description:
Pitch-shift sounds up or down without changing the tempo.
Method signatures and docstrings:
- def __init__(self, sample_rate: int, min_transpose_semitones: float=-4.0, max_transpose_semitones: float=4.0, mode: str='per_example', p: float=0.5,... | Implement the Python class `PitchShift` described below.
Class description:
Pitch-shift sounds up or down without changing the tempo.
Method signatures and docstrings:
- def __init__(self, sample_rate: int, min_transpose_semitones: float=-4.0, max_transpose_semitones: float=4.0, mode: str='per_example', p: float=0.5,... | 1a905acd1b8466a4250b5b68002f92375908efb4 | <|skeleton|>
class PitchShift:
"""Pitch-shift sounds up or down without changing the tempo."""
def __init__(self, sample_rate: int, min_transpose_semitones: float=-4.0, max_transpose_semitones: float=4.0, mode: str='per_example', p: float=0.5, p_mode: str=None):
""":param sample_rate: :param min_transp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PitchShift:
"""Pitch-shift sounds up or down without changing the tempo."""
def __init__(self, sample_rate: int, min_transpose_semitones: float=-4.0, max_transpose_semitones: float=4.0, mode: str='per_example', p: float=0.5, p_mode: str=None):
""":param sample_rate: :param min_transpose_semitones... | the_stack_v2_python_sparse | torch_audiomentations/augmentations/pitch_shift.py | ntzzc/torch-audiomentations | train | 0 |
9a1f579f155b09cff21d97024df76b1e45eff390 | [
"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. | CurrierRegisterServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrierRegisterServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetModel(self, request, context):
"""Missing associated doc... | stack_v2_sparse_classes_36k_train_015741 | 9,240 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Register",
"signature": "def Register(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetModel",
"signature": "def GetModel(self, request, c... | 2 | null | Implement the Python class `CurrierRegisterServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Register(self, request, context): Missing associated documentation comment in .proto file.
- def GetModel(self, request, context): M... | Implement the Python class `CurrierRegisterServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Register(self, request, context): Missing associated documentation comment in .proto file.
- def GetModel(self, request, context): M... | 039e4a679b554e085f935f8d725f560bdce6b688 | <|skeleton|>
class CurrierRegisterServicer:
"""Missing associated documentation comment in .proto file."""
def Register(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetModel(self, request, context):
"""Missing associated doc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurrierRegisterServicer:
"""Missing associated documentation comment in .proto file."""
def Register(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 | descarteslabs/common/proto/currier/currier_pb2_grpc.py | stjordanis/descarteslabs-python | train | 0 |
6c245ddc06d9365666f621c9c4c120719fb95d62 | [
"Document = current_app_ils.document_record_cls\ntry:\n Document.get_record_by_pid(document_pid)\nexcept PIDDoesNotExistError:\n raise DocumentNotFoundError(document_pid)",
"InternalLocation = current_app_ils.internal_location_record_cls\ntry:\n InternalLocation.get_record_by_pid(internal_location_pid)\n... | <|body_start_0|>
Document = current_app_ils.document_record_cls
try:
Document.get_record_by_pid(document_pid)
except PIDDoesNotExistError:
raise DocumentNotFoundError(document_pid)
<|end_body_0|>
<|body_start_1|>
InternalLocation = current_app_ils.internal_locati... | Item record validator. | ItemValidator | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemValidator:
"""Item record validator."""
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
<|body_0|>
def ensure_internal_location_exists(self, internal_location_pid):
"""Ensure internal location exists or raise."""
... | stack_v2_sparse_classes_36k_train_015742 | 7,413 | permissive | [
{
"docstring": "Ensure document exists or raise.",
"name": "ensure_document_exists",
"signature": "def ensure_document_exists(self, document_pid)"
},
{
"docstring": "Ensure internal location exists or raise.",
"name": "ensure_internal_location_exists",
"signature": "def ensure_internal_l... | 4 | null | Implement the Python class `ItemValidator` described below.
Class description:
Item record validator.
Method signatures and docstrings:
- def ensure_document_exists(self, document_pid): Ensure document exists or raise.
- def ensure_internal_location_exists(self, internal_location_pid): Ensure internal location exists... | Implement the Python class `ItemValidator` described below.
Class description:
Item record validator.
Method signatures and docstrings:
- def ensure_document_exists(self, document_pid): Ensure document exists or raise.
- def ensure_internal_location_exists(self, internal_location_pid): Ensure internal location exists... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class ItemValidator:
"""Item record validator."""
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
<|body_0|>
def ensure_internal_location_exists(self, internal_location_pid):
"""Ensure internal location exists or raise."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemValidator:
"""Item record validator."""
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
Document = current_app_ils.document_record_cls
try:
Document.get_record_by_pid(document_pid)
except PIDDoesNotExistError:
... | the_stack_v2_python_sparse | invenio_app_ils/items/api.py | inveniosoftware/invenio-app-ils | train | 64 |
8d7b3cf0b1e2a111e3d8a82569e91076c37a4e87 | [
"objs = IndivRecord.objects.distinct('discipline').order_by('discipline')\nfor obj in objs:\n obj.titel = disc2str[obj.discipline]\n obj.img_src = DISCIPLINE_TO_ICON[obj.discipline]\n obj.tekst = 'Toon alle verbeterbare records van de discipline %s.' % obj.titel\n url_disc = disc2url[obj.discipline]\n ... | <|body_start_0|>
objs = IndivRecord.objects.distinct('discipline').order_by('discipline')
for obj in objs:
obj.titel = disc2str[obj.discipline]
obj.img_src = DISCIPLINE_TO_ICON[obj.discipline]
obj.tekst = 'Toon alle verbeterbare records van de discipline %s.' % obj.ti... | Deze view laat de gebruiker een discipline kiezen | RecordsVerbeterbaarKiesDisc | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordsVerbeterbaarKiesDisc:
"""Deze view laat de gebruiker een discipline kiezen"""
def get_queryset(self):
"""called by the template system to get the queryset or list of objects for the template"""
<|body_0|>
def get_context_data(self, **kwargs):
"""called by ... | stack_v2_sparse_classes_36k_train_015743 | 8,410 | permissive | [
{
"docstring": "called by the template system to get the queryset or list of objects for the template",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "called by the template system to get the context data for the template",
"name": "get_context_data",
"s... | 2 | stack_v2_sparse_classes_30k_train_006792 | Implement the Python class `RecordsVerbeterbaarKiesDisc` described below.
Class description:
Deze view laat de gebruiker een discipline kiezen
Method signatures and docstrings:
- def get_queryset(self): called by the template system to get the queryset or list of objects for the template
- def get_context_data(self, ... | Implement the Python class `RecordsVerbeterbaarKiesDisc` described below.
Class description:
Deze view laat de gebruiker een discipline kiezen
Method signatures and docstrings:
- def get_queryset(self): called by the template system to get the queryset or list of objects for the template
- def get_context_data(self, ... | 5ed38165a231f0caa56f67e8faf2dd074916e500 | <|skeleton|>
class RecordsVerbeterbaarKiesDisc:
"""Deze view laat de gebruiker een discipline kiezen"""
def get_queryset(self):
"""called by the template system to get the queryset or list of objects for the template"""
<|body_0|>
def get_context_data(self, **kwargs):
"""called by ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordsVerbeterbaarKiesDisc:
"""Deze view laat de gebruiker een discipline kiezen"""
def get_queryset(self):
"""called by the template system to get the queryset or list of objects for the template"""
objs = IndivRecord.objects.distinct('discipline').order_by('discipline')
for obj... | the_stack_v2_python_sparse | Records/views_verbeterbaar.py | RamonvdW/nhb-apps | train | 2 |
da1d2eda97be2578ba2f29834122b116e3c305f3 | [
"super().__init__(coordinator, entry, system_zone_id, zone_data)\nself._attr_name = f'{zone_data[AZD_NAME]} {description.name}'\nself._attr_unique_id = f'{self._attr_unique_id}_{system_zone_id}_{description.key}'\nself.entity_description = description\nself.values_dict = {v: k for k, v in description.options_dict.i... | <|body_start_0|>
super().__init__(coordinator, entry, system_zone_id, zone_data)
self._attr_name = f'{zone_data[AZD_NAME]} {description.name}'
self._attr_unique_id = f'{self._attr_unique_id}_{system_zone_id}_{description.key}'
self.entity_description = description
self.values_dic... | Define an Airzone Zone select. | AirzoneZoneSelect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirzoneZoneSelect:
"""Define an Airzone Zone select."""
def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
"""Initialize."""
<|body_0|>
async def as... | stack_v2_sparse_classes_36k_train_015744 | 4,946 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None"
},
{
"docstring": "Change the selected option.",
"name... | 2 | stack_v2_sparse_classes_30k_train_013331 | Implement the Python class `AirzoneZoneSelect` described below.
Class description:
Define an Airzone Zone select.
Method signatures and docstrings:
- def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> ... | Implement the Python class `AirzoneZoneSelect` described below.
Class description:
Define an Airzone Zone select.
Method signatures and docstrings:
- def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AirzoneZoneSelect:
"""Define an Airzone Zone select."""
def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
"""Initialize."""
<|body_0|>
async def as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AirzoneZoneSelect:
"""Define an Airzone Zone select."""
def __init__(self, coordinator: AirzoneUpdateCoordinator, description: AirzoneSelectDescription, entry: ConfigEntry, system_zone_id: str, zone_data: dict[str, Any]) -> None:
"""Initialize."""
super().__init__(coordinator, entry, syst... | the_stack_v2_python_sparse | homeassistant/components/airzone/select.py | home-assistant/core | train | 35,501 |
51f5a45329b8d2879ffafdf6cb82c2f9f10dc0f7 | [
"traversal, stack = ([], [(root, False)])\nwhile stack:\n node, visited = stack.pop()\n if node:\n if visited:\n traversal.append(node.val)\n else:\n stack.append((node, True))\n stack.append((node.right, False))\n stack.append((node.left, False))\nret... | <|body_start_0|>
traversal, stack = ([], [(root, False)])
while stack:
node, visited = stack.pop()
if node:
if visited:
traversal.append(node.val)
else:
stack.append((node, True))
stack.ap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int] beats 94.77%"""
<|body_0|>
def postorderTraversal1(self, root):
""":param root: :return: beats 23.73%"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
traversal, ... | stack_v2_sparse_classes_36k_train_015745 | 1,860 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int] beats 94.77%",
"name": "postorderTraversal",
"signature": "def postorderTraversal(self, root)"
},
{
"docstring": ":param root: :return: beats 23.73%",
"name": "postorderTraversal1",
"signature": "def postorderTraversal1(self, root)"
... | 2 | stack_v2_sparse_classes_30k_train_016608 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int] beats 94.77%
- def postorderTraversal1(self, root): :param root: :return: beats 23.73% | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int] beats 94.77%
- def postorderTraversal1(self, root): :param root: :return: beats 23.73%
<|skeleton|>
cl... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int] beats 94.77%"""
<|body_0|>
def postorderTraversal1(self, root):
""":param root: :return: beats 23.73%"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int] beats 94.77%"""
traversal, stack = ([], [(root, False)])
while stack:
node, visited = stack.pop()
if node:
if visited:
traversal.append(no... | the_stack_v2_python_sparse | LeetCode/145_binary_tree_postorder_traversal.py | yao23/Machine_Learning_Playground | train | 12 | |
4f76462f64fb10d845a4d0e21f1c979f2ff96ee0 | [
"super().__init__()\nself.idim = idim\nself.odim = odim\nself.ctx_size = ctx_size\nself.stride = stride\nself.dilation = dilation\nself.batch_norm = batch_norm\nself.relu = relu\nself.tdnn = torch.nn.Conv1d(idim, odim, ctx_size, stride=stride, dilation=dilation)\nif self.batch_norm:\n self.bn = torch.nn.BatchNor... | <|body_start_0|>
super().__init__()
self.idim = idim
self.odim = odim
self.ctx_size = ctx_size
self.stride = stride
self.dilation = dilation
self.batch_norm = batch_norm
self.relu = relu
self.tdnn = torch.nn.Conv1d(idim, odim, ctx_size, stride=stri... | TDNN implementation based on Peddinti et al. implementation. Reference: https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Args: idim (int): dimension of inputs odim (int): dimension of outputs ctx_size (int): size of context window stride (int): stride of the sliding blocks dilation (int): parameter to... | TDNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDNN:
"""TDNN implementation based on Peddinti et al. implementation. Reference: https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Args: idim (int): dimension of inputs odim (int): dimension of outputs ctx_size (int): size of context window stride (int): stride of the sliding blo... | stack_v2_sparse_classes_36k_train_015746 | 2,279 | permissive | [
{
"docstring": "Construct a TDNN object.",
"name": "__init__",
"signature": "def __init__(self, idim, odim, ctx_size=5, dilation=1, stride=1, batch_norm=True, relu=True, dropout_rate=0.0)"
},
{
"docstring": "Forward TDNN. Args: xs (torch.Tensor): input tensor (B, seq_len, idim) masks (torch.Tens... | 2 | stack_v2_sparse_classes_30k_train_011225 | Implement the Python class `TDNN` described below.
Class description:
TDNN implementation based on Peddinti et al. implementation. Reference: https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Args: idim (int): dimension of inputs odim (int): dimension of outputs ctx_size (int): size of context window ... | Implement the Python class `TDNN` described below.
Class description:
TDNN implementation based on Peddinti et al. implementation. Reference: https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Args: idim (int): dimension of inputs odim (int): dimension of outputs ctx_size (int): size of context window ... | 6ecde88045e1b706b2390f98eb1950ce4075a07d | <|skeleton|>
class TDNN:
"""TDNN implementation based on Peddinti et al. implementation. Reference: https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Args: idim (int): dimension of inputs odim (int): dimension of outputs ctx_size (int): size of context window stride (int): stride of the sliding blo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TDNN:
"""TDNN implementation based on Peddinti et al. implementation. Reference: https://www.danielpovey.com/files/2015_interspeech_multisplice.pdf Args: idim (int): dimension of inputs odim (int): dimension of outputs ctx_size (int): size of context window stride (int): stride of the sliding blocks dilation ... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/tdnn.py | sw005320/espnet-1 | train | 4 |
d675ffb926b6f8f2fb131440c062b5fa10eee2f4 | [
"super().__init__()\nself.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)\nself.max = nn.MaxPool2d(2)",
"x = self.conv(x)\nx = F.relu(x)\nx = self.max(x)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
self.max = nn.MaxPool2d(2)
<|end_body_0|>
<|body_start_1|>
x = self.conv(x)
x = F.relu(x)
x = self.max(x)
return x
<|end_body_1|>
| Convolutional block. 3x3 kernel with 1 padding, Max pooling and Relu activations. Channels must be specified by user. | DownConvBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownConvBlock:
"""Convolutional block. 3x3 kernel with 1 padding, Max pooling and Relu activations. Channels must be specified by user."""
def __init__(self, in_channels, out_channels):
"""Init. Args: in_channels(int): Input channels. out_channels(int): Output channels."""
<|... | stack_v2_sparse_classes_36k_train_015747 | 10,936 | no_license | [
{
"docstring": "Init. Args: in_channels(int): Input channels. out_channels(int): Output channels.",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels)"
},
{
"docstring": "Forward pass. Args: x(torch.Tensor): Input data. Returns: torch.Tensor: Activations.",
"name... | 2 | stack_v2_sparse_classes_30k_train_007192 | Implement the Python class `DownConvBlock` described below.
Class description:
Convolutional block. 3x3 kernel with 1 padding, Max pooling and Relu activations. Channels must be specified by user.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels): Init. Args: in_channels(int): Input ch... | Implement the Python class `DownConvBlock` described below.
Class description:
Convolutional block. 3x3 kernel with 1 padding, Max pooling and Relu activations. Channels must be specified by user.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels): Init. Args: in_channels(int): Input ch... | 9027b529eaa4cf0a38f25512141810f92db99639 | <|skeleton|>
class DownConvBlock:
"""Convolutional block. 3x3 kernel with 1 padding, Max pooling and Relu activations. Channels must be specified by user."""
def __init__(self, in_channels, out_channels):
"""Init. Args: in_channels(int): Input channels. out_channels(int): Output channels."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownConvBlock:
"""Convolutional block. 3x3 kernel with 1 padding, Max pooling and Relu activations. Channels must be specified by user."""
def __init__(self, in_channels, out_channels):
"""Init. Args: in_channels(int): Input channels. out_channels(int): Output channels."""
super().__init_... | the_stack_v2_python_sparse | grae/models/torch_modules.py | jakerhodes/GRAE | train | 0 |
3d727342e706e426f0caaedef1cae0e7363776b9 | [
"self.avg_speed = avg_speed\nself.margin = 1000\nself.motors = {}\nself.inverted = inverted\nself.attach_motors()",
"speed += self.avg_speed\nif self.inverted:\n speed = -speed\nif speed > self.margin:\n speed = self.margin\nelif speed < -self.margin:\n speed = self.margin\nfor p in ports:\n if self.m... | <|body_start_0|>
self.avg_speed = avg_speed
self.margin = 1000
self.motors = {}
self.inverted = inverted
self.attach_motors()
<|end_body_0|>
<|body_start_1|>
speed += self.avg_speed
if self.inverted:
speed = -speed
if speed > self.margin:
... | Klasse zum Verbinden und Ansteueren mehrere Motoren gleichzeitg Attribute: margin: Maximalwert Geschwindigkeit (mit Speedregulation) motors: Dictionary mit den jeweiligen Motoren(value) und Ports(key) | MotorControl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotorControl:
"""Klasse zum Verbinden und Ansteueren mehrere Motoren gleichzeitg Attribute: margin: Maximalwert Geschwindigkeit (mit Speedregulation) motors: Dictionary mit den jeweiligen Motoren(value) und Ports(key)"""
def __init__(self, avg_speed, inverted=False, **kwargs):
"""INI... | stack_v2_sparse_classes_36k_train_015748 | 8,924 | no_license | [
{
"docstring": "INIT-Argument: avg_speed: Mittlere Geschwindigkeit an den Motoren inverted: falls die Motoren sich anders herum drehen sollen zusaetzliche Keywordargumente der Motoren sh ev3dev Dokumentation",
"name": "__init__",
"signature": "def __init__(self, avg_speed, inverted=False, **kwargs)"
}... | 5 | stack_v2_sparse_classes_30k_train_017360 | Implement the Python class `MotorControl` described below.
Class description:
Klasse zum Verbinden und Ansteueren mehrere Motoren gleichzeitg Attribute: margin: Maximalwert Geschwindigkeit (mit Speedregulation) motors: Dictionary mit den jeweiligen Motoren(value) und Ports(key)
Method signatures and docstrings:
- def... | Implement the Python class `MotorControl` described below.
Class description:
Klasse zum Verbinden und Ansteueren mehrere Motoren gleichzeitg Attribute: margin: Maximalwert Geschwindigkeit (mit Speedregulation) motors: Dictionary mit den jeweiligen Motoren(value) und Ports(key)
Method signatures and docstrings:
- def... | a9a7160bf7fb3b528716ebabd4c16b4482d8d9cf | <|skeleton|>
class MotorControl:
"""Klasse zum Verbinden und Ansteueren mehrere Motoren gleichzeitg Attribute: margin: Maximalwert Geschwindigkeit (mit Speedregulation) motors: Dictionary mit den jeweiligen Motoren(value) und Ports(key)"""
def __init__(self, avg_speed, inverted=False, **kwargs):
"""INI... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MotorControl:
"""Klasse zum Verbinden und Ansteueren mehrere Motoren gleichzeitg Attribute: margin: Maximalwert Geschwindigkeit (mit Speedregulation) motors: Dictionary mit den jeweiligen Motoren(value) und Ports(key)"""
def __init__(self, avg_speed, inverted=False, **kwargs):
"""INIT-Argument: a... | the_stack_v2_python_sparse | node/ev3con/linienverfolgung/control.py | Fuzzyma/network-controlled-line-follower | train | 0 |
29076f2d6f4e42e95daaab293c89d159fef68bc7 | [
"self.spSym = spSym = confRadio['samplesPerSym']\nwavePhase = np.ones(spSym) / spSym * 2 * np.pi * 0.5\nself.LUT = np.array([-wavePhase, wavePhase])",
"outPhase = np.cumsum(symTransLUTDopp[bitData]) - (bitData[0] * 2 - 1) * np.pi / 2\noutPhaseWrap = np.mod(outPhase, 2 * np.pi)\nlog.debug('length output data: {}'.... | <|body_start_0|>
self.spSym = spSym = confRadio['samplesPerSym']
wavePhase = np.ones(spSym) / spSym * 2 * np.pi * 0.5
self.LUT = np.array([-wavePhase, wavePhase])
<|end_body_0|>
<|body_start_1|>
outPhase = np.cumsum(symTransLUTDopp[bitData]) - (bitData[0] * 2 - 1) * np.pi / 2
ou... | FSKmod | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FSKmod:
def __init__(self, protocol, confRadio):
"""Create a LUT for FSK modulation. FSK changes the phase by +f for a 1 and -f for a zero. There is no ISI between the symbols The waveform is restored by integrating the LUT and taking the complex exponential of this"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_015749 | 1,311 | permissive | [
{
"docstring": "Create a LUT for FSK modulation. FSK changes the phase by +f for a 1 and -f for a zero. There is no ISI between the symbols The waveform is restored by integrating the LUT and taking the complex exponential of this",
"name": "__init__",
"signature": "def __init__(self, protocol, confRadi... | 2 | stack_v2_sparse_classes_30k_train_007589 | Implement the Python class `FSKmod` described below.
Class description:
Implement the FSKmod class.
Method signatures and docstrings:
- def __init__(self, protocol, confRadio): Create a LUT for FSK modulation. FSK changes the phase by +f for a 1 and -f for a zero. There is no ISI between the symbols The waveform is r... | Implement the Python class `FSKmod` described below.
Class description:
Implement the FSKmod class.
Method signatures and docstrings:
- def __init__(self, protocol, confRadio): Create a LUT for FSK modulation. FSK changes the phase by +f for a 1 and -f for a zero. There is no ISI between the symbols The waveform is r... | 012aad85a66fd02bb13e325e2b0a978d7667a718 | <|skeleton|>
class FSKmod:
def __init__(self, protocol, confRadio):
"""Create a LUT for FSK modulation. FSK changes the phase by +f for a 1 and -f for a zero. There is no ISI between the symbols The waveform is restored by integrating the LUT and taking the complex exponential of this"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FSKmod:
def __init__(self, protocol, confRadio):
"""Create a LUT for FSK modulation. FSK changes the phase by +f for a 1 and -f for a zero. There is no ISI between the symbols The waveform is restored by integrating the LUT and taking the complex exponential of this"""
self.spSym = spSym = con... | the_stack_v2_python_sparse | pyCuSDR/modulator/modulators/FSK_LUT.py | epeters13/pyCuSDR | train | 1 | |
6baaee55c1090333de99e81c5fbb7e41789b19c4 | [
"old_depth = cluster.depth\nnode = self.add_evaluation_node(ActivationNode(activation, evaluation), cluster, is_type)\ncluster.depth += 1\nif node is not None and self.config.max_depth != float('inf'):\n for subeval in activation.evaluations:\n self.process_evaluation(subeval, cluster, False)\ncluster.dep... | <|body_start_0|>
old_depth = cluster.depth
node = self.add_evaluation_node(ActivationNode(activation, evaluation), cluster, is_type)
cluster.depth += 1
if node is not None and self.config.max_depth != float('inf'):
for subeval in activation.evaluations:
self.p... | Create a dependency graph with a single cluster | DependencyClusterizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyClusterizer:
"""Create a dependency graph with a single cluster"""
def add_cluster_node(self, activation, evaluation, cluster, is_type):
"""Create new cluster"""
<|body_0|>
def process_cluster(self, cluster):
"""Process only main cluster"""
<|bo... | stack_v2_sparse_classes_36k_train_015750 | 14,055 | permissive | [
{
"docstring": "Create new cluster",
"name": "add_cluster_node",
"signature": "def add_cluster_node(self, activation, evaluation, cluster, is_type)"
},
{
"docstring": "Process only main cluster",
"name": "process_cluster",
"signature": "def process_cluster(self, cluster)"
}
] | 2 | null | Implement the Python class `DependencyClusterizer` described below.
Class description:
Create a dependency graph with a single cluster
Method signatures and docstrings:
- def add_cluster_node(self, activation, evaluation, cluster, is_type): Create new cluster
- def process_cluster(self, cluster): Process only main cl... | Implement the Python class `DependencyClusterizer` described below.
Class description:
Create a dependency graph with a single cluster
Method signatures and docstrings:
- def add_cluster_node(self, activation, evaluation, cluster, is_type): Create new cluster
- def process_cluster(self, cluster): Process only main cl... | 32943ecbed699e9d4967ed17ff066ba005a7c24b | <|skeleton|>
class DependencyClusterizer:
"""Create a dependency graph with a single cluster"""
def add_cluster_node(self, activation, evaluation, cluster, is_type):
"""Create new cluster"""
<|body_0|>
def process_cluster(self, cluster):
"""Process only main cluster"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DependencyClusterizer:
"""Create a dependency graph with a single cluster"""
def add_cluster_node(self, activation, evaluation, cluster, is_type):
"""Create new cluster"""
old_depth = cluster.depth
node = self.add_evaluation_node(ActivationNode(activation, evaluation), cluster, is... | the_stack_v2_python_sparse | capture/noworkflow/now/models/dependency_graph/clusterizer.py | gems-uff/noworkflow | train | 119 |
b3131f38564bfb6dde59c315d852decff05f695d | [
"if not root:\n return 0\nfrom queue import Queue\nq = Queue()\nq.put(root)\nmin_depth = 1\nwhile not q.empty():\n q_size = q.qsize()\n for _ in range(q_size):\n cur = q.get()\n if not cur.right and (not cur.left):\n return min_depth\n for n in [cur.left, cur.right]:\n ... | <|body_start_0|>
if not root:
return 0
from queue import Queue
q = Queue()
q.put(root)
min_depth = 1
while not q.empty():
q_size = q.qsize()
for _ in range(q_size):
cur = q.get()
if not cur.right and (not... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""层次遍历,遇到叶子节点即结束返回当前深度"""
<|body_0|>
def minDepth_dfs(self, root: TreeNode) -> int:
"""DFS解法,遍历整棵树,存储最短路径"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
... | stack_v2_sparse_classes_36k_train_015751 | 2,112 | no_license | [
{
"docstring": "层次遍历,遇到叶子节点即结束返回当前深度",
"name": "minDepth",
"signature": "def minDepth(self, root: TreeNode) -> int"
},
{
"docstring": "DFS解法,遍历整棵树,存储最短路径",
"name": "minDepth_dfs",
"signature": "def minDepth_dfs(self, root: TreeNode) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_001066 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: 层次遍历,遇到叶子节点即结束返回当前深度
- def minDepth_dfs(self, root: TreeNode) -> int: DFS解法,遍历整棵树,存储最短路径 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root: TreeNode) -> int: 层次遍历,遇到叶子节点即结束返回当前深度
- def minDepth_dfs(self, root: TreeNode) -> int: DFS解法,遍历整棵树,存储最短路径
<|skeleton|>
class Solution:
def minDept... | c9eed637887753eb28d78cf252ea3763231e23a2 | <|skeleton|>
class Solution:
def minDepth(self, root: TreeNode) -> int:
"""层次遍历,遇到叶子节点即结束返回当前深度"""
<|body_0|>
def minDepth_dfs(self, root: TreeNode) -> int:
"""DFS解法,遍历整棵树,存储最短路径"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root: TreeNode) -> int:
"""层次遍历,遇到叶子节点即结束返回当前深度"""
if not root:
return 0
from queue import Queue
q = Queue()
q.put(root)
min_depth = 1
while not q.empty():
q_size = q.qsize()
for _ in range... | the_stack_v2_python_sparse | CODE/111. 二叉树的最小深度.py | moshlwx/leetcode | train | 5 | |
6932b54e6f076c25a26099e948fd818f0ac8d8d5 | [
"self._inputs = inputs\nif self._inputs < 2:\n raise Exception(('spam', 'eggs'))\nself._dimensions = self.initDimensions(inputs)\nComponent.__init__(self, canvas, location, self._dimensions[0], self._dimensions[1], direction, width)\nself._inputList = []",
"widthx = inputs / sqrt(inputs * 2) * WIDTH\nheight = ... | <|body_start_0|>
self._inputs = inputs
if self._inputs < 2:
raise Exception(('spam', 'eggs'))
self._dimensions = self.initDimensions(inputs)
Component.__init__(self, canvas, location, self._dimensions[0], self._dimensions[1], direction, width)
self._inputList = []
<|e... | A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs. | MultiInSingleOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiInSingleOut:
"""A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs."""
def __init__(self, canvas, location, direction=E... | stack_v2_sparse_classes_36k_train_015752 | 8,062 | no_license | [
{
"docstring": "Initializes a Component instance with a certain number of inputs and dimensions which are dependent on the number of inputs.",
"name": "__init__",
"signature": "def __init__(self, canvas, location, direction=E, width=1, inputs=2, size=1)"
},
{
"docstring": "Initialize the dimensi... | 4 | stack_v2_sparse_classes_30k_train_019352 | Implement the Python class `MultiInSingleOut` described below.
Class description:
A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs.
Method signature... | Implement the Python class `MultiInSingleOut` described below.
Class description:
A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs.
Method signature... | 5b046f6ccacd397df7b319a9f96235dba4b653d7 | <|skeleton|>
class MultiInSingleOut:
"""A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs."""
def __init__(self, canvas, location, direction=E... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiInSingleOut:
"""A standard class for components with multiple inputs on one side and a single output on the other. It is assumed that any such object will have at least 2 inputs and has initial dimensions based on the number of inputs."""
def __init__(self, canvas, location, direction=E, width=1, in... | the_stack_v2_python_sparse | AntiochComponent.py | piannaf/Antioch | train | 0 |
f7995dcc983f170d4ee16c37154540c4bc6d8d03 | [
"super(TimeToFailure, self).__init__(*args, **kwargs)\nself._pinger = pinger\nself.target = target\nself.target = target\nself.timeout = timeout\nself.threshold = threshold\nreturn",
"if self._pinger is None:\n self._pinger = ping.ADBPing()\nreturn self._pinger",
"if parameters.target is None:\n target = ... | <|body_start_0|>
super(TimeToFailure, self).__init__(*args, **kwargs)
self._pinger = pinger
self.target = target
self.target = target
self.timeout = timeout
self.threshold = threshold
return
<|end_body_0|>
<|body_start_1|>
if self._pinger is None:
... | A TimeToFailure pings a target until the pings fail. | TimeToFailure | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeToFailure:
"""A TimeToFailure pings a target until the pings fail."""
def __init__(self, pinger=None, target=None, timeout=300, threshold=5, *args, **kwargs):
""":param: - `pinger`: An object to ping a target. - `target`: The target address to ping - `timeout`: The length of time... | stack_v2_sparse_classes_36k_train_015753 | 2,387 | permissive | [
{
"docstring": ":param: - `pinger`: An object to ping a target. - `target`: The target address to ping - `timeout`: The length of time to try in seconds. - `threshold`: The number of consecutive failures to make a fail",
"name": "__init__",
"signature": "def __init__(self, pinger=None, target=None, time... | 3 | null | Implement the Python class `TimeToFailure` described below.
Class description:
A TimeToFailure pings a target until the pings fail.
Method signatures and docstrings:
- def __init__(self, pinger=None, target=None, timeout=300, threshold=5, *args, **kwargs): :param: - `pinger`: An object to ping a target. - `target`: T... | Implement the Python class `TimeToFailure` described below.
Class description:
A TimeToFailure pings a target until the pings fail.
Method signatures and docstrings:
- def __init__(self, pinger=None, target=None, timeout=300, threshold=5, *args, **kwargs): :param: - `pinger`: An object to ping a target. - `target`: T... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class TimeToFailure:
"""A TimeToFailure pings a target until the pings fail."""
def __init__(self, pinger=None, target=None, timeout=300, threshold=5, *args, **kwargs):
""":param: - `pinger`: An object to ping a target. - `target`: The target address to ping - `timeout`: The length of time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeToFailure:
"""A TimeToFailure pings a target until the pings fail."""
def __init__(self, pinger=None, target=None, timeout=300, threshold=5, *args, **kwargs):
""":param: - `pinger`: An object to ping a target. - `target`: The target address to ping - `timeout`: The length of time to try in se... | the_stack_v2_python_sparse | apetools/tools/timetofailure.py | russell-n/oldape | train | 0 |
3ef300e086afbc252bf4172732b4c908347dd30a | [
"self.root = root\nself.pre = None\nself.tree = []\nif root:\n self.tree.append(root)",
"if self.root and self.tree:\n return True\nreturn False",
"tmp = self.tree.pop()\nif not tmp.left or tmp.left == self.pre or (self.pre and self.pre.val > tmp.left.val):\n if tmp.right:\n self.tree.append(tmp... | <|body_start_0|>
self.root = root
self.pre = None
self.tree = []
if root:
self.tree.append(root)
<|end_body_0|>
<|body_start_1|>
if self.root and self.tree:
return True
return False
<|end_body_1|>
<|body_start_2|>
tmp = self.tree.pop()
... | BSTIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.root = root
... | stack_v2_sparse_classes_36k_train_015754 | 1,665 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasNext(self)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
}
] | 3 | null | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int
<|skeleton|>
class BSTIterator:
def __init__(self, root... | 8d83f6f1f4123c61a2be7c369ffa964f382f6bda | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.root = root
self.pre = None
self.tree = []
if root:
self.tree.append(root)
def hasNext(self):
""":rtype: bool"""
if self.root and self.tree:
return True
... | the_stack_v2_python_sparse | leetcode/173_binary_search_tree_iterator.py | shoumu/HuntingJobPractice | train | 0 | |
ba8a930db3af42b2ca17b90efc439dc39e395b1c | [
"super(PrintResourceStats, self).__init__(experiment, name='PrintResourceStats', label=label)\nself.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)\nself.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experiment.config.getint('Experiment',... | <|body_start_0|>
super(PrintResourceStats, self).__init__(experiment, name='PrintResourceStats', label=label)
self.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)
self.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.expe... | Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at w... | PrintResourceStats | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrintResourceStats:
"""Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of exp... | stack_v2_sparse_classes_36k_train_015755 | 3,818 | permissive | [
{
"docstring": "Initialize the PrintResourceStats Action",
"name": "__init__",
"signature": "def __init__(self, experiment, label=None)"
},
{
"docstring": "Execute the action",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008074 | Implement the Python class `PrintResourceStats` described below.
Class description:
Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which... | Implement the Python class `PrintResourceStats` described below.
Class description:
Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which... | a114ac66e62a960e18127faf52cff9e48831e212 | <|skeleton|>
class PrintResourceStats:
"""Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of exp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrintResourceStats:
"""Write information about the distribution of the given resource Configuration is done in the [PrintResourceStats] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) freq... | the_stack_v2_python_sparse | seeds/plugins/action/PrintResourceStats.py | namlehai/seeds | train | 0 |
7be39121b3aedb938e13cbec15035f6d6f0f5638 | [
"wx.Frame.__init__(self, parent, id, 'Idle Test')\nwx.Button(self, ID_START, 'Start', pos=(0, 0))\nwx.Button(self, ID_STOP, 'Stop', pos=(0, 50))\nself.status = wx.StaticText(self, -1, '', pos=(0, 100))\nself.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)\nself.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP)\nself.Bind... | <|body_start_0|>
wx.Frame.__init__(self, parent, id, 'Idle Test')
wx.Button(self, ID_START, 'Start', pos=(0, 0))
wx.Button(self, ID_STOP, 'Stop', pos=(0, 50))
self.status = wx.StaticText(self, -1, '', pos=(0, 100))
self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
self.... | Class MainFrame. | MainFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainFrame:
"""Class MainFrame."""
def __init__(self, parent, id):
"""Create the MainFrame."""
<|body_0|>
def OnStart(self, event):
"""Start Computation."""
<|body_1|>
def OnIdle(self, event):
"""Idle Handler."""
<|body_2|>
def On... | stack_v2_sparse_classes_36k_train_015756 | 2,278 | no_license | [
{
"docstring": "Create the MainFrame.",
"name": "__init__",
"signature": "def __init__(self, parent, id)"
},
{
"docstring": "Start Computation.",
"name": "OnStart",
"signature": "def OnStart(self, event)"
},
{
"docstring": "Idle Handler.",
"name": "OnIdle",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_016894 | Implement the Python class `MainFrame` described below.
Class description:
Class MainFrame.
Method signatures and docstrings:
- def __init__(self, parent, id): Create the MainFrame.
- def OnStart(self, event): Start Computation.
- def OnIdle(self, event): Idle Handler.
- def OnStop(self, event): Stop Computation. | Implement the Python class `MainFrame` described below.
Class description:
Class MainFrame.
Method signatures and docstrings:
- def __init__(self, parent, id): Create the MainFrame.
- def OnStart(self, event): Start Computation.
- def OnIdle(self, event): Idle Handler.
- def OnStop(self, event): Stop Computation.
<|... | 20f07e8fb7d7cd7ccdb20b78666115df49a65bc8 | <|skeleton|>
class MainFrame:
"""Class MainFrame."""
def __init__(self, parent, id):
"""Create the MainFrame."""
<|body_0|>
def OnStart(self, event):
"""Start Computation."""
<|body_1|>
def OnIdle(self, event):
"""Idle Handler."""
<|body_2|>
def On... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainFrame:
"""Class MainFrame."""
def __init__(self, parent, id):
"""Create the MainFrame."""
wx.Frame.__init__(self, parent, id, 'Idle Test')
wx.Button(self, ID_START, 'Start', pos=(0, 0))
wx.Button(self, ID_STOP, 'Stop', pos=(0, 50))
self.status = wx.StaticText(s... | the_stack_v2_python_sparse | pyruler/obsolete/wx_robin.py | baluneboy/biomedken | train | 0 |
87eecfe418aaa77fcea55b16285fc983073c9120 | [
"n = len(nums)\nnums.sort()\nres = 0\nfor i in range(n - 1, 1, -1):\n left, right = (0, i - 1)\n while left < right:\n if nums[left] + nums[right] > nums[i]:\n res += right - left\n right -= 1\n else:\n left += 1\nreturn res",
"n = len(nums)\nnums.sort()\nres =... | <|body_start_0|>
n = len(nums)
nums.sort()
res = 0
for i in range(n - 1, 1, -1):
left, right = (0, i - 1)
while left < right:
if nums[left] + nums[right] > nums[i]:
res += right - left
right -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
"""排序+双指针O(n^2)"""
<|body_0|>
def triangleNumber2(self, nums: List[int]) -> int:
"""二分查找O(n^2logn)"""
<|body_1|>
def triangleNumber3(self, nums: List[int]) -> int:
"""二分查找O(n^2logn) 要求任意... | stack_v2_sparse_classes_36k_train_015757 | 1,898 | no_license | [
{
"docstring": "排序+双指针O(n^2)",
"name": "triangleNumber",
"signature": "def triangleNumber(self, nums: List[int]) -> int"
},
{
"docstring": "二分查找O(n^2logn)",
"name": "triangleNumber2",
"signature": "def triangleNumber2(self, nums: List[int]) -> int"
},
{
"docstring": "二分查找O(n^2log... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def triangleNumber(self, nums: List[int]) -> int: 排序+双指针O(n^2)
- def triangleNumber2(self, nums: List[int]) -> int: 二分查找O(n^2logn)
- def triangleNumber3(self, nums: List[int]) ->... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def triangleNumber(self, nums: List[int]) -> int: 排序+双指针O(n^2)
- def triangleNumber2(self, nums: List[int]) -> int: 二分查找O(n^2logn)
- def triangleNumber3(self, nums: List[int]) ->... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
"""排序+双指针O(n^2)"""
<|body_0|>
def triangleNumber2(self, nums: List[int]) -> int:
"""二分查找O(n^2logn)"""
<|body_1|>
def triangleNumber3(self, nums: List[int]) -> int:
"""二分查找O(n^2logn) 要求任意... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def triangleNumber(self, nums: List[int]) -> int:
"""排序+双指针O(n^2)"""
n = len(nums)
nums.sort()
res = 0
for i in range(n - 1, 1, -1):
left, right = (0, i - 1)
while left < right:
if nums[left] + nums[right] > nums[i]:
... | the_stack_v2_python_sparse | 15_双指针/分类/头尾指针/611. 有效三角形的个数.py | 981377660LMT/algorithm-study | train | 225 | |
d3b59bc79146b533b1bfc9ded068a3927a496f0a | [
"params = params or {}\nif params:\n url += '?' + urllib.parse.urlencode(params)\nreturn Downloader.download(url, on_complete=on_complete)",
"try:\n if on_complete:\n from ..threads import BackgroundThread\n return BackgroundThread(func=Downloader.download, args=[url, checksum, None], on_compl... | <|body_start_0|>
params = params or {}
if params:
url += '?' + urllib.parse.urlencode(params)
return Downloader.download(url, on_complete=on_complete)
<|end_body_0|>
<|body_start_1|>
try:
if on_complete:
from ..threads import BackgroundThread
... | A general purpose downloader | Downloader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Downloader:
"""A general purpose downloader"""
def request(url, params=None, on_complete=None):
"""Send the HTTP GET request and returns data from specified url @param url: url to send the request @param params: parameters to pass to the url @param on_complete: a callback function if... | stack_v2_sparse_classes_36k_train_015758 | 3,188 | permissive | [
{
"docstring": "Send the HTTP GET request and returns data from specified url @param url: url to send the request @param params: parameters to pass to the url @param on_complete: a callback function if provided, method will become an async task and will callback when request is complete",
"name": "request",... | 3 | stack_v2_sparse_classes_30k_train_019591 | Implement the Python class `Downloader` described below.
Class description:
A general purpose downloader
Method signatures and docstrings:
- def request(url, params=None, on_complete=None): Send the HTTP GET request and returns data from specified url @param url: url to send the request @param params: parameters to p... | Implement the Python class `Downloader` described below.
Class description:
A general purpose downloader
Method signatures and docstrings:
- def request(url, params=None, on_complete=None): Send the HTTP GET request and returns data from specified url @param url: url to send the request @param params: parameters to p... | b38d4f9d852565d6dcecb236386628b4e56d9d09 | <|skeleton|>
class Downloader:
"""A general purpose downloader"""
def request(url, params=None, on_complete=None):
"""Send the HTTP GET request and returns data from specified url @param url: url to send the request @param params: parameters to pass to the url @param on_complete: a callback function if... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Downloader:
"""A general purpose downloader"""
def request(url, params=None, on_complete=None):
"""Send the HTTP GET request and returns data from specified url @param url: url to send the request @param params: parameters to pass to the url @param on_complete: a callback function if provided, me... | the_stack_v2_python_sparse | utils/downloader.py | evandroforks/Javatar | train | 1 |
22861d043b1f770aae6fb2a1642c34732b6f22e7 | [
"exchange = quote(exchange, '')\nproperties = properties or {}\nbody = json.dumps({'routing_key': routing_key, 'payload': body, 'payload_encoding': payload_encoding, 'properties': properties, 'vhost': virtual_host})\nvirtual_host = quote(virtual_host, '')\nreturn self.http_client.post(API_BASIC_PUBLISH % (virtual_h... | <|body_start_0|>
exchange = quote(exchange, '')
properties = properties or {}
body = json.dumps({'routing_key': routing_key, 'payload': body, 'payload_encoding': payload_encoding, 'properties': properties, 'vhost': virtual_host})
virtual_host = quote(virtual_host, '')
return self... | Basic | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Basic:
def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'):
"""Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish... | stack_v2_sparse_classes_36k_train_015759 | 3,574 | permissive | [
{
"docstring": "Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message to :param str virtual_host: Virtual host name :param dict properties: Message properties :param str payload_encoding: Payload enc... | 2 | stack_v2_sparse_classes_30k_train_006471 | Implement the Python class `Basic` described below.
Class description:
Implement the Basic class.
Method signatures and docstrings:
- def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'): Publish a Message. :param bytes|str|unicode body: Message pa... | Implement the Python class `Basic` described below.
Class description:
Implement the Basic class.
Method signatures and docstrings:
- def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'): Publish a Message. :param bytes|str|unicode body: Message pa... | ca2e086818433abc08c014dd06bfd22d4985ea2a | <|skeleton|>
class Basic:
def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'):
"""Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Basic:
def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'):
"""Publish a Message. :param bytes|str|unicode body: Message payload :param str routing_key: Message routing key :param str exchange: The exchange to publish the message t... | the_stack_v2_python_sparse | amqpstorm/management/basic.py | fake-name/ReadableWebProxy | train | 207 | |
c4e0264c8b70f9757b101593ec856195f3637764 | [
"self.mean = patches.mean(0)\nself.std = np.sqrt(patches.var(0) + self.epsilon)\nreturn self",
"patches -= self.mean\npatches /= self.std\nreturn patches",
"assert self.mean is not None, 'Must call fit() first.'\npatches *= self.std\npatches += self.mean\nreturn patches"
] | <|body_start_0|>
self.mean = patches.mean(0)
self.std = np.sqrt(patches.var(0) + self.epsilon)
return self
<|end_body_0|>
<|body_start_1|>
patches -= self.mean
patches /= self.std
return patches
<|end_body_1|>
<|body_start_2|>
assert self.mean is not None, 'Must... | Normalize contrast per variable across patches. | GlobalContrastNormalizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalContrastNormalizer:
"""Normalize contrast per variable across patches."""
def fit(self, patches):
"""Estimate global contrast."""
<|body_0|>
def transform(self, patches):
"""Operates *in-place*."""
<|body_1|>
def inverse_transform(self, patches... | stack_v2_sparse_classes_36k_train_015760 | 9,118 | permissive | [
{
"docstring": "Estimate global contrast.",
"name": "fit",
"signature": "def fit(self, patches)"
},
{
"docstring": "Operates *in-place*.",
"name": "transform",
"signature": "def transform(self, patches)"
},
{
"docstring": "Operates *in-place*.",
"name": "inverse_transform",
... | 3 | null | Implement the Python class `GlobalContrastNormalizer` described below.
Class description:
Normalize contrast per variable across patches.
Method signatures and docstrings:
- def fit(self, patches): Estimate global contrast.
- def transform(self, patches): Operates *in-place*.
- def inverse_transform(self, patches): O... | Implement the Python class `GlobalContrastNormalizer` described below.
Class description:
Normalize contrast per variable across patches.
Method signatures and docstrings:
- def fit(self, patches): Estimate global contrast.
- def transform(self, patches): Operates *in-place*.
- def inverse_transform(self, patches): O... | 8b98390850351385acfda5be3088cd4db4cc4a09 | <|skeleton|>
class GlobalContrastNormalizer:
"""Normalize contrast per variable across patches."""
def fit(self, patches):
"""Estimate global contrast."""
<|body_0|>
def transform(self, patches):
"""Operates *in-place*."""
<|body_1|>
def inverse_transform(self, patches... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlobalContrastNormalizer:
"""Normalize contrast per variable across patches."""
def fit(self, patches):
"""Estimate global contrast."""
self.mean = patches.mean(0)
self.std = np.sqrt(patches.var(0) + self.epsilon)
return self
def transform(self, patches):
"""O... | the_stack_v2_python_sparse | glimpse/prototypes/utils.py | mthomure/glimpse-project | train | 1 |
cdc3ee5efc52eac849a22d7d405c65592590d056 | [
"if not root:\n return 0\nif root.left and root.right:\n return min(self.minDepth(root.left), self.minDepth(root.right)) + 1\nelse:\n return max(self.minDepth(root.left), self.minDepth(root.right)) + 1",
"if not root:\n return 0\ni = 1\ns = [root]\nwhile s:\n ss = []\n for node in s:\n if... | <|body_start_0|>
if not root:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
<|end_body_0|>
<|body_start_1|>
if not ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
if root.lef... | stack_v2_sparse_classes_36k_train_015761 | 1,091 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth",
"signature": "def minDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth",
"signature": "def minDepth(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def minDepth(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def minDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def minDepth(self, root... | c4e6c9590bb8531feeb4ac88d9ce95f823ef07e7 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left), self.... | the_stack_v2_python_sparse | Facebook/phone/Binary Tree - Minimum Depth.py | armsky/Preps | train | 0 | |
b5b7e04f815fabcdc671f5078c02c5d646684dcf | [
"super(ConvNet, self).__init__()\nself.conv = nn.Sequential(nn.Conv2d(1, 10, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(10), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(10, 30, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(30), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_si... | <|body_start_0|>
super(ConvNet, self).__init__()
self.conv = nn.Sequential(nn.Conv2d(1, 10, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(10), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(10, 30, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(30), nn.ReLU(inplace=Tr... | CNN model. | ConvNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvNet:
"""CNN model."""
def __init__(self: 'ConvNet') -> None:
"""Initialize CNN model."""
<|body_0|>
def forward(self: 'ConvNet', x: Tensor) -> Tensor:
"""Forward pass function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ConvNet, s... | stack_v2_sparse_classes_36k_train_015762 | 1,456 | permissive | [
{
"docstring": "Initialize CNN model.",
"name": "__init__",
"signature": "def __init__(self: 'ConvNet') -> None"
},
{
"docstring": "Forward pass function.",
"name": "forward",
"signature": "def forward(self: 'ConvNet', x: Tensor) -> Tensor"
}
] | 2 | stack_v2_sparse_classes_30k_train_008141 | Implement the Python class `ConvNet` described below.
Class description:
CNN model.
Method signatures and docstrings:
- def __init__(self: 'ConvNet') -> None: Initialize CNN model.
- def forward(self: 'ConvNet', x: Tensor) -> Tensor: Forward pass function. | Implement the Python class `ConvNet` described below.
Class description:
CNN model.
Method signatures and docstrings:
- def __init__(self: 'ConvNet') -> None: Initialize CNN model.
- def forward(self: 'ConvNet', x: Tensor) -> Tensor: Forward pass function.
<|skeleton|>
class ConvNet:
"""CNN model."""
def __... | 699598fb60dcc23f6cccd5abb30a03b294d21598 | <|skeleton|>
class ConvNet:
"""CNN model."""
def __init__(self: 'ConvNet') -> None:
"""Initialize CNN model."""
<|body_0|>
def forward(self: 'ConvNet', x: Tensor) -> Tensor:
"""Forward pass function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvNet:
"""CNN model."""
def __init__(self: 'ConvNet') -> None:
"""Initialize CNN model."""
super(ConvNet, self).__init__()
self.conv = nn.Sequential(nn.Conv2d(1, 10, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(10), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, strid... | the_stack_v2_python_sparse | src/anu/models/cnn/model.py | ankitskvmdam/anu | train | 0 |
ff13bd7410075b8af031fe179537e3e4b5883eaa | [
"ret = []\nfor code, component_cls in ComponentLibrary.components.get('rpc', {}).items():\n rpc_api = {'name': component_cls.name, 'key': code, 'req_params': []}\n if isinstance(component_cls.Form, DeclarativeFieldsMetaclass):\n for field_name, field in component_cls.Form.declared_fields.items():\n ... | <|body_start_0|>
ret = []
for code, component_cls in ComponentLibrary.components.get('rpc', {}).items():
rpc_api = {'name': component_cls.name, 'key': code, 'req_params': []}
if isinstance(component_cls.Form, DeclarativeFieldsMetaclass):
for field_name, field in c... | RpcApiViewSet | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpcApiViewSet:
def get(self, request, *args, **kwargs):
"""获取rpc的API列表"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""指定rpc的API, 获取返回结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
for code, component_cls in Component... | stack_v2_sparse_classes_36k_train_015763 | 12,428 | permissive | [
{
"docstring": "获取rpc的API列表",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "指定rpc的API, 获取返回结果",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `RpcApiViewSet` described below.
Class description:
Implement the RpcApiViewSet class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取rpc的API列表
- def post(self, request, *args, **kwargs): 指定rpc的API, 获取返回结果 | Implement the Python class `RpcApiViewSet` described below.
Class description:
Implement the RpcApiViewSet class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取rpc的API列表
- def post(self, request, *args, **kwargs): 指定rpc的API, 获取返回结果
<|skeleton|>
class RpcApiViewSet:
def get(self,... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class RpcApiViewSet:
def get(self, request, *args, **kwargs):
"""获取rpc的API列表"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""指定rpc的API, 获取返回结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RpcApiViewSet:
def get(self, request, *args, **kwargs):
"""获取rpc的API列表"""
ret = []
for code, component_cls in ComponentLibrary.components.get('rpc', {}).items():
rpc_api = {'name': component_cls.name, 'key': code, 'req_params': []}
if isinstance(component_cls.Fo... | the_stack_v2_python_sparse | itsm/postman/views.py | TencentBlueKing/bk-itsm | train | 100 | |
61c1bfbecef7de0eba4d102724e086051661809f | [
"if len(prices) == 0:\n return 0\ns0 = -prices[0]\ns1 = -2 ** 31\nfor i in range(1, len(prices)):\n s0 = max(s0, -prices[i])\n s1 = max(s1, prices[i] + s0)\nreturn max(0, s1)",
"maxNum = 0\nlength = len(prices)\nfor i in range(length):\n for j in range(i + 1, length):\n profit = prices[j] - pri... | <|body_start_0|>
if len(prices) == 0:
return 0
s0 = -prices[0]
s1 = -2 ** 31
for i in range(1, len(prices)):
s0 = max(s0, -prices[i])
s1 = max(s1, prices[i] + s0)
return max(0, s1)
<|end_body_0|>
<|body_start_1|>
maxNum = 0
len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(prices) == 0:
return 0... | stack_v2_sparse_classes_36k_train_015764 | 1,603 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009796 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxProf... | 328408860fcf6bffbbd2096b4c7182d8abb2ea66 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if len(prices) == 0:
return 0
s0 = -prices[0]
s1 = -2 ** 31
for i in range(1, len(prices)):
s0 = max(s0, -prices[i])
s1 = max(s1, prices[i] + s0)
... | the_stack_v2_python_sparse | lcode1-99/ex83/maxProfit.py | rh01/gofiles | train | 0 | |
f624fe26f77d7a82b04b32ea8a9d1ab4c61b6c40 | [
"self.homepage = homepage\nself.pages = [homepage]\nself.current = 0",
"if self.current != len(self.pages) - 1:\n self.pages = self.pages[:self.current + 1]\n self.pages.append(url)\n self.current = len(self.pages) - 1\n return self.pages[self.current]\nelse:\n self.pages.append(url)\n self.curr... | <|body_start_0|>
self.homepage = homepage
self.pages = [homepage]
self.current = 0
<|end_body_0|>
<|body_start_1|>
if self.current != len(self.pages) - 1:
self.pages = self.pages[:self.current + 1]
self.pages.append(url)
self.current = len(self.pages)... | BrowserHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str if the user chooses steps too big, then r... | stack_v2_sparse_classes_36k_train_015765 | 1,465 | no_license | [
{
"docstring": ":type homepage: str",
"name": "__init__",
"signature": "def __init__(self, homepage)"
},
{
"docstring": ":type url: str :rtype: None",
"name": "visit",
"signature": "def visit(self, url)"
},
{
"docstring": ":type steps: int :rtype: str if the user chooses steps to... | 4 | null | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str if the use... | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str if the use... | 6d6afba93d20665d033fe542c97e3eb50368bd3c | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str if the user chooses steps too big, then r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
self.homepage = homepage
self.pages = [homepage]
self.current = 0
def visit(self, url):
""":type url: str :rtype: None"""
if self.current != len(self.pages) - 1:
self.pages ... | the_stack_v2_python_sparse | browser_history.py | naomi397liu/AlgorithmPactice | train | 1 | |
a0a20a41e7f3944d4d5a59014060c54a8c27b0bc | [
"super(CollaborativeMemoryNetwork, self).__init__(config)\nself._embedding_initializers = {'embeddings': tf.truncated_normal_initializer(stddev=0.01)}\nself._initializers = {'w': tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False)}\nself._hops_init = {'w': tf.contrib.layers.vari... | <|body_start_0|>
super(CollaborativeMemoryNetwork, self).__init__(config)
self._embedding_initializers = {'embeddings': tf.truncated_normal_initializer(stddev=0.01)}
self._initializers = {'w': tf.contrib.layers.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False)}
self.... | CollaborativeMemoryNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollaborativeMemoryNetwork:
def __init__(self, config):
""":param config:"""
<|body_0|>
def _construct(self):
"""Construct the model; main part of it goes here"""
<|body_1|>
def _construct_placeholders(self):
"""Create placeholders for our model"... | stack_v2_sparse_classes_36k_train_015766 | 7,457 | permissive | [
{
"docstring": ":param config:",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Construct the model; main part of it goes here",
"name": "_construct",
"signature": "def _construct(self)"
},
{
"docstring": "Create placeholders for our model",
... | 4 | stack_v2_sparse_classes_30k_train_019500 | Implement the Python class `CollaborativeMemoryNetwork` described below.
Class description:
Implement the CollaborativeMemoryNetwork class.
Method signatures and docstrings:
- def __init__(self, config): :param config:
- def _construct(self): Construct the model; main part of it goes here
- def _construct_placeholder... | Implement the Python class `CollaborativeMemoryNetwork` described below.
Class description:
Implement the CollaborativeMemoryNetwork class.
Method signatures and docstrings:
- def __init__(self, config): :param config:
- def _construct(self): Construct the model; main part of it goes here
- def _construct_placeholder... | 7a483cbbbe515ad395928311759505707bd72503 | <|skeleton|>
class CollaborativeMemoryNetwork:
def __init__(self, config):
""":param config:"""
<|body_0|>
def _construct(self):
"""Construct the model; main part of it goes here"""
<|body_1|>
def _construct_placeholders(self):
"""Create placeholders for our model"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollaborativeMemoryNetwork:
def __init__(self, config):
""":param config:"""
super(CollaborativeMemoryNetwork, self).__init__(config)
self._embedding_initializers = {'embeddings': tf.truncated_normal_initializer(stddev=0.01)}
self._initializers = {'w': tf.contrib.layers.varianc... | the_stack_v2_python_sparse | recommendation_system_demos/Basic-CMN-Demo/util/cmn.py | sweetpand/Tensorflow_Best_practices | train | 3 | |
c5292bbceda91908eadcb996dce9e5466d6e728e | [
"products = response.xpath('//a[@class=\"tile\"]')\nfor product in products:\n href = product.xpath('@href').extract_first()\n yield response.follow(href, callback=self.parse_product)\nnext_page = response.xpath('//span[@class=\"pager_next\"]/a')\nif next_page:\n href = next_page.xpath('@href').extract_fir... | <|body_start_0|>
products = response.xpath('//a[@class="tile"]')
for product in products:
href = product.xpath('@href').extract_first()
yield response.follow(href, callback=self.parse_product)
next_page = response.xpath('//span[@class="pager_next"]/a')
if next_pag... | Beautylish Products Spider | BeautylishProductsSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BeautylishProductsSpider:
"""Beautylish Products Spider"""
def parse(self, response):
"""Extract product links, follow them and go to next page if exists @url https://www.beautylish.com/shop/browse @returns requests 1 @returns items 0 0"""
<|body_0|>
def parse_product(se... | stack_v2_sparse_classes_36k_train_015767 | 6,662 | no_license | [
{
"docstring": "Extract product links, follow them and go to next page if exists @url https://www.beautylish.com/shop/browse @returns requests 1 @returns items 0 0",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Extract product details @url https://www.beautylish.c... | 6 | stack_v2_sparse_classes_30k_train_004876 | Implement the Python class `BeautylishProductsSpider` described below.
Class description:
Beautylish Products Spider
Method signatures and docstrings:
- def parse(self, response): Extract product links, follow them and go to next page if exists @url https://www.beautylish.com/shop/browse @returns requests 1 @returns ... | Implement the Python class `BeautylishProductsSpider` described below.
Class description:
Beautylish Products Spider
Method signatures and docstrings:
- def parse(self, response): Extract product links, follow them and go to next page if exists @url https://www.beautylish.com/shop/browse @returns requests 1 @returns ... | 67eeb08962725fd3aff8c8cb7e16360ffd651f06 | <|skeleton|>
class BeautylishProductsSpider:
"""Beautylish Products Spider"""
def parse(self, response):
"""Extract product links, follow them and go to next page if exists @url https://www.beautylish.com/shop/browse @returns requests 1 @returns items 0 0"""
<|body_0|>
def parse_product(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BeautylishProductsSpider:
"""Beautylish Products Spider"""
def parse(self, response):
"""Extract product links, follow them and go to next page if exists @url https://www.beautylish.com/shop/browse @returns requests 1 @returns items 0 0"""
products = response.xpath('//a[@class="tile"]')
... | the_stack_v2_python_sparse | pipeline/pipeline/spiders/beautylish.py | DataRetrieval/pipeline | train | 1 |
f13f51ae6ca9e5819d9a91a07a4e207f260340ec | [
"question_text = json_dict['question']\ntable_rows = json_dict['table'].split('\\n')\ninstance = self._dataset_reader.text_to_instance(question_text, table_rows)\nreturn instance",
"instance = self._json_to_instance(inputs)\nindex_to_rule = [production_rule_field.rule for production_rule_field in instance.fields[... | <|body_start_0|>
question_text = json_dict['question']
table_rows = json_dict['table'].split('\n')
instance = self._dataset_reader.text_to_instance(question_text, table_rows)
return instance
<|end_body_0|>
<|body_start_1|>
instance = self._json_to_instance(inputs)
index_... | Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_semantic_parser.WikiTablesSemanticParser` model. | WikiTablesParserPredictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiTablesParserPredictor:
"""Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_semantic_parser.WikiTablesSemanticParser` model."""
def _json_to_instance(self, json_dict: JsonDict) -> Instance:
"""Expects JSON that looks like ``{"question": "...", "table": "..."}``... | stack_v2_sparse_classes_36k_train_015768 | 3,591 | permissive | [
{
"docstring": "Expects JSON that looks like ``{\"question\": \"...\", \"table\": \"...\"}``.",
"name": "_json_to_instance",
"signature": "def _json_to_instance(self, json_dict: JsonDict) -> Instance"
},
{
"docstring": "We need to override this because of the interactive beam search aspects.",
... | 2 | stack_v2_sparse_classes_30k_train_009660 | Implement the Python class `WikiTablesParserPredictor` described below.
Class description:
Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_semantic_parser.WikiTablesSemanticParser` model.
Method signatures and docstrings:
- def _json_to_instance(self, json_dict: JsonDict) -> Instance: Expects JSO... | Implement the Python class `WikiTablesParserPredictor` described below.
Class description:
Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_semantic_parser.WikiTablesSemanticParser` model.
Method signatures and docstrings:
- def _json_to_instance(self, json_dict: JsonDict) -> Instance: Expects JSO... | c863900e3e1fe7be540b9a0632a7a032491fc3ab | <|skeleton|>
class WikiTablesParserPredictor:
"""Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_semantic_parser.WikiTablesSemanticParser` model."""
def _json_to_instance(self, json_dict: JsonDict) -> Instance:
"""Expects JSON that looks like ``{"question": "...", "table": "..."}``... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikiTablesParserPredictor:
"""Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_semantic_parser.WikiTablesSemanticParser` model."""
def _json_to_instance(self, json_dict: JsonDict) -> Instance:
"""Expects JSON that looks like ``{"question": "...", "table": "..."}``."""
... | the_stack_v2_python_sparse | allennlp/predictors/wikitables_parser.py | Whu-wxy/allennlp | train | 6 |
1f1b70baa0c472824f3f387e8004dad64b696ece | [
"ans = str(numerator / denominator)\nif len(ans) < len(str(1 / 9)):\n return ans\n\ndef find(ans):\n for i in range(len(ans) - 3):\n temp = ans[i:-1]\n for j in range(1, len(temp)):\n if temp[:-j] == temp[j:]:\n return (i, j)\n return (0, 0)\ni, j = find(ans[2:])\nif... | <|body_start_0|>
ans = str(numerator / denominator)
if len(ans) < len(str(1 / 9)):
return ans
def find(ans):
for i in range(len(ans) - 3):
temp = ans[i:-1]
for j in range(1, len(temp)):
if temp[:-j] == temp[j:]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fractionToDecimal(self, numerator, denominator):
""":type numerator: int :type denominator: int :rtype: str"""
<|body_0|>
def fractionToDecimal_1(self, numerator, denominator):
""":type numerator: int :type denominator: int :rtype: str 39ms 找到重复出现的余数的时候... | stack_v2_sparse_classes_36k_train_015769 | 1,904 | no_license | [
{
"docstring": ":type numerator: int :type denominator: int :rtype: str",
"name": "fractionToDecimal",
"signature": "def fractionToDecimal(self, numerator, denominator)"
},
{
"docstring": ":type numerator: int :type denominator: int :rtype: str 39ms 找到重复出现的余数的时候就是开始重复的时候!!!!!!",
"name": "fra... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fractionToDecimal(self, numerator, denominator): :type numerator: int :type denominator: int :rtype: str
- def fractionToDecimal_1(self, numerator, denominator): :type numera... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fractionToDecimal(self, numerator, denominator): :type numerator: int :type denominator: int :rtype: str
- def fractionToDecimal_1(self, numerator, denominator): :type numera... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def fractionToDecimal(self, numerator, denominator):
""":type numerator: int :type denominator: int :rtype: str"""
<|body_0|>
def fractionToDecimal_1(self, numerator, denominator):
""":type numerator: int :type denominator: int :rtype: str 39ms 找到重复出现的余数的时候... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fractionToDecimal(self, numerator, denominator):
""":type numerator: int :type denominator: int :rtype: str"""
ans = str(numerator / denominator)
if len(ans) < len(str(1 / 9)):
return ans
def find(ans):
for i in range(len(ans) - 3):
... | the_stack_v2_python_sparse | FractionToRecurringDecimal_MID_166.py | 953250587/leetcode-python | train | 2 | |
1020b881b33e5448f54efae186c252d35bc479b6 | [
"self.cont = np.array([])\nself.disc_reg = np.array([])\nself.disc = np.array([])\nself.zero_poi = np.array([])\nself.reg = np.array([])",
"if fixed_cont is None:\n self.cont = np.zeros(initial_node.x.cont.clus.array.shape[0])\nelse:\n self.cont = fixed_cont\nself.reg = np.hstack([self.reg, self.cont])\nif ... | <|body_start_0|>
self.cont = np.array([])
self.disc_reg = np.array([])
self.disc = np.array([])
self.zero_poi = np.array([])
self.reg = np.array([])
<|end_body_0|>
<|body_start_1|>
if fixed_cont is None:
self.cont = np.zeros(initial_node.x.cont.clus.array.sha... | Fixed Attributes: cont (np.array[boolean of 0/1]): 1d-array of fixed continuous features disc_reg (np.array[boolean of 0/1]): 1d-array of fixed discrete features disc (np.array[boolean of 0/1]): 1d-array of fixed discrete features zero_poi (np.array[boolean of 0/1]): 1d-array of fixed zero_poi features | XFixed | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XFixed:
"""Fixed Attributes: cont (np.array[boolean of 0/1]): 1d-array of fixed continuous features disc_reg (np.array[boolean of 0/1]): 1d-array of fixed discrete features disc (np.array[boolean of 0/1]): 1d-array of fixed discrete features zero_poi (np.array[boolean of 0/1]): 1d-array of fixed ... | stack_v2_sparse_classes_36k_train_015770 | 33,380 | permissive | [
{
"docstring": "A constructor of XFixed Args:",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "set fixed feature If not directed (None),define np.zeros (all features are not fixed). Args: fixed_cont (np.array[boolean or 0/1]): 1d-array of fixed continuous features fixed... | 2 | stack_v2_sparse_classes_30k_train_000620 | Implement the Python class `XFixed` described below.
Class description:
Fixed Attributes: cont (np.array[boolean of 0/1]): 1d-array of fixed continuous features disc_reg (np.array[boolean of 0/1]): 1d-array of fixed discrete features disc (np.array[boolean of 0/1]): 1d-array of fixed discrete features zero_poi (np.arr... | Implement the Python class `XFixed` described below.
Class description:
Fixed Attributes: cont (np.array[boolean of 0/1]): 1d-array of fixed continuous features disc_reg (np.array[boolean of 0/1]): 1d-array of fixed discrete features disc (np.array[boolean of 0/1]): 1d-array of fixed discrete features zero_poi (np.arr... | f63da68802965d7f0eaaa1926b06b5ee1b0b48fe | <|skeleton|>
class XFixed:
"""Fixed Attributes: cont (np.array[boolean of 0/1]): 1d-array of fixed continuous features disc_reg (np.array[boolean of 0/1]): 1d-array of fixed discrete features disc (np.array[boolean of 0/1]): 1d-array of fixed discrete features zero_poi (np.array[boolean of 0/1]): 1d-array of fixed ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XFixed:
"""Fixed Attributes: cont (np.array[boolean of 0/1]): 1d-array of fixed continuous features disc_reg (np.array[boolean of 0/1]): 1d-array of fixed discrete features disc (np.array[boolean of 0/1]): 1d-array of fixed discrete features zero_poi (np.array[boolean of 0/1]): 1d-array of fixed zero_poi feat... | the_stack_v2_python_sparse | path_search_algorithm.py | clinfo/actionable_path_planning | train | 0 |
a2d789c4a6e1e1f3f6c35b7548189952cb21faae | [
"super(AdamWeightDecayOptimizer, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay",
"assignments = []\nfor grad, param in grads... | <|body_start_0|>
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_fro... | A basic Adam optimizer that includes "correct" L2 weight decay. | AdamWeightDecayOptimizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer'):
"""Constructs a AdamWeig... | stack_v2_sparse_classes_36k_train_015771 | 6,604 | no_license | [
{
"docstring": "Constructs a AdamWeightDecayOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer')"
},
{
"docstring": "See base class.",
... | 4 | stack_v2_sparse_classes_30k_train_008222 | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None... | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None... | 47566d0813462c623db40940ac7c8c8de2e71f7e | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer'):
"""Constructs a AdamWeig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer'):
"""Constructs a AdamWeightDecayOptimi... | the_stack_v2_python_sparse | transformer+onlstm/optimization.py | Vipning/latest-chinese-ner-model | train | 9 |
71451c77233a845fd30a13fa73dc2c918dce6e58 | [
"super().__init__(repo_path)\nself.oss_fuzz_project_name = oss_fuzz_project_name\nself.fuzzer_stats_url = _get_oss_fuzz_fuzzer_stats_dir_url(self.oss_fuzz_project_name)\nif self.fuzzer_stats_url is None:\n raise CoverageError('Could not get latest coverage.')",
"if not self.fuzzer_stats_url:\n return None\n... | <|body_start_0|>
super().__init__(repo_path)
self.oss_fuzz_project_name = oss_fuzz_project_name
self.fuzzer_stats_url = _get_oss_fuzz_fuzzer_stats_dir_url(self.oss_fuzz_project_name)
if self.fuzzer_stats_url is None:
raise CoverageError('Could not get latest coverage.')
<|end... | Gets coverage data for a project from OSS-Fuzz. | OSSFuzzCoverage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSSFuzzCoverage:
"""Gets coverage data for a project from OSS-Fuzz."""
def __init__(self, repo_path, oss_fuzz_project_name):
"""Constructor for OSSFuzzCoverage."""
<|body_0|>
def get_target_coverage(self, target):
"""Get the coverage report for a specific fuzz ta... | stack_v2_sparse_classes_36k_train_015772 | 7,002 | permissive | [
{
"docstring": "Constructor for OSSFuzzCoverage.",
"name": "__init__",
"signature": "def __init__(self, repo_path, oss_fuzz_project_name)"
},
{
"docstring": "Get the coverage report for a specific fuzz target. Args: target: The name of the fuzz target whose coverage is requested. Returns: The ta... | 2 | stack_v2_sparse_classes_30k_train_009975 | Implement the Python class `OSSFuzzCoverage` described below.
Class description:
Gets coverage data for a project from OSS-Fuzz.
Method signatures and docstrings:
- def __init__(self, repo_path, oss_fuzz_project_name): Constructor for OSSFuzzCoverage.
- def get_target_coverage(self, target): Get the coverage report f... | Implement the Python class `OSSFuzzCoverage` described below.
Class description:
Gets coverage data for a project from OSS-Fuzz.
Method signatures and docstrings:
- def __init__(self, repo_path, oss_fuzz_project_name): Constructor for OSSFuzzCoverage.
- def get_target_coverage(self, target): Get the coverage report f... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class OSSFuzzCoverage:
"""Gets coverage data for a project from OSS-Fuzz."""
def __init__(self, repo_path, oss_fuzz_project_name):
"""Constructor for OSSFuzzCoverage."""
<|body_0|>
def get_target_coverage(self, target):
"""Get the coverage report for a specific fuzz ta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OSSFuzzCoverage:
"""Gets coverage data for a project from OSS-Fuzz."""
def __init__(self, repo_path, oss_fuzz_project_name):
"""Constructor for OSSFuzzCoverage."""
super().__init__(repo_path)
self.oss_fuzz_project_name = oss_fuzz_project_name
self.fuzzer_stats_url = _get_o... | the_stack_v2_python_sparse | infra/cifuzz/get_coverage.py | google/oss-fuzz | train | 9,438 |
e4a19b6b9787c07eb346e964ea60fe609f281f99 | [
"tools.get('%s/archive/refs/heads/%s.zip' % (self.url, self.version))\nif self.settings.os == 'Windows':\n tools.patch(patch_file='vs2019.diff')\nelse:\n tools.patch(patch_file='linux.diff')",
"with tools.chdir(os.path.join(self.build_folder, 'PhysX-4.1', 'physx')):\n if self.settings.os == 'Windows':\n ... | <|body_start_0|>
tools.get('%s/archive/refs/heads/%s.zip' % (self.url, self.version))
if self.settings.os == 'Windows':
tools.patch(patch_file='vs2019.diff')
else:
tools.patch(patch_file='linux.diff')
<|end_body_0|>
<|body_start_1|>
with tools.chdir(os.path.join(... | PhysixConan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhysixConan:
def source(self):
"""Retrieve source code."""
<|body_0|>
def build(self):
"""Build the elements to package."""
<|body_1|>
def package(self):
"""Assemble the package."""
<|body_2|>
def package_info(self):
"""Edit ... | stack_v2_sparse_classes_36k_train_015773 | 2,581 | no_license | [
{
"docstring": "Retrieve source code.",
"name": "source",
"signature": "def source(self)"
},
{
"docstring": "Build the elements to package.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Assemble the package.",
"name": "package",
"signature": "def pa... | 4 | null | Implement the Python class `PhysixConan` described below.
Class description:
Implement the PhysixConan class.
Method signatures and docstrings:
- def source(self): Retrieve source code.
- def build(self): Build the elements to package.
- def package(self): Assemble the package.
- def package_info(self): Edit package ... | Implement the Python class `PhysixConan` described below.
Class description:
Implement the PhysixConan class.
Method signatures and docstrings:
- def source(self): Retrieve source code.
- def build(self): Build the elements to package.
- def package(self): Assemble the package.
- def package_info(self): Edit package ... | 514007facbd1777799d17d041fc34dffef61eff8 | <|skeleton|>
class PhysixConan:
def source(self):
"""Retrieve source code."""
<|body_0|>
def build(self):
"""Build the elements to package."""
<|body_1|>
def package(self):
"""Assemble the package."""
<|body_2|>
def package_info(self):
"""Edit ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhysixConan:
def source(self):
"""Retrieve source code."""
tools.get('%s/archive/refs/heads/%s.zip' % (self.url, self.version))
if self.settings.os == 'Windows':
tools.patch(patch_file='vs2019.diff')
else:
tools.patch(patch_file='linux.diff')
def bu... | the_stack_v2_python_sparse | PhysX_4.1/conanfile.py | MercenariesEngineering/conan_recipes | train | 7 | |
7b9da84531f622f0c3432a315b1430e4224ee1f0 | [
"super().__init__(request, params, model, model_admin)\nif self.boundaries is None or len(self.boundaries) < 2:\n raise ValueError(\"The range filter '{}' does not specify at least 2 items in 'boundaries'.\".format(self.__class__.__name__))\nif self.filter_on is None:\n self.filter_on = self.parameter_name",
... | <|body_start_0|>
super().__init__(request, params, model, model_admin)
if self.boundaries is None or len(self.boundaries) < 2:
raise ValueError("The range filter '{}' does not specify at least 2 items in 'boundaries'.".format(self.__class__.__name__))
if self.filter_on is None:
... | Simple ListFilter base for filtering on numeric ranges. | RangeListFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangeListFilter:
"""Simple ListFilter base for filtering on numeric ranges."""
def __init__(self, request, params, model, model_admin):
"""Check for mandatory settings."""
<|body_0|>
def lookups(self, request, model_admin):
"""Return a set choices to filter on ba... | stack_v2_sparse_classes_36k_train_015774 | 1,773 | no_license | [
{
"docstring": "Check for mandatory settings.",
"name": "__init__",
"signature": "def __init__(self, request, params, model, model_admin)"
},
{
"docstring": "Return a set choices to filter on based on the boundaries.",
"name": "lookups",
"signature": "def lookups(self, request, model_adm... | 3 | stack_v2_sparse_classes_30k_train_004186 | Implement the Python class `RangeListFilter` described below.
Class description:
Simple ListFilter base for filtering on numeric ranges.
Method signatures and docstrings:
- def __init__(self, request, params, model, model_admin): Check for mandatory settings.
- def lookups(self, request, model_admin): Return a set ch... | Implement the Python class `RangeListFilter` described below.
Class description:
Simple ListFilter base for filtering on numeric ranges.
Method signatures and docstrings:
- def __init__(self, request, params, model, model_admin): Check for mandatory settings.
- def lookups(self, request, model_admin): Return a set ch... | d882abb37c20489987dffb41e37717c4e354c57a | <|skeleton|>
class RangeListFilter:
"""Simple ListFilter base for filtering on numeric ranges."""
def __init__(self, request, params, model, model_admin):
"""Check for mandatory settings."""
<|body_0|>
def lookups(self, request, model_admin):
"""Return a set choices to filter on ba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RangeListFilter:
"""Simple ListFilter base for filtering on numeric ranges."""
def __init__(self, request, params, model, model_admin):
"""Check for mandatory settings."""
super().__init__(request, params, model, model_admin)
if self.boundaries is None or len(self.boundaries) < 2:... | the_stack_v2_python_sparse | abusor/events/admin_helpers.py | whyscream/abusor | train | 1 |
4f75578cbc00d66b331afea34ac3c6748d33d9c5 | [
"params = kwarg['params']\ncmd = 'tc {} filter {} '.format(params.get('options', ''), command)\nif 'dev' in params:\n cmd += 'dev {} '.format(params.get('dev'))\nif 'block' in params:\n cmd += 'block {} '.format(params.get('block'))\nreturn cmd",
"params = kwarg['params']\ncmd = 'tc {} filter {} '.format(pa... | <|body_start_0|>
params = kwarg['params']
cmd = 'tc {} filter {} '.format(params.get('options', ''), command)
if 'dev' in params:
cmd += 'dev {} '.format(params.get('dev'))
if 'block' in params:
cmd += 'block {} '.format(params.get('block'))
return cmd
<|e... | LinuxTcFilterImpl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinuxTcFilterImpl:
def format_modify(self, command, *argv, **kwarg):
"""tc [ OPTIONS ] filter [ add | change | replace | delete | get ] dev DEV [ parent qdisc-id | root ] [ handle filter-id ] protocol protocol prio priority filtertype [ filtertype specific parameters ] flowid flow-id tc ... | stack_v2_sparse_classes_36k_train_015775 | 1,443 | permissive | [
{
"docstring": "tc [ OPTIONS ] filter [ add | change | replace | delete | get ] dev DEV [ parent qdisc-id | root ] [ handle filter-id ] protocol protocol prio priority filtertype [ filtertype specific parameters ] flowid flow-id tc [ OPTIONS ] filter [ add | change | replace | delete | get ] block BLOCK_INDEX [... | 2 | stack_v2_sparse_classes_30k_train_000692 | Implement the Python class `LinuxTcFilterImpl` described below.
Class description:
Implement the LinuxTcFilterImpl class.
Method signatures and docstrings:
- def format_modify(self, command, *argv, **kwarg): tc [ OPTIONS ] filter [ add | change | replace | delete | get ] dev DEV [ parent qdisc-id | root ] [ handle fi... | Implement the Python class `LinuxTcFilterImpl` described below.
Class description:
Implement the LinuxTcFilterImpl class.
Method signatures and docstrings:
- def format_modify(self, command, *argv, **kwarg): tc [ OPTIONS ] filter [ add | change | replace | delete | get ] dev DEV [ parent qdisc-id | root ] [ handle fi... | e4c8221e18cd94e7424c30e12eb0fb82f7767267 | <|skeleton|>
class LinuxTcFilterImpl:
def format_modify(self, command, *argv, **kwarg):
"""tc [ OPTIONS ] filter [ add | change | replace | delete | get ] dev DEV [ parent qdisc-id | root ] [ handle filter-id ] protocol protocol prio priority filtertype [ filtertype specific parameters ] flowid flow-id tc ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinuxTcFilterImpl:
def format_modify(self, command, *argv, **kwarg):
"""tc [ OPTIONS ] filter [ add | change | replace | delete | get ] dev DEV [ parent qdisc-id | root ] [ handle filter-id ] protocol protocol prio priority filtertype [ filtertype specific parameters ] flowid flow-id tc [ OPTIONS ] fi... | the_stack_v2_python_sparse | Amazon_Framework/DentOsTestbedLib/src/dent_os_testbed/lib/tc/linux/linux_tc_filter_impl.py | tld3daniel/testing | train | 0 | |
cb4b23c483aa85ace41821f37df3857508b6cf8b | [
"type_option = validate_type_option(request.GET.get('type'))\nv2_format = request.GET.get('v2') == '1'\nnotification_preferences = serialize(user, request.user, NotificationSettingsSerializer(), type=type_option)\nif v2_format:\n return Response({'providers': list(map(lambda x: x.name, get_providers_for_recipien... | <|body_start_0|>
type_option = validate_type_option(request.GET.get('type'))
v2_format = request.GET.get('v2') == '1'
notification_preferences = serialize(user, request.user, NotificationSettingsSerializer(), type=type_option)
if v2_format:
return Response({'providers': list(... | This Notification Settings endpoint is the generic way to interact with the NotificationSettings table via the API. TODO(mgaeta): If this is going to replace the UserNotificationDetailsEndpoint and UserNotificationFineTuningEndpoint endpoints, then it should probably be able to translate legacy values from UserOptions. | UserNotificationSettingsDetailsEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserNotificationSettingsDetailsEndpoint:
"""This Notification Settings endpoint is the generic way to interact with the NotificationSettings table via the API. TODO(mgaeta): If this is going to replace the UserNotificationDetailsEndpoint and UserNotificationFineTuningEndpoint endpoints, then it s... | stack_v2_sparse_classes_36k_train_015776 | 3,499 | permissive | [
{
"docstring": "Get the Notification Settings for a given User. ```````````````````````````````` :pparam string user_id: A User's `user_id` or \"me\" for current user. :qparam string type: If set, filter the NotificationSettings to this type. :auth required:",
"name": "get",
"signature": "def get(self, ... | 2 | null | Implement the Python class `UserNotificationSettingsDetailsEndpoint` described below.
Class description:
This Notification Settings endpoint is the generic way to interact with the NotificationSettings table via the API. TODO(mgaeta): If this is going to replace the UserNotificationDetailsEndpoint and UserNotification... | Implement the Python class `UserNotificationSettingsDetailsEndpoint` described below.
Class description:
This Notification Settings endpoint is the generic way to interact with the NotificationSettings table via the API. TODO(mgaeta): If this is going to replace the UserNotificationDetailsEndpoint and UserNotification... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class UserNotificationSettingsDetailsEndpoint:
"""This Notification Settings endpoint is the generic way to interact with the NotificationSettings table via the API. TODO(mgaeta): If this is going to replace the UserNotificationDetailsEndpoint and UserNotificationFineTuningEndpoint endpoints, then it s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserNotificationSettingsDetailsEndpoint:
"""This Notification Settings endpoint is the generic way to interact with the NotificationSettings table via the API. TODO(mgaeta): If this is going to replace the UserNotificationDetailsEndpoint and UserNotificationFineTuningEndpoint endpoints, then it should probabl... | the_stack_v2_python_sparse | src/sentry/api/endpoints/user_notification_settings_details.py | nagyist/sentry | train | 0 |
7b2139b174309dcf4c032d7844d6227f85ea14d4 | [
"self.directory = dr\nself.images = []\nself.srclists = []\nself.populate()",
"if dr is not None:\n self.directory = dr\nfor k in OM.glob_strings:\n string = self.directory + '/' + OM.glob_strings[k]\n print('OM::populate -- Checking ', k, ' (', string, ')', end='')\n fnames = glob.glob(string)\n p... | <|body_start_0|>
self.directory = dr
self.images = []
self.srclists = []
self.populate()
<|end_body_0|>
<|body_start_1|>
if dr is not None:
self.directory = dr
for k in OM.glob_strings:
string = self.directory + '/' + OM.glob_strings[k]
... | OM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OM:
def __init__(self, dr):
"""Parameters ---------- dr : str, directory"""
<|body_0|>
def populate(self, dr=None):
"""Use glob strings to populate the filename arrays"""
<|body_1|>
def source_positions(self, dist_cutoff=None):
"""Sky coordinates... | stack_v2_sparse_classes_36k_train_015777 | 5,127 | no_license | [
{
"docstring": "Parameters ---------- dr : str, directory",
"name": "__init__",
"signature": "def __init__(self, dr)"
},
{
"docstring": "Use glob strings to populate the filename arrays",
"name": "populate",
"signature": "def populate(self, dr=None)"
},
{
"docstring": "Sky coordi... | 4 | stack_v2_sparse_classes_30k_train_019517 | Implement the Python class `OM` described below.
Class description:
Implement the OM class.
Method signatures and docstrings:
- def __init__(self, dr): Parameters ---------- dr : str, directory
- def populate(self, dr=None): Use glob strings to populate the filename arrays
- def source_positions(self, dist_cutoff=Non... | Implement the Python class `OM` described below.
Class description:
Implement the OM class.
Method signatures and docstrings:
- def __init__(self, dr): Parameters ---------- dr : str, directory
- def populate(self, dr=None): Use glob strings to populate the filename arrays
- def source_positions(self, dist_cutoff=Non... | dbd06e111859d3a173180d1b39469c4de55b3c73 | <|skeleton|>
class OM:
def __init__(self, dr):
"""Parameters ---------- dr : str, directory"""
<|body_0|>
def populate(self, dr=None):
"""Use glob strings to populate the filename arrays"""
<|body_1|>
def source_positions(self, dist_cutoff=None):
"""Sky coordinates... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OM:
def __init__(self, dr):
"""Parameters ---------- dr : str, directory"""
self.directory = dr
self.images = []
self.srclists = []
self.populate()
def populate(self, dr=None):
"""Use glob strings to populate the filename arrays"""
if dr is not None... | the_stack_v2_python_sparse | ana/tools/om.py | pcschneider/solar_analogs | train | 0 | |
042618efe066bb589c1e401df26c69e45d500705 | [
"if self.fields_before_postal is None:\n return []\nfields = []\nfor field in self.fields_before_postal:\n try:\n fields.append(self[field])\n except KeyError:\n continue\nreturn fields",
"fields = []\nfor field in self.fields_after_postal or self.fields:\n try:\n fields.append(se... | <|body_start_0|>
if self.fields_before_postal is None:
return []
fields = []
for field in self.fields_before_postal:
try:
fields.append(self[field])
except KeyError:
continue
return fields
<|end_body_0|>
<|body_start_1|... | Base class for all address forms. **Attributes:** fields_before_postal List of field names which are supposed to be displayed before the postal form fields. fields_before_postal List of field names which are supposed to be displayed after the postal form fields. | AddressBaseForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressBaseForm:
"""Base class for all address forms. **Attributes:** fields_before_postal List of field names which are supposed to be displayed before the postal form fields. fields_before_postal List of field names which are supposed to be displayed after the postal form fields."""
def ge... | stack_v2_sparse_classes_36k_train_015778 | 3,388 | no_license | [
{
"docstring": "Returns the fields which are supposed to be displayed before the postal form fields.",
"name": "get_fields_before_postal",
"signature": "def get_fields_before_postal(self)"
},
{
"docstring": "Returns the fields which are supposed to be displayed before the postal form fields.",
... | 2 | stack_v2_sparse_classes_30k_train_016791 | Implement the Python class `AddressBaseForm` described below.
Class description:
Base class for all address forms. **Attributes:** fields_before_postal List of field names which are supposed to be displayed before the postal form fields. fields_before_postal List of field names which are supposed to be displayed after... | Implement the Python class `AddressBaseForm` described below.
Class description:
Base class for all address forms. **Attributes:** fields_before_postal List of field names which are supposed to be displayed before the postal form fields. fields_before_postal List of field names which are supposed to be displayed after... | 77e9c70687b35fd8b65a7f2d879e0261ae69c00e | <|skeleton|>
class AddressBaseForm:
"""Base class for all address forms. **Attributes:** fields_before_postal List of field names which are supposed to be displayed before the postal form fields. fields_before_postal List of field names which are supposed to be displayed after the postal form fields."""
def ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddressBaseForm:
"""Base class for all address forms. **Attributes:** fields_before_postal List of field names which are supposed to be displayed before the postal form fields. fields_before_postal List of field names which are supposed to be displayed after the postal form fields."""
def get_fields_befo... | the_stack_v2_python_sparse | eggs/django_lfs-0.10.2-py2.7.egg/lfs/addresses/forms.py | yunmengyanjin/website | train | 2 |
486273fa4544d88b42e6021de396a99d48cd07df | [
"if width != None and height != None:\n SnapConfig.info = SnapConfig(width, height)\nelif SnapConfig.info == None:\n SnapConfig.info = SnapConfig()\nreturn SnapConfig.info",
"self.width = width\nself.height = height\nif self.width / 8 % 8 == 0:\n self.square_x = 64\nelse:\n self.square_x = 40\nif self... | <|body_start_0|>
if width != None and height != None:
SnapConfig.info = SnapConfig(width, height)
elif SnapConfig.info == None:
SnapConfig.info = SnapConfig()
return SnapConfig.info
<|end_body_0|>
<|body_start_1|>
self.width = width
self.height = height
... | Store last motion information | SnapConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapConfig:
"""Store last motion information"""
def get(width=None, height=None):
"""Get the last motion information"""
<|body_0|>
def __init__(self, width=800, height=600):
"""Constructor"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if width... | stack_v2_sparse_classes_36k_train_015779 | 17,709 | permissive | [
{
"docstring": "Get the last motion information",
"name": "get",
"signature": "def get(width=None, height=None)"
},
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, width=800, height=600)"
}
] | 2 | null | Implement the Python class `SnapConfig` described below.
Class description:
Store last motion information
Method signatures and docstrings:
- def get(width=None, height=None): Get the last motion information
- def __init__(self, width=800, height=600): Constructor | Implement the Python class `SnapConfig` described below.
Class description:
Store last motion information
Method signatures and docstrings:
- def get(width=None, height=None): Get the last motion information
- def __init__(self, width=800, height=600): Constructor
<|skeleton|>
class SnapConfig:
"""Store last mot... | d86814625a7cd2f7e5fa01b8e1652efc811cef3a | <|skeleton|>
class SnapConfig:
"""Store last motion information"""
def get(width=None, height=None):
"""Get the last motion information"""
<|body_0|>
def __init__(self, width=800, height=600):
"""Constructor"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapConfig:
"""Store last motion information"""
def get(width=None, height=None):
"""Get the last motion information"""
if width != None and height != None:
SnapConfig.info = SnapConfig(width, height)
elif SnapConfig.info == None:
SnapConfig.info = SnapConf... | the_stack_v2_python_sparse | modules/lib/motion/motion.py | antiquefu/pycameresp | train | 0 |
5dea14c4eaad8b138fdd760667df9439dee73689 | [
"super(ListWebhooks, cls).setUpClass()\nwebhook1_response = cls.autoscale_client.create_webhook(cls.group.id, cls.policy['id'], 'webhook1').entity\ncls.webhook1 = cls.autoscale_behaviors.get_webhooks_properties(webhook1_response)\nwebhook2_response = cls.autoscale_client.create_webhook(cls.group.id, cls.policy['id'... | <|body_start_0|>
super(ListWebhooks, cls).setUpClass()
webhook1_response = cls.autoscale_client.create_webhook(cls.group.id, cls.policy['id'], 'webhook1').entity
cls.webhook1 = cls.autoscale_behaviors.get_webhooks_properties(webhook1_response)
webhook2_response = cls.autoscale_client.cre... | Verify list webhooks | ListWebhooks | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListWebhooks:
"""Verify list webhooks"""
def setUpClass(cls):
"""Creates a scaling group with a policy and 3 webhooks on the policy"""
<|body_0|>
def test_list_webhooks(self):
"""Verify the list webhooks call for response code 201, headers and data"""
<|b... | stack_v2_sparse_classes_36k_train_015780 | 1,861 | permissive | [
{
"docstring": "Creates a scaling group with a policy and 3 webhooks on the policy",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Verify the list webhooks call for response code 201, headers and data",
"name": "test_list_webhooks",
"signature": "def test_li... | 2 | stack_v2_sparse_classes_30k_train_016614 | Implement the Python class `ListWebhooks` described below.
Class description:
Verify list webhooks
Method signatures and docstrings:
- def setUpClass(cls): Creates a scaling group with a policy and 3 webhooks on the policy
- def test_list_webhooks(self): Verify the list webhooks call for response code 201, headers an... | Implement the Python class `ListWebhooks` described below.
Class description:
Verify list webhooks
Method signatures and docstrings:
- def setUpClass(cls): Creates a scaling group with a policy and 3 webhooks on the policy
- def test_list_webhooks(self): Verify the list webhooks call for response code 201, headers an... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class ListWebhooks:
"""Verify list webhooks"""
def setUpClass(cls):
"""Creates a scaling group with a policy and 3 webhooks on the policy"""
<|body_0|>
def test_list_webhooks(self):
"""Verify the list webhooks call for response code 201, headers and data"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListWebhooks:
"""Verify list webhooks"""
def setUpClass(cls):
"""Creates a scaling group with a policy and 3 webhooks on the policy"""
super(ListWebhooks, cls).setUpClass()
webhook1_response = cls.autoscale_client.create_webhook(cls.group.id, cls.policy['id'], 'webhook1').entity
... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/functional/webhooks/test_list_webhooks.py | rackerlabs/otter | train | 20 |
a45326ac658c0a0bb40499156c5730a5a8adb289 | [
"n = len(s)\nif n == 0:\n return 0\ndp = [0] * n\nfor i in range(1, n):\n if s[i] == ')':\n if s[i - dp[i - 1] - 1] == '(' and i - dp[i - 1] - 1 >= 0:\n dp[i] = dp[i - 1] + 2 + 0 if i - dp[i - 1] - 2 == -1 else dp[i - dp[i - 1] - 2]\nreturn max(dp)",
"n = len(s)\nif n == 0:\n return 0\n... | <|body_start_0|>
n = len(s)
if n == 0:
return 0
dp = [0] * n
for i in range(1, n):
if s[i] == ')':
if s[i - dp[i - 1] - 1] == '(' and i - dp[i - 1] - 1 >= 0:
dp[i] = dp[i - 1] + 2 + 0 if i - dp[i - 1] - 2 == -1 else dp[i - dp[i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s: str) -> int:
"""LC 32. Longest Valid Parentheses Time complexity: O(N) Space: O(N) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2"""
<|body_0|>
def longestValidParentheses2(self, s: str) -> int:
"""Greedy approach"""
... | stack_v2_sparse_classes_36k_train_015781 | 1,405 | no_license | [
{
"docstring": "LC 32. Longest Valid Parentheses Time complexity: O(N) Space: O(N) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s: str) -> int"
},
{
"docstring": "Greedy approach",
"name": "longestValidPare... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s: str) -> int: LC 32. Longest Valid Parentheses Time complexity: O(N) Space: O(N) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
- def longestVa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s: str) -> int: LC 32. Longest Valid Parentheses Time complexity: O(N) Space: O(N) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
- def longestVa... | 89b6c180bb772978b6646131f9734b122e745f9c | <|skeleton|>
class Solution:
def longestValidParentheses(self, s: str) -> int:
"""LC 32. Longest Valid Parentheses Time complexity: O(N) Space: O(N) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2"""
<|body_0|>
def longestValidParentheses2(self, s: str) -> int:
"""Greedy approach"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParentheses(self, s: str) -> int:
"""LC 32. Longest Valid Parentheses Time complexity: O(N) Space: O(N) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2"""
n = len(s)
if n == 0:
return 0
dp = [0] * n
for i in range(1, n):
i... | the_stack_v2_python_sparse | dp/python/longest-valid-parentheses.py | dyf102/LC-daily | train | 2 | |
02b5351fa7c9121cf8ca2b1262c13661041b6bf4 | [
"if n == 0:\n return 1.0\nhalf = self.fastpow(x, n / 2)\nif n % 2 == 1:\n return half * half * x\nreturn half * half",
"if n < 0:\n n = -n\n x = 1 / x\nreturn self.fastpow(x, n)"
] | <|body_start_0|>
if n == 0:
return 1.0
half = self.fastpow(x, n / 2)
if n % 2 == 1:
return half * half * x
return half * half
<|end_body_0|>
<|body_start_1|>
if n < 0:
n = -n
x = 1 / x
return self.fastpow(x, n)
<|end_body_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fastpow(self, x, n):
"""fast pow"""
<|body_0|>
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return 1.0
half = self.fastpow(x, n / 2)
... | stack_v2_sparse_classes_36k_train_015782 | 780 | no_license | [
{
"docstring": "fast pow",
"name": "fastpow",
"signature": "def fastpow(self, x, n)"
},
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow",
"signature": "def myPow(self, x, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017811 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fastpow(self, x, n): fast pow
- def myPow(self, x, n): :type x: float :type n: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fastpow(self, x, n): fast pow
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
<|skeleton|>
class Solution:
def fastpow(self, x, n):
"""fast p... | 1a18711fb1ea479fe6fbbe4bd6120950e00ba3ff | <|skeleton|>
class Solution:
def fastpow(self, x, n):
"""fast pow"""
<|body_0|>
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fastpow(self, x, n):
"""fast pow"""
if n == 0:
return 1.0
half = self.fastpow(x, n / 2)
if n % 2 == 1:
return half * half * x
return half * half
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
... | the_stack_v2_python_sparse | 050.Pow_x_n.py | chaoswork/leetcode | train | 0 | |
11a72443dfdce4db6dd71ccd35e37422d9a7c62d | [
"if value is self.field.missing_value:\n return []\nwidget = self.widget\nif widget.terms is None:\n widget.update_terms()\nvalues = []\nfor entry in value:\n try:\n values.append(widget.terms.getTerm(entry).token)\n except LookupError:\n pass\nreturn values",
"widget = self.widget\nif w... | <|body_start_0|>
if value is self.field.missing_value:
return []
widget = self.widget
if widget.terms is None:
widget.update_terms()
values = []
for entry in value:
try:
values.append(widget.terms.getTerm(entry).token)
... | A special converter between collections and sequence widgets. | CollectionSequenceDataConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConver... | stack_v2_sparse_classes_36k_train_015783 | 16,755 | permissive | [
{
"docstring": "Convert from Python bool to HTML representation.",
"name": "to_widget_value",
"signature": "def to_widget_value(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "to_field_value",
"signature": "def to_field_value(self, value)"
}
] | 2 | null | Implement the Python class `CollectionSequenceDataConverter` described below.
Class description:
A special converter between collections and sequence widgets.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, value): See i... | Implement the Python class `CollectionSequenceDataConverter` described below.
Class description:
A special converter between collections and sequence widgets.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, value): See i... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConver... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
if value is self.field.missing_value:
return []
widget = self.widget
if... | the_stack_v2_python_sparse | src/pyams_form/converter.py | Py-AMS/pyams-form | train | 0 |
9b25e9c4ca79565ef88be4d1f856b42199de3a75 | [
"self.mgr = mgr\nself.base_components = base_components\nself.quit = False",
"print(f'Running on {socket.gethostname()}')\nself.mgr.run(self.base_components)\nwith cli_connection.server(paths.beeflow_socket()) as server:\n while not self.quit:\n self.handle_client(server)\n self.mgr.poll()\n ... | <|body_start_0|>
self.mgr = mgr
self.base_components = base_components
self.quit = False
<|end_body_0|>
<|body_start_1|>
print(f'Running on {socket.gethostname()}')
self.mgr.run(self.base_components)
with cli_connection.server(paths.beeflow_socket()) as server:
... | Beeflow class for handling the main loop. | Beeflow | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Beeflow:
"""Beeflow class for handling the main loop."""
def __init__(self, mgr, base_components):
"""Create the Beeflow class."""
<|body_0|>
def loop(self):
"""Run the main loop."""
<|body_1|>
def handle_client(self, server):
"""Handle a mes... | stack_v2_sparse_classes_36k_train_015784 | 14,670 | permissive | [
{
"docstring": "Create the Beeflow class.",
"name": "__init__",
"signature": "def __init__(self, mgr, base_components)"
},
{
"docstring": "Run the main loop.",
"name": "loop",
"signature": "def loop(self)"
},
{
"docstring": "Handle a message from the client.",
"name": "handle... | 3 | stack_v2_sparse_classes_30k_train_000049 | Implement the Python class `Beeflow` described below.
Class description:
Beeflow class for handling the main loop.
Method signatures and docstrings:
- def __init__(self, mgr, base_components): Create the Beeflow class.
- def loop(self): Run the main loop.
- def handle_client(self, server): Handle a message from the c... | Implement the Python class `Beeflow` described below.
Class description:
Beeflow class for handling the main loop.
Method signatures and docstrings:
- def __init__(self, mgr, base_components): Create the Beeflow class.
- def loop(self): Run the main loop.
- def handle_client(self, server): Handle a message from the c... | 4d2f965765bc0d54236898d62bbd9d01a4b850e8 | <|skeleton|>
class Beeflow:
"""Beeflow class for handling the main loop."""
def __init__(self, mgr, base_components):
"""Create the Beeflow class."""
<|body_0|>
def loop(self):
"""Run the main loop."""
<|body_1|>
def handle_client(self, server):
"""Handle a mes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Beeflow:
"""Beeflow class for handling the main loop."""
def __init__(self, mgr, base_components):
"""Create the Beeflow class."""
self.mgr = mgr
self.base_components = base_components
self.quit = False
def loop(self):
"""Run the main loop."""
print(f'... | the_stack_v2_python_sparse | beeflow/cli.py | lanl/BEE | train | 18 |
64c900bf7d9bc534d2deeb8049667c13f3488140 | [
"self.fitness = fitness\nself.breed = breed\nself.best_fitness = -np.inf\nself.best_fitness_history = []\nself.best_solution = None\nself.population = None\nself.nthreads = nthreads",
"self.population = init_pop\nkeep = int(round(elitist_frac * len(self.population)))\nfor gen in range(max_gens):\n fitnesses = ... | <|body_start_0|>
self.fitness = fitness
self.breed = breed
self.best_fitness = -np.inf
self.best_fitness_history = []
self.best_solution = None
self.population = None
self.nthreads = nthreads
<|end_body_0|>
<|body_start_1|>
self.population = init_pop
... | GeneticOptimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneticOptimizer:
def __init__(self, fitness, breed, nthreads=1):
"""fitness(sol) is a function that defines the fitness of a solution. Space of solutions is implicitly defined by fitness function. breed(solist) takes a list of solutions and produces a new solution. mutate(sol,frac) take... | stack_v2_sparse_classes_36k_train_015785 | 12,215 | permissive | [
{
"docstring": "fitness(sol) is a function that defines the fitness of a solution. Space of solutions is implicitly defined by fitness function. breed(solist) takes a list of solutions and produces a new solution. mutate(sol,frac) takes a solution and perturbs a fraction of it.",
"name": "__init__",
"si... | 2 | stack_v2_sparse_classes_30k_train_009407 | Implement the Python class `GeneticOptimizer` described below.
Class description:
Implement the GeneticOptimizer class.
Method signatures and docstrings:
- def __init__(self, fitness, breed, nthreads=1): fitness(sol) is a function that defines the fitness of a solution. Space of solutions is implicitly defined by fit... | Implement the Python class `GeneticOptimizer` described below.
Class description:
Implement the GeneticOptimizer class.
Method signatures and docstrings:
- def __init__(self, fitness, breed, nthreads=1): fitness(sol) is a function that defines the fitness of a solution. Space of solutions is implicitly defined by fit... | 7d37356046617d3f7f0a22c72301b6ad0680aefe | <|skeleton|>
class GeneticOptimizer:
def __init__(self, fitness, breed, nthreads=1):
"""fitness(sol) is a function that defines the fitness of a solution. Space of solutions is implicitly defined by fitness function. breed(solist) takes a list of solutions and produces a new solution. mutate(sol,frac) take... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneticOptimizer:
def __init__(self, fitness, breed, nthreads=1):
"""fitness(sol) is a function that defines the fitness of a solution. Space of solutions is implicitly defined by fitness function. breed(solist) takes a list of solutions and produces a new solution. mutate(sol,frac) takes a solution a... | the_stack_v2_python_sparse | assets/notebooks/gen_alg.py | Paul-St-Young/algorithms | train | 2 | |
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115 | [
"if db_field.name == 'topic' and (not request.user.is_superuser):\n kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())\nreturn super(TopicTableAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)",
"topic = TopicTable.objects.get(id=object_id)\noff_days = [day for... | <|body_start_0|>
if db_field.name == 'topic' and (not request.user.is_superuser):
kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())
return super(TopicTableAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | TopicTableAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicTableAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits Topics field to user's topics."""
<|body_0|>
def change_view(self, request, object_id, form_url='', extra_context=None):
"""Overrides the change view that displays change_form... | stack_v2_sparse_classes_36k_train_015786 | 9,167 | permissive | [
{
"docstring": "limits Topics field to user's topics.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Overrides the change view that displays change_form.html",
"name": "change_view",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_004416 | Implement the Python class `TopicTableAdmin` described below.
Class description:
Implement the TopicTableAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits Topics field to user's topics.
- def change_view(self, request, object_id, form_url='', extr... | Implement the Python class `TopicTableAdmin` described below.
Class description:
Implement the TopicTableAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): limits Topics field to user's topics.
- def change_view(self, request, object_id, form_url='', extr... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class TopicTableAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits Topics field to user's topics."""
<|body_0|>
def change_view(self, request, object_id, form_url='', extra_context=None):
"""Overrides the change view that displays change_form... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopicTableAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""limits Topics field to user's topics."""
if db_field.name == 'topic' and (not request.user.is_superuser):
kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())
... | the_stack_v2_python_sparse | cms/admin.py | Ibrahem3amer/bala7 | train | 0 | |
f28daa8e8d56ff63e92da13ef0ca64f11f60a493 | [
"super().__init__()\nself.name = 'VoxelMeanVFE'\nnum_output_filters = [num_input_features + 6] + list(num_filters)\nvfe_layers = []\nfor i in range(len(num_output_filters) - 1):\n in_filters = num_output_filters[i]\n out_filters = num_output_filters[i + 1]\n if i < len(num_output_filters) - 2:\n las... | <|body_start_0|>
super().__init__()
self.name = 'VoxelMeanVFE'
num_output_filters = [num_input_features + 6] + list(num_filters)
vfe_layers = []
for i in range(len(num_output_filters) - 1):
in_filters = num_output_filters[i]
out_filters = num_output_filter... | VoxelMeanVFE | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxelMeanVFE:
def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]):
"""Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. ... | stack_v2_sparse_classes_36k_train_015787 | 8,913 | permissive | [
{
"docstring": "Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. Number of input features, either x, y, z or x, y, z, r. :param num_filters: (<int>: N). Number of features in each of the N PFNLayers.",
"name": "__init__... | 3 | null | Implement the Python class `VoxelMeanVFE` described below.
Class description:
Implement the VoxelMeanVFE class.
Method signatures and docstrings:
- def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]): Voxel Feature Net. The network prepar... | Implement the Python class `VoxelMeanVFE` described below.
Class description:
Implement the VoxelMeanVFE class.
Method signatures and docstrings:
- def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]): Voxel Feature Net. The network prepar... | 7f2bd81c41bcd41af34f6953101038201a4f7d37 | <|skeleton|>
class VoxelMeanVFE:
def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]):
"""Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VoxelMeanVFE:
def __init__(self, num_input_features=4, num_filters=(64,), voxel_size=[0.2, 0.2, 4], pc_range=[0.0, -40.0, -3.0, 70.4, 40.0, 1.0]):
"""Voxel Feature Net. The network prepares the voxel features and performs forward pass through VFELayers. :param num_input_features: <int>. Number of inpu... | the_stack_v2_python_sparse | mvt/blocks/backbones/voxel_vfe.py | visriv/multi-visual-tasks | train | 1 | |
193a89d30b0d2d193242d752e05a660769faddf0 | [
"super().__init__(NAME)\nif language_model is None:\n self.language_model = seq2seq.Gru()\nelse:\n self.language_model = language_model\nself.scaling_ghi = preprocessing.min_max_scaling_ghi()\nself.flatten = layers.Flatten()\nself.max_pool = layers.MaxPooling3D((1, 2, 2))\nself.conv1 = layers.Conv3D(64, kerne... | <|body_start_0|>
super().__init__(NAME)
if language_model is None:
self.language_model = seq2seq.Gru()
else:
self.language_model = language_model
self.scaling_ghi = preprocessing.min_max_scaling_ghi()
self.flatten = layers.Flatten()
self.max_pool =... | Create Conv3D model to be used with the language model. Generated futur images are used instead of past image. | Conv3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv3D:
"""Create Conv3D model to be used with the language model. Generated futur images are used instead of past image."""
def __init__(self, language_model: seq2seq.Seq2Seq=None):
"""Initialize the architecture."""
<|body_0|>
def call(self, data: Tuple[tf.Tensor, tf.T... | stack_v2_sparse_classes_36k_train_015788 | 3,337 | no_license | [
{
"docstring": "Initialize the architecture.",
"name": "__init__",
"signature": "def __init__(self, language_model: seq2seq.Seq2Seq=None)"
},
{
"docstring": "Performs the forward pass in the neural network.",
"name": "call",
"signature": "def call(self, data: Tuple[tf.Tensor, tf.Tensor],... | 4 | stack_v2_sparse_classes_30k_val_000259 | Implement the Python class `Conv3D` described below.
Class description:
Create Conv3D model to be used with the language model. Generated futur images are used instead of past image.
Method signatures and docstrings:
- def __init__(self, language_model: seq2seq.Seq2Seq=None): Initialize the architecture.
- def call(s... | Implement the Python class `Conv3D` described below.
Class description:
Create Conv3D model to be used with the language model. Generated futur images are used instead of past image.
Method signatures and docstrings:
- def __init__(self, language_model: seq2seq.Seq2Seq=None): Initialize the architecture.
- def call(s... | b20d809bff84bb508190be8540a815fb9b8b3f8b | <|skeleton|>
class Conv3D:
"""Create Conv3D model to be used with the language model. Generated futur images are used instead of past image."""
def __init__(self, language_model: seq2seq.Seq2Seq=None):
"""Initialize the architecture."""
<|body_0|>
def call(self, data: Tuple[tf.Tensor, tf.T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv3D:
"""Create Conv3D model to be used with the language model. Generated futur images are used instead of past image."""
def __init__(self, language_model: seq2seq.Seq2Seq=None):
"""Initialize the architecture."""
super().__init__(NAME)
if language_model is None:
s... | the_stack_v2_python_sparse | src/model/conv3d_lm.py | nathanielsimard/Solar-Irradiance-Prediction | train | 0 |
51bed8c1d4a0d38fb5d8f98412798e5308e8acce | [
"if metadata:\n msg.update(metadata)\nts = msg['data']['timestamp']\nreturn OrderBookMessage(OrderBookMessageType.SNAPSHOT, {'trading_pair': msg['trading_pair'], 'update_id': int(ts), 'bids': convert_from_x18(msg['data']['bids']), 'asks': convert_from_x18(msg['data']['asks'])}, timestamp=timestamp)",
"if metad... | <|body_start_0|>
if metadata:
msg.update(metadata)
ts = msg['data']['timestamp']
return OrderBookMessage(OrderBookMessageType.SNAPSHOT, {'trading_pair': msg['trading_pair'], 'update_id': int(ts), 'bids': convert_from_x18(msg['data']['bids']), 'asks': convert_from_x18(msg['data']['ask... | VertexOrderBook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VertexOrderBook:
def snapshot_message_from_exchange_websocket(cls, msg: Dict[str, Any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage:
"""Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the ... | stack_v2_sparse_classes_36k_train_015789 | 4,655 | permissive | [
{
"docstring": "Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the order book snapshot :param timestamp: the snapshot timestamp :param metadata: a dictionary with extra information to add to the snapshot data :return: a snapshot message... | 4 | null | Implement the Python class `VertexOrderBook` described below.
Class description:
Implement the VertexOrderBook class.
Method signatures and docstrings:
- def snapshot_message_from_exchange_websocket(cls, msg: Dict[str, Any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage: Creates a snapshot mess... | Implement the Python class `VertexOrderBook` described below.
Class description:
Implement the VertexOrderBook class.
Method signatures and docstrings:
- def snapshot_message_from_exchange_websocket(cls, msg: Dict[str, Any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage: Creates a snapshot mess... | c3f101759ab7e7a2165cd23a3a3e94c90c642a9b | <|skeleton|>
class VertexOrderBook:
def snapshot_message_from_exchange_websocket(cls, msg: Dict[str, Any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage:
"""Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VertexOrderBook:
def snapshot_message_from_exchange_websocket(cls, msg: Dict[str, Any], timestamp: float, metadata: Optional[Dict]=None) -> OrderBookMessage:
"""Creates a snapshot message with the order book snapshot message :param msg: the response from the exchange when requesting the order book sna... | the_stack_v2_python_sparse | hummingbot/connector/exchange/vertex/vertex_order_book.py | CoinAlpha/hummingbot | train | 135 | |
d02667f46aac7cca81b59ddfa2b7aad03f8bf943 | [
"if value is None:\n return ''\nelse:\n return value",
"if isinstance(value, models.EmailField):\n return value\nif value is None:\n return ''\nreturn value",
"if value is '':\n return None\nelse:\n return value"
] | <|body_start_0|>
if value is None:
return ''
else:
return value
<|end_body_0|>
<|body_start_1|>
if isinstance(value, models.EmailField):
return value
if value is None:
return ''
return value
<|end_body_1|>
<|body_start_2|>
... | Subclass of the EmailField that allows empty strings to be stored as NULL. | NullableEmailField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NullableEmailField:
"""Subclass of the EmailField that allows empty strings to be stored as NULL."""
def from_db_value(self, value, expression, connection, contex):
"""Gets value right out of the db and changes it if its ``None``."""
<|body_0|>
def to_python(self, value)... | stack_v2_sparse_classes_36k_train_015790 | 2,246 | no_license | [
{
"docstring": "Gets value right out of the db and changes it if its ``None``.",
"name": "from_db_value",
"signature": "def from_db_value(self, value, expression, connection, contex)"
},
{
"docstring": "Gets value right out of the db or an instance, and changes it if its ``None``.",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_014056 | Implement the Python class `NullableEmailField` described below.
Class description:
Subclass of the EmailField that allows empty strings to be stored as NULL.
Method signatures and docstrings:
- def from_db_value(self, value, expression, connection, contex): Gets value right out of the db and changes it if its ``None... | Implement the Python class `NullableEmailField` described below.
Class description:
Subclass of the EmailField that allows empty strings to be stored as NULL.
Method signatures and docstrings:
- def from_db_value(self, value, expression, connection, contex): Gets value right out of the db and changes it if its ``None... | d7dfd1608099b732046a7e943c303e8407185901 | <|skeleton|>
class NullableEmailField:
"""Subclass of the EmailField that allows empty strings to be stored as NULL."""
def from_db_value(self, value, expression, connection, contex):
"""Gets value right out of the db and changes it if its ``None``."""
<|body_0|>
def to_python(self, value)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NullableEmailField:
"""Subclass of the EmailField that allows empty strings to be stored as NULL."""
def from_db_value(self, value, expression, connection, contex):
"""Gets value right out of the db and changes it if its ``None``."""
if value is None:
return ''
else:
... | the_stack_v2_python_sparse | vishleva/models.py | webmalc/vishleva.com.old | train | 1 |
a66bca88cd1b5b913c061a0a0be76a38fb34e3a4 | [
"self.jobs = jobs\nself.logical_size_in_bytes = logical_size_in_bytes\nself.parent_source = parent_source\nself.protection_source_uid_list = protection_source_uid_list\nself.source = source\nself.uuid = uuid",
"if dictionary is None:\n return None\njobs = None\nif dictionary.get('jobs') != None:\n jobs = li... | <|body_start_0|>
self.jobs = jobs
self.logical_size_in_bytes = logical_size_in_bytes
self.parent_source = parent_source
self.protection_source_uid_list = protection_source_uid_list
self.source = source
self.uuid = uuid
<|end_body_0|>
<|body_start_1|>
if dictionar... | Implementation of the 'ProtectionSourceResponse' model. Specifies the information about the individual object from search api response. Attributes: jobs (list of ProtectionJobSummary): Specifies the list of Protection Jobs that protect the object. logical_size_in_bytes (long|int): Specifies the logical size of Protecti... | ProtectionSourceResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionSourceResponse:
"""Implementation of the 'ProtectionSourceResponse' model. Specifies the information about the individual object from search api response. Attributes: jobs (list of ProtectionJobSummary): Specifies the list of Protection Jobs that protect the object. logical_size_in_byte... | stack_v2_sparse_classes_36k_train_015791 | 3,960 | permissive | [
{
"docstring": "Constructor for the ProtectionSourceResponse class",
"name": "__init__",
"signature": "def __init__(self, jobs=None, logical_size_in_bytes=None, parent_source=None, protection_source_uid_list=None, source=None, uuid=None)"
},
{
"docstring": "Creates an instance of this model from... | 2 | stack_v2_sparse_classes_30k_train_011467 | Implement the Python class `ProtectionSourceResponse` described below.
Class description:
Implementation of the 'ProtectionSourceResponse' model. Specifies the information about the individual object from search api response. Attributes: jobs (list of ProtectionJobSummary): Specifies the list of Protection Jobs that p... | Implement the Python class `ProtectionSourceResponse` described below.
Class description:
Implementation of the 'ProtectionSourceResponse' model. Specifies the information about the individual object from search api response. Attributes: jobs (list of ProtectionJobSummary): Specifies the list of Protection Jobs that p... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionSourceResponse:
"""Implementation of the 'ProtectionSourceResponse' model. Specifies the information about the individual object from search api response. Attributes: jobs (list of ProtectionJobSummary): Specifies the list of Protection Jobs that protect the object. logical_size_in_byte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectionSourceResponse:
"""Implementation of the 'ProtectionSourceResponse' model. Specifies the information about the individual object from search api response. Attributes: jobs (list of ProtectionJobSummary): Specifies the list of Protection Jobs that protect the object. logical_size_in_bytes (long|int):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_source_response.py | cohesity/management-sdk-python | train | 24 |
91f4b515cc1511fa185ce42f9b25ff083bf27a35 | [
"masked_img = inputs\nmasks = data_samples.mask\nmasks = 1.0 - masks\nmasks = masks.repeat(1, 3, 1, 1)\nfake_reses, _ = self.generator(masked_img, masks)\nfake_imgs = fake_reses * (1.0 - masks) + masked_img * masks\nreturn (fake_reses, fake_imgs)",
"data = self.data_preprocessor(data, True)\nbatch_inputs, data_sa... | <|body_start_0|>
masked_img = inputs
masks = data_samples.mask
masks = 1.0 - masks
masks = masks.repeat(1, 3, 1, 1)
fake_reses, _ = self.generator(masked_img, masks)
fake_imgs = fake_reses * (1.0 - masks) + masked_img * masks
return (fake_reses, fake_imgs)
<|end_b... | Inpaintor for Partial Convolution method. This inpaintor is implemented according to the paper: Image inpainting for irregular holes using partial convolutions | PConvInpaintor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PConvInpaintor:
"""Inpaintor for Partial Convolution method. This inpaintor is implemented according to the paper: Image inpainting for irregular holes using partial convolutions"""
def forward_tensor(self, inputs, data_samples):
"""Forward function in tensor mode. Args: inputs (torc... | stack_v2_sparse_classes_36k_train_015792 | 2,825 | permissive | [
{
"docstring": "Forward function in tensor mode. Args: inputs (torch.Tensor): Input tensor. data_sample (dict): Dict contains data sample. Returns: dict: Dict contains output results.",
"name": "forward_tensor",
"signature": "def forward_tensor(self, inputs, data_samples)"
},
{
"docstring": "Tra... | 2 | null | Implement the Python class `PConvInpaintor` described below.
Class description:
Inpaintor for Partial Convolution method. This inpaintor is implemented according to the paper: Image inpainting for irregular holes using partial convolutions
Method signatures and docstrings:
- def forward_tensor(self, inputs, data_samp... | Implement the Python class `PConvInpaintor` described below.
Class description:
Inpaintor for Partial Convolution method. This inpaintor is implemented according to the paper: Image inpainting for irregular holes using partial convolutions
Method signatures and docstrings:
- def forward_tensor(self, inputs, data_samp... | a382f143c0fd20d227e1e5524831ba26a568190d | <|skeleton|>
class PConvInpaintor:
"""Inpaintor for Partial Convolution method. This inpaintor is implemented according to the paper: Image inpainting for irregular holes using partial convolutions"""
def forward_tensor(self, inputs, data_samples):
"""Forward function in tensor mode. Args: inputs (torc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PConvInpaintor:
"""Inpaintor for Partial Convolution method. This inpaintor is implemented according to the paper: Image inpainting for irregular holes using partial convolutions"""
def forward_tensor(self, inputs, data_samples):
"""Forward function in tensor mode. Args: inputs (torch.Tensor): In... | the_stack_v2_python_sparse | mmagic/models/editors/pconv/pconv_inpaintor.py | open-mmlab/mmagic | train | 1,370 |
5e5b5018b690c4bb49322e0a7c680754a474c4a1 | [
"self.maximum = maximum_value\nif maximum_value <= 0:\n self.maximum = -1\nself.__writer = output\nself.__barwidth = 30\nself.__last_percent = -1",
"if config.SILENT:\n return None\nif self.maximum == -1:\n return False\nt_percent_done = int((new_value + 1) / self.maximum * self.__barwidth)\nif t_percent... | <|body_start_0|>
self.maximum = maximum_value
if maximum_value <= 0:
self.maximum = -1
self.__writer = output
self.__barwidth = 30
self.__last_percent = -1
<|end_body_0|>
<|body_start_1|>
if config.SILENT:
return None
if self.maximum == -1... | progressbar | [
"MIT",
"X11-distribute-modifications-variant"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class progressbar:
def __init__(self, maximum_value, output=sys.stderr):
"""Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use."""
<|body_0|>
def update(self, ne... | stack_v2_sparse_classes_36k_train_015793 | 2,033 | permissive | [
{
"docstring": "Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use.",
"name": "__init__",
"signature": "def __init__(self, maximum_value, output=sys.stderr)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_019588 | Implement the Python class `progressbar` described below.
Class description:
Implement the progressbar class.
Method signatures and docstrings:
- def __init__(self, maximum_value, output=sys.stderr): Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Op... | Implement the Python class `progressbar` described below.
Class description:
Implement the progressbar class.
Method signatures and docstrings:
- def __init__(self, maximum_value, output=sys.stderr): Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Op... | a1e35eba86fb62b336d559c0b8c0015f38426781 | <|skeleton|>
class progressbar:
def __init__(self, maximum_value, output=sys.stderr):
"""Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use."""
<|body_0|>
def update(self, ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class progressbar:
def __init__(self, maximum_value, output=sys.stderr):
"""Initialise the progress bar **Arguments** maximum_value (Required) the maximum_value to move the bar up to. output (Optional, defaults to stderr) the output device to use."""
self.maximum = maximum_value
if maximum_v... | the_stack_v2_python_sparse | progress.py | oaxiom/glbase3 | train | 12 | |
abae5d1a773105e0b3f52dca88e0b7eb38fd0453 | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.ffn = tf.keras.Sequential([self.dense_hidden, self.dense_output])\nself.layer... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.ffn = tf.keras.Sequent... | This class create an encoder block for a transformer | DecoderBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""This class create an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""All starts here"""
<|body_0|>
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
"""This method call the model""... | stack_v2_sparse_classes_36k_train_015794 | 2,365 | permissive | [
{
"docstring": "All starts here",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "This method call the model",
"name": "call",
"signature": "def call(self, x, encoder_output, training, look_ahead_mask, padding_mask)"
}
] | 2 | null | Implement the Python class `DecoderBlock` described below.
Class description:
This class create an encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): All starts here
- def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): This me... | Implement the Python class `DecoderBlock` described below.
Class description:
This class create an encoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): All starts here
- def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): This me... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class DecoderBlock:
"""This class create an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""All starts here"""
<|body_0|>
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
"""This method call the model""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""This class create an encoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""All starts here"""
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.de... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | linkem97/holbertonschool-machine_learning | train | 0 |
3c321685a951e2bba0e31eebd2cba4075c4d70c3 | [
"self._dataframe = dataframe\nif self._dataframe is None:\n raise ValueError('The dataframe must be valid.')",
"label_statistics = DataFrame(columns=[label_col, constants.PANDAS_COUNT_AGG_COLUMN, constants.PANDAS_PCT_AGG_COLUMN])\ntotal = len(self._dataframe)\nlabel_counts = self._dataframe.groupby(label_col).... | <|body_start_0|>
self._dataframe = dataframe
if self._dataframe is None:
raise ValueError('The dataframe must be valid.')
<|end_body_0|>
<|body_start_1|>
label_statistics = DataFrame(columns=[label_col, constants.PANDAS_COUNT_AGG_COLUMN, constants.PANDAS_PCT_AGG_COLUMN])
tot... | LabelEvaluation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelEvaluation:
def __init__(self, dataframe):
"""It sets the input parameters Arguments: dataframe {A Pandas DataFrame} -- The candidate dataframe for evaluation."""
<|body_0|>
def distribution(self, label_col):
"""It creates a dictionary of labels with their perce... | stack_v2_sparse_classes_36k_train_015795 | 5,762 | no_license | [
{
"docstring": "It sets the input parameters Arguments: dataframe {A Pandas DataFrame} -- The candidate dataframe for evaluation.",
"name": "__init__",
"signature": "def __init__(self, dataframe)"
},
{
"docstring": "It creates a dictionary of labels with their percentages in the dataframe. Argum... | 4 | stack_v2_sparse_classes_30k_test_000590 | Implement the Python class `LabelEvaluation` described below.
Class description:
Implement the LabelEvaluation class.
Method signatures and docstrings:
- def __init__(self, dataframe): It sets the input parameters Arguments: dataframe {A Pandas DataFrame} -- The candidate dataframe for evaluation.
- def distribution(... | Implement the Python class `LabelEvaluation` described below.
Class description:
Implement the LabelEvaluation class.
Method signatures and docstrings:
- def __init__(self, dataframe): It sets the input parameters Arguments: dataframe {A Pandas DataFrame} -- The candidate dataframe for evaluation.
- def distribution(... | 08b697bc88667c1ded4d8fc8a102cf7432e31596 | <|skeleton|>
class LabelEvaluation:
def __init__(self, dataframe):
"""It sets the input parameters Arguments: dataframe {A Pandas DataFrame} -- The candidate dataframe for evaluation."""
<|body_0|>
def distribution(self, label_col):
"""It creates a dictionary of labels with their perce... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelEvaluation:
def __init__(self, dataframe):
"""It sets the input parameters Arguments: dataframe {A Pandas DataFrame} -- The candidate dataframe for evaluation."""
self._dataframe = dataframe
if self._dataframe is None:
raise ValueError('The dataframe must be valid.')
... | the_stack_v2_python_sparse | model/evaluation.py | NareshPS/humpback-whale | train | 1 | |
3454da691165366584f34eb20ff76e525d8e4579 | [
"if not coins or len(coins) == 0 or amount < 0:\n return -1\nif min(coins) > amount:\n return -1\nif amount == 0:\n return 0\nfrom sys import maxint\ndp = [maxint for i in range(amount + 1)]\ndp[0] = 0\nfor c in coins:\n if c < amount:\n dp[c] = 1\nfor a in range(1, amount + 1):\n for c in coi... | <|body_start_0|>
if not coins or len(coins) == 0 or amount < 0:
return -1
if min(coins) > amount:
return -1
if amount == 0:
return 0
from sys import maxint
dp = [maxint for i in range(amount + 1)]
dp[0] = 0
for c in coins:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_015796 | 2,985 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange2",
"signature": "def coinChange2(self, coins, amou... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
if not coins or len(coins) == 0 or amount < 0:
return -1
if min(coins) > amount:
return -1
if amount == 0:
return 0
from sys imp... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00322.Coin Change.py | roger6blog/LeetCode | train | 0 | |
3406fbd6c2d2a9ba10d76786ab6543f5989d89b5 | [
"if len(nums) <= 1:\n return False\nbuff_dict = {}\nfor i in range(len(nums)):\n if i == leftnum:\n continue\n if nums[i] in buff_dict:\n return [buff_dict[nums[i]], i]\n else:\n buff_dict[target - nums[i]] = i",
"leftnum = 0\nnumstack = []\nfor index in range(len(nums)):\n num... | <|body_start_0|>
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if i == leftnum:
continue
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target, leftnum):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015797 | 863 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target, leftnum)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009044 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target, leftnum): :type nums: List[int] :type target: int :rtype: List[int]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target, leftnum): :type nums: List[int] :type target: int :rtype: List[int]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|sk... | 90d95d72fb4fa0659a2f4861b65bc4f98647ab37 | <|skeleton|>
class Solution:
def twoSum(self, nums, target, leftnum):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target, leftnum):
""":type nums: List[int] :type target: int :rtype: List[int]"""
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if i == leftnum:
continue
if nums[i] ... | the_stack_v2_python_sparse | 3 sum.py | hyperion-mk2/git | train | 0 | |
87c9a92158525e8d2e177055031249372a6d157f | [
"self._bucket = defaultdict(list)\nself._elements = list()\nself._idle_idx = list()\nself._index_set = set()",
"is_not_contains = True if val not in self._bucket.keys() else False\nif len(self._idle_idx) != 0:\n idx = self._idle_idx.pop()\n self._elements[idx] = val\nelse:\n self._elements.append(val)\n ... | <|body_start_0|>
self._bucket = defaultdict(list)
self._elements = list()
self._idle_idx = list()
self._index_set = set()
<|end_body_0|>
<|body_start_1|>
is_not_contains = True if val not in self._bucket.keys() else False
if len(self._idle_idx) != 0:
idx = se... | RandomizedCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element."""
<|body_1... | stack_v2_sparse_classes_36k_train_015798 | 2,183 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the collection. Returns true if the collection did not already contain the specified element.",
"name": "insert",
"signature": "def insert(se... | 4 | stack_v2_sparse_classes_30k_train_016089 | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the collection. Returns true if the coll... | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the collection. Returns true if the coll... | 40cdc510e048164aee82a5a64a3d8e187cb75920 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
self._bucket = defaultdict(list)
self._elements = list()
self._idle_idx = list()
self._index_set = set()
def insert(self, val: int) -> bool:
"""Inserts a value to the colle... | the_stack_v2_python_sparse | subjects/0381_RandomizedCollection/RandomizedCollection.py | anchorhong/leetcode_python | train | 0 | |
55b7a4421a314d14ad956eb998907983a485d17a | [
"if not initializers:\n initializers = DEFAULT_INITIALIZERS\nif not inputs_per_timestep:\n inputs_per_timestep = [1] * num_timesteps\nif not outputs_per_timestep:\n outputs_per_timestep = [1] * num_timesteps\nself.num_timesteps = num_timesteps\nself.variance_min = variance_min\nself.initializers = initiali... | <|body_start_0|>
if not initializers:
initializers = DEFAULT_INITIALIZERS
if not inputs_per_timestep:
inputs_per_timestep = [1] * num_timesteps
if not outputs_per_timestep:
outputs_per_timestep = [1] * num_timesteps
self.num_timesteps = num_timesteps
... | A set of loc-scale distributions that are linear functions of inputs. This class defines a series of location-scale distributions such that the means are learnable linear functions of the inputs and the log variances are learnable constants. The functions and log variances are different across timesteps, allowing the d... | NonstationaryLinearDistribution | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonstationaryLinearDistribution:
"""A set of loc-scale distributions that are linear functions of inputs. This class defines a series of location-scale distributions such that the means are learnable linear functions of the inputs and the log variances are learnable constants. The functions and l... | stack_v2_sparse_classes_36k_train_015799 | 14,517 | permissive | [
{
"docstring": "Creates a NonstationaryLinearDistribution. Args: num_timesteps: The number of timesteps, i.e. the number of distributions. inputs_per_timestep: A list of python ints, the dimension of inputs to the linear function at each timestep. If not provided, the dimension at each timestep is assumed to be... | 2 | null | Implement the Python class `NonstationaryLinearDistribution` described below.
Class description:
A set of loc-scale distributions that are linear functions of inputs. This class defines a series of location-scale distributions such that the means are learnable linear functions of the inputs and the log variances are l... | Implement the Python class `NonstationaryLinearDistribution` described below.
Class description:
A set of loc-scale distributions that are linear functions of inputs. This class defines a series of location-scale distributions such that the means are learnable linear functions of the inputs and the log variances are l... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class NonstationaryLinearDistribution:
"""A set of loc-scale distributions that are linear functions of inputs. This class defines a series of location-scale distributions such that the means are learnable linear functions of the inputs and the log variances are learnable constants. The functions and l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonstationaryLinearDistribution:
"""A set of loc-scale distributions that are linear functions of inputs. This class defines a series of location-scale distributions such that the means are learnable linear functions of the inputs and the log variances are learnable constants. The functions and log variances ... | the_stack_v2_python_sparse | models/research/fivo/fivo/models/base.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.