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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08178f8b7e1a278bf325f70ab253568839dd2e9b | [
"path = self.request.get('path', None)\nif path is None:\n return []\nclassModule = getUtility(IDocumentationModule, 'Code')\nresults = []\nfor p in classRegistry.keys():\n if p.find(path) >= 0:\n klass = traverse(classModule, p.replace('.', '/'))\n results.append({'path': p, 'url': absoluteURL(... | <|body_start_0|>
path = self.request.get('path', None)
if path is None:
return []
classModule = getUtility(IDocumentationModule, 'Code')
results = []
for p in classRegistry.keys():
if p.find(path) >= 0:
klass = traverse(classModule, p.repla... | Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation. | Menu | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodul... | stack_v2_sparse_classes_36k_train_031100 | 5,400 | permissive | [
{
"docstring": "Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodule.class_ import Class >>> cm = apidoc.get('Code') >>> mod = cm['zope']['app']['apidoc']['codemodule']['browser'] Setup a couple of classes and register them. >>> class Foo(object): ... pass >>> mod._children... | 2 | stack_v2_sparse_classes_30k_train_000991 | Implement the Python class `Menu` described below.
Class description:
Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation.
Method signatures and docstrings:
- def findClasses(self): Find the classes that match a pa... | Implement the Python class `Menu` described below.
Class description:
Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation.
Method signatures and docstrings:
- def findClasses(self): Find the classes that match a pa... | 539d418fb28322e27fea252ceccc42192dd0d63d | <|skeleton|>
class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
"""Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation."""
def findClasses(self):
"""Find the classes that match a partial path. Examples:: >>> from zope.app.apidoc.codemodule.class_ impo... | the_stack_v2_python_sparse | src/zope/app/apidoc/codemodule/browser/menu.py | jean/zope.app.apidoc | train | 0 |
d8b2eb6a47b5d43f31724e2d341ff652a3c6392a | [
"self.title = 'Convert Miles to Kilometres'\nself.root = Builder.load_file('miles_to_kilometres.kv')\nreturn self.root",
"value = self.valid_miles()\nresult = value * MILES_TO_KM\nself.root.ids.output_label.text = str(result)",
"value = self.valid_miles() + up_or_down\nself.root.ids.input_number.text = str(valu... | <|body_start_0|>
self.title = 'Convert Miles to Kilometres'
self.root = Builder.load_file('miles_to_kilometres.kv')
return self.root
<|end_body_0|>
<|body_start_1|>
value = self.valid_miles()
result = value * MILES_TO_KM
self.root.ids.output_label.text = str(result)
<|en... | MilesToKilometresConverter is a Kivy App that converts user input of miles into kilometres. | MilesToKilometresConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MilesToKilometresConverter:
"""MilesToKilometresConverter is a Kivy App that converts user input of miles into kilometres."""
def build(self):
"""Build the Kivy app from .kv file"""
<|body_0|>
def handle_calculate(self):
"""Handles calculation from miles to kilom... | stack_v2_sparse_classes_36k_train_031101 | 1,184 | no_license | [
{
"docstring": "Build the Kivy app from .kv file",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "Handles calculation from miles to kilometres",
"name": "handle_calculate",
"signature": "def handle_calculate(self)"
},
{
"docstring": "Handles and updates user i... | 4 | stack_v2_sparse_classes_30k_train_015974 | Implement the Python class `MilesToKilometresConverter` described below.
Class description:
MilesToKilometresConverter is a Kivy App that converts user input of miles into kilometres.
Method signatures and docstrings:
- def build(self): Build the Kivy app from .kv file
- def handle_calculate(self): Handles calculatio... | Implement the Python class `MilesToKilometresConverter` described below.
Class description:
MilesToKilometresConverter is a Kivy App that converts user input of miles into kilometres.
Method signatures and docstrings:
- def build(self): Build the Kivy app from .kv file
- def handle_calculate(self): Handles calculatio... | fd46338604ad0bbd457e6cddf188244ba4ab951e | <|skeleton|>
class MilesToKilometresConverter:
"""MilesToKilometresConverter is a Kivy App that converts user input of miles into kilometres."""
def build(self):
"""Build the Kivy app from .kv file"""
<|body_0|>
def handle_calculate(self):
"""Handles calculation from miles to kilom... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MilesToKilometresConverter:
"""MilesToKilometresConverter is a Kivy App that converts user input of miles into kilometres."""
def build(self):
"""Build the Kivy app from .kv file"""
self.title = 'Convert Miles to Kilometres'
self.root = Builder.load_file('miles_to_kilometres.kv')
... | the_stack_v2_python_sparse | Prac07/miles_to_kilometres.py | luke-sexton/CP1404_Weekly_Practical_Activities | train | 0 |
7c9ccece9f340f3436927ea6c94ca002f13c93a3 | [
"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... | NOTE(const): Not used. TODO(const): Switch to Bittensor protocol. | BittensorServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BittensorServicer:
"""NOTE(const): Not used. TODO(const): Switch to Bittensor protocol."""
def Spike(self, request, context):
"""Query remote component with text-features, responses are var-length vector representations of the text."""
<|body_0|>
def Grade(self, request,... | stack_v2_sparse_classes_36k_train_031102 | 2,451 | permissive | [
{
"docstring": "Query remote component with text-features, responses are var-length vector representations of the text.",
"name": "Spike",
"signature": "def Spike(self, request, context)"
},
{
"docstring": "Query a remote component with gradients. Responses are boolean affirmatives.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_014853 | Implement the Python class `BittensorServicer` described below.
Class description:
NOTE(const): Not used. TODO(const): Switch to Bittensor protocol.
Method signatures and docstrings:
- def Spike(self, request, context): Query remote component with text-features, responses are var-length vector representations of the ... | Implement the Python class `BittensorServicer` described below.
Class description:
NOTE(const): Not used. TODO(const): Switch to Bittensor protocol.
Method signatures and docstrings:
- def Spike(self, request, context): Query remote component with text-features, responses are var-length vector representations of the ... | d1af6993c1d6bca273a0c8d147132ee9867f5543 | <|skeleton|>
class BittensorServicer:
"""NOTE(const): Not used. TODO(const): Switch to Bittensor protocol."""
def Spike(self, request, context):
"""Query remote component with text-features, responses are var-length vector representations of the text."""
<|body_0|>
def Grade(self, request,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BittensorServicer:
"""NOTE(const): Not used. TODO(const): Switch to Bittensor protocol."""
def Spike(self, request, context):
"""Query remote component with text-features, responses are var-length vector representations of the text."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | bittensor/proto/bittensor_pb2_grpc.py | unconst/BitTensor | train | 10 |
e3cb5d49288c0335426c48c218cd742c6a3ca0be | [
"super(HumanBooleanMember, self).init()\nself._human = dict.fromkeys(self._TRUE, True)\nself._human.update(dict.fromkeys(self._FALSE, False))",
"try:\n return self._human[str(value).lower()]\nexcept KeyError:\n raise ValueError(\"Value %r means neither 'true' nor 'false'\" % value)"
] | <|body_start_0|>
super(HumanBooleanMember, self).init()
self._human = dict.fromkeys(self._TRUE, True)
self._human.update(dict.fromkeys(self._FALSE, False))
<|end_body_0|>
<|body_start_1|>
try:
return self._human[str(value).lower()]
except KeyError:
raise ... | Boolean storage with translater from human readable booleans :CVariables: - `_TRUE`: The true words (``('word', ...)``) - `_FALSE`: The false words (``('word', ...)``) :IVariables: - `_human`: The dictionary containing true and false keys :Types: - `_TRUE`: ``tuple`` - `_FALSE`: ``tuple`` - `_human`: ``dict`` | HumanBooleanMember | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumanBooleanMember:
"""Boolean storage with translater from human readable booleans :CVariables: - `_TRUE`: The true words (``('word', ...)``) - `_FALSE`: The false words (``('word', ...)``) :IVariables: - `_human`: The dictionary containing true and false keys :Types: - `_TRUE`: ``tuple`` - `_FA... | stack_v2_sparse_classes_36k_train_031103 | 18,259 | permissive | [
{
"docstring": "Custom initialization",
"name": "init",
"signature": "def init(self)"
},
{
"docstring": "Turns into boolean :exception ValueError: The supplied value was not recognized as human boolean",
"name": "doTransform",
"signature": "def doTransform(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010641 | Implement the Python class `HumanBooleanMember` described below.
Class description:
Boolean storage with translater from human readable booleans :CVariables: - `_TRUE`: The true words (``('word', ...)``) - `_FALSE`: The false words (``('word', ...)``) :IVariables: - `_human`: The dictionary containing true and false k... | Implement the Python class `HumanBooleanMember` described below.
Class description:
Boolean storage with translater from human readable booleans :CVariables: - `_TRUE`: The true words (``('word', ...)``) - `_FALSE`: The false words (``('word', ...)``) :IVariables: - `_human`: The dictionary containing true and false k... | faecefdabd8fbf6d40738a24004772020c244f64 | <|skeleton|>
class HumanBooleanMember:
"""Boolean storage with translater from human readable booleans :CVariables: - `_TRUE`: The true words (``('word', ...)``) - `_FALSE`: The false words (``('word', ...)``) :IVariables: - `_human`: The dictionary containing true and false keys :Types: - `_TRUE`: ``tuple`` - `_FA... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HumanBooleanMember:
"""Boolean storage with translater from human readable booleans :CVariables: - `_TRUE`: The true words (``('word', ...)``) - `_FALSE`: The false words (``('word', ...)``) :IVariables: - `_human`: The dictionary containing true and false keys :Types: - `_TRUE`: ``tuple`` - `_FALSE`: ``tuple... | the_stack_v2_python_sparse | src/lib/svnmailer/settings/_accessors.py | m-tmatma/svnmailer | train | 1 |
c71e9233c60cbed4592f7aef12e5fe4eec39008c | [
"super(ClassHead, self).__init__()\nself._is_training = is_training\nself._num_classes = num_classes\nself._fc_hyperparams_fn = fc_hyperparams_fn\nself._use_dropout = use_dropout\nself._dropout_keep_prob = dropout_keep_prob",
"spatial_averaged_roi_pooled_features = tf.reduce_mean(roi_pooled_features, [1, 2], keep... | <|body_start_0|>
super(ClassHead, self).__init__()
self._is_training = is_training
self._num_classes = num_classes
self._fc_hyperparams_fn = fc_hyperparams_fn
self._use_dropout = use_dropout
self._dropout_keep_prob = dropout_keep_prob
<|end_body_0|>
<|body_start_1|>
... | Mask RCNN class prediction head. | ClassHead | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassHead:
"""Mask RCNN class prediction head."""
def __init__(self, is_training, num_classes, fc_hyperparams_fn, use_dropout, dropout_keep_prob):
"""Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_... | stack_v2_sparse_classes_36k_train_031104 | 3,430 | permissive | [
{
"docstring": "Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned ... | 2 | null | Implement the Python class `ClassHead` described below.
Class description:
Mask RCNN class prediction head.
Method signatures and docstrings:
- def __init__(self, is_training, num_classes, fc_hyperparams_fn, use_dropout, dropout_keep_prob): Constructor. Args: is_training: Indicates whether the BoxPredictor is in trai... | Implement the Python class `ClassHead` described below.
Class description:
Mask RCNN class prediction head.
Method signatures and docstrings:
- def __init__(self, is_training, num_classes, fc_hyperparams_fn, use_dropout, dropout_keep_prob): Constructor. Args: is_training: Indicates whether the BoxPredictor is in trai... | 8383e6c377a93304534c46e3c9fd7821cc068d98 | <|skeleton|>
class ClassHead:
"""Mask RCNN class prediction head."""
def __init__(self, is_training, num_classes, fc_hyperparams_fn, use_dropout, dropout_keep_prob):
"""Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassHead:
"""Mask RCNN class prediction head."""
def __init__(self, is_training, num_classes, fc_hyperparams_fn, use_dropout, dropout_keep_prob):
"""Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does... | the_stack_v2_python_sparse | deeplens/object_detection/tensorflow_detect/predictors/mask_rcnn_heads/class_head.py | sjyk/deeplens-cv | train | 11 |
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"self.num_layers = num_layers\nself.dtypes = OrderedDict([('policytc_id', 'i'), ('calcrule_id', 'i'), ('deductible1', 'f'), ('deductible2', 'f'), ('deductible3', 'f'), ('attachment1', 'f'), ('limit1', 'f'), ('share1', 'f'), ('share2', 'f'), ('share3', 'f')])\nself.start_stats = None\nself.data_length = 1 + num_laye... | <|body_start_0|>
self.num_layers = num_layers
self.dtypes = OrderedDict([('policytc_id', 'i'), ('calcrule_id', 'i'), ('deductible1', 'f'), ('deductible2', 'f'), ('deductible3', 'f'), ('attachment1', 'f'), ('limit1', 'f'), ('share1', 'f'), ('share2', 'f'), ('share3', 'f')])
self.start_stats = Non... | Generate data for Financial Model Profile dummy model Oasis file. This file contains the list of calculation rules with profile values used to generate insurance losses. Attributes: generate_data: Generate Financial Model Profile dummy model Oasis file data. | FMProfileFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FMProfileFile:
"""Generate data for Financial Model Profile dummy model Oasis file. This file contains the list of calculation rules with profile values used to generate insurance losses. Attributes: generate_data: Generate Financial Model Profile dummy model Oasis file data."""
def __init__... | stack_v2_sparse_classes_36k_train_031105 | 39,722 | permissive | [
{
"docstring": "Initialise Financial Model Profile file class. Args: num_layers (int): number of layers. directory (str): dummy model file destination.",
"name": "__init__",
"signature": "def __init__(self, num_layers, directory)"
},
{
"docstring": "Generate Financial Model Profile dummy model f... | 2 | null | Implement the Python class `FMProfileFile` described below.
Class description:
Generate data for Financial Model Profile dummy model Oasis file. This file contains the list of calculation rules with profile values used to generate insurance losses. Attributes: generate_data: Generate Financial Model Profile dummy mode... | Implement the Python class `FMProfileFile` described below.
Class description:
Generate data for Financial Model Profile dummy model Oasis file. This file contains the list of calculation rules with profile values used to generate insurance losses. Attributes: generate_data: Generate Financial Model Profile dummy mode... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class FMProfileFile:
"""Generate data for Financial Model Profile dummy model Oasis file. This file contains the list of calculation rules with profile values used to generate insurance losses. Attributes: generate_data: Generate Financial Model Profile dummy model Oasis file data."""
def __init__... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FMProfileFile:
"""Generate data for Financial Model Profile dummy model Oasis file. This file contains the list of calculation rules with profile values used to generate insurance losses. Attributes: generate_data: Generate Financial Model Profile dummy model Oasis file data."""
def __init__(self, num_la... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
31bb0aba5b272bf1944cb2404923dfe172d0ba40 | [
"self.r = radius\nself.x = x_center\nself.y = y_center",
"theta = random.uniform(0, 2 * pi)\nr = self.r * random.uniform(0, 1) ** 0.5\ny = sin(theta) * r\nx = cos(theta) * r\nreturn [x + self.x, y + self.y]",
"def in_circle(x, y):\n return x ** 2 + y ** 2 <= self.r ** 2\nwhile 1:\n x = random.uniform(-sel... | <|body_start_0|>
self.r = radius
self.x = x_center
self.y = y_center
<|end_body_0|>
<|body_start_1|>
theta = random.uniform(0, 2 * pi)
r = self.r * random.uniform(0, 1) ** 0.5
y = sin(theta) * r
x = cos(theta) * r
return [x + self.x, y + self.y]
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint1(self):
""":rtype: List[float]"""
<|body_1|>
def randPoint(self):
""":rtype: List[float]"""
... | stack_v2_sparse_classes_36k_train_031106 | 1,075 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint1",
"signature": "def randPoint1(self)"
},
{
"docstring":... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint1(self): :rtype: List[float]
- def randPoint(self):... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint1(self): :rtype: List[float]
- def randPoint(self):... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint1(self):
""":rtype: List[float]"""
<|body_1|>
def randPoint(self):
""":rtype: List[float]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.r = radius
self.x = x_center
self.y = y_center
def randPoint1(self):
""":rtype: List[float]"""
theta = random.uniform(0, 2 *... | the_stack_v2_python_sparse | python/leetcode.478.py | CalvinNeo/LeetCode | train | 3 | |
f71fb29799963828121804cc9c7f55e535a96040 | [
"for i in range(1, len(nums)):\n nums[i] += nums[i - 1]\nself.nums = nums",
"if i == 0:\n return self.nums[j]\nreturn self.nums[j] - self.nums[i - 1]"
] | <|body_start_0|>
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
self.nums = nums
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.nums[j]
return self.nums[j] - self.nums[i - 1]
<|end_body_1|>
| NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(1, len(nums)):
nums[i] += nums[i... | stack_v2_sparse_classes_36k_train_031107 | 1,602 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010824 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | c53264340a71305dd6c715b4408b5dec408ef2cc | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
self.nums = nums
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
if i == 0:
return self.nums[j]
... | the_stack_v2_python_sparse | range-sum-query-immutable.py | seattlegirl/leetcode | train | 0 | |
f784e4744c05b9f94cc8f2e29442ffbc198dba39 | [
"users = User.objects.all()\nresponse = UserListSchema().dump({'users': users}).data\nself.write(response)",
"self.verify_user_global_permission(USER_CREATE)\nuser_data = UserCreateSchema().load(self.request_body).data\ncreate_user(**user_data)\nself.set_status(201)"
] | <|body_start_0|>
users = User.objects.all()
response = UserListSchema().dump({'users': users}).data
self.write(response)
<|end_body_0|>
<|body_start_1|>
self.verify_user_global_permission(USER_CREATE)
user_data = UserCreateSchema().load(self.request_body).data
create_use... | UserListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListAPI:
def get(self):
"""--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users"""
<|body_0|>
def post(self):
"""--- summary: Create a new User parameters: ... | stack_v2_sparse_classes_36k_train_031108 | 6,509 | permissive | [
{
"docstring": "--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "--- summary: Create a new User parameters: - name: user... | 2 | stack_v2_sparse_classes_30k_val_000107 | Implement the Python class `UserListAPI` described below.
Class description:
Implement the UserListAPI class.
Method signatures and docstrings:
- def get(self): --- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Use... | Implement the Python class `UserListAPI` described below.
Class description:
Implement the UserListAPI class.
Method signatures and docstrings:
- def get(self): --- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Use... | a5fd2dcc2444409e243d3fdaa43d86695e5cb142 | <|skeleton|>
class UserListAPI:
def get(self):
"""--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users"""
<|body_0|>
def post(self):
"""--- summary: Create a new User parameters: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserListAPI:
def get(self):
"""--- summary: Retrieve all Users responses: 200: description: All Users schema: $ref: '#/definitions/UserList' 50x: $ref: '#/definitions/50xError' tags: - Users"""
users = User.objects.all()
response = UserListSchema().dump({'users': users}).data
s... | the_stack_v2_python_sparse | src/app/beer_garden/api/http/handlers/v1/user.py | beer-garden/beer-garden | train | 254 | |
2e6641b230386bcfed754f469b9959344d4c59d1 | [
"d = list(dominoes)\ni = 0\nwhile i < len(d):\n if d[i] == 'R':\n j = i\n while j < len(d) and d[j] != 'L':\n if d[j] == 'R':\n d[i:j] = ['R'] * (j - i)\n i = j\n j += 1\n if j < len(d):\n d[i:i + (j - i + 1) // 2] = ['R'] * ((j ... | <|body_start_0|>
d = list(dominoes)
i = 0
while i < len(d):
if d[i] == 'R':
j = i
while j < len(d) and d[j] != 'L':
if d[j] == 'R':
d[i:j] = ['R'] * (j - i)
i = j
j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pushDominoes(self, dominoes: str) -> str:
"""09/20/2020 12:39"""
<|body_0|>
def pushDominoes(self, dominoes: str) -> str:
"""Time complexity: O(n) Space complexity: O(n)"""
<|body_1|>
def pushDominoes(self, dominoes: str) -> str:
""... | stack_v2_sparse_classes_36k_train_031109 | 4,450 | no_license | [
{
"docstring": "09/20/2020 12:39",
"name": "pushDominoes",
"signature": "def pushDominoes(self, dominoes: str) -> str"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(n)",
"name": "pushDominoes",
"signature": "def pushDominoes(self, dominoes: str) -> str"
},
{
"docst... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pushDominoes(self, dominoes: str) -> str: 09/20/2020 12:39
- def pushDominoes(self, dominoes: str) -> str: Time complexity: O(n) Space complexity: O(n)
- def pushDominoes(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pushDominoes(self, dominoes: str) -> str: 09/20/2020 12:39
- def pushDominoes(self, dominoes: str) -> str: Time complexity: O(n) Space complexity: O(n)
- def pushDominoes(sel... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def pushDominoes(self, dominoes: str) -> str:
"""09/20/2020 12:39"""
<|body_0|>
def pushDominoes(self, dominoes: str) -> str:
"""Time complexity: O(n) Space complexity: O(n)"""
<|body_1|>
def pushDominoes(self, dominoes: str) -> str:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pushDominoes(self, dominoes: str) -> str:
"""09/20/2020 12:39"""
d = list(dominoes)
i = 0
while i < len(d):
if d[i] == 'R':
j = i
while j < len(d) and d[j] != 'L':
if d[j] == 'R':
... | the_stack_v2_python_sparse | leetcode/solved/868_Push_Dominoes/solution.py | sungminoh/algorithms | train | 0 | |
65d31aa0fed202753d1ad7f1bdf54cfa3b8c3f34 | [
"result = defaultdict(set)\nfor node in self.nodes:\n result[node.block_name].add(node)\nreturn result",
"graph_union = self + other\nversions = graph_union.versions\nconflictive = []\nfor vers in versions.itervalues():\n if len(vers) > 1:\n conflictive.extend(vers)\nresult = BlockVersionGraph()\nfor... | <|body_start_0|>
result = defaultdict(set)
for node in self.nodes:
result[node.block_name].add(node)
return result
<|end_body_0|>
<|body_start_1|>
graph_union = self + other
versions = graph_union.versions
conflictive = []
for vers in versions.iterval... | Graph of dependencies of published things with Nodes=BlockVersions | BlockVersionGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockVersionGraph:
"""Graph of dependencies of published things with Nodes=BlockVersions"""
def versions(self):
"""return all versions for all blocknames in a dictionary"""
<|body_0|>
def collision(self, other):
"""computation of the minimum graph that contains p... | stack_v2_sparse_classes_36k_train_031110 | 1,762 | permissive | [
{
"docstring": "return all versions for all blocknames in a dictionary",
"name": "versions",
"signature": "def versions(self)"
},
{
"docstring": "computation of the minimum graph that contains possible sources of incompatibilities param other: another BlockVersionGraph to compute the intersectio... | 3 | stack_v2_sparse_classes_30k_test_000030 | Implement the Python class `BlockVersionGraph` described below.
Class description:
Graph of dependencies of published things with Nodes=BlockVersions
Method signatures and docstrings:
- def versions(self): return all versions for all blocknames in a dictionary
- def collision(self, other): computation of the minimum ... | Implement the Python class `BlockVersionGraph` described below.
Class description:
Graph of dependencies of published things with Nodes=BlockVersions
Method signatures and docstrings:
- def versions(self): return all versions for all blocknames in a dictionary
- def collision(self, other): computation of the minimum ... | 45e9ca902be7bbbdd73dafe3ab8957bc4a006020 | <|skeleton|>
class BlockVersionGraph:
"""Graph of dependencies of published things with Nodes=BlockVersions"""
def versions(self):
"""return all versions for all blocknames in a dictionary"""
<|body_0|>
def collision(self, other):
"""computation of the minimum graph that contains p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockVersionGraph:
"""Graph of dependencies of published things with Nodes=BlockVersions"""
def versions(self):
"""return all versions for all blocknames in a dictionary"""
result = defaultdict(set)
for node in self.nodes:
result[node.block_name].add(node)
retu... | the_stack_v2_python_sparse | deps/block_version_graph.py | biicode/common | train | 17 |
e7335538c7050766f201666f2ed2f511f48731c8 | [
"tag = self.get_object()\nexporter = exports.ReferenceFlatComplete(queryset=models.Reference.objects.filter(tags=tag).order_by('id'), filename=f'{self.assessment}-{tag.slug}', assessment=self.assessment, tags=self.model.get_all_tags(self.assessment.id, json_encode=False), include_parent_tag=False)\nreturn Response(... | <|body_start_0|>
tag = self.get_object()
exporter = exports.ReferenceFlatComplete(queryset=models.Reference.objects.filter(tags=tag).order_by('id'), filename=f'{self.assessment}-{tag.slug}', assessment=self.assessment, tags=self.model.get_all_tags(self.assessment.id, json_encode=False), include_parent_t... | ReferenceFilterTagViewset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReferenceFilterTagViewset:
def references(self, request, pk):
"""Return all references for a selected tag; does not include tag-descendants."""
<|body_0|>
def references_table_builder(self, request, pk):
"""Return all references for a selected tag in table-builder im... | stack_v2_sparse_classes_36k_train_031111 | 11,341 | permissive | [
{
"docstring": "Return all references for a selected tag; does not include tag-descendants.",
"name": "references",
"signature": "def references(self, request, pk)"
},
{
"docstring": "Return all references for a selected tag in table-builder import format; does not include tag-descendants.",
... | 2 | stack_v2_sparse_classes_30k_train_006008 | Implement the Python class `ReferenceFilterTagViewset` described below.
Class description:
Implement the ReferenceFilterTagViewset class.
Method signatures and docstrings:
- def references(self, request, pk): Return all references for a selected tag; does not include tag-descendants.
- def references_table_builder(se... | Implement the Python class `ReferenceFilterTagViewset` described below.
Class description:
Implement the ReferenceFilterTagViewset class.
Method signatures and docstrings:
- def references(self, request, pk): Return all references for a selected tag; does not include tag-descendants.
- def references_table_builder(se... | 9f053e26efb40f146281944a04d6f2c6bb015253 | <|skeleton|>
class ReferenceFilterTagViewset:
def references(self, request, pk):
"""Return all references for a selected tag; does not include tag-descendants."""
<|body_0|>
def references_table_builder(self, request, pk):
"""Return all references for a selected tag in table-builder im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReferenceFilterTagViewset:
def references(self, request, pk):
"""Return all references for a selected tag; does not include tag-descendants."""
tag = self.get_object()
exporter = exports.ReferenceFlatComplete(queryset=models.Reference.objects.filter(tags=tag).order_by('id'), filename=f... | the_stack_v2_python_sparse | hawc/apps/lit/api.py | TahiriNadia/hawc | train | 0 | |
50ffd45f9ec308ec095f64d039174c1f931aa207 | [
"if hasattr(self, 'action_serializers'):\n if self.action in self.action_serializers:\n return self.action_serializers[self.action]\nreturn super(AppointmentView, self).get_serializer_class()",
"queryset = self.filter_queryset(self.get_queryset())\nif get_boolean_value(request.GET.get('paginate', 'true'... | <|body_start_0|>
if hasattr(self, 'action_serializers'):
if self.action in self.action_serializers:
return self.action_serializers[self.action]
return super(AppointmentView, self).get_serializer_class()
<|end_body_0|>
<|body_start_1|>
queryset = self.filter_queryset(... | Appointment View | AppointmentView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppointmentView:
"""Appointment View"""
def get_serializer_class(self):
"""Retrieve the appropriate serializer for every request method"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List Appointments"""
<|body_1|>
def create(self, reques... | stack_v2_sparse_classes_36k_train_031112 | 3,399 | no_license | [
{
"docstring": "Retrieve the appropriate serializer for every request method",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List Appointments",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_012847 | Implement the Python class `AppointmentView` described below.
Class description:
Appointment View
Method signatures and docstrings:
- def get_serializer_class(self): Retrieve the appropriate serializer for every request method
- def list(self, request, *args, **kwargs): List Appointments
- def create(self, request, *... | Implement the Python class `AppointmentView` described below.
Class description:
Appointment View
Method signatures and docstrings:
- def get_serializer_class(self): Retrieve the appropriate serializer for every request method
- def list(self, request, *args, **kwargs): List Appointments
- def create(self, request, *... | 3a849556e44eb2a12debc9ee2b0b31f5b98905b1 | <|skeleton|>
class AppointmentView:
"""Appointment View"""
def get_serializer_class(self):
"""Retrieve the appropriate serializer for every request method"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List Appointments"""
<|body_1|>
def create(self, reques... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppointmentView:
"""Appointment View"""
def get_serializer_class(self):
"""Retrieve the appropriate serializer for every request method"""
if hasattr(self, 'action_serializers'):
if self.action in self.action_serializers:
return self.action_serializers[self.act... | the_stack_v2_python_sparse | app_appointment/views.py | hachiman144/bookdoc-api | train | 0 |
956409423449cd2e82529109c5daf2568de4e463 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, name, password=password)\nuser.is_staff = True\nuser.save(using=self._db)... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.c... | email 을 id 로 사용하기 위한 custom user manager | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""email 을 id 로 사용하기 위한 custom user manager"""
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_staffuser(self, email, name, password):
"""Creates and sav... | stack_v2_sparse_classes_36k_train_031113 | 3,407 | no_license | [
{
"docstring": "Creates and saves a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a staff user with the given email and password.",
"name": "create_staffuser",
"signat... | 3 | null | Implement the Python class `CustomUserManager` described below.
Class description:
email 을 id 로 사용하기 위한 custom user manager
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email and password.
- def create_staffuser(self, email, name, passw... | Implement the Python class `CustomUserManager` described below.
Class description:
email 을 id 로 사용하기 위한 custom user manager
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email and password.
- def create_staffuser(self, email, name, passw... | b0a4b5d967210715b65f4a9d0e0db895cf92b3c4 | <|skeleton|>
class CustomUserManager:
"""email 을 id 로 사용하기 위한 custom user manager"""
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_staffuser(self, email, name, password):
"""Creates and sav... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
"""email 을 id 로 사용하기 위한 custom user manager"""
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(e... | the_stack_v2_python_sparse | app/accounts/models.py | fshilver/ems | train | 0 |
495a1130e368b06ad22eb3f79b86c4b10c0ff353 | [
"super(SourceManager, self).__init__(name=lambda slf: '%s/%s' % (slf.source.name, slf.source.identHashStr))\nself.source = source\nself.container = container\nif container:\n container.addManager(self)",
"super(SourceManager, self).allRefsDestroyed()\nif self.container:\n self.container.removeManager(self)\... | <|body_start_0|>
super(SourceManager, self).__init__(name=lambda slf: '%s/%s' % (slf.source.name, slf.source.identHashStr))
self.source = source
self.container = container
if container:
container.addManager(self)
<|end_body_0|>
<|body_start_1|>
super(SourceManager, s... | Manages one source. | SourceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceManager:
"""Manages one source."""
def __init__(self, source, container=None):
"""source -> An AwlSource or SymTabSource instance. container -> A SourceContainer instance or None."""
<|body_0|>
def allRefsDestroyed(self):
"""Called, if all source references... | stack_v2_sparse_classes_36k_train_031114 | 6,408 | no_license | [
{
"docstring": "source -> An AwlSource or SymTabSource instance. container -> A SourceContainer instance or None.",
"name": "__init__",
"signature": "def __init__(self, source, container=None)"
},
{
"docstring": "Called, if all source references are destroyed.",
"name": "allRefsDestroyed",
... | 2 | null | Implement the Python class `SourceManager` described below.
Class description:
Manages one source.
Method signatures and docstrings:
- def __init__(self, source, container=None): source -> An AwlSource or SymTabSource instance. container -> A SourceContainer instance or None.
- def allRefsDestroyed(self): Called, if ... | Implement the Python class `SourceManager` described below.
Class description:
Manages one source.
Method signatures and docstrings:
- def __init__(self, source, container=None): source -> An AwlSource or SymTabSource instance. container -> A SourceContainer instance or None.
- def allRefsDestroyed(self): Called, if ... | 7f2c1a9d3a8a0ca8d8ab9a8027c65bc0ff0db64c | <|skeleton|>
class SourceManager:
"""Manages one source."""
def __init__(self, source, container=None):
"""source -> An AwlSource or SymTabSource instance. container -> A SourceContainer instance or None."""
<|body_0|>
def allRefsDestroyed(self):
"""Called, if all source references... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceManager:
"""Manages one source."""
def __init__(self, source, container=None):
"""source -> An AwlSource or SymTabSource instance. container -> A SourceContainer instance or None."""
super(SourceManager, self).__init__(name=lambda slf: '%s/%s' % (slf.source.name, slf.source.identHas... | the_stack_v2_python_sparse | awlsim/common/sources.py | ITI/PLCNet | train | 2 |
d80d7c1e8eb0482fb276350dcd6cf334bcf53f05 | [
"self.logger = Logger.writeLog()\nself.user_email = user_email\nself.passwd = passwd\nself.smtp_server = smtp_server\nself.title = title\nself.addressee = addressee",
"enclosure_data = MIMEMultipart()\nenclosure_data.attach(email_data)\nwith open(file_path, 'rb') as f:\n file_data = MIMEText(f.read(), 'base64'... | <|body_start_0|>
self.logger = Logger.writeLog()
self.user_email = user_email
self.passwd = passwd
self.smtp_server = smtp_server
self.title = title
self.addressee = addressee
<|end_body_0|>
<|body_start_1|>
enclosure_data = MIMEMultipart()
enclosure_data... | EMail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EMail:
def __init__(self, user_email=None, passwd=None, title=None, smtp_server=None, addressee=None):
""":param self.user_email: 发件人邮箱 :param self.passwd: 发件人密码 :param title:标题 :param smtp_server:邮箱服务器 :param addressee:收件人邮箱"""
<|body_0|>
def enclosure(email_data, file_path... | stack_v2_sparse_classes_36k_train_031115 | 4,887 | no_license | [
{
"docstring": ":param self.user_email: 发件人邮箱 :param self.passwd: 发件人密码 :param title:标题 :param smtp_server:邮箱服务器 :param addressee:收件人邮箱",
"name": "__init__",
"signature": "def __init__(self, user_email=None, passwd=None, title=None, smtp_server=None, addressee=None)"
},
{
"docstring": "附件发送 :par... | 4 | stack_v2_sparse_classes_30k_train_008455 | Implement the Python class `EMail` described below.
Class description:
Implement the EMail class.
Method signatures and docstrings:
- def __init__(self, user_email=None, passwd=None, title=None, smtp_server=None, addressee=None): :param self.user_email: 发件人邮箱 :param self.passwd: 发件人密码 :param title:标题 :param smtp_serv... | Implement the Python class `EMail` described below.
Class description:
Implement the EMail class.
Method signatures and docstrings:
- def __init__(self, user_email=None, passwd=None, title=None, smtp_server=None, addressee=None): :param self.user_email: 发件人邮箱 :param self.passwd: 发件人密码 :param title:标题 :param smtp_serv... | 8c7ac74077ae9a807380711c28c6607de6668811 | <|skeleton|>
class EMail:
def __init__(self, user_email=None, passwd=None, title=None, smtp_server=None, addressee=None):
""":param self.user_email: 发件人邮箱 :param self.passwd: 发件人密码 :param title:标题 :param smtp_server:邮箱服务器 :param addressee:收件人邮箱"""
<|body_0|>
def enclosure(email_data, file_path... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EMail:
def __init__(self, user_email=None, passwd=None, title=None, smtp_server=None, addressee=None):
""":param self.user_email: 发件人邮箱 :param self.passwd: 发件人密码 :param title:标题 :param smtp_server:邮箱服务器 :param addressee:收件人邮箱"""
self.logger = Logger.writeLog()
self.user_email = user_em... | the_stack_v2_python_sparse | iutils/EmaliUtils.py | imyangdy/pytest | train | 0 | |
038bd1bc15dbe19c30505a5828df470eceacbaf9 | [
"if not A:\n return 0\nset_A, set_B = (set(), set())\nR, C = (len(A), len(A[0]))\nans = 0\nfor i in range(R):\n for j in range(C):\n if A[i][j] == 1:\n set_A.add((i, j))\n if B[i][j] == 1:\n set_B.add((i, j))\nfor i in range(-R + 1, R):\n for j in range(-C + 1, C):\n ... | <|body_start_0|>
if not A:
return 0
set_A, set_B = (set(), set())
R, C = (len(A), len(A[0]))
ans = 0
for i in range(R):
for j in range(C):
if A[i][j] == 1:
set_A.add((i, j))
if B[i][j] == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestOverlap_trans(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: int"""
<|body_0|>
def largestOverlap_count_delta(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_031116 | 2,249 | no_license | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: int",
"name": "largestOverlap_trans",
"signature": "def largestOverlap_trans(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: int",
"name": "largestOverlap_count_delta",
"si... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestOverlap_trans(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: int
- def largestOverlap_count_delta(self, A, B): :type A: List[List[int]] :type B... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestOverlap_trans(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: int
- def largestOverlap_count_delta(self, A, B): :type A: List[List[int]] :type B... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def largestOverlap_trans(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: int"""
<|body_0|>
def largestOverlap_count_delta(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestOverlap_trans(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: int"""
if not A:
return 0
set_A, set_B = (set(), set())
R, C = (len(A), len(A[0]))
ans = 0
for i in range(R):
for j in range(C):
... | the_stack_v2_python_sparse | medium/arrayandstring/test_835_Image_Overlap.py | wuxu1019/leetcode_sophia | train | 1 | |
bf4f7eb2850aa667fc78ae27efba43e384fe0ea3 | [
"try:\n value.store_diff()\nexcept AttributeError:\n pass\nContainerBase.append(self, value)",
"for config in self:\n try:\n config.pull_base()\n except AttributeError:\n pass",
"for config in self:\n try:\n config.store_diff()\n except AttributeError:\n pass",
"f... | <|body_start_0|>
try:
value.store_diff()
except AttributeError:
pass
ContainerBase.append(self, value)
<|end_body_0|>
<|body_start_1|>
for config in self:
try:
config.pull_base()
except AttributeError:
pass
... | A dict-type container with attribute, item and index style access intended to hold a attribute-accessible list of Data(). This is unordered. Assumptions: N/A Source: N/A | Container | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
"""A dict-type container with attribute, item and index style access intended to hold a attribute-accessible list of Data(). This is unordered. Assumptions: N/A Source: N/A"""
def append(self, value):
"""Appends the value to the containers Assumptions: None Source: N/A Inp... | stack_v2_sparse_classes_36k_train_031117 | 7,117 | no_license | [
{
"docstring": "Appends the value to the containers Assumptions: None Source: N/A Inputs: self Outputs: N/A Properties Used: N/A",
"name": "append",
"signature": "def append(self, value)"
},
{
"docstring": "Updates the differences Assumptions: N/A Source: N/A Inputs: N/A Outputs: N/A Properties ... | 4 | null | Implement the Python class `Container` described below.
Class description:
A dict-type container with attribute, item and index style access intended to hold a attribute-accessible list of Data(). This is unordered. Assumptions: N/A Source: N/A
Method signatures and docstrings:
- def append(self, value): Appends the ... | Implement the Python class `Container` described below.
Class description:
A dict-type container with attribute, item and index style access intended to hold a attribute-accessible list of Data(). This is unordered. Assumptions: N/A Source: N/A
Method signatures and docstrings:
- def append(self, value): Appends the ... | 0ef6f56a373cedc0cfb2ba30e6f6901da6cbe861 | <|skeleton|>
class Container:
"""A dict-type container with attribute, item and index style access intended to hold a attribute-accessible list of Data(). This is unordered. Assumptions: N/A Source: N/A"""
def append(self, value):
"""Appends the value to the containers Assumptions: None Source: N/A Inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Container:
"""A dict-type container with attribute, item and index style access intended to hold a attribute-accessible list of Data(). This is unordered. Assumptions: N/A Source: N/A"""
def append(self, value):
"""Appends the value to the containers Assumptions: None Source: N/A Inputs: self Out... | the_stack_v2_python_sparse | A22DSE/Models/SUAVE/SUAVE/Core/Diffed_Data.py | dsegroup22/A22CERES | train | 1 |
27ad550673add818c5c6b6dc3c6c66c77669957a | [
"if hasattr(self, '_ellipse_width'):\n return\nself._ellipse_width = Int(0)",
"from apysc.type import value_util\nself._initialize_ellipse_width_if_not_initialized()\nreturn value_util.get_copy(value=self._ellipse_width)",
"from apysc.validation import number_validation\nnumber_validation.validate_integer(in... | <|body_start_0|>
if hasattr(self, '_ellipse_width'):
return
self._ellipse_width = Int(0)
<|end_body_0|>
<|body_start_1|>
from apysc.type import value_util
self._initialize_ellipse_width_if_not_initialized()
return value_util.get_copy(value=self._ellipse_width)
<|end_... | EllipseWidthInterface | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EllipseWidthInterface:
def _initialize_ellipse_width_if_not_initialized(self) -> None:
"""Initialize _ellipse_width attribute if it is not initialized yet."""
<|body_0|>
def ellipse_width(self) -> Int:
"""Get ellipse width value. Returns ------- ellipse_width : Int E... | stack_v2_sparse_classes_36k_train_031118 | 3,581 | permissive | [
{
"docstring": "Initialize _ellipse_width attribute if it is not initialized yet.",
"name": "_initialize_ellipse_width_if_not_initialized",
"signature": "def _initialize_ellipse_width_if_not_initialized(self) -> None"
},
{
"docstring": "Get ellipse width value. Returns ------- ellipse_width : In... | 6 | null | Implement the Python class `EllipseWidthInterface` described below.
Class description:
Implement the EllipseWidthInterface class.
Method signatures and docstrings:
- def _initialize_ellipse_width_if_not_initialized(self) -> None: Initialize _ellipse_width attribute if it is not initialized yet.
- def ellipse_width(se... | Implement the Python class `EllipseWidthInterface` described below.
Class description:
Implement the EllipseWidthInterface class.
Method signatures and docstrings:
- def _initialize_ellipse_width_if_not_initialized(self) -> None: Initialize _ellipse_width attribute if it is not initialized yet.
- def ellipse_width(se... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class EllipseWidthInterface:
def _initialize_ellipse_width_if_not_initialized(self) -> None:
"""Initialize _ellipse_width attribute if it is not initialized yet."""
<|body_0|>
def ellipse_width(self) -> Int:
"""Get ellipse width value. Returns ------- ellipse_width : Int E... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EllipseWidthInterface:
def _initialize_ellipse_width_if_not_initialized(self) -> None:
"""Initialize _ellipse_width attribute if it is not initialized yet."""
if hasattr(self, '_ellipse_width'):
return
self._ellipse_width = Int(0)
def ellipse_width(self) -> Int:
... | the_stack_v2_python_sparse | apysc/display/ellipse_width_interface.py | TrendingTechnology/apysc | train | 0 | |
523791cbfd7c9899a178c6a9723bc2b70108192d | [
"self.activity = activity\nself.count = 0\nself.n_total = n_total\nself.report_every = report_every\nself.loglevel = loglevel",
"self.count += 1\nc = self.count\nn = self.n_total\nif c == 1 or c % self.report_every == 0 or c == n:\n if self.n_total is not None:\n of_n = f' of {n}'\n else:\n of... | <|body_start_0|>
self.activity = activity
self.count = 0
self.n_total = n_total
self.report_every = report_every
self.loglevel = loglevel
<|end_body_0|>
<|body_start_1|>
self.count += 1
c = self.count
n = self.n_total
if c == 1 or c % self.report_... | Simple class to report progress in a repetitive activity. | ActivityCounter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivityCounter:
"""Simple class to report progress in a repetitive activity."""
def __init__(self, activity: str, n_total: int=None, report_every: int=1000, loglevel: int=logging.DEBUG) -> None:
"""Args: activity: Description of the repetitive activity being performed. n_total: If k... | stack_v2_sparse_classes_36k_train_031119 | 2,422 | permissive | [
{
"docstring": "Args: activity: Description of the repetitive activity being performed. n_total: If known, the total number of iterations required. report_every: Report progress every n operations. loglevel: Log level to use.",
"name": "__init__",
"signature": "def __init__(self, activity: str, n_total:... | 2 | stack_v2_sparse_classes_30k_train_004709 | Implement the Python class `ActivityCounter` described below.
Class description:
Simple class to report progress in a repetitive activity.
Method signatures and docstrings:
- def __init__(self, activity: str, n_total: int=None, report_every: int=1000, loglevel: int=logging.DEBUG) -> None: Args: activity: Description ... | Implement the Python class `ActivityCounter` described below.
Class description:
Simple class to report progress in a repetitive activity.
Method signatures and docstrings:
- def __init__(self, activity: str, n_total: int=None, report_every: int=1000, loglevel: int=logging.DEBUG) -> None: Args: activity: Description ... | 86ec00e039a85b90609c8fe4b221d183912eaec4 | <|skeleton|>
class ActivityCounter:
"""Simple class to report progress in a repetitive activity."""
def __init__(self, activity: str, n_total: int=None, report_every: int=1000, loglevel: int=logging.DEBUG) -> None:
"""Args: activity: Description of the repetitive activity being performed. n_total: If k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivityCounter:
"""Simple class to report progress in a repetitive activity."""
def __init__(self, activity: str, n_total: int=None, report_every: int=1000, loglevel: int=logging.DEBUG) -> None:
"""Args: activity: Description of the repetitive activity being performed. n_total: If known, the tot... | the_stack_v2_python_sparse | cardinal_pythonlib/progress.py | RudolfCardinal/pythonlib | train | 12 |
c0815c5845ff883998cae1e460c6a74b45b6c1cc | [
"clf = svm.SVC(gamma='scale')\nclf.fit(train_set, train_label)\nreturn clf",
"test_predict = model.predict(test_set)\nscore = np.where(test_predict == test_label)[0].shape[0] / test_label.shape[0]\nself.logger.info('Test set score: %.2f' % score)"
] | <|body_start_0|>
clf = svm.SVC(gamma='scale')
clf.fit(train_set, train_label)
return clf
<|end_body_0|>
<|body_start_1|>
test_predict = model.predict(test_set)
score = np.where(test_predict == test_label)[0].shape[0] / test_label.shape[0]
self.logger.info('Test set score... | SVMModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVMModel:
def train(self, train_set: pd.DataFrame, train_label: pd.Series, args):
"""Train with logistic regression model :param train_set pd.DataFrame The vectorized training dataset :param train_label pd.Series The training set label :return SVM model"""
<|body_0|>
def tes... | stack_v2_sparse_classes_36k_train_031120 | 1,517 | no_license | [
{
"docstring": "Train with logistic regression model :param train_set pd.DataFrame The vectorized training dataset :param train_label pd.Series The training set label :return SVM model",
"name": "train",
"signature": "def train(self, train_set: pd.DataFrame, train_label: pd.Series, args)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_007333 | Implement the Python class `SVMModel` described below.
Class description:
Implement the SVMModel class.
Method signatures and docstrings:
- def train(self, train_set: pd.DataFrame, train_label: pd.Series, args): Train with logistic regression model :param train_set pd.DataFrame The vectorized training dataset :param ... | Implement the Python class `SVMModel` described below.
Class description:
Implement the SVMModel class.
Method signatures and docstrings:
- def train(self, train_set: pd.DataFrame, train_label: pd.Series, args): Train with logistic regression model :param train_set pd.DataFrame The vectorized training dataset :param ... | c077f61f6aec451b877daf41a4478d5f77a36698 | <|skeleton|>
class SVMModel:
def train(self, train_set: pd.DataFrame, train_label: pd.Series, args):
"""Train with logistic regression model :param train_set pd.DataFrame The vectorized training dataset :param train_label pd.Series The training set label :return SVM model"""
<|body_0|>
def tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVMModel:
def train(self, train_set: pd.DataFrame, train_label: pd.Series, args):
"""Train with logistic regression model :param train_set pd.DataFrame The vectorized training dataset :param train_label pd.Series The training set label :return SVM model"""
clf = svm.SVC(gamma='scale')
... | the_stack_v2_python_sparse | project/article_plagiarism/train_svm.py | enix223/nlp-course | train | 8 | |
a340863823656cb2e5664bb73bb0fedcdefa7cdd | [
"n = len(nums)\nones = 0\ntwos = 0\nfor t in nums:\n if t == 1:\n ones += 1\n elif t == 2:\n twos += 1\nnums[:] = [0] * (n - ones - twos) + [1] * ones + [2] * twos",
"n = len(nums)\nzero_ptr = 0\nfor i in range(n):\n if nums[i] == 0:\n t = nums[zero_ptr]\n nums[zero_ptr] = num... | <|body_start_0|>
n = len(nums)
ones = 0
twos = 0
for t in nums:
if t == 1:
ones += 1
elif t == 2:
twos += 1
nums[:] = [0] * (n - ones - twos) + [1] * ones + [2] * twos
<|end_body_0|>
<|body_start_1|>
n = len(nums)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums: [int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors(self, nums: [int]) -> None:
"""O(n) O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
... | stack_v2_sparse_classes_36k_train_031121 | 1,169 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums: [int]) -> None"
},
{
"docstring": "O(n) O(1)",
"name": "sortColors",
"signature": "def sortColors(self, nums: [int]) -> None"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: [int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors(self, nums: [int]) -> None: O(n) O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: [int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors(self, nums: [int]) -> None: O(n) O(1)
<|skeleton|>
class Soluti... | 26a467dfe8acd8ae4be0cd2784d79eebf09c06ce | <|skeleton|>
class Solution:
def sortColors(self, nums: [int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors(self, nums: [int]) -> None:
"""O(n) O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums: [int]) -> None:
"""Do not return anything, modify nums in-place instead."""
n = len(nums)
ones = 0
twos = 0
for t in nums:
if t == 1:
ones += 1
elif t == 2:
twos += 1
nu... | the_stack_v2_python_sparse | FuckLeetcode/75. 颜色分类.py | Alex-Beng/ojs | train | 0 | |
6371c480a582a25d00d420323b00f120d925f1bc | [
"try:\n if name is None or size is None:\n raise Exception('Cannot create logical volume without specified name and size')\n if uuid_str is None:\n uuid_str = str(uuid.uuid4())\n data = {'name': name, 'uuid': uuid_str, 'size': size}\n self.logger.debug('Creating logical volume %s in VG %s ... | <|body_start_0|>
try:
if name is None or size is None:
raise Exception('Cannot create logical volume without specified name and size')
if uuid_str is None:
uuid_str = str(uuid.uuid4())
data = {'name': name, 'uuid': uuid_str, 'size': size}
... | VolumeGroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeGroup:
def create_lv(self, name=None, uuid_str=None, size=None):
"""Create a logical volume in this volume group. :param name: Name of the logical volume :param uuid_str: A UUID4-format string specifying the LV uuid. Will be generated if left as None :param size: The size of the lo... | stack_v2_sparse_classes_36k_train_031122 | 5,626 | permissive | [
{
"docstring": "Create a logical volume in this volume group. :param name: Name of the logical volume :param uuid_str: A UUID4-format string specifying the LV uuid. Will be generated if left as None :param size: The size of the logical volume",
"name": "create_lv",
"signature": "def create_lv(self, name... | 4 | stack_v2_sparse_classes_30k_train_007592 | Implement the Python class `VolumeGroup` described below.
Class description:
Implement the VolumeGroup class.
Method signatures and docstrings:
- def create_lv(self, name=None, uuid_str=None, size=None): Create a logical volume in this volume group. :param name: Name of the logical volume :param uuid_str: A UUID4-for... | Implement the Python class `VolumeGroup` described below.
Class description:
Implement the VolumeGroup class.
Method signatures and docstrings:
- def create_lv(self, name=None, uuid_str=None, size=None): Create a logical volume in this volume group. :param name: Name of the logical volume :param uuid_str: A UUID4-for... | f99abfa4337f8cbb591513aac404b11208d4187c | <|skeleton|>
class VolumeGroup:
def create_lv(self, name=None, uuid_str=None, size=None):
"""Create a logical volume in this volume group. :param name: Name of the logical volume :param uuid_str: A UUID4-format string specifying the LV uuid. Will be generated if left as None :param size: The size of the lo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeGroup:
def create_lv(self, name=None, uuid_str=None, size=None):
"""Create a logical volume in this volume group. :param name: Name of the logical volume :param uuid_str: A UUID4-format string specifying the LV uuid. Will be generated if left as None :param size: The size of the logical volume""... | the_stack_v2_python_sparse | python/drydock_provisioner/drivers/node/maasdriver/models/volumegroup.py | airshipit/drydock | train | 13 | |
4e78b3a554dae0c1a360343783e23e8a7e5cad8e | [
"my_logger.info('create resource')\njsondata = resource.service_template.model\nmy_logger.debug('parse json & get yaml file!!! {}'.format(jsondata))\nuuid = resource.service_template.tracking.tracking_id\nresource_type = resource.service_template.resource.resource_type\nbase_url = pecan.request.application_url\njso... | <|body_start_0|>
my_logger.info('create resource')
jsondata = resource.service_template.model
my_logger.debug('parse json & get yaml file!!! {}'.format(jsondata))
uuid = resource.service_template.tracking.tracking_id
resource_type = resource.service_template.resource.resource_typ... | creatin new resource controller. | CreateNewResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateNewResource:
"""creatin new resource controller."""
def post(self, resource):
"""Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will b... | stack_v2_sparse_classes_36k_train_031123 | 10,382 | no_license | [
{
"docstring": "Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will be 201 created if success :return 409 for conflict :return 400 bad request handle json input",
"... | 3 | stack_v2_sparse_classes_30k_train_015418 | Implement the Python class `CreateNewResource` described below.
Class description:
creatin new resource controller.
Method signatures and docstrings:
- def post(self, resource): Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'ho... | Implement the Python class `CreateNewResource` described below.
Class description:
creatin new resource controller.
Method signatures and docstrings:
- def post(self, resource): Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'ho... | 3ea2dcb191d8e41498fe062a79349c9d055224c6 | <|skeleton|>
class CreateNewResource:
"""creatin new resource controller."""
def post(self, resource):
"""Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateNewResource:
"""creatin new resource controller."""
def post(self, resource):
"""Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will be 201 created... | the_stack_v2_python_sparse | orm/services/resource_distributor/rds/controllers/v1/resources/root.py | jq1581/ranger | train | 0 |
3aa4f68b7e6612bd01be9e40e467f0881b1f2583 | [
"super().__init__()\nself.temperature = temperature\nself.loss_weight = loss_weight\naccept_reduction = {'none', 'batchmean', 'sum', 'mean'}\nassert reduction in accept_reduction, f'KLDivergence supports reduction {accept_reduction}, but gets {reduction}.'\nself.reduction = reduction",
"softmax_pred_teacher = F.s... | <|body_start_0|>
super().__init__()
self.temperature = temperature
self.loss_weight = loss_weight
accept_reduction = {'none', 'batchmean', 'sum', 'mean'}
assert reduction in accept_reduction, f'KLDivergence supports reduction {accept_reduction}, but gets {reduction}.'
sel... | A measure of how one probability distribution Q is different from a second, reference probability distribution P. | KLDivergence | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KLDivergence:
"""A measure of how one probability distribution Q is different from a second, reference probability distribution P."""
def __init__(self, temperature=1.0, reduction='batchmean', loss_weight=1.0):
"""Args: temperature (float): Temperature coefficient. Defaults to 1.0. r... | stack_v2_sparse_classes_36k_train_031124 | 2,307 | permissive | [
{
"docstring": "Args: temperature (float): Temperature coefficient. Defaults to 1.0. reduction (str): Specifies the reduction to apply to the loss: none | batchmean | sum | mean none: no reduction will be applied batchmean: the sum of the output will be divided by the batchsize, sum: the output will be summed, ... | 2 | stack_v2_sparse_classes_30k_train_015250 | Implement the Python class `KLDivergence` described below.
Class description:
A measure of how one probability distribution Q is different from a second, reference probability distribution P.
Method signatures and docstrings:
- def __init__(self, temperature=1.0, reduction='batchmean', loss_weight=1.0): Args: tempera... | Implement the Python class `KLDivergence` described below.
Class description:
A measure of how one probability distribution Q is different from a second, reference probability distribution P.
Method signatures and docstrings:
- def __init__(self, temperature=1.0, reduction='batchmean', loss_weight=1.0): Args: tempera... | 10ab045fbd83066533a7c86390485d3c1c3fa210 | <|skeleton|>
class KLDivergence:
"""A measure of how one probability distribution Q is different from a second, reference probability distribution P."""
def __init__(self, temperature=1.0, reduction='batchmean', loss_weight=1.0):
"""Args: temperature (float): Temperature coefficient. Defaults to 1.0. r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KLDivergence:
"""A measure of how one probability distribution Q is different from a second, reference probability distribution P."""
def __init__(self, temperature=1.0, reduction='batchmean', loss_weight=1.0):
"""Args: temperature (float): Temperature coefficient. Defaults to 1.0. reduction (str... | the_stack_v2_python_sparse | src/model_optimizer/losses/kl_divergence.py | Adlik/model_optimizer | train | 35 |
cb62da01fc1993999dc0411b397616e3e8bda532 | [
"ret = 0\nold = -100001\ntop = len(candies) / 2\ncandies.sort()\nfor candy in candies:\n if candy == old:\n continue\n else:\n ret += 1\n old = candy\n if ret == top:\n return ret\nreturn ret",
"ret = 0\nhad = set()\ntop = len(candies) / 2\nfor candy in candies:\n i... | <|body_start_0|>
ret = 0
old = -100001
top = len(candies) / 2
candies.sort()
for candy in candies:
if candy == old:
continue
else:
ret += 1
old = candy
if ret == top:
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def distributeCandies1(self, candies):
""":type candies: List[int] :rtype: int"""
<|body_0|>
def distributeCandies2(self, candies):
""":type candies: List[int] :rtype: int"""
<|body_1|>
def distributeCandies(self, candies):
""":type can... | stack_v2_sparse_classes_36k_train_031125 | 1,541 | no_license | [
{
"docstring": ":type candies: List[int] :rtype: int",
"name": "distributeCandies1",
"signature": "def distributeCandies1(self, candies)"
},
{
"docstring": ":type candies: List[int] :rtype: int",
"name": "distributeCandies2",
"signature": "def distributeCandies2(self, candies)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distributeCandies1(self, candies): :type candies: List[int] :rtype: int
- def distributeCandies2(self, candies): :type candies: List[int] :rtype: int
- def distributeCandies(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distributeCandies1(self, candies): :type candies: List[int] :rtype: int
- def distributeCandies2(self, candies): :type candies: List[int] :rtype: int
- def distributeCandies(... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def distributeCandies1(self, candies):
""":type candies: List[int] :rtype: int"""
<|body_0|>
def distributeCandies2(self, candies):
""":type candies: List[int] :rtype: int"""
<|body_1|>
def distributeCandies(self, candies):
""":type can... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def distributeCandies1(self, candies):
""":type candies: List[int] :rtype: int"""
ret = 0
old = -100001
top = len(candies) / 2
candies.sort()
for candy in candies:
if candy == old:
continue
else:
... | the_stack_v2_python_sparse | python/leetcode/575_Distribute_Candies.py | bobcaoge/my-code | train | 0 | |
94ad5d8a58263a018c0166cc84be1875cf7427b4 | [
"if not root:\n return 0\nleft = self.minDepth(root.left)\nright = self.minDepth(root.right)\nif left and right:\n return min(left, right) + 1\nreturn max(left, right) + 1",
"if not root:\n return 0\nqueue = collections.deque([(root, 1)])\nwhile queue:\n node, step = queue.popleft()\n if not node.l... | <|body_start_0|>
if not root:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if left and right:
return min(left, right) + 1
return max(left, right) + 1
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDepth2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
left = sel... | stack_v2_sparse_classes_36k_train_031126 | 1,526 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth",
"signature": "def minDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth2",
"signature": "def minDepth2(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 minDepth2(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 minDepth2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def minDepth(self, roo... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDepth2(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
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if left and right:
return min(left, right) + 1
return max(left, right) + 1
... | the_stack_v2_python_sparse | python/111_Minimum_Depth_of_Binary_Tree.py | Moby5/myleetcode | train | 2 | |
c9e450278fa58eb84d97e5454eca9102d8042937 | [
"if t1 is None and t2 is None:\n return\nif t1 is None:\n return t2\nif t2 is None:\n return t1\nt1.val += t2.val\nt1.right = self.mergeTrees(t1.right, t2.right)\nt1.left = self.mergeTrees(t1.left, t2.left)\nreturn t1",
"if t1 and t2:\n root = TreeNode(t1.val + t2.val)\n root.left = self.mergeTrees... | <|body_start_0|>
if t1 is None and t2 is None:
return
if t1 is None:
return t2
if t2 is None:
return t1
t1.val += t2.val
t1.right = self.mergeTrees(t1.right, t2.right)
t1.left = self.mergeTrees(t1.left, t2.left)
return t1
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTrees(self, t1, t2):
""":param t1: :param t2: :return:"""
<|body_0|>
def mergeTrees_02(self, t1, t2):
""":param t1: :param t2: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if t1 is None and t2 is None:
retu... | stack_v2_sparse_classes_36k_train_031127 | 1,304 | no_license | [
{
"docstring": ":param t1: :param t2: :return:",
"name": "mergeTrees",
"signature": "def mergeTrees(self, t1, t2)"
},
{
"docstring": ":param t1: :param t2: :return:",
"name": "mergeTrees_02",
"signature": "def mergeTrees_02(self, t1, t2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, t1, t2): :param t1: :param t2: :return:
- def mergeTrees_02(self, t1, t2): :param t1: :param t2: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTrees(self, t1, t2): :param t1: :param t2: :return:
- def mergeTrees_02(self, t1, t2): :param t1: :param t2: :return:
<|skeleton|>
class Solution:
def mergeTrees(s... | 7f89c28917c9949fd4f19d3fbbb282abeec2f427 | <|skeleton|>
class Solution:
def mergeTrees(self, t1, t2):
""":param t1: :param t2: :return:"""
<|body_0|>
def mergeTrees_02(self, t1, t2):
""":param t1: :param t2: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTrees(self, t1, t2):
""":param t1: :param t2: :return:"""
if t1 is None and t2 is None:
return
if t1 is None:
return t2
if t2 is None:
return t1
t1.val += t2.val
t1.right = self.mergeTrees(t1.right, t2.right... | the_stack_v2_python_sparse | Tree/10_merge_two_binary_trees.py | xiaoguangjj/leetcode | train | 2 | |
aa0e47b2db689ce6f2281c885025a77e7a99fa39 | [
"sec = False\nkey = '%s_%s_%s' % (SERVER_NAME, LOCK_WAIT, pm)\nif value is None:\n value = time.time() * 1000\nvalue = str(value)\nwhile True:\n keys = redis_client.keys('%s_trade_%s*' % (SERVER_NAME, pm))\n if trade == False:\n if len(keys) > 0 and wait == False:\n break\n elif le... | <|body_start_0|>
sec = False
key = '%s_%s_%s' % (SERVER_NAME, LOCK_WAIT, pm)
if value is None:
value = time.time() * 1000
value = str(value)
while True:
keys = redis_client.keys('%s_trade_%s*' % (SERVER_NAME, pm))
if trade == False:
... | 平台锁 | LockWait | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockWait:
"""平台锁"""
def add_lock(self, pm, value=None, timeout=None, wait=True, trade=False):
"""lock.wait改为redis锁 params timeout 超时时间,毫秒 return sec, value"""
<|body_0|>
def remove_lock(self, pm, value):
"""删除lock.wait"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_031128 | 3,929 | no_license | [
{
"docstring": "lock.wait改为redis锁 params timeout 超时时间,毫秒 return sec, value",
"name": "add_lock",
"signature": "def add_lock(self, pm, value=None, timeout=None, wait=True, trade=False)"
},
{
"docstring": "删除lock.wait",
"name": "remove_lock",
"signature": "def remove_lock(self, pm, value)"... | 2 | stack_v2_sparse_classes_30k_val_000739 | Implement the Python class `LockWait` described below.
Class description:
平台锁
Method signatures and docstrings:
- def add_lock(self, pm, value=None, timeout=None, wait=True, trade=False): lock.wait改为redis锁 params timeout 超时时间,毫秒 return sec, value
- def remove_lock(self, pm, value): 删除lock.wait | Implement the Python class `LockWait` described below.
Class description:
平台锁
Method signatures and docstrings:
- def add_lock(self, pm, value=None, timeout=None, wait=True, trade=False): lock.wait改为redis锁 params timeout 超时时间,毫秒 return sec, value
- def remove_lock(self, pm, value): 删除lock.wait
<|skeleton|>
class Loc... | 933327852b63b10e7d4254f5708739673bdf750d | <|skeleton|>
class LockWait:
"""平台锁"""
def add_lock(self, pm, value=None, timeout=None, wait=True, trade=False):
"""lock.wait改为redis锁 params timeout 超时时间,毫秒 return sec, value"""
<|body_0|>
def remove_lock(self, pm, value):
"""删除lock.wait"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LockWait:
"""平台锁"""
def add_lock(self, pm, value=None, timeout=None, wait=True, trade=False):
"""lock.wait改为redis锁 params timeout 超时时间,毫秒 return sec, value"""
sec = False
key = '%s_%s_%s' % (SERVER_NAME, LOCK_WAIT, pm)
if value is None:
value = time.time() * 10... | the_stack_v2_python_sparse | publib/locker.py | sunlewei-nuanguang/offlinedata_process | train | 0 |
4dc63b922656a2fb05122b7c64420738e435b6ee | [
"if not matrix:\n return\nm, n = (len(matrix), len(matrix[0]))\ndp = [[0 for _ in xrange(n)] for _ in xrange(m)]\nfor i in xrange(m):\n for j in xrange(n):\n dp[i][j] = matrix[i][j]\n if i > 0:\n dp[i][j] += dp[i - 1][j]\n if j > 0:\n dp[i][j] += dp[i][j - 1]\n ... | <|body_start_0|>
if not matrix:
return
m, n = (len(matrix), len(matrix[0]))
dp = [[0 for _ in xrange(n)] for _ in xrange(m)]
for i in xrange(m):
for j in xrange(n):
dp[i][j] = matrix[i][j]
if i > 0:
dp[i][j] += d... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k_train_031129 | 1,325 | no_license | [
{
"docstring": "initialize your data structure here. :type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtyp... | 2 | stack_v2_sparse_classes_30k_train_010170 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here. :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): sum of elements matrix[(row1,col1)... | 0f45a05d258d7dced844c657da2362d87bee15a8 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
"""initialize your data structure here. :type matrix: List[List[int]]"""
if not matrix:
return
m, n = (len(matrix), len(matrix[0]))
dp = [[0 for _ in xrange(n)] for _ in xrange(m)]
for i in xrange(m):
for j ... | the_stack_v2_python_sparse | 304-Range-Sum-Query-2D---Immutable/solution.py | zmxrice/leetcodetraining | train | 0 | |
687341131ab5ad62d11898a65a9c9362f4160ad3 | [
"if not isfile(local_file_name):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc=local_file_name + 'Dataset') as pbar:\n urlretrieve(url, local_file_name, pbar.hook)\nelse:\n logger.info('Resusing the file: {}'.format(local_file_name))\nreturn local_file_name",
"extracted_folder_name = ... | <|body_start_0|>
if not isfile(local_file_name):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc=local_file_name + 'Dataset') as pbar:
urlretrieve(url, local_file_name, pbar.hook)
else:
logger.info('Resusing the file: {}'.format(local_file_name))
... | Class to download data sets form the web. | Downloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Downloader:
"""Class to download data sets form the web."""
def get(url: str, local_file_name: str):
""":param url: URL of the file to be downloaded :param local_file_name: File path where to be locally to be stored :return:"""
<|body_0|>
def extract_tar(file_name: str, ... | stack_v2_sparse_classes_36k_train_031130 | 1,702 | no_license | [
{
"docstring": ":param url: URL of the file to be downloaded :param local_file_name: File path where to be locally to be stored :return:",
"name": "get",
"signature": "def get(url: str, local_file_name: str)"
},
{
"docstring": "Extracts the file contents :param file_name: Tar file path :return:"... | 2 | stack_v2_sparse_classes_30k_train_014928 | Implement the Python class `Downloader` described below.
Class description:
Class to download data sets form the web.
Method signatures and docstrings:
- def get(url: str, local_file_name: str): :param url: URL of the file to be downloaded :param local_file_name: File path where to be locally to be stored :return:
- ... | Implement the Python class `Downloader` described below.
Class description:
Class to download data sets form the web.
Method signatures and docstrings:
- def get(url: str, local_file_name: str): :param url: URL of the file to be downloaded :param local_file_name: File path where to be locally to be stored :return:
- ... | 37927094c279e5c8a95d845c379fcebb409cfdff | <|skeleton|>
class Downloader:
"""Class to download data sets form the web."""
def get(url: str, local_file_name: str):
""":param url: URL of the file to be downloaded :param local_file_name: File path where to be locally to be stored :return:"""
<|body_0|>
def extract_tar(file_name: str, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Downloader:
"""Class to download data sets form the web."""
def get(url: str, local_file_name: str):
""":param url: URL of the file to be downloaded :param local_file_name: File path where to be locally to be stored :return:"""
if not isfile(local_file_name):
with DLProgress(u... | the_stack_v2_python_sparse | dhira/data/download/downloader.py | Mageswaran1989/dhira | train | 4 |
bb0a0edc82b3387f1d7c7aac57e8e127f676dc9e | [
"global tensorflow\nimport tensorflow\ntensorflow.random.set_seed(base.random_state_.random())\nself.model_class = tensorflow.keras.Model\nself.optim_class = tensorflow.keras.optimizers.Optimizer\nsuper(TensorflowEngine, self).__init__(base, X, Y, A)",
"Y_pred = self.predictor_model(X, training=False)\nY_pred = Y... | <|body_start_0|>
global tensorflow
import tensorflow
tensorflow.random.set_seed(base.random_state_.random())
self.model_class = tensorflow.keras.Model
self.optim_class = tensorflow.keras.optimizers.Optimizer
super(TensorflowEngine, self).__init__(base, X, Y, A)
<|end_body... | Adds TensorFlow specific functions. | TensorflowEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorflowEngine:
"""Adds TensorFlow specific functions."""
def __init__(self, base, X, Y, A):
"""Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!"... | stack_v2_sparse_classes_36k_train_031131 | 6,175 | permissive | [
{
"docstring": "Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!",
"name": "__init__",
"signature": "def __init__(self, base, X, Y, A)"
},
{
"docstring": "Eval... | 6 | stack_v2_sparse_classes_30k_train_003187 | Implement the Python class `TensorflowEngine` described below.
Class description:
Adds TensorFlow specific functions.
Method signatures and docstrings:
- def __init__(self, base, X, Y, A): Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, b... | Implement the Python class `TensorflowEngine` described below.
Class description:
Adds TensorFlow specific functions.
Method signatures and docstrings:
- def __init__(self, base, X, Y, A): Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, b... | bc75fc8ad1a98125c73bdc24a4d934b2f930c249 | <|skeleton|>
class TensorflowEngine:
"""Adds TensorFlow specific functions."""
def __init__(self, base, X, Y, A):
"""Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TensorflowEngine:
"""Adds TensorFlow specific functions."""
def __init__(self, base, X, Y, A):
"""Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!"""
gl... | the_stack_v2_python_sparse | fairlearn/adversarial/_tensorflow_engine.py | fairlearn/fairlearn | train | 1,551 |
378a3aaae839bda08b62e2fb54670a15e2b8b8c6 | [
"if not hasattr(settings, 'MEDIA_DIRS'):\n return\nfor dir in settings.MEDIA_DIRS:\n t = os.path.join(settings.MEDIA_ROOT, dir)\n if not os.path.isdir(t):\n os.makedirs(t)",
"from apps.post.models import Category\nfrom apps.other.models import FeedbackCategory\nfrom apps.user.models import User\nU... | <|body_start_0|>
if not hasattr(settings, 'MEDIA_DIRS'):
return
for dir in settings.MEDIA_DIRS:
t = os.path.join(settings.MEDIA_ROOT, dir)
if not os.path.isdir(t):
os.makedirs(t)
<|end_body_0|>
<|body_start_1|>
from apps.post.models import Cat... | InitServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitServer:
def create_default_media_dir(self):
"""创建默认media目录 :return:"""
<|body_0|>
def init(self):
"""初始化服务准备工作 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not hasattr(settings, 'MEDIA_DIRS'):
return
for dir in... | stack_v2_sparse_classes_36k_train_031132 | 1,258 | no_license | [
{
"docstring": "创建默认media目录 :return:",
"name": "create_default_media_dir",
"signature": "def create_default_media_dir(self)"
},
{
"docstring": "初始化服务准备工作 :return:",
"name": "init",
"signature": "def init(self)"
}
] | 2 | null | Implement the Python class `InitServer` described below.
Class description:
Implement the InitServer class.
Method signatures and docstrings:
- def create_default_media_dir(self): 创建默认media目录 :return:
- def init(self): 初始化服务准备工作 :return: | Implement the Python class `InitServer` described below.
Class description:
Implement the InitServer class.
Method signatures and docstrings:
- def create_default_media_dir(self): 创建默认media目录 :return:
- def init(self): 初始化服务准备工作 :return:
<|skeleton|>
class InitServer:
def create_default_media_dir(self):
... | 4d6eda7c6358571d6680a1f2a2949ee3ac4220e7 | <|skeleton|>
class InitServer:
def create_default_media_dir(self):
"""创建默认media目录 :return:"""
<|body_0|>
def init(self):
"""初始化服务准备工作 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitServer:
def create_default_media_dir(self):
"""创建默认media目录 :return:"""
if not hasattr(settings, 'MEDIA_DIRS'):
return
for dir in settings.MEDIA_DIRS:
t = os.path.join(settings.MEDIA_ROOT, dir)
if not os.path.isdir(t):
os.makedirs(... | the_stack_v2_python_sparse | sheep/sheep/init_server.py | L-BraveDog/sheep | train | 0 | |
494967e79f0a9fa3e6333dfe2d57f191ece3b6e5 | [
"AxisFormat.__init__(self, 'clustersnew')\nself._axes['energy'] = 0\nself._axes['eta'] = 1\nself._axes['phi'] = 2\nself._axes['vertexz'] = 3\nself._axes['mbtrigger'] = 4",
"newobj = AxisFormatClustersNew()\nnewobj._Deepcopy(self, memo)\nreturn newobj",
"newobj = AxisFormatClustersNew()\nnewobj._Copy(self)\nretu... | <|body_start_0|>
AxisFormat.__init__(self, 'clustersnew')
self._axes['energy'] = 0
self._axes['eta'] = 1
self._axes['phi'] = 2
self._axes['vertexz'] = 3
self._axes['mbtrigger'] = 4
<|end_body_0|>
<|body_start_1|>
newobj = AxisFormatClustersNew()
newobj._D... | Axis format for new cluster THnSparse | AxisFormatClustersNew | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisFormatClustersNew:
"""Axis format for new cluster THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy constructor"""... | stack_v2_sparse_classes_36k_train_031133 | 5,256 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Deep copy constructor",
"name": "__deepcopy__",
"signature": "def __deepcopy__(self, memo)"
},
{
"docstring": "Shallow copy constructor",
"name": "__copy__",
"signature"... | 3 | stack_v2_sparse_classes_30k_val_001202 | Implement the Python class `AxisFormatClustersNew` described below.
Class description:
Axis format for new cluster THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor | Implement the Python class `AxisFormatClustersNew` described below.
Class description:
Axis format for new cluster THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __deepcopy__(self, memo): Deep copy constructor
- def __copy__(self, other): Shallow copy constructor
<|skeleton|>
cla... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class AxisFormatClustersNew:
"""Axis format for new cluster THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __deepcopy__(self, memo):
"""Deep copy constructor"""
<|body_1|>
def __copy__(self, other):
"""Shallow copy constructor"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisFormatClustersNew:
"""Axis format for new cluster THnSparse"""
def __init__(self):
"""Constructor"""
AxisFormat.__init__(self, 'clustersnew')
self._axes['energy'] = 0
self._axes['eta'] = 1
self._axes['phi'] = 2
self._axes['vertexz'] = 3
self._ax... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/ClusterTHnSparse.py | alisw/AliPhysics | train | 129 |
ce6be203fe4c25aac454fe48fb11897de6924242 | [
"t = u\nl = t * 2\nr = t * 2 + 1\nif l <= k and heap[t] < heap[l]:\n t = l\nif r <= k and heap[t] < heap[r]:\n t = r\nif u != t:\n heap[t], heap[u] = (heap[u], heap[t])\n self.down(heap, t, k)",
"if k == 0:\n return []\nheap = [0] + arr[:k]\nfor i in range(k // 2, 0, -1):\n self.down(heap, i, k)... | <|body_start_0|>
t = u
l = t * 2
r = t * 2 + 1
if l <= k and heap[t] < heap[l]:
t = l
if r <= k and heap[t] < heap[r]:
t = r
if u != t:
heap[t], heap[u] = (heap[u], heap[t])
self.down(heap, t, k)
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def down(self, heap, u, k):
"""节点 u 向下移动, 和比 u 小的儿子做交换 :param heap: 堆 :param k: 堆元素个数 :return:"""
<|body_0|>
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
"""建堆 :param arr: :param k: :return:"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_031134 | 1,773 | no_license | [
{
"docstring": "节点 u 向下移动, 和比 u 小的儿子做交换 :param heap: 堆 :param k: 堆元素个数 :return:",
"name": "down",
"signature": "def down(self, heap, u, k)"
},
{
"docstring": "建堆 :param arr: :param k: :return:",
"name": "getLeastNumbers",
"signature": "def getLeastNumbers(self, arr: List[int], k: int) ->... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def down(self, heap, u, k): 节点 u 向下移动, 和比 u 小的儿子做交换 :param heap: 堆 :param k: 堆元素个数 :return:
- def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: 建堆 :param arr: :para... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def down(self, heap, u, k): 节点 u 向下移动, 和比 u 小的儿子做交换 :param heap: 堆 :param k: 堆元素个数 :return:
- def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: 建堆 :param arr: :para... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def down(self, heap, u, k):
"""节点 u 向下移动, 和比 u 小的儿子做交换 :param heap: 堆 :param k: 堆元素个数 :return:"""
<|body_0|>
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
"""建堆 :param arr: :param k: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def down(self, heap, u, k):
"""节点 u 向下移动, 和比 u 小的儿子做交换 :param heap: 堆 :param k: 堆元素个数 :return:"""
t = u
l = t * 2
r = t * 2 + 1
if l <= k and heap[t] < heap[l]:
t = l
if r <= k and heap[t] < heap[r]:
t = r
if u != t:
... | the_stack_v2_python_sparse | 剑指offer/面试题40. 最小的k个数.py | lovehhf/LeetCode | train | 0 | |
178b9feef02172cf624586a2297447f07cb94888 | [
"try:\n from pymatgen.core import Structure\nexcept:\n raise ImportError('This class requires pymatgen to be installed.')\nif type(structure) is not Structure:\n structure = Structure(**structure)\nself.aos = aos\nself.cutoff = np.around(cutoff, 2)\nself.setup_env = _load_primitive_cell(structure, aos, pbc... | <|body_start_0|>
try:
from pymatgen.core import Structure
except:
raise ImportError('This class requires pymatgen to be installed.')
if type(structure) is not Structure:
structure = Structure(**structure)
self.aos = aos
self.cutoff = np.around(... | Calculates the 2-D Surface graph features in 6 different permutations- Based on the implementation of Lattice Graph Convolution Neural Network (LCNN). This method produces the Atom wise features ( One Hot Encoding) and Adjacent neighbour in the specified order of permutations. Neighbors are determined by first extracti... | LCNNFeaturizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCNNFeaturizer:
"""Calculates the 2-D Surface graph features in 6 different permutations- Based on the implementation of Lattice Graph Convolution Neural Network (LCNN). This method produces the Atom wise features ( One Hot Encoding) and Adjacent neighbour in the specified order of permutations. ... | stack_v2_sparse_classes_36k_train_031135 | 28,058 | permissive | [
{
"docstring": "Parameters ---------- structure: : PymatgenStructure Pymatgen Structure object of the primitive cell used for calculating neighbors from lattice transformations.It also requires site_properties attribute with \"Sitetypes\"(Active or spectator site). aos: List[str] A list of all the active site s... | 2 | null | Implement the Python class `LCNNFeaturizer` described below.
Class description:
Calculates the 2-D Surface graph features in 6 different permutations- Based on the implementation of Lattice Graph Convolution Neural Network (LCNN). This method produces the Atom wise features ( One Hot Encoding) and Adjacent neighbour i... | Implement the Python class `LCNNFeaturizer` described below.
Class description:
Calculates the 2-D Surface graph features in 6 different permutations- Based on the implementation of Lattice Graph Convolution Neural Network (LCNN). This method produces the Atom wise features ( One Hot Encoding) and Adjacent neighbour i... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class LCNNFeaturizer:
"""Calculates the 2-D Surface graph features in 6 different permutations- Based on the implementation of Lattice Graph Convolution Neural Network (LCNN). This method produces the Atom wise features ( One Hot Encoding) and Adjacent neighbour in the specified order of permutations. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LCNNFeaturizer:
"""Calculates the 2-D Surface graph features in 6 different permutations- Based on the implementation of Lattice Graph Convolution Neural Network (LCNN). This method produces the Atom wise features ( One Hot Encoding) and Adjacent neighbour in the specified order of permutations. Neighbors are... | the_stack_v2_python_sparse | deepchem/feat/material_featurizers/lcnn_featurizer.py | deepchem/deepchem | train | 4,876 |
230d9e790fa1a4451b9f05311212c422ba79189b | [
"self.warmup_epochs = warmup_epochs\nself.max_epochs = max_epochs\nself.warmup_start_lr = warmup_start_lr\nself.eta_min = eta_min\nsuper().__init__(optimizer, last_epoch)",
"if not self._get_lr_called_within_step:\n warnings.warn('To get the last learning rate computed by the scheduler, please use `get_last_lr... | <|body_start_0|>
self.warmup_epochs = warmup_epochs
self.max_epochs = max_epochs
self.warmup_start_lr = warmup_start_lr
self.eta_min = eta_min
super().__init__(optimizer, last_epoch)
<|end_body_0|>
<|body_start_1|>
if not self._get_lr_called_within_step:
warn... | Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by a cosine annealing schedule between base_lr and eta_min. | LinearWarmupCosineAnnealingLR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearWarmupCosineAnnealingLR:
"""Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by a cosine annealing schedule between base_lr and eta_min."""
def __init__(self, optimizer: Optimizer, warmup_epochs: int, max_epo... | stack_v2_sparse_classes_36k_train_031136 | 3,997 | permissive | [
{
"docstring": "Args: optimizer (Optimizer): Wrapped optimizer. warmup_epochs (int): Maximum number of iterations for linear warmup max_epochs (int): Maximum number of iterations warmup_start_lr (float): Learning rate to start the linear warmup. Default: 0. eta_min (float): Minimum learning rate. Default: 0. la... | 3 | null | Implement the Python class `LinearWarmupCosineAnnealingLR` described below.
Class description:
Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by a cosine annealing schedule between base_lr and eta_min.
Method signatures and docstrings:
- ... | Implement the Python class `LinearWarmupCosineAnnealingLR` described below.
Class description:
Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by a cosine annealing schedule between base_lr and eta_min.
Method signatures and docstrings:
- ... | b199b45fbd895e254cedfb0d3572661f32bf1cff | <|skeleton|>
class LinearWarmupCosineAnnealingLR:
"""Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by a cosine annealing schedule between base_lr and eta_min."""
def __init__(self, optimizer: Optimizer, warmup_epochs: int, max_epo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearWarmupCosineAnnealingLR:
"""Sets the learning rate of each parameter group to follow a linear warmup schedule between warmup_start_lr and base_lr followed by a cosine annealing schedule between base_lr and eta_min."""
def __init__(self, optimizer: Optimizer, warmup_epochs: int, max_epochs: int, war... | the_stack_v2_python_sparse | src/climate_learn/models/lr_scheduler.py | aditya-grover/climate-learn | train | 232 |
3c8904294cda68b80c523771b10891d9064201bd | [
"path = [six.text_type(edge) for edge in edges]\nif len(field_names) > 1:\n path.append('{{{}}}'.format(','.join(sorted(field_names))))\nelif field_names:\n path.append(field_names[0])\nreturn '.'.join(path)",
"type_ = type(message).__name__\nbase_msg = 'Failed to parse value(s) in protobuf [{type_}]:'.form... | <|body_start_0|>
path = [six.text_type(edge) for edge in edges]
if len(field_names) > 1:
path.append('{{{}}}'.format(','.join(sorted(field_names))))
elif field_names:
path.append(field_names[0])
return '.'.join(path)
<|end_body_0|>
<|body_start_1|>
type_ ... | Indicates an error in decoding a protorpclite message. | DecodeError | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodeError:
"""Indicates an error in decoding a protorpclite message."""
def _FormatProtoPath(cls, edges, field_names):
"""Returns a string representation of a path to a proto field. The return value represents one or more fields in a python dictionary representation of a message (j... | stack_v2_sparse_classes_36k_train_031137 | 5,880 | permissive | [
{
"docstring": "Returns a string representation of a path to a proto field. The return value represents one or more fields in a python dictionary representation of a message (json/yaml) that could not be decoded into the message as a string. The format is a dot separated list of python like sub field references... | 2 | stack_v2_sparse_classes_30k_train_003044 | Implement the Python class `DecodeError` described below.
Class description:
Indicates an error in decoding a protorpclite message.
Method signatures and docstrings:
- def _FormatProtoPath(cls, edges, field_names): Returns a string representation of a path to a proto field. The return value represents one or more fie... | Implement the Python class `DecodeError` described below.
Class description:
Indicates an error in decoding a protorpclite message.
Method signatures and docstrings:
- def _FormatProtoPath(cls, edges, field_names): Returns a string representation of a path to a proto field. The return value represents one or more fie... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class DecodeError:
"""Indicates an error in decoding a protorpclite message."""
def _FormatProtoPath(cls, edges, field_names):
"""Returns a string representation of a path to a proto field. The return value represents one or more fields in a python dictionary representation of a message (j... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecodeError:
"""Indicates an error in decoding a protorpclite message."""
def _FormatProtoPath(cls, edges, field_names):
"""Returns a string representation of a path to a proto field. The return value represents one or more fields in a python dictionary representation of a message (json/yaml) tha... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/api_lib/util/messages.py | bopopescu/socialliteapp | train | 0 |
d78ded9245649e3ba3019fc5702ec13f7a7e5c21 | [
"s = test_limit_of_send_email(g.current_user, AccountOperations.CHANGE_EMAIL)\nif s == -2:\n token = generate_email_confirm_token(g.current_user.username, AccountOperations.CHANGE_EMAIL)\n send_change_email_email.delay(token, g.current_user.email, g.current_user.username)\n return ok(message='请到 %s 查收邮件!' ... | <|body_start_0|>
s = test_limit_of_send_email(g.current_user, AccountOperations.CHANGE_EMAIL)
if s == -2:
token = generate_email_confirm_token(g.current_user.username, AccountOperations.CHANGE_EMAIL)
send_change_email_email.delay(token, g.current_user.email, g.current_user.userna... | UserEmail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserEmail:
def put(self):
"""change email"""
<|body_0|>
def post(self):
"""resent email for confirm"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = test_limit_of_send_email(g.current_user, AccountOperations.CHANGE_EMAIL)
if s == -2:
... | stack_v2_sparse_classes_36k_train_031138 | 17,895 | permissive | [
{
"docstring": "change email",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "resent email for confirm",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004318 | Implement the Python class `UserEmail` described below.
Class description:
Implement the UserEmail class.
Method signatures and docstrings:
- def put(self): change email
- def post(self): resent email for confirm | Implement the Python class `UserEmail` described below.
Class description:
Implement the UserEmail class.
Method signatures and docstrings:
- def put(self): change email
- def post(self): resent email for confirm
<|skeleton|>
class UserEmail:
def put(self):
"""change email"""
<|body_0|>
def... | fb1e88eccee1140d215ef8f1f789f215b1b3c2cf | <|skeleton|>
class UserEmail:
def put(self):
"""change email"""
<|body_0|>
def post(self):
"""resent email for confirm"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserEmail:
def put(self):
"""change email"""
s = test_limit_of_send_email(g.current_user, AccountOperations.CHANGE_EMAIL)
if s == -2:
token = generate_email_confirm_token(g.current_user.username, AccountOperations.CHANGE_EMAIL)
send_change_email_email.delay(toke... | the_stack_v2_python_sparse | app/v2/user.py | shanhezhao/flask_douban_moive_web | train | 0 | |
d6a1b10239710e84255053a1949b25a24290514c | [
"if len(nums) <= 2:\n return target in nums\nelse:\n L = 0\n H = len(nums) - 1\n M = (L + H) // 2\n Lo = nums[L]\n Hi = nums[H]\n Mid = nums[M]\n if Lo <= Mid <= Hi:\n return self.search(nums[L:M], target) or self.search(nums[M:], target)\n elif Lo > Mid and Mid <= Hi:\n ret... | <|body_start_0|>
if len(nums) <= 2:
return target in nums
else:
L = 0
H = len(nums) - 1
M = (L + H) // 2
Lo = nums[L]
Hi = nums[H]
Mid = nums[M]
if Lo <= Mid <= Hi:
return self.search(nums[L:M... | Solution_A2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_A2:
def search(self, nums: List[int], target: int) -> bool:
"""本质上是与VersionA1同一个意思,只是少一个helper判断两段是否是sorted. 把这个Helper的判断直接引入到了递归判断之中. 代码更简洁,但是缺点是,判断不够准确导致可能要连续对两段都使用search,递归层数增多"""
<|body_0|>
def binarysearch(self, nums: List[int], target: int) -> bool:
""... | stack_v2_sparse_classes_36k_train_031139 | 6,122 | permissive | [
{
"docstring": "本质上是与VersionA1同一个意思,只是少一个helper判断两段是否是sorted. 把这个Helper的判断直接引入到了递归判断之中. 代码更简洁,但是缺点是,判断不够准确导致可能要连续对两段都使用search,递归层数增多",
"name": "search",
"signature": "def search(self, nums: List[int], target: int) -> bool"
},
{
"docstring": "Binary search in sorted array",
"name": "binarysea... | 2 | stack_v2_sparse_classes_30k_train_018605 | Implement the Python class `Solution_A2` described below.
Class description:
Implement the Solution_A2 class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> bool: 本质上是与VersionA1同一个意思,只是少一个helper判断两段是否是sorted. 把这个Helper的判断直接引入到了递归判断之中. 代码更简洁,但是缺点是,判断不够准确导致可能要连续对两段都使用search,递归层数增多... | Implement the Python class `Solution_A2` described below.
Class description:
Implement the Solution_A2 class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> bool: 本质上是与VersionA1同一个意思,只是少一个helper判断两段是否是sorted. 把这个Helper的判断直接引入到了递归判断之中. 代码更简洁,但是缺点是,判断不够准确导致可能要连续对两段都使用search,递归层数增多... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_A2:
def search(self, nums: List[int], target: int) -> bool:
"""本质上是与VersionA1同一个意思,只是少一个helper判断两段是否是sorted. 把这个Helper的判断直接引入到了递归判断之中. 代码更简洁,但是缺点是,判断不够准确导致可能要连续对两段都使用search,递归层数增多"""
<|body_0|>
def binarysearch(self, nums: List[int], target: int) -> bool:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_A2:
def search(self, nums: List[int], target: int) -> bool:
"""本质上是与VersionA1同一个意思,只是少一个helper判断两段是否是sorted. 把这个Helper的判断直接引入到了递归判断之中. 代码更简洁,但是缺点是,判断不够准确导致可能要连续对两段都使用search,递归层数增多"""
if len(nums) <= 2:
return target in nums
else:
L = 0
H = l... | the_stack_v2_python_sparse | LeetCode/LC081_search_in_rotated_sorted_array_ii.py | jxie0755/Learning_Python | train | 0 | |
aba95fb1b22b570c6156c66d02944fd6bdef5d1a | [
"with open(config_filename) as f:\n vehicle = yaml.safe_load(f)\nself.thrusters = []\nfor t_dict in vehicle['thrusters']:\n t = Thruster(t_dict['pos'], t_dict['rpy'], t_dict['flipped'])\n self.thrusters.append(t)\nself.wrenchmat = np.empty((6, len(self.thrusters)))\nfor i, t in enumerate(self.thrusters):\n... | <|body_start_0|>
with open(config_filename) as f:
vehicle = yaml.safe_load(f)
self.thrusters = []
for t_dict in vehicle['thrusters']:
t = Thruster(t_dict['pos'], t_dict['rpy'], t_dict['flipped'])
self.thrusters.append(t)
self.wrenchmat = np.empty((6, l... | Compiles all thruster data, generating a wrench matrix that holds the force and torque of each thruster. Uses this matrix to calculate thruster allocations based on desired control effort in each degree of freedom (x, y, z, roll, pitch, yaw). Attributes: thrusters: The thrusters that are part of the robot. wrenchmat: A... | ThrusterManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThrusterManager:
"""Compiles all thruster data, generating a wrench matrix that holds the force and torque of each thruster. Uses this matrix to calculate thruster allocations based on desired control effort in each degree of freedom (x, y, z, roll, pitch, yaw). Attributes: thrusters: The thruste... | stack_v2_sparse_classes_36k_train_031140 | 3,230 | no_license | [
{
"docstring": "Creates a thruster manager object. Retrieves thruster data from a yaml config file and constructs Thrusters and wrench matrix. Args: config_filename: The vehicle configuration file holding thruster data",
"name": "__init__",
"signature": "def __init__(self, config_filename)"
},
{
... | 2 | null | Implement the Python class `ThrusterManager` described below.
Class description:
Compiles all thruster data, generating a wrench matrix that holds the force and torque of each thruster. Uses this matrix to calculate thruster allocations based on desired control effort in each degree of freedom (x, y, z, roll, pitch, y... | Implement the Python class `ThrusterManager` described below.
Class description:
Compiles all thruster data, generating a wrench matrix that holds the force and torque of each thruster. Uses this matrix to calculate thruster allocations based on desired control effort in each degree of freedom (x, y, z, roll, pitch, y... | e2fd7ab924d143bf6354806a104f49d982f32fb1 | <|skeleton|>
class ThrusterManager:
"""Compiles all thruster data, generating a wrench matrix that holds the force and torque of each thruster. Uses this matrix to calculate thruster allocations based on desired control effort in each degree of freedom (x, y, z, roll, pitch, yaw). Attributes: thrusters: The thruste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThrusterManager:
"""Compiles all thruster data, generating a wrench matrix that holds the force and torque of each thruster. Uses this matrix to calculate thruster allocations based on desired control effort in each degree of freedom (x, y, z, roll, pitch, yaw). Attributes: thrusters: The thrusters that are p... | the_stack_v2_python_sparse | onboard/catkin_ws/src/controls/scripts/thruster_manager.py | DukeRobotics/robosub-ros | train | 24 |
cd20a3a1ce484aa2d645e4bfb2ea1b57df8ad5ac | [
"Block.__init__(self, parent, idevice)\nself.activity = idevice.activity\nself.answer = idevice.answer\nself.activityInstruc = idevice.activityInstruc\nself.answerInstruc = idevice.answerInstruc",
"Block.process(self, request)\nif 'activity' + self.id in request.args:\n self.idevice.activity = request.args['ac... | <|body_start_0|>
Block.__init__(self, parent, idevice)
self.activity = idevice.activity
self.answer = idevice.answer
self.activityInstruc = idevice.activityInstruc
self.answerInstruc = idevice.answerInstruc
<|end_body_0|>
<|body_start_1|>
Block.process(self, request)
... | ReflectionBlock can render and process ReflectionIdevices as XHTML | ReflectionBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflectionBlock:
"""ReflectionBlock can render and process ReflectionIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize a new Block object"""
<|body_0|>
def process(self, request):
"""Process the request arguments from the web server"""
... | stack_v2_sparse_classes_36k_train_031141 | 3,032 | no_license | [
{
"docstring": "Initialize a new Block object",
"name": "__init__",
"signature": "def __init__(self, parent, idevice)"
},
{
"docstring": "Process the request arguments from the web server",
"name": "process",
"signature": "def process(self, request)"
},
{
"docstring": "Returns an... | 4 | null | Implement the Python class `ReflectionBlock` described below.
Class description:
ReflectionBlock can render and process ReflectionIdevices as XHTML
Method signatures and docstrings:
- def __init__(self, parent, idevice): Initialize a new Block object
- def process(self, request): Process the request arguments from th... | Implement the Python class `ReflectionBlock` described below.
Class description:
ReflectionBlock can render and process ReflectionIdevices as XHTML
Method signatures and docstrings:
- def __init__(self, parent, idevice): Initialize a new Block object
- def process(self, request): Process the request arguments from th... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class ReflectionBlock:
"""ReflectionBlock can render and process ReflectionIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize a new Block object"""
<|body_0|>
def process(self, request):
"""Process the request arguments from the web server"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReflectionBlock:
"""ReflectionBlock can render and process ReflectionIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize a new Block object"""
Block.__init__(self, parent, idevice)
self.activity = idevice.activity
self.answer = idevice.answer
se... | the_stack_v2_python_sparse | eXe/rev2283-2366/base-trunk-2283/exe/webui/reflectionblock.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
2bb687a146058139522e0630c08b2505e73d2816 | [
"redirect_msg = self._MaybeRedirectToDomainDefaultProject(mr)\nlogging.info(redirect_msg)\ncan_create_project = permissions.CanCreateProject(mr.perms)\npipeline = projectsearch.ProjectSearchPipeline(mr, self.services)\nwith work_env.WorkEnv(mr, self.services) as we:\n starred_projects = we.ListStarredProjects()\... | <|body_start_0|>
redirect_msg = self._MaybeRedirectToDomainDefaultProject(mr)
logging.info(redirect_msg)
can_create_project = permissions.CanCreateProject(mr.perms)
pipeline = projectsearch.ProjectSearchPipeline(mr, self.services)
with work_env.WorkEnv(mr, self.services) as we:
... | HostingHome shows the project list and link to create a project. | HostingHome | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostingHome:
"""HostingHome shows the project list and link to create a project."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rend... | stack_v2_sparse_classes_36k_train_031142 | 3,972 | permissive | [
{
"docstring": "Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering the page.",
"name": "GatherPageData",
"signature": "def GatherPageData(self, mr)"
},
{
"docstring": "If the... | 2 | null | Implement the Python class `HostingHome` described below.
Class description:
HostingHome shows the project list and link to create a project.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from ... | Implement the Python class `HostingHome` described below.
Class description:
HostingHome shows the project list and link to create a project.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from ... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class HostingHome:
"""HostingHome shows the project list and link to create a project."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rend... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostingHome:
"""HostingHome shows the project list and link to create a project."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering the pag... | the_stack_v2_python_sparse | appengine/monorail/sitewide/hostinghome.py | xinghun61/infra | train | 2 |
597e48c02b829c47f0e35566742eff4a6a5af8ae | [
"n = len(matrix[0])\nfor i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nfor i in range(n):\n matrix[i].reverse()\nreturn matrix",
"n = len(matrix[0])\nfor i in range(n // 2 + n % 2):\n for j in range(n // 2):\n temp = matrix[n - 1 - j][i]... | <|body_start_0|>
n = len(matrix[0])
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
for i in range(n):
matrix[i].reverse()
return matrix
<|end_body_0|>
<|body_start_1|>
n = len(matrix[0])
... | RotateImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotateImage:
def to_90_degrees(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: Transpose and then reverse. Time Complexity: O(n^2) Space Complexity: O(1) :param matrix: :return:"""
<|body_0|>
def to_90_degrees_(self, matrix: List[List[int]]) -> List[List[int]... | stack_v2_sparse_classes_36k_train_031143 | 1,519 | no_license | [
{
"docstring": "Approach: Transpose and then reverse. Time Complexity: O(n^2) Space Complexity: O(1) :param matrix: :return:",
"name": "to_90_degrees",
"signature": "def to_90_degrees(self, matrix: List[List[int]]) -> List[List[int]]"
},
{
"docstring": "Approach: Rotate four rectangles in one si... | 2 | null | Implement the Python class `RotateImage` described below.
Class description:
Implement the RotateImage class.
Method signatures and docstrings:
- def to_90_degrees(self, matrix: List[List[int]]) -> List[List[int]]: Approach: Transpose and then reverse. Time Complexity: O(n^2) Space Complexity: O(1) :param matrix: :re... | Implement the Python class `RotateImage` described below.
Class description:
Implement the RotateImage class.
Method signatures and docstrings:
- def to_90_degrees(self, matrix: List[List[int]]) -> List[List[int]]: Approach: Transpose and then reverse. Time Complexity: O(n^2) Space Complexity: O(1) :param matrix: :re... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class RotateImage:
def to_90_degrees(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: Transpose and then reverse. Time Complexity: O(n^2) Space Complexity: O(1) :param matrix: :return:"""
<|body_0|>
def to_90_degrees_(self, matrix: List[List[int]]) -> List[List[int]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RotateImage:
def to_90_degrees(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: Transpose and then reverse. Time Complexity: O(n^2) Space Complexity: O(1) :param matrix: :return:"""
n = len(matrix[0])
for i in range(n):
for j in range(i, n):
m... | the_stack_v2_python_sparse | data_structures/rotate_image.py | Shiv2157k/leet_code | train | 1 | |
943705ebdc8def2ab13dbd5763d822f59ccabba3 | [
"self.vertices = {}\nself.conversion = {}\nself.vertice_central = None",
"vertice = Vertice(dato)\nself.conversion[dato] = vertice\nself.vertices[vertice] = []",
"try:\n vertice1 = self.conversion[dato1]\n vertice2 = self.conversion[dato2]\n self.vertices[vertice1].append((peso, vertice2))\n self.ve... | <|body_start_0|>
self.vertices = {}
self.conversion = {}
self.vertice_central = None
<|end_body_0|>
<|body_start_1|>
vertice = Vertice(dato)
self.conversion[dato] = vertice
self.vertices[vertice] = []
<|end_body_1|>
<|body_start_2|>
try:
vertice1 = s... | Clase que representa un Grafo mediante un diccionario de adyacencias | Grafo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grafo:
"""Clase que representa un Grafo mediante un diccionario de adyacencias"""
def __init__(self):
"""Crea una instancia de la clase sin vértices ni aristas y con el vértice central indefinido. El vértice central es aquel desde el cual se calculan las distancia ménimas a todos los... | stack_v2_sparse_classes_36k_train_031144 | 3,585 | no_license | [
{
"docstring": "Crea una instancia de la clase sin vértices ni aristas y con el vértice central indefinido. El vértice central es aquel desde el cual se calculan las distancia ménimas a todos los demás vértices cuando se llama a Dijkstra.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_002573 | Implement the Python class `Grafo` described below.
Class description:
Clase que representa un Grafo mediante un diccionario de adyacencias
Method signatures and docstrings:
- def __init__(self): Crea una instancia de la clase sin vértices ni aristas y con el vértice central indefinido. El vértice central es aquel de... | Implement the Python class `Grafo` described below.
Class description:
Clase que representa un Grafo mediante un diccionario de adyacencias
Method signatures and docstrings:
- def __init__(self): Crea una instancia de la clase sin vértices ni aristas y con el vértice central indefinido. El vértice central es aquel de... | 87ea0fa294c3f816bb51d94ee683c713b54b80bc | <|skeleton|>
class Grafo:
"""Clase que representa un Grafo mediante un diccionario de adyacencias"""
def __init__(self):
"""Crea una instancia de la clase sin vértices ni aristas y con el vértice central indefinido. El vértice central es aquel desde el cual se calculan las distancia ménimas a todos los... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Grafo:
"""Clase que representa un Grafo mediante un diccionario de adyacencias"""
def __init__(self):
"""Crea una instancia de la clase sin vértices ni aristas y con el vértice central indefinido. El vértice central es aquel desde el cual se calculan las distancia ménimas a todos los demás vértic... | the_stack_v2_python_sparse | tp2/Grafos/Grafo.py | tomasmussi/tda | train | 0 |
80d599a72b2874f7c907b3cc362274669670f885 | [
"super().__init__(input_key, output_key)\nlambda_fn = lambda_fn or (lambda x: x)\nself.lambda_fn = functools.partial(lambda_fn, **kwargs)",
"if self.input_key is not None:\n element = element[self.input_key]\noutput = self.lambda_fn(element)\nif self.output_key is not None:\n output = {self.output_key: outp... | <|body_start_0|>
super().__init__(input_key, output_key)
lambda_fn = lambda_fn or (lambda x: x)
self.lambda_fn = functools.partial(lambda_fn, **kwargs)
<|end_body_0|>
<|body_start_1|>
if self.input_key is not None:
element = element[self.input_key]
output = self.lamb... | Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it. | LambdaReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LambdaReader:
"""Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it."""
def __init__(self, input_key: str, output_key: Optional[str]=None, lambda_fn: Optional[Callable]=None, **kwargs):
"""Args: input_key: input key to use f... | stack_v2_sparse_classes_36k_train_031145 | 5,229 | permissive | [
{
"docstring": "Args: input_key: input key to use from annotation dict output_key: output key to use to store the result lambda_fn: encode function to use to prepare your data (for example convert chars/words/tokens to indices, etc) kwargs: kwargs for encode function",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_017481 | Implement the Python class `LambdaReader` described below.
Class description:
Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it.
Method signatures and docstrings:
- def __init__(self, input_key: str, output_key: Optional[str]=None, lambda_fn: Optional[Calla... | Implement the Python class `LambdaReader` described below.
Class description:
Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it.
Method signatures and docstrings:
- def __init__(self, input_key: str, output_key: Optional[str]=None, lambda_fn: Optional[Calla... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class LambdaReader:
"""Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it."""
def __init__(self, input_key: str, output_key: Optional[str]=None, lambda_fn: Optional[Callable]=None, **kwargs):
"""Args: input_key: input key to use f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LambdaReader:
"""Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it."""
def __init__(self, input_key: str, output_key: Optional[str]=None, lambda_fn: Optional[Callable]=None, **kwargs):
"""Args: input_key: input key to use from annotatio... | the_stack_v2_python_sparse | catalyst/contrib/data/reader.py | catalyst-team/catalyst | train | 3,038 |
cba1ea24a567e79da68a2c7009238e606d69608a | [
"if not needle:\n return 0\nfor i in range(len(haystack) - len(needle) + 1):\n if haystack[i:i + len(needle)] == needle:\n return i\n else:\n i += 1\nreturn -1",
"n = len(haystack)\nm = len(needle)\nfor i in range(n - m + 1):\n for k in range(m):\n if haystack[i + k] != needle[k]:... | <|body_start_0|>
if not needle:
return 0
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
else:
i += 1
return -1
<|end_body_0|>
<|body_start_1|>
n = len(haystack)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def strStr(self, haystack, needle):
""":type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def strStrB(self, haystack, needle):
""":type haystack: str :type needle: str :rtype: int needle: | m | haystack: | n - m | m |, 0 -> n-m +1"""
<|... | stack_v2_sparse_classes_36k_train_031146 | 1,492 | no_license | [
{
"docstring": ":type haystack: str :type needle: str :rtype: int",
"name": "strStr",
"signature": "def strStr(self, haystack, needle)"
},
{
"docstring": ":type haystack: str :type needle: str :rtype: int needle: | m | haystack: | n - m | m |, 0 -> n-m +1",
"name": "strStrB",
"signature"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, haystack, needle): :type haystack: str :type needle: str :rtype: int
- def strStrB(self, haystack, needle): :type haystack: str :type needle: str :rtype: int nee... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def strStr(self, haystack, needle): :type haystack: str :type needle: str :rtype: int
- def strStrB(self, haystack, needle): :type haystack: str :type needle: str :rtype: int nee... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def strStr(self, haystack, needle):
""":type haystack: str :type needle: str :rtype: int"""
<|body_0|>
def strStrB(self, haystack, needle):
""":type haystack: str :type needle: str :rtype: int needle: | m | haystack: | n - m | m |, 0 -> n-m +1"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def strStr(self, haystack, needle):
""":type haystack: str :type needle: str :rtype: int"""
if not needle:
return 0
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
else:
... | the_stack_v2_python_sparse | 11. STRING MANIP/28_implement strStr()/solution.py | kimmyoo/python_leetcode | train | 1 | |
b826610512ac010529b36a12de4f4f1156bcd1b8 | [
"self.response = response\nself.log_function = logfunc\nself.error = err\nself.data = ''\nself.status = 0\nif self.response:\n self.status = self.response.getcode()\n result = self.response.read()\n while result:\n self.data += result\n result = self.response.read()\nif self.error:\n self.... | <|body_start_0|>
self.response = response
self.log_function = logfunc
self.error = err
self.data = ''
self.status = 0
if self.response:
self.status = self.response.getcode()
result = self.response.read()
while result:
se... | Result from a REST API operation. | RestResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestResult:
"""Result from a REST API operation."""
def __init__(self, logfunc=None, response=None, err=None):
"""Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error."""
<|... | stack_v2_sparse_classes_36k_train_031147 | 12,813 | permissive | [
{
"docstring": "Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error.",
"name": "__init__",
"signature": "def __init__(self, logfunc=None, response=None, err=None)"
},
{
"docstring": "Get an HT... | 2 | stack_v2_sparse_classes_30k_val_000294 | Implement the Python class `RestResult` described below.
Class description:
Result from a REST API operation.
Method signatures and docstrings:
- def __init__(self, logfunc=None, response=None, err=None): Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param respo... | Implement the Python class `RestResult` described below.
Class description:
Result from a REST API operation.
Method signatures and docstrings:
- def __init__(self, logfunc=None, response=None, err=None): Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param respo... | a93a844398a11a8a85f204782fb9456f7caccdbe | <|skeleton|>
class RestResult:
"""Result from a REST API operation."""
def __init__(self, logfunc=None, response=None, err=None):
"""Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestResult:
"""Result from a REST API operation."""
def __init__(self, logfunc=None, response=None, err=None):
"""Initialize a RestResult containing the results from a REST call. :param logfunc: debug log function. :param response: HTTP response. :param err: HTTP error."""
self.response =... | the_stack_v2_python_sparse | manila/share/drivers/zfssa/restclient.py | openstack/manila | train | 178 |
5c85b8021c67cf302622c215b1e7b4d784c0cb2d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IntelligenceProfile()",
"from ..entity import Entity\nfrom .formatted_content import FormattedContent\nfrom .intelligence_profile_country_or_region_of_origin import IntelligenceProfileCountryOrRegionOfOrigin\nfrom .intelligence_profile... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IntelligenceProfile()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .formatted_content import FormattedContent
from .intelligence_profile_country_or_region_of_... | IntelligenceProfile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntelligenceProfile:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfile:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k_train_031148 | 6,060 | 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: IntelligenceProfile",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `IntelligenceProfile` described below.
Class description:
Implement the IntelligenceProfile class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfile: Creates a new instance of the appropriate class based on d... | Implement the Python class `IntelligenceProfile` described below.
Class description:
Implement the IntelligenceProfile class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfile: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IntelligenceProfile:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfile:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntelligenceProfile:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntelligenceProfile:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/models/security/intelligence_profile.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
12e99bf8c76f41ab3907afa4bcc21e01a8cfeb9e | [
"self.context = MathParseContext(context_name)\nself.function_list = []\nself.source = ''\nself.objast = None",
"result = {}\nfor func in self.function_list:\n stmts = func.body\n result.update(invert_dict(func.args))\n result.update({'_{}_stmt_{}'.format(func.name, i): func.translate_function_statement(... | <|body_start_0|>
self.context = MathParseContext(context_name)
self.function_list = []
self.source = ''
self.objast = None
<|end_body_0|>
<|body_start_1|>
result = {}
for func in self.function_list:
stmts = func.body
result.update(invert_dict(func... | Encapsulate the state required to translate a sequence of functions in a single context. | MathParse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MathParse:
"""Encapsulate the state required to translate a sequence of functions in a single context."""
def __init__(self, context_name='_'):
"""Set default empty values for instance variables."""
<|body_0|>
def translate(self):
"""Translate this context's func... | stack_v2_sparse_classes_36k_train_031149 | 17,164 | no_license | [
{
"docstring": "Set default empty values for instance variables.",
"name": "__init__",
"signature": "def __init__(self, context_name='_')"
},
{
"docstring": "Translate this context's function list.",
"name": "translate",
"signature": "def translate(self)"
},
{
"docstring": "Consu... | 4 | stack_v2_sparse_classes_30k_test_000466 | Implement the Python class `MathParse` described below.
Class description:
Encapsulate the state required to translate a sequence of functions in a single context.
Method signatures and docstrings:
- def __init__(self, context_name='_'): Set default empty values for instance variables.
- def translate(self): Translat... | Implement the Python class `MathParse` described below.
Class description:
Encapsulate the state required to translate a sequence of functions in a single context.
Method signatures and docstrings:
- def __init__(self, context_name='_'): Set default empty values for instance variables.
- def translate(self): Translat... | 97f7f037116ff057993aa84677e3d45d3aa72193 | <|skeleton|>
class MathParse:
"""Encapsulate the state required to translate a sequence of functions in a single context."""
def __init__(self, context_name='_'):
"""Set default empty values for instance variables."""
<|body_0|>
def translate(self):
"""Translate this context's func... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MathParse:
"""Encapsulate the state required to translate a sequence of functions in a single context."""
def __init__(self, context_name='_'):
"""Set default empty values for instance variables."""
self.context = MathParseContext(context_name)
self.function_list = []
self... | the_stack_v2_python_sparse | ctxmathparse.py | piratejon/a396 | train | 0 |
b7a6264e14f9614ad5c5c272e7f574593d8532fd | [
"zeroList = []\nfor i in range(len(nums) - 2):\n for j in range(i + 1, len(nums) - 1):\n for k in range(j + 1, len(nums)):\n if nums[i] + nums[j] + nums[k] == 0:\n numList = (nums[i], nums[j], nums[k])\n if sorted(numList) not in zeroList:\n zero... | <|body_start_0|>
zeroList = []
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
numList = (nums[i], nums[j], nums[k])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum_naive(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
zeroList = []
... | stack_v2_sparse_classes_36k_train_031150 | 1,788 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum_naive",
"signature": "def threeSum_naive(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_006492 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum_naive(self, nums): :type nums: List[int] :rtype: List[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 threeSum_naive(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Soluti... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def threeSum_naive(self, nums):
""":type nums: List[int] :rtype: List[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 threeSum_naive(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
zeroList = []
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] + nums... | the_stack_v2_python_sparse | 15_threeSum.py | Anirban2404/LeetCodePractice | train | 1 | |
77b161680bc2daf57b3edfcf9dadcbe4412d435f | [
"serial = []\n\ndef preorder(node):\n if not node:\n return\n serial.append(node.val)\n for child in node.children:\n preorder(child)\n serial.append('#')\n return\npreorder(root)\nreturn serial",
"if not data:\n return None\ndata = collections.deque(data)\nroot = Node(data.popleft... | <|body_start_0|>
serial = []
def preorder(node):
if not node:
return
serial.append(node.val)
for child in node.children:
preorder(child)
serial.append('#')
return
preorder(root)
return serial
<|e... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_031151 | 3,065 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | e278ae6ded32f6a2d054ae11ad8fcc45e7bd0f86 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
serial = []
def preorder(node):
if not node:
return
serial.append(node.val)
for child in node.children:
preorder(... | the_stack_v2_python_sparse | Premuim/428. Serialize and Deserialize N-ary Tree.py | NiuNiu-jupiter/Leetcode | train | 0 | |
0db05f26679c1f753d5fcd0e60f5f9349a80bed1 | [
"lhs_bytes = old_contentfile_bytes\npatch_bytes_ex = patch_bytes\nrhs_bytes = file_patch(lhs_bytes, patch_bytes_ex, ver=1)\nnew_contentfile_bytes = rhs_bytes\nreturn new_contentfile_bytes",
"ls = []\nfor patch_idx, imay_parent_idx, user_data_dir_path, contentfile_path, content_binary_ifile in iter_tpl5s:\n wit... | <|body_start_0|>
lhs_bytes = old_contentfile_bytes
patch_bytes_ex = patch_bytes
rhs_bytes = file_patch(lhs_bytes, patch_bytes_ex, ver=1)
new_contentfile_bytes = rhs_bytes
return new_contentfile_bytes
<|end_body_0|>
<|body_start_1|>
ls = []
for patch_idx, imay_par... | IRepositorySetting__using_file_cmp__file_patch_ver1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IRepositorySetting__using_file_cmp__file_patch_ver1:
def contentfile_patch(sf, old_contentfile_bytes, patch_bytes, /):
"""old_contentfile_bytes -> patch_bytes -> new_contentfile_bytes"""
<|body_0|>
def ___open_patch_idx___(sf, iter_tpl5s, /):
"""Iter (patch_idx, imay... | stack_v2_sparse_classes_36k_train_031152 | 1,796 | no_license | [
{
"docstring": "old_contentfile_bytes -> patch_bytes -> new_contentfile_bytes",
"name": "contentfile_patch",
"signature": "def contentfile_patch(sf, old_contentfile_bytes, patch_bytes, /)"
},
{
"docstring": "Iter (patch_idx, imay_parent_idx, user_data_dir_path, contentfile_path, content_binary_i... | 2 | stack_v2_sparse_classes_30k_train_010889 | Implement the Python class `IRepositorySetting__using_file_cmp__file_patch_ver1` described below.
Class description:
Implement the IRepositorySetting__using_file_cmp__file_patch_ver1 class.
Method signatures and docstrings:
- def contentfile_patch(sf, old_contentfile_bytes, patch_bytes, /): old_contentfile_bytes -> p... | Implement the Python class `IRepositorySetting__using_file_cmp__file_patch_ver1` described below.
Class description:
Implement the IRepositorySetting__using_file_cmp__file_patch_ver1 class.
Method signatures and docstrings:
- def contentfile_patch(sf, old_contentfile_bytes, patch_bytes, /): old_contentfile_bytes -> p... | 41f3a506feffb5f33d4559e5b69717d9bb6303c9 | <|skeleton|>
class IRepositorySetting__using_file_cmp__file_patch_ver1:
def contentfile_patch(sf, old_contentfile_bytes, patch_bytes, /):
"""old_contentfile_bytes -> patch_bytes -> new_contentfile_bytes"""
<|body_0|>
def ___open_patch_idx___(sf, iter_tpl5s, /):
"""Iter (patch_idx, imay... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IRepositorySetting__using_file_cmp__file_patch_ver1:
def contentfile_patch(sf, old_contentfile_bytes, patch_bytes, /):
"""old_contentfile_bytes -> patch_bytes -> new_contentfile_bytes"""
lhs_bytes = old_contentfile_bytes
patch_bytes_ex = patch_bytes
rhs_bytes = file_patch(lhs_b... | the_stack_v2_python_sparse | nn_ns/filedir/backup_tools/IRepositorySetting__using_file_cmp__file_patch.py | edt-yxz-zzd/python3_src | train | 2 | |
95ee67a269e813e23d273cef3779dad7371532cd | [
"if s in self.canWinTable:\n return self.canWinTable[s]\nnextStates = self.generatePossibleNextMoves(s)\nfor state in nextStates:\n if not self.canWin(state):\n self.canWinTable[s] = True\n return True\nself.canWinTable[s] = False\nreturn False",
"result = []\nfor i in range(len(s) - 1):\n ... | <|body_start_0|>
if s in self.canWinTable:
return self.canWinTable[s]
nextStates = self.generatePossibleNextMoves(s)
for state in nextStates:
if not self.canWin(state):
self.canWinTable[s] = True
return True
self.canWinTable[s] = Fa... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def generatePossibleNextMoves(self, s):
""":type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s in self.canWinTable:
return self.can... | stack_v2_sparse_classes_36k_train_031153 | 1,057 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "canWin",
"signature": "def canWin(self, s)"
},
{
"docstring": ":type s: str :rtype: List[str]",
"name": "generatePossibleNextMoves",
"signature": "def generatePossibleNextMoves(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010238 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canWin(self, s): :type s: str :rtype: bool
- def generatePossibleNextMoves(self, s): :type s: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canWin(self, s): :type s: str :rtype: bool
- def generatePossibleNextMoves(self, s): :type s: str :rtype: List[str]
<|skeleton|>
class Solution:
def canWin(self, s):
... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def generatePossibleNextMoves(self, s):
""":type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canWin(self, s):
""":type s: str :rtype: bool"""
if s in self.canWinTable:
return self.canWinTable[s]
nextStates = self.generatePossibleNextMoves(s)
for state in nextStates:
if not self.canWin(state):
self.canWinTable[s] = T... | the_stack_v2_python_sparse | Python_leetcode/294_flip_game_II.py | xiangcao/Leetcode | train | 0 | |
63ac2b328db81ba976fd0713a1d7ecc6d97f1ccb | [
"default_options = Options(**{constants().Name: 'FEM Composite', constants().Line: 0.0, constants().Column: 0.0, constants().Previous: None, constants().Domain: None})\nwhole_options = default_options << options\nsuper(IFEM, self).__init__(whole_options, **kw)",
"result = self.name + 'formed by: '\nfor iEquation ... | <|body_start_0|>
default_options = Options(**{constants().Name: 'FEM Composite', constants().Line: 0.0, constants().Column: 0.0, constants().Previous: None, constants().Domain: None})
whole_options = default_options << options
super(IFEM, self).__init__(whole_options, **kw)
<|end_body_0|>
<|bod... | A class to create a term based on the basic terms. This class can be used in runtime or for the developer to define a new term. | IFEM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IFEM:
"""A class to create a term based on the basic terms. This class can be used in runtime or for the developer to define a new term."""
def __init__(self, options=Options(), **kw):
"""The initializer for the class receives a list of terms that the composed term is going to be bas... | stack_v2_sparse_classes_36k_train_031154 | 2,854 | no_license | [
{
"docstring": "The initializer for the class receives a list of terms that the composed term is going to be based in. It's used like: Composed_Term(diffusion = Galerking_Diffusion,...)",
"name": "__init__",
"signature": "def __init__(self, options=Options(), **kw)"
},
{
"docstring": "Handle the... | 4 | null | Implement the Python class `IFEM` described below.
Class description:
A class to create a term based on the basic terms. This class can be used in runtime or for the developer to define a new term.
Method signatures and docstrings:
- def __init__(self, options=Options(), **kw): The initializer for the class receives ... | Implement the Python class `IFEM` described below.
Class description:
A class to create a term based on the basic terms. This class can be used in runtime or for the developer to define a new term.
Method signatures and docstrings:
- def __init__(self, options=Options(), **kw): The initializer for the class receives ... | 66258b1669337f13cdb8d5bf48825e1f6dbfa294 | <|skeleton|>
class IFEM:
"""A class to create a term based on the basic terms. This class can be used in runtime or for the developer to define a new term."""
def __init__(self, options=Options(), **kw):
"""The initializer for the class receives a list of terms that the composed term is going to be bas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IFEM:
"""A class to create a term based on the basic terms. This class can be used in runtime or for the developer to define a new term."""
def __init__(self, options=Options(), **kw):
"""The initializer for the class receives a list of terms that the composed term is going to be based in. It's u... | the_stack_v2_python_sparse | NeuroCore/Equations/Composite/FEM.py | dabrunhosa/PhD_Program | train | 0 |
a1d27eb64efdca8c60bfd2875c5dc565b24c1f6f | [
"if '@' in username:\n kwargs = {'email': username}\nelse:\n kwargs = {'username': username}\ntry:\n user = User.objects.get(**kwargs)\n if user.check_password(password):\n return user\nexcept User.DoesNotExist:\n return None",
"try:\n return User.objects.get(pk=user_id)\nexcept User.Does... | <|body_start_0|>
if '@' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
except User.DoesNotExist:
... | Allows user to authenticate with username or email address. | EmailOrUsernameModelBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailOrUsernameModelBackend:
"""Allows user to authenticate with username or email address."""
def authenticate(cls, username=None, password=None):
"""Checks email or username."""
<|body_0|>
def get_user(cls, user_id):
"""Get user object by id."""
<|body_... | stack_v2_sparse_classes_36k_train_031155 | 998 | no_license | [
{
"docstring": "Checks email or username.",
"name": "authenticate",
"signature": "def authenticate(cls, username=None, password=None)"
},
{
"docstring": "Get user object by id.",
"name": "get_user",
"signature": "def get_user(cls, user_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020195 | Implement the Python class `EmailOrUsernameModelBackend` described below.
Class description:
Allows user to authenticate with username or email address.
Method signatures and docstrings:
- def authenticate(cls, username=None, password=None): Checks email or username.
- def get_user(cls, user_id): Get user object by i... | Implement the Python class `EmailOrUsernameModelBackend` described below.
Class description:
Allows user to authenticate with username or email address.
Method signatures and docstrings:
- def authenticate(cls, username=None, password=None): Checks email or username.
- def get_user(cls, user_id): Get user object by i... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class EmailOrUsernameModelBackend:
"""Allows user to authenticate with username or email address."""
def authenticate(cls, username=None, password=None):
"""Checks email or username."""
<|body_0|>
def get_user(cls, user_id):
"""Get user object by id."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailOrUsernameModelBackend:
"""Allows user to authenticate with username or email address."""
def authenticate(cls, username=None, password=None):
"""Checks email or username."""
if '@' in username:
kwargs = {'email': username}
else:
kwargs = {'username': ... | the_stack_v2_python_sparse | common/backends.py | wcirillo/ten | train | 0 |
8f1929cd23c7c935b303f55b4bdb2ca7937e7610 | [
"links = self.fetch_advisory_links('https://tomcat.apache.org/security')\nfor page_url in links:\n yield requests.get(page_url).content",
"data = requests.get(url).content\nsoup = BeautifulSoup(data, features='lxml')\nfor tag in soup.find_all('a'):\n link = tag.get('href')\n if link and 'security-' in li... | <|body_start_0|>
links = self.fetch_advisory_links('https://tomcat.apache.org/security')
for page_url in links:
yield requests.get(page_url).content
<|end_body_0|>
<|body_start_1|>
data = requests.get(url).content
soup = BeautifulSoup(data, features='lxml')
for tag i... | ApacheTomcatImporter | [
"Apache-2.0",
"CC-BY-SA-4.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApacheTomcatImporter:
def fetch_advisory_pages(self):
"""Yield the content of each HTML page containing version-related security data."""
<|body_0|>
def fetch_advisory_links(self, url):
"""Yield the URLs of each Tomcat version security-related page. Each page link is... | stack_v2_sparse_classes_36k_train_031156 | 19,740 | permissive | [
{
"docstring": "Yield the content of each HTML page containing version-related security data.",
"name": "fetch_advisory_pages",
"signature": "def fetch_advisory_pages(self)"
},
{
"docstring": "Yield the URLs of each Tomcat version security-related page. Each page link is in the form of `https://... | 4 | null | Implement the Python class `ApacheTomcatImporter` described below.
Class description:
Implement the ApacheTomcatImporter class.
Method signatures and docstrings:
- def fetch_advisory_pages(self): Yield the content of each HTML page containing version-related security data.
- def fetch_advisory_links(self, url): Yield... | Implement the Python class `ApacheTomcatImporter` described below.
Class description:
Implement the ApacheTomcatImporter class.
Method signatures and docstrings:
- def fetch_advisory_pages(self): Yield the content of each HTML page containing version-related security data.
- def fetch_advisory_links(self, url): Yield... | eec05bb0f796d743e408a1b402df8abfc8344669 | <|skeleton|>
class ApacheTomcatImporter:
def fetch_advisory_pages(self):
"""Yield the content of each HTML page containing version-related security data."""
<|body_0|>
def fetch_advisory_links(self, url):
"""Yield the URLs of each Tomcat version security-related page. Each page link is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApacheTomcatImporter:
def fetch_advisory_pages(self):
"""Yield the content of each HTML page containing version-related security data."""
links = self.fetch_advisory_links('https://tomcat.apache.org/security')
for page_url in links:
yield requests.get(page_url).content
... | the_stack_v2_python_sparse | vulnerabilities/importers/apache_tomcat.py | nexB/vulnerablecode | train | 371 | |
9566707095fed517fb2e60767227fc540e48e93d | [
"try:\n args = invite_user_arguments.parse_args()\n sender = args.sender\n to = args.to\n groupId = args.group\n try:\n if groupId is not None and User.exists(to):\n id = User.sendInvite(sender, to, groupId)\n if id[0] != -1:\n return make_response(jsonify(... | <|body_start_0|>
try:
args = invite_user_arguments.parse_args()
sender = args.sender
to = args.to
groupId = args.group
try:
if groupId is not None and User.exists(to):
id = User.sendInvite(sender, to, groupId)
... | Invites | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Invites:
def post(self):
"""Sends an invitation to the user"""
<|body_0|>
def get(self, username):
"""Gets invitations sent to the user passed as param"""
<|body_1|>
def put(self, username):
"""Accepts or refuses the invitation"""
<|body_... | stack_v2_sparse_classes_36k_train_031157 | 8,609 | no_license | [
{
"docstring": "Sends an invitation to the user",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Gets invitations sent to the user passed as param",
"name": "get",
"signature": "def get(self, username)"
},
{
"docstring": "Accepts or refuses the invitation",
... | 3 | stack_v2_sparse_classes_30k_test_000022 | Implement the Python class `Invites` described below.
Class description:
Implement the Invites class.
Method signatures and docstrings:
- def post(self): Sends an invitation to the user
- def get(self, username): Gets invitations sent to the user passed as param
- def put(self, username): Accepts or refuses the invit... | Implement the Python class `Invites` described below.
Class description:
Implement the Invites class.
Method signatures and docstrings:
- def post(self): Sends an invitation to the user
- def get(self, username): Gets invitations sent to the user passed as param
- def put(self, username): Accepts or refuses the invit... | 72ba34ce64482da23020d84a41819b889dad51f1 | <|skeleton|>
class Invites:
def post(self):
"""Sends an invitation to the user"""
<|body_0|>
def get(self, username):
"""Gets invitations sent to the user passed as param"""
<|body_1|>
def put(self, username):
"""Accepts or refuses the invitation"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Invites:
def post(self):
"""Sends an invitation to the user"""
try:
args = invite_user_arguments.parse_args()
sender = args.sender
to = args.to
groupId = args.group
try:
if groupId is not None and User.exists(to):
... | the_stack_v2_python_sparse | WakeOnLan-server/flask/api/namespaces/users_ns.py | DarioGar/WakeOnLan | train | 0 | |
a06b9283e02bf721dc19c904389708be3aa496aa | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods to retrieve information about disk types. | DiskTypeServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiskTypeServiceServicer:
"""A set of methods to retrieve information about disk types."""
def Get(self, request, context):
"""Returns the information about specified disk type. To get the list of available disk types, make a [List] request."""
<|body_0|>
def List(self, r... | stack_v2_sparse_classes_36k_train_031158 | 4,886 | permissive | [
{
"docstring": "Returns the information about specified disk type. To get the list of available disk types, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of disk types for the specified folder.",
"name": "List",
... | 2 | stack_v2_sparse_classes_30k_val_000925 | Implement the Python class `DiskTypeServiceServicer` described below.
Class description:
A set of methods to retrieve information about disk types.
Method signatures and docstrings:
- def Get(self, request, context): Returns the information about specified disk type. To get the list of available disk types, make a [L... | Implement the Python class `DiskTypeServiceServicer` described below.
Class description:
A set of methods to retrieve information about disk types.
Method signatures and docstrings:
- def Get(self, request, context): Returns the information about specified disk type. To get the list of available disk types, make a [L... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class DiskTypeServiceServicer:
"""A set of methods to retrieve information about disk types."""
def Get(self, request, context):
"""Returns the information about specified disk type. To get the list of available disk types, make a [List] request."""
<|body_0|>
def List(self, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiskTypeServiceServicer:
"""A set of methods to retrieve information about disk types."""
def Get(self, request, context):
"""Returns the information about specified disk type. To get the list of available disk types, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTE... | the_stack_v2_python_sparse | yandex/cloud/compute/v1/disk_type_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
ce5ecb505a6b9d2d505c89b31e8c74f1f7e32794 | [
"self.snmp_target = snmp_target\nself.snmp_port = snmp_port\nself.verbosity = verbosity\nself.peer = '{}:{}'.format(self.snmp_target, snmp_port)",
"cmdGen = cmdgen.CommandGenerator()\ntry:\n errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(cmdgen.CommunityData(community_string, mpModel=versio... | <|body_start_0|>
self.snmp_target = snmp_target
self.snmp_port = snmp_port
self.verbosity = verbosity
self.peer = '{}:{}'.format(self.snmp_target, snmp_port)
<|end_body_0|>
<|body_start_1|>
cmdGen = cmdgen.CommandGenerator()
try:
errorIndication, errorStatus,... | SNMP Client provides methods to handle communication with SNMP server | SNMPCli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SNMPCli:
"""SNMP Client provides methods to handle communication with SNMP server"""
def __init__(self, snmp_target: str, snmp_port: int, verbosity: bool=False) -> None:
"""SNMP client constructor :param str snmp_target: target SNMP server ip address :param port snmp_port: target SNM... | stack_v2_sparse_classes_36k_train_031159 | 2,853 | permissive | [
{
"docstring": "SNMP client constructor :param str snmp_target: target SNMP server ip address :param port snmp_port: target SNMP server port :param bool verbosity: display verbose output :return None:",
"name": "__init__",
"signature": "def __init__(self, snmp_target: str, snmp_port: int, verbosity: boo... | 2 | null | Implement the Python class `SNMPCli` described below.
Class description:
SNMP Client provides methods to handle communication with SNMP server
Method signatures and docstrings:
- def __init__(self, snmp_target: str, snmp_port: int, verbosity: bool=False) -> None: SNMP client constructor :param str snmp_target: target... | Implement the Python class `SNMPCli` described below.
Class description:
SNMP Client provides methods to handle communication with SNMP server
Method signatures and docstrings:
- def __init__(self, snmp_target: str, snmp_port: int, verbosity: bool=False) -> None: SNMP client constructor :param str snmp_target: target... | 56ae6325c08bcedd22c57b9fe11b58f1b38314ca | <|skeleton|>
class SNMPCli:
"""SNMP Client provides methods to handle communication with SNMP server"""
def __init__(self, snmp_target: str, snmp_port: int, verbosity: bool=False) -> None:
"""SNMP client constructor :param str snmp_target: target SNMP server ip address :param port snmp_port: target SNM... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SNMPCli:
"""SNMP Client provides methods to handle communication with SNMP server"""
def __init__(self, snmp_target: str, snmp_port: int, verbosity: bool=False) -> None:
"""SNMP client constructor :param str snmp_target: target SNMP server ip address :param port snmp_port: target SNMP server port... | the_stack_v2_python_sparse | maza/core/snmp/snmp_client.py | ArturSpirin/maza | train | 2 |
5922d5e60a25afa90560123d121796bf0ff523c7 | [
"try:\n return ParameterSetting.objects.get(base_parameter=instance, project=self.context.get('view').kwargs.get('project')).raw_value\nexcept ParameterSetting.DoesNotExist:\n return None",
"if instance.type == BaseParameter.CHOICE_TYPE:\n return [x.value for x in instance.get_typed_parameter().get_avail... | <|body_start_0|>
try:
return ParameterSetting.objects.get(base_parameter=instance, project=self.context.get('view').kwargs.get('project')).raw_value
except ParameterSetting.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
if instance.type == BaseParameter.CHOICE... | Serializer for Parameter model. | ParameterSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterSerializer:
"""Serializer for Parameter model."""
def get_value(self, instance):
"""Get the value of the ParameterSetting belonging to the Parameter."""
<|body_0|>
def get_choices(self, instance):
"""Get choices corresponding to Choice parameter."""
... | stack_v2_sparse_classes_36k_train_031160 | 6,038 | no_license | [
{
"docstring": "Get the value of the ParameterSetting belonging to the Parameter.",
"name": "get_value",
"signature": "def get_value(self, instance)"
},
{
"docstring": "Get choices corresponding to Choice parameter.",
"name": "get_choices",
"signature": "def get_choices(self, instance)"
... | 3 | stack_v2_sparse_classes_30k_train_020626 | Implement the Python class `ParameterSerializer` described below.
Class description:
Serializer for Parameter model.
Method signatures and docstrings:
- def get_value(self, instance): Get the value of the ParameterSetting belonging to the Parameter.
- def get_choices(self, instance): Get choices corresponding to Choi... | Implement the Python class `ParameterSerializer` described below.
Class description:
Serializer for Parameter model.
Method signatures and docstrings:
- def get_value(self, instance): Get the value of the ParameterSetting belonging to the Parameter.
- def get_choices(self, instance): Get choices corresponding to Choi... | dfa60c9a812e52fa44f0d3cf1c201943574976df | <|skeleton|>
class ParameterSerializer:
"""Serializer for Parameter model."""
def get_value(self, instance):
"""Get the value of the ParameterSetting belonging to the Parameter."""
<|body_0|>
def get_choices(self, instance):
"""Get choices corresponding to Choice parameter."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterSerializer:
"""Serializer for Parameter model."""
def get_value(self, instance):
"""Get the value of the ParameterSetting belonging to the Parameter."""
try:
return ParameterSetting.objects.get(base_parameter=instance, project=self.context.get('view').kwargs.get('proj... | the_stack_v2_python_sparse | equestria/processes/api/v1/serializers.py | KiOui/CLST-2020 | train | 0 |
5514f14a802e561780fb03a9718b9af8c2133e14 | [
"likelihood_source = config.get_string(option_section, 'likelihood_source', '')\nif likelihood_source == '':\n likelihood_source = config[option_section, 'firecrown_config']\nrequire_nonlinear_pk = config.get_bool(option_section, 'require_nonlinear_pk', False)\nbuild_parameters = extract_section(config, option_s... | <|body_start_0|>
likelihood_source = config.get_string(option_section, 'likelihood_source', '')
if likelihood_source == '':
likelihood_source = config[option_section, 'firecrown_config']
require_nonlinear_pk = config.get_bool(option_section, 'require_nonlinear_pk', False)
bui... | CosmoSIS likelihood module for calculating Firecrown likelihood. In this simplest implementation, we have only a single module. This module is responsible for calling CCL to perform theory calculations, based on the output of CAMB, and also for calculating the data likelihood based on this theory. :param config: curren... | FirecrownLikelihood | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirecrownLikelihood:
"""CosmoSIS likelihood module for calculating Firecrown likelihood. In this simplest implementation, we have only a single module. This module is responsible for calling CCL to perform theory calculations, based on the output of CAMB, and also for calculating the data likelih... | stack_v2_sparse_classes_36k_train_031161 | 7,360 | permissive | [
{
"docstring": "Create the FirecrownLikelihood object from the given configuration.",
"name": "__init__",
"signature": "def __init__(self, config: cosmosis.datablock)"
},
{
"docstring": "This is the method called for each sample generated by the sampler.",
"name": "execute",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_019423 | Implement the Python class `FirecrownLikelihood` described below.
Class description:
CosmoSIS likelihood module for calculating Firecrown likelihood. In this simplest implementation, we have only a single module. This module is responsible for calling CCL to perform theory calculations, based on the output of CAMB, an... | Implement the Python class `FirecrownLikelihood` described below.
Class description:
CosmoSIS likelihood module for calculating Firecrown likelihood. In this simplest implementation, we have only a single module. This module is responsible for calling CCL to perform theory calculations, based on the output of CAMB, an... | 8b2ce0d218751cc622759441bfe8d1063a49f35f | <|skeleton|>
class FirecrownLikelihood:
"""CosmoSIS likelihood module for calculating Firecrown likelihood. In this simplest implementation, we have only a single module. This module is responsible for calling CCL to perform theory calculations, based on the output of CAMB, and also for calculating the data likelih... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirecrownLikelihood:
"""CosmoSIS likelihood module for calculating Firecrown likelihood. In this simplest implementation, we have only a single module. This module is responsible for calling CCL to perform theory calculations, based on the output of CAMB, and also for calculating the data likelihood based on ... | the_stack_v2_python_sparse | firecrown/connector/cosmosis/likelihood.py | LSSTDESC/firecrown | train | 26 |
40b3ef854f76eb9f8f06d629f60acf07286e1e0d | [
"def dfs(cur: int, pre: int, v1: int, v2: int, d: int) -> int:\n count = 1\n for next in adjList[cur]:\n if next != pre:\n if (dist[v1][next] < d or (dist[v1][next] == d and next > v2)) and (dist[v2][next] < d or (dist[v2][next] == d and next > v1)):\n count *= dfs(next, cur, ... | <|body_start_0|>
def dfs(cur: int, pre: int, v1: int, v2: int, d: int) -> int:
count = 1
for next in adjList[cur]:
if next != pre:
if (dist[v1][next] < d or (dist[v1][next] == d and next > v2)) and (dist[v2][next] < d or (dist[v2][next] == d and next >... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
"""O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-sub... | stack_v2_sparse_classes_36k_train_031162 | 7,378 | no_license | [
{
"docstring": "O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/shi-xian-hen-jian-dan-yuan-li-lue-you-xie-fu-za-de/",
"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-citi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-citi... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
"""O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-sub... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:
"""O(n^3)枚举直径端点+乘法原理 https://leetcode.cn/problems/count-subtrees-with-max-distance-between-cities/solution/tu-jie-on3-mei-ju-zhi-jing-duan-dian-che-am2n/ https://leetcode.cn/problems/count-subtrees-with-max... | the_stack_v2_python_sparse | 7_graph/带权图最短路和最小生成树/floyd多源/1617. 统计子树中城市之间最大距离.py | 981377660LMT/algorithm-study | train | 225 | |
5e85f509df1cf3df89e54b79b58fa7c7cd5f7fa7 | [
"super(SQLTableIdentifier, self).__init__()\nself.name = name\nself.row_identifier = row_identifier",
"if self.name is not None and self.row_identifier is not None:\n return '{0:s}.{1:d}'.format(self.name, self.row_identifier)\nreturn None"
] | <|body_start_0|>
super(SQLTableIdentifier, self).__init__()
self.name = name
self.row_identifier = row_identifier
<|end_body_0|>
<|body_start_1|>
if self.name is not None and self.row_identifier is not None:
return '{0:s}.{1:d}'.format(self.name, self.row_identifier)
... | SQL table attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a SQLite database file. Attributes: name (str): name of the table. row_identifier (int): unique identifier of the row in the table. | SQLTableIdentifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLTableIdentifier:
"""SQL table attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a SQLite database file. Attributes: name (str): name of the table. row_identifier (int... | stack_v2_sparse_classes_36k_train_031163 | 4,240 | permissive | [
{
"docstring": "Initializes a SQL table attribute container identifier. Args: name (str): name of the table. row_identifier (int): unique identifier of the row in the table.",
"name": "__init__",
"signature": "def __init__(self, name, row_identifier)"
},
{
"docstring": "Copies the identifier to ... | 2 | null | Implement the Python class `SQLTableIdentifier` described below.
Class description:
SQL table attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a SQLite database file. Attributes: name (str):... | Implement the Python class `SQLTableIdentifier` described below.
Class description:
SQL table attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a SQLite database file. Attributes: name (str):... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class SQLTableIdentifier:
"""SQL table attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a SQLite database file. Attributes: name (str): name of the table. row_identifier (int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLTableIdentifier:
"""SQL table attribute container identifier. The identifier is used to uniquely identify attribute containers. Where for example an attribute container is stored as a JSON serialized data in a SQLite database file. Attributes: name (str): name of the table. row_identifier (int): unique ide... | the_stack_v2_python_sparse | plaso/storage/identifiers.py | cyb3rfox/plaso | train | 3 |
0800c4305b83ed8a597e5c257d6492c5ad238238 | [
"self.space = space\nself.subspace = subspace\nmesh = space.mesh()\ndegree = space.ufl_element().degree()\nif space.ufl_element().sobolev_space().name != 'L2' or ((type(degree) is tuple and np.any([deg != 1 for deg in degree])) and degree != 1):\n raise ValueError('DG1 limiter can only be applied to DG1 space')\... | <|body_start_0|>
self.space = space
self.subspace = subspace
mesh = space.mesh()
degree = space.ufl_element().degree()
if space.ufl_element().sobolev_space().name != 'L2' or ((type(degree) is tuple and np.any([deg != 1 for deg in degree])) and degree != 1):
raise Valu... | A vertex-based limiter for the degree 1 discontinuous Galerkin space. A vertex based limiter for fields in the DG1 space. This wraps around the vertex-based limiter implemented in Firedrake, but ensures that this is done in the space using the appropriate "equispaced" elements. | DG1Limiter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DG1Limiter:
"""A vertex-based limiter for the degree 1 discontinuous Galerkin space. A vertex based limiter for fields in the DG1 space. This wraps around the vertex-based limiter implemented in Firedrake, but ensures that this is done in the space using the appropriate "equispaced" elements."""
... | stack_v2_sparse_classes_36k_train_031164 | 7,242 | permissive | [
{
"docstring": "Args: space (:class:`FunctionSpace`): the space in which the transported variables lies. It should be the DG1 space, or a mixed function space containing the DG1 space. subspace (int, optional): specifies that the limiter works on this component of a :class:`MixedFunctionSpace`. Raises: ValueErr... | 2 | stack_v2_sparse_classes_30k_test_000196 | Implement the Python class `DG1Limiter` described below.
Class description:
A vertex-based limiter for the degree 1 discontinuous Galerkin space. A vertex based limiter for fields in the DG1 space. This wraps around the vertex-based limiter implemented in Firedrake, but ensures that this is done in the space using the... | Implement the Python class `DG1Limiter` described below.
Class description:
A vertex-based limiter for the degree 1 discontinuous Galerkin space. A vertex based limiter for fields in the DG1 space. This wraps around the vertex-based limiter implemented in Firedrake, but ensures that this is done in the space using the... | ab93672a84d4a71019abad4249529403e4b0c8d7 | <|skeleton|>
class DG1Limiter:
"""A vertex-based limiter for the degree 1 discontinuous Galerkin space. A vertex based limiter for fields in the DG1 space. This wraps around the vertex-based limiter implemented in Firedrake, but ensures that this is done in the space using the appropriate "equispaced" elements."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DG1Limiter:
"""A vertex-based limiter for the degree 1 discontinuous Galerkin space. A vertex based limiter for fields in the DG1 space. This wraps around the vertex-based limiter implemented in Firedrake, but ensures that this is done in the space using the appropriate "equispaced" elements."""
def __in... | the_stack_v2_python_sparse | gusto/limiters.py | firedrakeproject/gusto | train | 10 |
505bdbc5051899409c5705d3b571bf3e7d806e50 | [
"for subclass in cls.__subclasses__():\n yield from subclass.get_all_subclasses()\n yield subclass",
"result = None\nfor subclass in cls.get_all_subclasses():\n if subclass.__name__.lower() == class_name.lower():\n if result is None:\n result = subclass\n else:\n raise... | <|body_start_0|>
for subclass in cls.__subclasses__():
yield from subclass.get_all_subclasses()
yield subclass
<|end_body_0|>
<|body_start_1|>
result = None
for subclass in cls.get_all_subclasses():
if subclass.__name__.lower() == class_name.lower():
... | 用于动态加载枚举类 | LoadEnumInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadEnumInterface:
"""用于动态加载枚举类"""
def get_all_subclasses(cls) -> Iterable[Any]:
"""Return a generator of all subclasses"""
<|body_0|>
def load_class(cls, class_name) -> Any:
"""Return a subclass of ``class_name``, case insensitively :param cls_name (str): target... | stack_v2_sparse_classes_36k_train_031165 | 2,732 | no_license | [
{
"docstring": "Return a generator of all subclasses",
"name": "get_all_subclasses",
"signature": "def get_all_subclasses(cls) -> Iterable[Any]"
},
{
"docstring": "Return a subclass of ``class_name``, case insensitively :param cls_name (str): target class name :return:",
"name": "load_class"... | 2 | stack_v2_sparse_classes_30k_train_005864 | Implement the Python class `LoadEnumInterface` described below.
Class description:
用于动态加载枚举类
Method signatures and docstrings:
- def get_all_subclasses(cls) -> Iterable[Any]: Return a generator of all subclasses
- def load_class(cls, class_name) -> Any: Return a subclass of ``class_name``, case insensitively :param c... | Implement the Python class `LoadEnumInterface` described below.
Class description:
用于动态加载枚举类
Method signatures and docstrings:
- def get_all_subclasses(cls) -> Iterable[Any]: Return a generator of all subclasses
- def load_class(cls, class_name) -> Any: Return a subclass of ``class_name``, case insensitively :param c... | a07087a77d6e0c7eeb0a7b4da23baac9bbbfb3d6 | <|skeleton|>
class LoadEnumInterface:
"""用于动态加载枚举类"""
def get_all_subclasses(cls) -> Iterable[Any]:
"""Return a generator of all subclasses"""
<|body_0|>
def load_class(cls, class_name) -> Any:
"""Return a subclass of ``class_name``, case insensitively :param cls_name (str): target... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadEnumInterface:
"""用于动态加载枚举类"""
def get_all_subclasses(cls) -> Iterable[Any]:
"""Return a generator of all subclasses"""
for subclass in cls.__subclasses__():
yield from subclass.get_all_subclasses()
yield subclass
def load_class(cls, class_name) -> Any:
... | the_stack_v2_python_sparse | novela/_utils/metaclass.py | Zessay/novel_analysis | train | 2 |
6fa5383f2cfa65f72482de72e3e17786a030b1f5 | [
"assert os.path.exists(filepath), \"Can't file file at path {}\".format(filepath)\nwb = load_workbook(filepath, data_only=True, read_only=True)\ndata = [(name, cls.extract_sheet(wb, name)) for name in wb.sheetnames]\nwb.close()\nreturn data",
"ws = wb[name]\n_ = lambda x: x.strip() if strip and hasattr(x, 'strip'... | <|body_start_0|>
assert os.path.exists(filepath), "Can't file file at path {}".format(filepath)
wb = load_workbook(filepath, data_only=True, read_only=True)
data = [(name, cls.extract_sheet(wb, name)) for name in wb.sheetnames]
wb.close()
return data
<|end_body_0|>
<|body_start_... | A class used to extract data from an Excel file. Parameters ---------- object : type The parent object for the ExcelExtractor class. Returns ------- object An instance of the class. See Also -------- openpyxl.load_workbook : Load a workbook from a file. Notes ----- This class requires the openpyxl package to be install... | ExcelExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelExtractor:
"""A class used to extract data from an Excel file. Parameters ---------- object : type The parent object for the ExcelExtractor class. Returns ------- object An instance of the class. See Also -------- openpyxl.load_workbook : Load a workbook from a file. Notes ----- This class r... | stack_v2_sparse_classes_36k_train_031166 | 3,547 | permissive | [
{
"docstring": "Extract data from an Excel file. Parameters ---------- filepath : str The path to the Excel file. Returns ------- list A list of tuples containing the name of each sheet in the file and the data from each sheet. Raises ------ AssertionError If the file at 'filepath' does not exist.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_012842 | Implement the Python class `ExcelExtractor` described below.
Class description:
A class used to extract data from an Excel file. Parameters ---------- object : type The parent object for the ExcelExtractor class. Returns ------- object An instance of the class. See Also -------- openpyxl.load_workbook : Load a workboo... | Implement the Python class `ExcelExtractor` described below.
Class description:
A class used to extract data from an Excel file. Parameters ---------- object : type The parent object for the ExcelExtractor class. Returns ------- object An instance of the class. See Also -------- openpyxl.load_workbook : Load a workboo... | 0c3c7288a897f57511ce17a6be1698e2cb9b08a1 | <|skeleton|>
class ExcelExtractor:
"""A class used to extract data from an Excel file. Parameters ---------- object : type The parent object for the ExcelExtractor class. Returns ------- object An instance of the class. See Also -------- openpyxl.load_workbook : Load a workbook from a file. Notes ----- This class r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcelExtractor:
"""A class used to extract data from an Excel file. Parameters ---------- object : type The parent object for the ExcelExtractor class. Returns ------- object An instance of the class. See Also -------- openpyxl.load_workbook : Load a workbook from a file. Notes ----- This class requires the o... | the_stack_v2_python_sparse | bw2io/extractors/excel.py | brightway-lca/brightway2-io | train | 13 |
2ed6e026e6178a8ab56ed028ff342fb59747ffce | [
"self.product = kwargs.pop('product')\nsuper().__init__(*args, **kwargs)\nself.initial.update(self.get_initial())",
"initial = {}\ninitial['product_id'] = self.product.pk\ninitial['range_order'] = self.product.range_order\nreturn initial",
"data = self.cleaned_data\nproduct = get_object_or_404(models.Product, p... | <|body_start_0|>
self.product = kwargs.pop('product')
super().__init__(*args, **kwargs)
self.initial.update(self.get_initial())
<|end_body_0|>
<|body_start_1|>
initial = {}
initial['product_id'] = self.product.pk
initial['range_order'] = self.product.range_order
... | Form for setting the order of products within a range. | ProductOrderForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductOrderForm:
"""Form for setting the order of products within a range."""
def __init__(self, *args, **kwargs):
"""Add product to the form."""
<|body_0|>
def get_initial(self):
"""Return initial data."""
<|body_1|>
def save(self):
"""Upda... | stack_v2_sparse_classes_36k_train_031167 | 1,310 | no_license | [
{
"docstring": "Add product to the form.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Return initial data.",
"name": "get_initial",
"signature": "def get_initial(self)"
},
{
"docstring": "Update the order of products.",
"name": "... | 3 | null | Implement the Python class `ProductOrderForm` described below.
Class description:
Form for setting the order of products within a range.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add product to the form.
- def get_initial(self): Return initial data.
- def save(self): Update the order of... | Implement the Python class `ProductOrderForm` described below.
Class description:
Form for setting the order of products within a range.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Add product to the form.
- def get_initial(self): Return initial data.
- def save(self): Update the order of... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class ProductOrderForm:
"""Form for setting the order of products within a range."""
def __init__(self, *args, **kwargs):
"""Add product to the form."""
<|body_0|>
def get_initial(self):
"""Return initial data."""
<|body_1|>
def save(self):
"""Upda... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductOrderForm:
"""Form for setting the order of products within a range."""
def __init__(self, *args, **kwargs):
"""Add product to the form."""
self.product = kwargs.pop('product')
super().__init__(*args, **kwargs)
self.initial.update(self.get_initial())
def get_in... | the_stack_v2_python_sparse | inventory/forms/product_order.py | stcstores/stcadmin | train | 0 |
2e4425708b5b83bcb5a806ae0f01bfee33d19fe6 | [
"super(ClusterDeploymentConfigs, self).__init__()\nself.log = logger.setup_logging(self.__class__.__name__)\nself.schema_class = 'cluster_deployment_configs_schema.ClusterDeploymentConfigsSchema'\nself.set_connection(service.get_connection())\nself.create_endpoint = 'si/deploy'\nself.delete_endpoint = 'si/deploy/' ... | <|body_start_0|>
super(ClusterDeploymentConfigs, self).__init__()
self.log = logger.setup_logging(self.__class__.__name__)
self.schema_class = 'cluster_deployment_configs_schema.ClusterDeploymentConfigsSchema'
self.set_connection(service.get_connection())
self.create_endpoint = '... | ClusterDeploymentConfigs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterDeploymentConfigs:
def __init__(self, service=None):
"""Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured"""
<|body_0|>
def delete(self, schema_object=None):
"""Over riding delete met... | stack_v2_sparse_classes_36k_train_031168 | 1,442 | no_license | [
{
"docstring": "Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured",
"name": "__init__",
"signature": "def __init__(self, service=None)"
},
{
"docstring": "Over riding delete method to perform DELETE operation",
"nam... | 2 | stack_v2_sparse_classes_30k_train_002821 | Implement the Python class `ClusterDeploymentConfigs` described below.
Class description:
Implement the ClusterDeploymentConfigs class.
Method signatures and docstrings:
- def __init__(self, service=None): Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to... | Implement the Python class `ClusterDeploymentConfigs` described below.
Class description:
Implement the ClusterDeploymentConfigs class.
Method signatures and docstrings:
- def __init__(self, service=None): Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class ClusterDeploymentConfigs:
def __init__(self, service=None):
"""Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured"""
<|body_0|>
def delete(self, schema_object=None):
"""Over riding delete met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterDeploymentConfigs:
def __init__(self, service=None):
"""Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured"""
super(ClusterDeploymentConfigs, self).__init__()
self.log = logger.setup_logging(self.__class... | the_stack_v2_python_sparse | SystemTesting/pylib/nsx/vsm/service_insertion/cluster_deployment_configs.py | Cloudxtreme/MyProject | train | 0 | |
8015a76dd6a164cd17806e3f73cc400aae743b9a | [
"redirect_uri = self._OAUTH_REDIRECT_URL\nif self.get_argument('code', False):\n self.get_authenticated_user(redirect_uri=redirect_uri, client_id=AMGUT_CONFIG.open_humans_client_id, client_secret=AMGUT_CONFIG.open_humans_client_secret, code=self.get_argument('code'), callback=self._on_login_cb)\nelse:\n extra... | <|body_start_0|>
redirect_uri = self._OAUTH_REDIRECT_URL
if self.get_argument('code', False):
self.get_authenticated_user(redirect_uri=redirect_uri, client_id=AMGUT_CONFIG.open_humans_client_id, client_secret=AMGUT_CONFIG.open_humans_client_secret, code=self.get_argument('code'), callback=se... | Handles the OAuth2 connection to Open Humans. | OpenHumansLoginHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenHumansLoginHandler:
"""Handles the OAuth2 connection to Open Humans."""
def get(self):
"""Display the Open Humans connection page."""
<|body_0|>
def _on_login_cb(self, user):
"""Handle the user object from the login request."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_031169 | 6,708 | permissive | [
{
"docstring": "Display the Open Humans connection page.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Handle the user object from the login request.",
"name": "_on_login_cb",
"signature": "def _on_login_cb(self, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001762 | Implement the Python class `OpenHumansLoginHandler` described below.
Class description:
Handles the OAuth2 connection to Open Humans.
Method signatures and docstrings:
- def get(self): Display the Open Humans connection page.
- def _on_login_cb(self, user): Handle the user object from the login request. | Implement the Python class `OpenHumansLoginHandler` described below.
Class description:
Handles the OAuth2 connection to Open Humans.
Method signatures and docstrings:
- def get(self): Display the Open Humans connection page.
- def _on_login_cb(self, user): Handle the user object from the login request.
<|skeleton|>... | 0edf4fd621b04d1de8768ed154864825904d0638 | <|skeleton|>
class OpenHumansLoginHandler:
"""Handles the OAuth2 connection to Open Humans."""
def get(self):
"""Display the Open Humans connection page."""
<|body_0|>
def _on_login_cb(self, user):
"""Handle the user object from the login request."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenHumansLoginHandler:
"""Handles the OAuth2 connection to Open Humans."""
def get(self):
"""Display the Open Humans connection page."""
redirect_uri = self._OAUTH_REDIRECT_URL
if self.get_argument('code', False):
self.get_authenticated_user(redirect_uri=redirect_uri,... | the_stack_v2_python_sparse | amgut/handlers/open_humans.py | biocore/american-gut-web | train | 5 |
26072f407e089cb7a4f607f4a260f6d854ce2d5f | [
"s = sampling_class(threshold=100, eps=0.1, delta=1.0 / FAILURE_PROBABILITY_INVERSE, sampling_method=sampling_method)\ns.process(1, 1)\nself.assertEmpty(s.elements)",
"sampling_method, threshold = sampling_method_and_threshold\ndistance_from_half = 0.01\nn = int(6.0 / distance_from_half ** 2 * math.log(2 * FAILUR... | <|body_start_0|>
s = sampling_class(threshold=100, eps=0.1, delta=1.0 / FAILURE_PROBABILITY_INVERSE, sampling_method=sampling_method)
s.process(1, 1)
self.assertEmpty(s.elements)
<|end_body_0|>
<|body_start_1|>
sampling_method, threshold = sampling_method_and_threshold
distance_... | Tests for the private threshold sampling classes. | PrivateThresholdSampleTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrivateThresholdSampleTest:
"""Tests for the private threshold sampling classes."""
def test_low_delta_weight_one_not_sampled(self, sampling_class, sampling_method):
"""Checks that for very low delta, an element with weight 1 is not sampled. The motivation for that test is that the p... | stack_v2_sparse_classes_36k_train_031170 | 15,491 | permissive | [
{
"docstring": "Checks that for very low delta, an element with weight 1 is not sampled. The motivation for that test is that the probability of including a key with weight 1 in a private sample can be at most delta (even if the threshold is high and without privacy the key is supposed to be included with high ... | 5 | stack_v2_sparse_classes_30k_train_012569 | Implement the Python class `PrivateThresholdSampleTest` described below.
Class description:
Tests for the private threshold sampling classes.
Method signatures and docstrings:
- def test_low_delta_weight_one_not_sampled(self, sampling_class, sampling_method): Checks that for very low delta, an element with weight 1 i... | Implement the Python class `PrivateThresholdSampleTest` described below.
Class description:
Tests for the private threshold sampling classes.
Method signatures and docstrings:
- def test_low_delta_weight_one_not_sampled(self, sampling_class, sampling_method): Checks that for very low delta, an element with weight 1 i... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class PrivateThresholdSampleTest:
"""Tests for the private threshold sampling classes."""
def test_low_delta_weight_one_not_sampled(self, sampling_class, sampling_method):
"""Checks that for very low delta, an element with weight 1 is not sampled. The motivation for that test is that the p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrivateThresholdSampleTest:
"""Tests for the private threshold sampling classes."""
def test_low_delta_weight_one_not_sampled(self, sampling_class, sampling_method):
"""Checks that for very low delta, an element with weight 1 is not sampled. The motivation for that test is that the probability of... | the_stack_v2_python_sparse | private_sampling/private_sampling_test.py | Jimmy-INL/google-research | train | 1 |
aef4684aa0a78c136e357c62ad0a1623a244d660 | [
"with tables(db.engine, 'vcfs') as (con, runs):\n q = select(runs.c).order_by(desc(runs.c.id))\n return [dict(r) for r in q.execute().fetchall()]",
"run = request.validated_body\ntry:\n expect_one_of(request.validated_body, 'project_name', 'project_id')\nexcept voluptuous.MultipleInvalid as e:\n error... | <|body_start_0|>
with tables(db.engine, 'vcfs') as (con, runs):
q = select(runs.c).order_by(desc(runs.c.id))
return [dict(r) for r in q.execute().fetchall()]
<|end_body_0|>
<|body_start_1|>
run = request.validated_body
try:
expect_one_of(request.validated_bod... | RunList | [
"Apache-2.0",
"CC-BY-3.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunList:
def get(self):
"""Get list of all runs in order of recency."""
<|body_0|>
def post(self):
"""Create a new run. This will import the VCF's genotypes into the database in a worker, as well as annotate it with gene names."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_031171 | 7,342 | permissive | [
{
"docstring": "Get list of all runs in order of recency.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new run. This will import the VCF's genotypes into the database in a worker, as well as annotate it with gene names.",
"name": "post",
"signature": "def pos... | 2 | stack_v2_sparse_classes_30k_train_003471 | Implement the Python class `RunList` described below.
Class description:
Implement the RunList class.
Method signatures and docstrings:
- def get(self): Get list of all runs in order of recency.
- def post(self): Create a new run. This will import the VCF's genotypes into the database in a worker, as well as annotate... | Implement the Python class `RunList` described below.
Class description:
Implement the RunList class.
Method signatures and docstrings:
- def get(self): Get list of all runs in order of recency.
- def post(self): Create a new run. This will import the VCF's genotypes into the database in a worker, as well as annotate... | a436c4fc212e4429fb5196a9a4d36c37bd050c52 | <|skeleton|>
class RunList:
def get(self):
"""Get list of all runs in order of recency."""
<|body_0|>
def post(self):
"""Create a new run. This will import the VCF's genotypes into the database in a worker, as well as annotate it with gene names."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunList:
def get(self):
"""Get list of all runs in order of recency."""
with tables(db.engine, 'vcfs') as (con, runs):
q = select(runs.c).order_by(desc(runs.c.id))
return [dict(r) for r in q.execute().fetchall()]
def post(self):
"""Create a new run. This wi... | the_stack_v2_python_sparse | cycledash/api/runs.py | haoziyeung/cycledash | train | 0 | |
2002a2cb97c69129b4ac16445eee3d9be3f38a2e | [
"attrs = attrs or []\nself.attrs = list(attrs)\nif ORTH in self.attrs:\n self.attrs.pop(ORTH)\nif SPACY in self.attrs:\n self.attrs.pop(SPACY)\nself.attrs.insert(0, ORTH)\nself.tokens = []\nself.spaces = []\nself.strings = set()",
"array = doc.to_array(self.attrs)\nif len(array.shape) == 1:\n array = arr... | <|body_start_0|>
attrs = attrs or []
self.attrs = list(attrs)
if ORTH in self.attrs:
self.attrs.pop(ORTH)
if SPACY in self.attrs:
self.attrs.pop(SPACY)
self.attrs.insert(0, ORTH)
self.tokens = []
self.spaces = []
self.strings = set(... | Serialize analyses from a collection of doc objects. | Binder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binder:
"""Serialize analyses from a collection of doc objects."""
def __init__(self, attrs=None):
"""Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to ... | stack_v2_sparse_classes_36k_train_031172 | 4,226 | permissive | [
{
"docstring": "Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to None.",
"name": "__init__",
"signature": "def __init__(self, attrs=None)"
},
{
"docstring": "Add a... | 6 | stack_v2_sparse_classes_30k_train_001653 | Implement the Python class `Binder` described below.
Class description:
Serialize analyses from a collection of doc objects.
Method signatures and docstrings:
- def __init__(self, attrs=None): Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are... | Implement the Python class `Binder` described below.
Class description:
Serialize analyses from a collection of doc objects.
Method signatures and docstrings:
- def __init__(self, attrs=None): Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are... | a062c118f12b93172e31e8ca115ce3f871b64461 | <|skeleton|>
class Binder:
"""Serialize analyses from a collection of doc objects."""
def __init__(self, attrs=None):
"""Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binder:
"""Serialize analyses from a collection of doc objects."""
def __init__(self, attrs=None):
"""Create a Binder object, to hold serialized annotations. attrs (list): List of attributes to serialize. 'orth' and 'spacy' are always serialized, so they're not required. Defaults to None."""
... | the_stack_v2_python_sparse | python/spaCy/2018/12/_serialize.py | rosoareslv/SED99 | train | 1 |
6440171fe35623d249abf8fe8af270cd9eaf469e | [
"if not root:\n self.smallest = None\n return\nself.stack = []\ncurrent = root\nwhile current is not None:\n self.stack.append(current)\n current = current.left\nself.smallest = self.stack[-1]",
"if self.smallest is not None:\n return True\nelse:\n return False",
"current = self.smallest\nresu... | <|body_start_0|>
if not root:
self.smallest = None
return
self.stack = []
current = root
while current is not None:
self.stack.append(current)
current = current.left
self.smallest = self.stack[-1]
<|end_body_0|>
<|body_start_1|>
... | 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|>
if not root:
... | stack_v2_sparse_classes_36k_train_031173 | 2,077 | 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 | stack_v2_sparse_classes_30k_val_000445 | 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... | fcf6c3d5d60d13706950247d8a2327adc5faf17e | <|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"""
if not root:
self.smallest = None
return
self.stack = []
current = root
while current is not None:
self.stack.append(current)
current = current.left
... | the_stack_v2_python_sparse | Medium/BinarySearchTreeIterator.py | mangalagb/Leetcode | train | 0 | |
7b8de9e1db1ee5d28edc2808b2d6a62cfa656588 | [
"self.target_height = target_height\nself.margin = margin\nself.upper = target_height + margin\nself.lower = target_height - margin",
"above = 2\ngood = 1\nbelow = 0\nif cur_height < self.lower:\n return below\nif cur_height > self.upper:\n return above\nreturn good",
"def decide_level(current_height):\n ... | <|body_start_0|>
self.target_height = target_height
self.margin = margin
self.upper = target_height + margin
self.lower = target_height - margin
<|end_body_0|>
<|body_start_1|>
above = 2
good = 1
below = 0
if cur_height < self.lower:
return be... | Encapsulates decision making in the water-regulation module | Decider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decider:
"""Encapsulates decision making in the water-regulation module"""
def __init__(self, target_height, margin):
"""Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below th... | stack_v2_sparse_classes_36k_train_031174 | 2,235 | no_license | [
{
"docstring": "Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below the target height for which the pump should not turn on. Ex: .05 represents a 5% margin above and below the target_height.",
"name"... | 3 | null | Implement the Python class `Decider` described below.
Class description:
Encapsulates decision making in the water-regulation module
Method signatures and docstrings:
- def __init__(self, target_height, margin): Create a new decider instance for this tank. :param target_height: the target height for liquid in this ta... | Implement the Python class `Decider` described below.
Class description:
Encapsulates decision making in the water-regulation module
Method signatures and docstrings:
- def __init__(self, target_height, margin): Create a new decider instance for this tank. :param target_height: the target height for liquid in this ta... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class Decider:
"""Encapsulates decision making in the water-regulation module"""
def __init__(self, target_height, margin):
"""Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decider:
"""Encapsulates decision making in the water-regulation module"""
def __init__(self, target_height, margin):
"""Create a new decider instance for this tank. :param target_height: the target height for liquid in this tank :param margin: the margin of liquid above and below the target heig... | the_stack_v2_python_sparse | students/SeanTasaki/Lesson06/water-regulation/waterregulation/decider.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
6c1b288224cd952f879121389f09ca032d29d15f | [
"self.id = id\nself.title = title\nself.sort_priority = sort_priority\nself.create_on = create_on\nself.update_on = update_on\nself.created_by = created_by\nself.updated_by = updated_by\nself.create_on_persian_date = create_on_persian_date\nself.update_on_persian_date = update_on_persian_date",
"if dictionary is ... | <|body_start_0|>
self.id = id
self.title = title
self.sort_priority = sort_priority
self.create_on = create_on
self.update_on = update_on
self.created_by = created_by
self.updated_by = updated_by
self.create_on_persian_date = create_on_persian_date
... | Implementation of the 'DamageType' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. sort_priority (string): TODO: type description here. create_on (string): TODO: type description here. update_on (string): TODO: type description he... | DamageType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DamageType:
"""Implementation of the 'DamageType' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. sort_priority (string): TODO: type description here. create_on (string): TODO: type description here. update_... | stack_v2_sparse_classes_36k_train_031175 | 3,511 | permissive | [
{
"docstring": "Constructor for the DamageType class",
"name": "__init__",
"signature": "def __init__(self, id=None, title=None, create_on=None, update_on=None, created_by=None, create_on_persian_date=None, update_on_persian_date=None, sort_priority=None, updated_by=None)"
},
{
"docstring": "Cre... | 2 | stack_v2_sparse_classes_30k_train_015425 | Implement the Python class `DamageType` described below.
Class description:
Implementation of the 'DamageType' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. sort_priority (string): TODO: type description here. create_on (string... | Implement the Python class `DamageType` described below.
Class description:
Implementation of the 'DamageType' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. sort_priority (string): TODO: type description here. create_on (string... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class DamageType:
"""Implementation of the 'DamageType' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. sort_priority (string): TODO: type description here. create_on (string): TODO: type description here. update_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DamageType:
"""Implementation of the 'DamageType' model. TODO: type model description here. Attributes: id (int): TODO: type description here. title (string): TODO: type description here. sort_priority (string): TODO: type description here. create_on (string): TODO: type description here. update_on (string): ... | the_stack_v2_python_sparse | easybimehlanding/models/damage_type.py | kmelodi/EasyBimehLanding_Python | train | 0 |
df8801b358a40c0079308ce0a943089d2866a5c5 | [
"self.ufp_required_field = split_tuple(self.ufp_required_field)\nself.ufp_value = split_tuple(self.ufp_value)\nself.ufp_enabled = split_tuple(self.ufp_enabled)",
"if (ufp_value := self.ufp_value) is not None:\n if TYPE_CHECKING:\n assert isinstance(ufp_value, tuple)\n return get_nested_attr(obj, ufp_... | <|body_start_0|>
self.ufp_required_field = split_tuple(self.ufp_required_field)
self.ufp_value = split_tuple(self.ufp_value)
self.ufp_enabled = split_tuple(self.ufp_enabled)
<|end_body_0|>
<|body_start_1|>
if (ufp_value := self.ufp_value) is not None:
if TYPE_CHECKING:
... | Mixin for required keys. | ProtectRequiredKeysMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectRequiredKeysMixin:
"""Mixin for required keys."""
def __post_init__(self) -> None:
"""Pre-convert strings to tuples for faster get_nested_attr."""
<|body_0|>
def get_ufp_value(self, obj: T) -> Any:
"""Return value from UniFi Protect device."""
<|bo... | stack_v2_sparse_classes_36k_train_031176 | 5,372 | permissive | [
{
"docstring": "Pre-convert strings to tuples for faster get_nested_attr.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Return value from UniFi Protect device.",
"name": "get_ufp_value",
"signature": "def get_ufp_value(self, obj: T) -> Any"
... | 4 | stack_v2_sparse_classes_30k_train_000950 | Implement the Python class `ProtectRequiredKeysMixin` described below.
Class description:
Mixin for required keys.
Method signatures and docstrings:
- def __post_init__(self) -> None: Pre-convert strings to tuples for faster get_nested_attr.
- def get_ufp_value(self, obj: T) -> Any: Return value from UniFi Protect de... | Implement the Python class `ProtectRequiredKeysMixin` described below.
Class description:
Mixin for required keys.
Method signatures and docstrings:
- def __post_init__(self) -> None: Pre-convert strings to tuples for faster get_nested_attr.
- def get_ufp_value(self, obj: T) -> Any: Return value from UniFi Protect de... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ProtectRequiredKeysMixin:
"""Mixin for required keys."""
def __post_init__(self) -> None:
"""Pre-convert strings to tuples for faster get_nested_attr."""
<|body_0|>
def get_ufp_value(self, obj: T) -> Any:
"""Return value from UniFi Protect device."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectRequiredKeysMixin:
"""Mixin for required keys."""
def __post_init__(self) -> None:
"""Pre-convert strings to tuples for faster get_nested_attr."""
self.ufp_required_field = split_tuple(self.ufp_required_field)
self.ufp_value = split_tuple(self.ufp_value)
self.ufp_en... | the_stack_v2_python_sparse | homeassistant/components/unifiprotect/models.py | home-assistant/core | train | 35,501 |
25262f39b7ed73a520188e7724426f33d3fa670e | [
"self.is_empty = threading.Event()\nself.is_empty.set()\nself._lock = threading.RLock()\nself._task_wrappers_in_graph = {}\nself._top_level_task_semaphore = threading.Semaphore(top_level_task_limit)",
"if dependent_task_ids is None:\n self._top_level_task_semaphore.acquire()\nwith self._lock:\n if task.para... | <|body_start_0|>
self.is_empty = threading.Event()
self.is_empty.set()
self._lock = threading.RLock()
self._task_wrappers_in_graph = {}
self._top_level_task_semaphore = threading.Semaphore(top_level_task_limit)
<|end_body_0|>
<|body_start_1|>
if dependent_task_ids is Non... | Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in it. | TaskGraph | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGraph:
"""Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in... | stack_v2_sparse_classes_36k_train_031177 | 8,008 | permissive | [
{
"docstring": "Initializes a TaskGraph instance. Args: top_level_task_limit (int): A top-level task is a task that no other tasks depend on for completion (i.e. dependent_task_ids is None). Adding top-level tasks with TaskGraph.add will block until there are fewer than this number of top-level tasks in the gra... | 3 | stack_v2_sparse_classes_30k_train_004262 | Implement the Python class `TaskGraph` described below.
Class description:
Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set()... | Implement the Python class `TaskGraph` described below.
Class description:
Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set()... | 849d09dd7863efecbdf4072a504e1554e119f6ae | <|skeleton|>
class TaskGraph:
"""Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskGraph:
"""Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in it."""
... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/task_graph.py | PrateekKhatri/gcloud_cli | train | 0 |
abeafe9badce162495d97711b4beda6fec871ab8 | [
"(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\ntrain_images = train_images.reshape(60000, 784)\ntrain_images = train_images.astype('float32')\ntrain_images = train_images / 255\ntrain_images = 1 - train_images\ntrain_dataset = tf.data.Dataset.from_tensor_slices(train_images)\ntrain_d... | <|body_start_0|>
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape(60000, 784)
train_images = train_images.astype('float32')
train_images = train_images / 255
train_images = 1 - train_images
train_dataset = tf... | Donnees | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Donnees:
def train_donnees_mnist(cls):
""""Methode qui charge et prepare des images de l'entrainement FashionMNIST dans le format nécessaire pour l'entraînement. :return: dataset a utiliser pour l'entraînement :rtype: class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'"""
... | stack_v2_sparse_classes_36k_train_031178 | 5,675 | no_license | [
{
"docstring": "\"Methode qui charge et prepare des images de l'entrainement FashionMNIST dans le format nécessaire pour l'entraînement. :return: dataset a utiliser pour l'entraînement :rtype: class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'",
"name": "train_donnees_mnist",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_train_001662 | Implement the Python class `Donnees` described below.
Class description:
Implement the Donnees class.
Method signatures and docstrings:
- def train_donnees_mnist(cls): "Methode qui charge et prepare des images de l'entrainement FashionMNIST dans le format nécessaire pour l'entraînement. :return: dataset a utiliser po... | Implement the Python class `Donnees` described below.
Class description:
Implement the Donnees class.
Method signatures and docstrings:
- def train_donnees_mnist(cls): "Methode qui charge et prepare des images de l'entrainement FashionMNIST dans le format nécessaire pour l'entraînement. :return: dataset a utiliser po... | bad9fe47ef72b66fad289985484de4d5c58c48eb | <|skeleton|>
class Donnees:
def train_donnees_mnist(cls):
""""Methode qui charge et prepare des images de l'entrainement FashionMNIST dans le format nécessaire pour l'entraînement. :return: dataset a utiliser pour l'entraînement :rtype: class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Donnees:
def train_donnees_mnist(cls):
""""Methode qui charge et prepare des images de l'entrainement FashionMNIST dans le format nécessaire pour l'entraînement. :return: dataset a utiliser pour l'entraînement :rtype: class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'"""
(train_images... | the_stack_v2_python_sparse | AutoencodeurProbabiliste/sourceae/Donnees.py | Anastasija-Kuramzina/ProjetAutoencodeur | train | 0 | |
6f11a93820d1f8f053b07934b0238a3ba8a4af93 | [
"response = requests.get('https://samoa.dcs.gla.ac.uk/events/rest/Event/searchtext?search=')\nevents = response.json()\nself.assertEqual(response.status_code, status.HTTP_200_OK)\nself.assertEqual(response.headers['Content-Type'], 'application/json')\nself.assertGreater(len(events), 1)",
"response = requests.get(... | <|body_start_0|>
response = requests.get('https://samoa.dcs.gla.ac.uk/events/rest/Event/searchtext?search=')
events = response.json()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.headers['Content-Type'], 'application/json')
self.assertGreat... | SamoaTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SamoaTests:
def test_connection_to_samoa_api(self):
"""Tests whether a connection to samoa is successful."""
<|body_0|>
def test_17012_returns_systems_coffee(self):
"""Tests whether the event with id 17012 returns the correct seminar."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_031179 | 13,057 | permissive | [
{
"docstring": "Tests whether a connection to samoa is successful.",
"name": "test_connection_to_samoa_api",
"signature": "def test_connection_to_samoa_api(self)"
},
{
"docstring": "Tests whether the event with id 17012 returns the correct seminar.",
"name": "test_17012_returns_systems_coffe... | 2 | stack_v2_sparse_classes_30k_train_014537 | Implement the Python class `SamoaTests` described below.
Class description:
Implement the SamoaTests class.
Method signatures and docstrings:
- def test_connection_to_samoa_api(self): Tests whether a connection to samoa is successful.
- def test_17012_returns_systems_coffee(self): Tests whether the event with id 1701... | Implement the Python class `SamoaTests` described below.
Class description:
Implement the SamoaTests class.
Method signatures and docstrings:
- def test_connection_to_samoa_api(self): Tests whether a connection to samoa is successful.
- def test_17012_returns_systems_coffee(self): Tests whether the event with id 1701... | c8330258778dd7f71b1289c5dfe611e5637cf71d | <|skeleton|>
class SamoaTests:
def test_connection_to_samoa_api(self):
"""Tests whether a connection to samoa is successful."""
<|body_0|>
def test_17012_returns_systems_coffee(self):
"""Tests whether the event with id 17012 returns the correct seminar."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SamoaTests:
def test_connection_to_samoa_api(self):
"""Tests whether a connection to samoa is successful."""
response = requests.get('https://samoa.dcs.gla.ac.uk/events/rest/Event/searchtext?search=')
events = response.json()
self.assertEqual(response.status_code, status.HTTP_2... | the_stack_v2_python_sparse | seminar-roulette/backend/tests.py | olliegardner/seminar-roulette | train | 0 | |
a3a3634021cdca9cca82327300fafe76125bad40 | [
"res = super(stock_picking, self).create(cr, uid, values, context=context)\nif 'delivery_tracking_ids' in values:\n for delivery_tracking_ids in values['delivery_tracking_ids']:\n self.pool.get('delivery.tracking.numbers').write(cr, uid, tracking_num_ids[1], {'delivery_id': res})\nreturn res",
"if 'deli... | <|body_start_0|>
res = super(stock_picking, self).create(cr, uid, values, context=context)
if 'delivery_tracking_ids' in values:
for delivery_tracking_ids in values['delivery_tracking_ids']:
self.pool.get('delivery.tracking.numbers').write(cr, uid, tracking_num_ids[1], {'deli... | stock_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking:
def create(self, cr, uid, values, context=None):
"""set delivery order id in the tracking number db table records on create"""
<|body_0|>
def write(self, cr, uid, ids, values, context=None):
"""set delivery order id in the tracking number db table reco... | stack_v2_sparse_classes_36k_train_031180 | 5,870 | no_license | [
{
"docstring": "set delivery order id in the tracking number db table records on create",
"name": "create",
"signature": "def create(self, cr, uid, values, context=None)"
},
{
"docstring": "set delivery order id in the tracking number db table records on create",
"name": "write",
"signat... | 2 | null | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def create(self, cr, uid, values, context=None): set delivery order id in the tracking number db table records on create
- def write(self, cr, uid, ids, values, context... | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def create(self, cr, uid, values, context=None): set delivery order id in the tracking number db table records on create
- def write(self, cr, uid, ids, values, context... | 3a0d7ddb85d497b4f576678370a1fbbfd71379f4 | <|skeleton|>
class stock_picking:
def create(self, cr, uid, values, context=None):
"""set delivery order id in the tracking number db table records on create"""
<|body_0|>
def write(self, cr, uid, ids, values, context=None):
"""set delivery order id in the tracking number db table reco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_picking:
def create(self, cr, uid, values, context=None):
"""set delivery order id in the tracking number db table records on create"""
res = super(stock_picking, self).create(cr, uid, values, context=context)
if 'delivery_tracking_ids' in values:
for delivery_trackin... | the_stack_v2_python_sparse | 7.0/ursa_tracking/tracking_numbers.py | alephobjects/ao-openerp | train | 3 | |
c2a0f2e14b096204d3db7fbe12c6abe961d4ea29 | [
"self.drone_id = drone_id\nself.duration = 20\nself.droneStates = droneStates",
"x = 0.1\ny = 0.2\nz = 0.3\nfor _ in range(self.duration):\n if not run_event.is_set():\n return\n self.droneStates.append({'drone_id': self.drone_id, 'type': 'physical', 'longitude': x, 'latitude': y, 'altitude': z, 'vel... | <|body_start_0|>
self.drone_id = drone_id
self.duration = 20
self.droneStates = droneStates
<|end_body_0|>
<|body_start_1|>
x = 0.1
y = 0.2
z = 0.3
for _ in range(self.duration):
if not run_event.is_set():
return
self.drone... | Simulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulator:
def __init__(self, droneStates, drone_id):
"""Simulator of a Drone data sender. Teams should implement their own data sender which takes a droneStates queue and appends drone states to it. Initialize variables: duration: duration of simulation in seconds. droneStates: queue of... | stack_v2_sparse_classes_36k_train_031181 | 1,556 | no_license | [
{
"docstring": "Simulator of a Drone data sender. Teams should implement their own data sender which takes a droneStates queue and appends drone states to it. Initialize variables: duration: duration of simulation in seconds. droneStates: queue of states to which we will add new states received from drone.",
... | 2 | stack_v2_sparse_classes_30k_train_011099 | Implement the Python class `Simulator` described below.
Class description:
Implement the Simulator class.
Method signatures and docstrings:
- def __init__(self, droneStates, drone_id): Simulator of a Drone data sender. Teams should implement their own data sender which takes a droneStates queue and appends drone stat... | Implement the Python class `Simulator` described below.
Class description:
Implement the Simulator class.
Method signatures and docstrings:
- def __init__(self, droneStates, drone_id): Simulator of a Drone data sender. Teams should implement their own data sender which takes a droneStates queue and appends drone stat... | ef81426a6bd57e95103474f46e1061362ab48694 | <|skeleton|>
class Simulator:
def __init__(self, droneStates, drone_id):
"""Simulator of a Drone data sender. Teams should implement their own data sender which takes a droneStates queue and appends drone states to it. Initialize variables: duration: duration of simulation in seconds. droneStates: queue of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulator:
def __init__(self, droneStates, drone_id):
"""Simulator of a Drone data sender. Teams should implement their own data sender which takes a droneStates queue and appends drone states to it. Initialize variables: duration: duration of simulation in seconds. droneStates: queue of states to whi... | the_stack_v2_python_sparse | Simulator.py | gnoliyil/aa241x | train | 0 | |
1317b0047d48a4e565184914a6f198c00ddfb5cb | [
"module = mojom.Module('test_module', 'test_namespace')\nstruct = mojom.Struct('TestStruct', module=module)\nwith self.assertRaises(Exception) as e:\n mojom.InterfaceRequest(struct)\nself.assertEquals(e.exception.__str__(), \"Interface request requires 'x:TestStruct' to be an interface.\")",
"module = mojom.Mo... | <|body_start_0|>
module = mojom.Module('test_module', 'test_namespace')
struct = mojom.Struct('TestStruct', module=module)
with self.assertRaises(Exception) as e:
mojom.InterfaceRequest(struct)
self.assertEquals(e.exception.__str__(), "Interface request requires 'x:TestStruct... | ModuleTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTest:
def testNonInterfaceAsInterfaceRequest(self):
"""Tests that a non-interface cannot be used for interface requests."""
<|body_0|>
def testNonInterfaceAsAssociatedInterface(self):
"""Tests that a non-interface type cannot be used for associated interfaces."... | stack_v2_sparse_classes_36k_train_031182 | 1,170 | permissive | [
{
"docstring": "Tests that a non-interface cannot be used for interface requests.",
"name": "testNonInterfaceAsInterfaceRequest",
"signature": "def testNonInterfaceAsInterfaceRequest(self)"
},
{
"docstring": "Tests that a non-interface type cannot be used for associated interfaces.",
"name":... | 2 | null | Implement the Python class `ModuleTest` described below.
Class description:
Implement the ModuleTest class.
Method signatures and docstrings:
- def testNonInterfaceAsInterfaceRequest(self): Tests that a non-interface cannot be used for interface requests.
- def testNonInterfaceAsAssociatedInterface(self): Tests that ... | Implement the Python class `ModuleTest` described below.
Class description:
Implement the ModuleTest class.
Method signatures and docstrings:
- def testNonInterfaceAsInterfaceRequest(self): Tests that a non-interface cannot be used for interface requests.
- def testNonInterfaceAsAssociatedInterface(self): Tests that ... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class ModuleTest:
def testNonInterfaceAsInterfaceRequest(self):
"""Tests that a non-interface cannot be used for interface requests."""
<|body_0|>
def testNonInterfaceAsAssociatedInterface(self):
"""Tests that a non-interface type cannot be used for associated interfaces."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleTest:
def testNonInterfaceAsInterfaceRequest(self):
"""Tests that a non-interface cannot be used for interface requests."""
module = mojom.Module('test_module', 'test_namespace')
struct = mojom.Struct('TestStruct', module=module)
with self.assertRaises(Exception) as e:
... | the_stack_v2_python_sparse | mojo/public/tools/mojom/mojom/generate/module_unittest.py | chromium/chromium | train | 17,408 | |
922779d62712c10b4d0423cb4dce0b5fe6ed2fe6 | [
"creds_list = self._client.list(user.id)\nif check:\n assert_that(creds_list, is_not(empty()))\nreturn creds_list",
"credentials = self._client.create(user_id=user.id, project_id=project.id)\nif check:\n self.check_presence(credentials)\n assert_that(credentials, has_properties(user_id=user.id, tenant_id... | <|body_start_0|>
creds_list = self._client.list(user.id)
if check:
assert_that(creds_list, is_not(empty()))
return creds_list
<|end_body_0|>
<|body_start_1|>
credentials = self._client.create(user_id=user.id, project_id=project.id)
if check:
self.check_pr... | Ec2 credentials steps | Ec2Steps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ec2Steps:
"""Ec2 credentials steps"""
def list(self, user, check=True):
"""Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed""... | stack_v2_sparse_classes_36k_train_031183 | 3,590 | no_license | [
{
"docstring": "Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed",
"name": "list",
"signature": "def list(self, user, check=True)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_020095 | Implement the Python class `Ec2Steps` described below.
Class description:
Ec2 credentials steps
Method signatures and docstrings:
- def list(self, user, check=True): Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ... | Implement the Python class `Ec2Steps` described below.
Class description:
Ec2 credentials steps
Method signatures and docstrings:
- def list(self, user, check=True): Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class Ec2Steps:
"""Ec2 credentials steps"""
def list(self, user, check=True):
"""Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ec2Steps:
"""Ec2 credentials steps"""
def list(self, user, check=True):
"""Step to list all ec2 credentials. Args: user (object): user check (bool): flag whether to check step or not Returns: keystoneclient.v3.ec2.Ec2: list of ec2 credentials Raises: AssertionError: if check failed"""
cre... | the_stack_v2_python_sparse | stepler/keystone/steps/ec2.py | Mirantis/stepler | train | 16 |
4333df00ec618e58e518a068dbc1612dee970410 | [
"self.dataSource = dataSource\nself.nextId = 1\nself.subscribers = {}",
"businessDates = self.dataSource.getBusinessDates(startDate=startDate, endDate=endDate)\nfor asOfDate in businessDates:\n print('Processing', asOfDate)\n self.notifyAll(asOfDate)",
"subId = self.nextId\nself.nextId += 1\nself.subscrib... | <|body_start_0|>
self.dataSource = dataSource
self.nextId = 1
self.subscribers = {}
<|end_body_0|>
<|body_start_1|>
businessDates = self.dataSource.getBusinessDates(startDate=startDate, endDate=endDate)
for asOfDate in businessDates:
print('Processing', asOfDate)
... | Data publish engine for stock backtesting. | StockBacktestDataPublisher | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockBacktestDataPublisher:
"""Data publish engine for stock backtesting."""
def __init__(self, dataSource):
"""Initialize the data publisher. Parameters ---------- dataSource : data.api.stocks.DataSource Stock data source."""
<|body_0|>
def connect(self, startDate='2012... | stack_v2_sparse_classes_36k_train_031184 | 4,905 | permissive | [
{
"docstring": "Initialize the data publisher. Parameters ---------- dataSource : data.api.stocks.DataSource Stock data source.",
"name": "__init__",
"signature": "def __init__(self, dataSource)"
},
{
"docstring": "Put the DataFeed engine online and listened to the data change. For backtest engi... | 6 | stack_v2_sparse_classes_30k_train_010203 | Implement the Python class `StockBacktestDataPublisher` described below.
Class description:
Data publish engine for stock backtesting.
Method signatures and docstrings:
- def __init__(self, dataSource): Initialize the data publisher. Parameters ---------- dataSource : data.api.stocks.DataSource Stock data source.
- d... | Implement the Python class `StockBacktestDataPublisher` described below.
Class description:
Data publish engine for stock backtesting.
Method signatures and docstrings:
- def __init__(self, dataSource): Initialize the data publisher. Parameters ---------- dataSource : data.api.stocks.DataSource Stock data source.
- d... | 139d604177da3855503643e0fcfa87711ba7e588 | <|skeleton|>
class StockBacktestDataPublisher:
"""Data publish engine for stock backtesting."""
def __init__(self, dataSource):
"""Initialize the data publisher. Parameters ---------- dataSource : data.api.stocks.DataSource Stock data source."""
<|body_0|>
def connect(self, startDate='2012... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockBacktestDataPublisher:
"""Data publish engine for stock backtesting."""
def __init__(self, dataSource):
"""Initialize the data publisher. Parameters ---------- dataSource : data.api.stocks.DataSource Stock data source."""
self.dataSource = dataSource
self.nextId = 1
s... | the_stack_v2_python_sparse | datafeed/stockBacktestEngine.py | WinQuant/arsenal | train | 0 |
e04f4ba55e5799f7c6d4990e9c3306dc8d85cbf0 | [
"def preorder(root):\n if not root:\n return ['null']\n return [str(root.val)] + preorder(root.left) + preorder(root.right)\nreturn '[' + ','.join(preorder(root)) + ']'",
"arr = data[1:-1].split(',')\nself.index = 0\n\ndef construct():\n if arr[self.index] == 'null':\n self.index += 1\n ... | <|body_start_0|>
def preorder(root):
if not root:
return ['null']
return [str(root.val)] + preorder(root.left) + preorder(root.right)
return '[' + ','.join(preorder(root)) + ']'
<|end_body_0|>
<|body_start_1|>
arr = data[1:-1].split(',')
self.inde... | 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_031185 | 1,360 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002334 | 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:... | 19be0766f6b9c298fb32754f66416f79567843c1 | <|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"""
def preorder(root):
if not root:
return ['null']
return [str(root.val)] + preorder(root.left) + preorder(root.right)
return '[' + ','.join... | the_stack_v2_python_sparse | leetcode/Problems/297--Serialize-and-Deserialize-Binary-Tree-Hard.py | niteesh2268/coding-prepation | train | 0 | |
c793207626c423bbf2cc159ffc8d8a5e88c08c86 | [
"super(RateConverter, self).__init__(id=id)\nself.base_currency = base_currency\nself.user = user\nself.key = key",
"errors = super(RateConverter, self).add_data(data)\nself.cache_currencies()\nreturn errors",
"from .serializers import RateAmountSerializer\nerrors = []\nfor line in data:\n serializer = RateA... | <|body_start_0|>
super(RateConverter, self).__init__(id=id)
self.base_currency = base_currency
self.user = user
self.key = key
<|end_body_0|>
<|body_start_1|>
errors = super(RateConverter, self).add_data(data)
self.cache_currencies()
return errors
<|end_body_1|>
... | Converter of rates | RateConverter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateConverter:
"""Converter of rates"""
def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY):
"""Initialize :param user: Django User :param key: key for user :param base_currency: destination currency"""
<|body_0|>
def ad... | stack_v2_sparse_classes_36k_train_031186 | 16,208 | permissive | [
{
"docstring": "Initialize :param user: Django User :param key: key for user :param base_currency: destination currency",
"name": "__init__",
"signature": "def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY)"
},
{
"docstring": "Check data and ad... | 5 | stack_v2_sparse_classes_30k_train_005612 | Implement the Python class `RateConverter` described below.
Class description:
Converter of rates
Method signatures and docstrings:
- def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY): Initialize :param user: Django User :param key: key for user :param base_currenc... | Implement the Python class `RateConverter` described below.
Class description:
Converter of rates
Method signatures and docstrings:
- def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY): Initialize :param user: Django User :param key: key for user :param base_currenc... | 23cc075377d47ac631634cd71fd0e7d6b0a57bad | <|skeleton|>
class RateConverter:
"""Converter of rates"""
def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY):
"""Initialize :param user: Django User :param key: key for user :param base_currency: destination currency"""
<|body_0|>
def ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RateConverter:
"""Converter of rates"""
def __init__(self, user: User, id: str=None, key: str=None, base_currency: str=settings.BASE_CURRENCY):
"""Initialize :param user: Django User :param key: key for user :param base_currency: destination currency"""
super(RateConverter, self).__init__... | the_stack_v2_python_sparse | src/geocurrency/rates/models.py | fmeurou/geocurrency | train | 5 |
aaa9dcdb4bce2e61a58e426639a168bd91edddef | [
"if not root:\n return ''\nqueue = deque()\nqueue.append(root)\nres = ''\nwhile len(queue):\n node = queue.popleft()\n if not node:\n res += 'n '\n continue\n res += str(node.val) + ' '\n queue.append(node.left)\n queue.append(node.right)\nreturn res",
"if data == '':\n return N... | <|body_start_0|>
if not root:
return ''
queue = deque()
queue.append(root)
res = ''
while len(queue):
node = queue.popleft()
if not node:
res += 'n '
continue
res += str(node.val) + ' '
qu... | Codec | [
"MIT"
] | 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_031187 | 1,455 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_008022 | 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:... | 90b6287b742c8bfd3797540c408d679be2821a40 | <|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"""
if not root:
return ''
queue = deque()
queue.append(root)
res = ''
while len(queue):
node = queue.popleft()
if not nod... | the_stack_v2_python_sparse | LeetCodeSolutions/python/297_Serialize_and_Deserialize_Binary_Tree.py | ChuanleiGuo/AlgorithmsPlayground | train | 1 | |
4e795d4488a814ebc494485f02c8f499cea11005 | [
"try:\n blog = Blog.find(year, month, day, slug)\nexcept Blog.DoesNotExist:\n abort(404, message='No such blog')\nexcept ValueError:\n abort(409, message='Multiple blogs found')\nreturn blog",
"try:\n blog = Blog.find(year, month, day, slug)\nexcept Blog.DoesNotExist:\n abort(404, message='No such ... | <|body_start_0|>
try:
blog = Blog.find(year, month, day, slug)
except Blog.DoesNotExist:
abort(404, message='No such blog')
except ValueError:
abort(409, message='Multiple blogs found')
return blog
<|end_body_0|>
<|body_start_1|>
try:
... | BlogAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogAPI:
def get(self, year, month, day, slug):
"""Get blog post details"""
<|body_0|>
def patch(self, args, year, month, day, slug):
"""Edit blog post details"""
<|body_1|>
def delete(self, year, month, day, slug):
"""Delete blog post"""
... | stack_v2_sparse_classes_36k_train_031188 | 4,891 | permissive | [
{
"docstring": "Get blog post details",
"name": "get",
"signature": "def get(self, year, month, day, slug)"
},
{
"docstring": "Edit blog post details",
"name": "patch",
"signature": "def patch(self, args, year, month, day, slug)"
},
{
"docstring": "Delete blog post",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_018811 | Implement the Python class `BlogAPI` described below.
Class description:
Implement the BlogAPI class.
Method signatures and docstrings:
- def get(self, year, month, day, slug): Get blog post details
- def patch(self, args, year, month, day, slug): Edit blog post details
- def delete(self, year, month, day, slug): Del... | Implement the Python class `BlogAPI` described below.
Class description:
Implement the BlogAPI class.
Method signatures and docstrings:
- def get(self, year, month, day, slug): Get blog post details
- def patch(self, args, year, month, day, slug): Edit blog post details
- def delete(self, year, month, day, slug): Del... | dffc3b1e16c24dd49e516e36aaa731a8dd299e66 | <|skeleton|>
class BlogAPI:
def get(self, year, month, day, slug):
"""Get blog post details"""
<|body_0|>
def patch(self, args, year, month, day, slug):
"""Edit blog post details"""
<|body_1|>
def delete(self, year, month, day, slug):
"""Delete blog post"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlogAPI:
def get(self, year, month, day, slug):
"""Get blog post details"""
try:
blog = Blog.find(year, month, day, slug)
except Blog.DoesNotExist:
abort(404, message='No such blog')
except ValueError:
abort(409, message='Multiple blogs found... | the_stack_v2_python_sparse | tilda/api/blog.py | tilda-center/backend | train | 0 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nproposal = Semester.from_dict(api.payload)\nif proposal is not None:\n 'Wir verwenden Semester_id und Grade des Proposals für die Erzeugung eines Semester-Objektes.'\n sem = adm.create_semester(proposal.get_id(), proposal.get_name())\n return (sem, 200)\nelse:\n return ('... | <|body_start_0|>
adm = ProjectAdministration()
proposal = Semester.from_dict(api.payload)
if proposal is not None:
'Wir verwenden Semester_id und Grade des Proposals für die Erzeugung eines Semester-Objektes.'
sem = adm.create_semester(proposal.get_id(), proposal.get_name... | SemesterOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemesterOperations:
def post(self):
"""Anlegen eines neuen Semester-Objekts"""
<|body_0|>
def put(self):
"""Update eines bestimmten Semester-Objektes."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = ProjectAdministration()
proposal = S... | stack_v2_sparse_classes_36k_train_031189 | 44,493 | no_license | [
{
"docstring": "Anlegen eines neuen Semester-Objekts",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update eines bestimmten Semester-Objektes.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009282 | Implement the Python class `SemesterOperations` described below.
Class description:
Implement the SemesterOperations class.
Method signatures and docstrings:
- def post(self): Anlegen eines neuen Semester-Objekts
- def put(self): Update eines bestimmten Semester-Objektes. | Implement the Python class `SemesterOperations` described below.
Class description:
Implement the SemesterOperations class.
Method signatures and docstrings:
- def post(self): Anlegen eines neuen Semester-Objekts
- def put(self): Update eines bestimmten Semester-Objektes.
<|skeleton|>
class SemesterOperations:
... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class SemesterOperations:
def post(self):
"""Anlegen eines neuen Semester-Objekts"""
<|body_0|>
def put(self):
"""Update eines bestimmten Semester-Objektes."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemesterOperations:
def post(self):
"""Anlegen eines neuen Semester-Objekts"""
adm = ProjectAdministration()
proposal = Semester.from_dict(api.payload)
if proposal is not None:
'Wir verwenden Semester_id und Grade des Proposals für die Erzeugung eines Semester-Objek... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
35d481b571d81f07fe7e8093729b2979824ed2e0 | [
"temp_dir = recreate_nist()\nnist_preprocessor = NISTPreprocessor(temp_dir.name)\nnist_preprocessor.preprocess()\npreprocessed_df = nist_preprocessor._preprocessed_df\nnist_sampler = NistSampler(preprocessed_df)\nsampled_df = nist_sampler.sample(sampling_type='niid', frac=1.0, random_seed=42)\nassert_that(str(sampl... | <|body_start_0|>
temp_dir = recreate_nist()
nist_preprocessor = NISTPreprocessor(temp_dir.name)
nist_preprocessor.preprocess()
preprocessed_df = nist_preprocessor._preprocessed_df
nist_sampler = NistSampler(preprocessed_df)
sampled_df = nist_sampler.sample(sampling_type='... | Test NIST sampler. | TestNistSampler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNistSampler:
"""Test NIST sampler."""
def test_niid_sampling_information(self):
"""Checks if the sampled dataframe has a string denoting the location."""
<|body_0|>
def test_full_niid_size(self):
"""Tests if the fully sampled data is the same as processed dat... | stack_v2_sparse_classes_36k_train_031190 | 2,372 | permissive | [
{
"docstring": "Checks if the sampled dataframe has a string denoting the location.",
"name": "test_niid_sampling_information",
"signature": "def test_niid_sampling_information(self)"
},
{
"docstring": "Tests if the fully sampled data is the same as processed data.",
"name": "test_full_niid_... | 3 | null | Implement the Python class `TestNistSampler` described below.
Class description:
Test NIST sampler.
Method signatures and docstrings:
- def test_niid_sampling_information(self): Checks if the sampled dataframe has a string denoting the location.
- def test_full_niid_size(self): Tests if the fully sampled data is the ... | Implement the Python class `TestNistSampler` described below.
Class description:
Test NIST sampler.
Method signatures and docstrings:
- def test_niid_sampling_information(self): Checks if the sampled dataframe has a string denoting the location.
- def test_full_niid_size(self): Tests if the fully sampled data is the ... | 55be690535e5f3feb33c888c3e4a586b7bdbf489 | <|skeleton|>
class TestNistSampler:
"""Test NIST sampler."""
def test_niid_sampling_information(self):
"""Checks if the sampled dataframe has a string denoting the location."""
<|body_0|>
def test_full_niid_size(self):
"""Tests if the fully sampled data is the same as processed dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestNistSampler:
"""Test NIST sampler."""
def test_niid_sampling_information(self):
"""Checks if the sampled dataframe has a string denoting the location."""
temp_dir = recreate_nist()
nist_preprocessor = NISTPreprocessor(temp_dir.name)
nist_preprocessor.preprocess()
... | the_stack_v2_python_sparse | baselines/flwr_baselines/flwr_baselines/publications/leaf/femnist/dataset/nist_sampler_test.py | adap/flower | train | 2,999 |
f11aa84083bcff3f71ed59c26f4cbe45af557708 | [
"login_url = 'http://192.168.30.128:8080/futureloan/mvc/api/member/login'\nmethod = 'get'\nparam = {'mobilephone': '15810901234', 'pwd': '123456'}\nexpected = '登录成功'\nres = HttpReq().http_requests(login_url, method, param).json()\nself.assertEqual(expected, res['msg'])",
"login_url = 'http://192.168.30.128:8080/f... | <|body_start_0|>
login_url = 'http://192.168.30.128:8080/futureloan/mvc/api/member/login'
method = 'get'
param = {'mobilephone': '15810901234', 'pwd': '123456'}
expected = '登录成功'
res = HttpReq().http_requests(login_url, method, param).json()
self.assertEqual(expected, res... | TestAdd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdd:
def test_normal_001(self):
"""正确用户名和正确密码,get请求"""
<|body_0|>
def test_normal_002(self):
"""正确用户名和密码,post请求"""
<|body_1|>
def test_abnormal_001(self):
"""空用户名登录"""
<|body_2|>
def test_abnormal_002(self):
"""空密码登录"""
... | stack_v2_sparse_classes_36k_train_031191 | 3,808 | no_license | [
{
"docstring": "正确用户名和正确密码,get请求",
"name": "test_normal_001",
"signature": "def test_normal_001(self)"
},
{
"docstring": "正确用户名和密码,post请求",
"name": "test_normal_002",
"signature": "def test_normal_002(self)"
},
{
"docstring": "空用户名登录",
"name": "test_abnormal_001",
"signat... | 4 | null | Implement the Python class `TestAdd` described below.
Class description:
Implement the TestAdd class.
Method signatures and docstrings:
- def test_normal_001(self): 正确用户名和正确密码,get请求
- def test_normal_002(self): 正确用户名和密码,post请求
- def test_abnormal_001(self): 空用户名登录
- def test_abnormal_002(self): 空密码登录 | Implement the Python class `TestAdd` described below.
Class description:
Implement the TestAdd class.
Method signatures and docstrings:
- def test_normal_001(self): 正确用户名和正确密码,get请求
- def test_normal_002(self): 正确用户名和密码,post请求
- def test_abnormal_001(self): 空用户名登录
- def test_abnormal_002(self): 空密码登录
<|skeleton|>
cl... | f38151a7adde66e380674f82785794db460daab3 | <|skeleton|>
class TestAdd:
def test_normal_001(self):
"""正确用户名和正确密码,get请求"""
<|body_0|>
def test_normal_002(self):
"""正确用户名和密码,post请求"""
<|body_1|>
def test_abnormal_001(self):
"""空用户名登录"""
<|body_2|>
def test_abnormal_002(self):
"""空密码登录"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAdd:
def test_normal_001(self):
"""正确用户名和正确密码,get请求"""
login_url = 'http://192.168.30.128:8080/futureloan/mvc/api/member/login'
method = 'get'
param = {'mobilephone': '15810901234', 'pwd': '123456'}
expected = '登录成功'
res = HttpReq().http_requests(login_url, ... | the_stack_v2_python_sparse | Homework/homework_0321/test_case.py | HackYe/uitest | train | 0 | |
afd2f719e4b272cfe0882469aeea77e30b4d0068 | [
"context = super().get_context_data(**kwargs)\nchannel = self.object\nfilename = channel.get_log_filename()\nbucket = []\nfor log in (x.strip() for x in tail_log_file(filename, 0, self.max_num_lines)):\n if not log:\n continue\n try:\n time, msg = log.split(' [-] ')\n time_key = time.spli... | <|body_start_0|>
context = super().get_context_data(**kwargs)
channel = self.object
filename = channel.get_log_filename()
bucket = []
for log in (x.strip() for x in tail_log_file(filename, 0, self.max_num_lines)):
if not log:
continue
try:
... | Returns the log entries for a given channel. | ChannelDetailView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelDetailView:
"""Returns the log entries for a given channel."""
def get_context_data(self, **kwargs):
"""Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: context (dict): Django context object"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_031192 | 5,329 | permissive | [
{
"docstring": "Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: context (dict): Django context object",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Override of Django hook that ... | 2 | null | Implement the Python class `ChannelDetailView` described below.
Class description:
Returns the log entries for a given channel.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: cont... | Implement the Python class `ChannelDetailView` described below.
Class description:
Returns the log entries for a given channel.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: cont... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class ChannelDetailView:
"""Returns the log entries for a given channel."""
def get_context_data(self, **kwargs):
"""Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: context (dict): Django context object"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelDetailView:
"""Returns the log entries for a given channel."""
def get_context_data(self, **kwargs):
"""Django hook; before we can display the channel logs, we need to recall the logfile and read its lines. Returns: context (dict): Django context object"""
context = super().get_con... | the_stack_v2_python_sparse | evennia/web/website/views/channels.py | evennia/evennia | train | 1,781 |
98adc5c63a38b5ff4ce92c774c489c30ca8e0399 | [
"self.margin = margin\nif margin is not None:\n self.ranking_loss = nn.MarginRankingLoss(margin=margin)\nelse:\n self.ranking_loss = nn.SoftMarginLoss()",
"if self.margin is not None:\n loss = self.ranking_loss(dist_an, dist_ap, y)\nelse:\n loss = self.ranking_loss(dist_an - dist_ap, y)\nreturn loss"
... | <|body_start_0|>
self.margin = margin
if margin is not None:
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
else:
self.ranking_loss = nn.SoftMarginLoss()
<|end_body_0|>
<|body_start_1|>
if self.margin is not None:
loss = self.ranking_loss(dis... | Reference: https://github.com/Cysu/open-reid In Defense of the Triplet Loss_Meter for Person Re-Identification | _TripletLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TripletLoss:
"""Reference: https://github.com/Cysu/open-reid In Defense of the Triplet Loss_Meter for Person Re-Identification"""
def __init__(self, margin=None):
"""Args: margin: margin We can choose two Margin Loss_Meter: MarginRankingLoss(margin=margin) SoftMarginLoss() Returns: ... | stack_v2_sparse_classes_36k_train_031193 | 13,556 | permissive | [
{
"docstring": "Args: margin: margin We can choose two Margin Loss_Meter: MarginRankingLoss(margin=margin) SoftMarginLoss() Returns: self.ranking_loss",
"name": "__init__",
"signature": "def __init__(self, margin=None)"
},
{
"docstring": "Args: dist_ap: pytorch tensor, distance between anchor an... | 2 | stack_v2_sparse_classes_30k_train_004638 | Implement the Python class `_TripletLoss` described below.
Class description:
Reference: https://github.com/Cysu/open-reid In Defense of the Triplet Loss_Meter for Person Re-Identification
Method signatures and docstrings:
- def __init__(self, margin=None): Args: margin: margin We can choose two Margin Loss_Meter: Ma... | Implement the Python class `_TripletLoss` described below.
Class description:
Reference: https://github.com/Cysu/open-reid In Defense of the Triplet Loss_Meter for Person Re-Identification
Method signatures and docstrings:
- def __init__(self, margin=None): Args: margin: margin We can choose two Margin Loss_Meter: Ma... | 107b25f31c961f360f69560cfddd78dfc0da3291 | <|skeleton|>
class _TripletLoss:
"""Reference: https://github.com/Cysu/open-reid In Defense of the Triplet Loss_Meter for Person Re-Identification"""
def __init__(self, margin=None):
"""Args: margin: margin We can choose two Margin Loss_Meter: MarginRankingLoss(margin=margin) SoftMarginLoss() Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TripletLoss:
"""Reference: https://github.com/Cysu/open-reid In Defense of the Triplet Loss_Meter for Person Re-Identification"""
def __init__(self, margin=None):
"""Args: margin: margin We can choose two Margin Loss_Meter: MarginRankingLoss(margin=margin) SoftMarginLoss() Returns: self.ranking_... | the_stack_v2_python_sparse | MDRSREID/Loss_Meter/triplet_loss.py | nickhuang1996/HJL-re-id | train | 54 |
1f577996c98d6982d49db5e0f9d1622f8a0aac7e | [
"res = 0\na = 0\nfor i in range(32):\n if sum([n >> i & 1 for n in nums]) % 3:\n if i == 31:\n a -= 1 << i\n else:\n a |= 1 << i\nreturn a",
"from collections import Counter\nnums_set = Counter(nums)\nfor k, v in nums_set.items():\n if v == 1:\n return k",
"from ... | <|body_start_0|>
res = 0
a = 0
for i in range(32):
if sum([n >> i & 1 for n in nums]) % 3:
if i == 31:
a -= 1 << i
else:
a |= 1 << i
return a
<|end_body_0|>
<|body_start_1|>
from collections impo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums) -> int:
"""位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)"""
<|body_0|>
def singleNumber_sliding_window(self, nums) -> int:
"""滑动窗口,当窗口内只含出现一次时右移,否则左移 时间O(n) 空间O(1),存储左右指针"""
<|body_... | stack_v2_sparse_classes_36k_train_031194 | 2,225 | no_license | [
{
"docstring": "位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)",
"name": "singleNumber",
"signature": "def singleNumber(self, nums) -> int"
},
{
"docstring": "滑动窗口,当窗口内只含出现一次时右移,否则左移 时间O(n) 空间O(1),存储左右指针",
"name": "singleNumber_sliding_window",
"sign... | 3 | stack_v2_sparse_classes_30k_train_008881 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums) -> int: 位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)
- def singleNumber_sliding_window(self, nums) -> int: 滑动... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums) -> int: 位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)
- def singleNumber_sliding_window(self, nums) -> int: 滑动... | c9eed637887753eb28d78cf252ea3763231e23a2 | <|skeleton|>
class Solution:
def singleNumber(self, nums) -> int:
"""位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)"""
<|body_0|>
def singleNumber_sliding_window(self, nums) -> int:
"""滑动窗口,当窗口内只含出现一次时右移,否则左移 时间O(n) 空间O(1),存储左右指针"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums) -> int:
"""位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)"""
res = 0
a = 0
for i in range(32):
if sum([n >> i & 1 for n in nums]) % 3:
if i == 31:
a -= 1... | the_stack_v2_python_sparse | CODE/剑指 Offer II 004. 只出现一次的数字 .py | moshlwx/leetcode | train | 5 | |
f9a1ca9b0399a026942a49d8c612e1e1493fec3c | [
"Girl.__init__(self, girl)\nself.happiness = 0\nself.costOfGiftsRec = 0\nself.bfName = ''\nself.blackList = ''",
"self.costOfGiftsRec = amount\nfor i in range(0, len(giftBasket)):\n if giftBasket[i][0] == 'Luxury':\n amount += giftBasket[i][1]\nif amount / self.maintainanceCost > 0:\n self.happiness ... | <|body_start_0|>
Girl.__init__(self, girl)
self.happiness = 0
self.costOfGiftsRec = 0
self.bfName = ''
self.blackList = ''
<|end_body_0|>
<|body_start_1|>
self.costOfGiftsRec = amount
for i in range(0, len(giftBasket)):
if giftBasket[i][0] == 'Luxury'... | Girl class for girlType = 'Choosy' | girlChoosy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class girlChoosy:
"""Girl class for girlType = 'Choosy'"""
def __init__(self, girl):
"""constructor"""
<|body_0|>
def happinessCalculator(self, giftBasket, amount):
"""Calculates the happiness for girls of type Choosy"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_031195 | 818 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, girl)"
},
{
"docstring": "Calculates the happiness for girls of type Choosy",
"name": "happinessCalculator",
"signature": "def happinessCalculator(self, giftBasket, amount)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010436 | Implement the Python class `girlChoosy` described below.
Class description:
Girl class for girlType = 'Choosy'
Method signatures and docstrings:
- def __init__(self, girl): constructor
- def happinessCalculator(self, giftBasket, amount): Calculates the happiness for girls of type Choosy | Implement the Python class `girlChoosy` described below.
Class description:
Girl class for girlType = 'Choosy'
Method signatures and docstrings:
- def __init__(self, girl): constructor
- def happinessCalculator(self, giftBasket, amount): Calculates the happiness for girls of type Choosy
<|skeleton|>
class girlChoosy... | 6498c5a03fae3740caeaa9ba42603f7ad7974e8c | <|skeleton|>
class girlChoosy:
"""Girl class for girlType = 'Choosy'"""
def __init__(self, girl):
"""constructor"""
<|body_0|>
def happinessCalculator(self, giftBasket, amount):
"""Calculates the happiness for girls of type Choosy"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class girlChoosy:
"""Girl class for girlType = 'Choosy'"""
def __init__(self, girl):
"""constructor"""
Girl.__init__(self, girl)
self.happiness = 0
self.costOfGiftsRec = 0
self.bfName = ''
self.blackList = ''
def happinessCalculator(self, giftBasket, amount)... | the_stack_v2_python_sparse | Question9/girlChoosy.py | PPL-IIITA/ppl-assignment-stark03 | train | 0 |
e18ad7ed910da93fae4ccba82e5242f1574f652b | [
"self.feature_parser = self.get_feature_parser(features, allowed_feature_types=lambda fty: fty.is_discrete())\nself.values = values\nself.values_column = values_column\nself.raster_dtype = raster_dtype\nself.rasterio_params = rasterio_params",
"mask = np.isin(raster, self.values) if self.values is not None else N... | <|body_start_0|>
self.feature_parser = self.get_feature_parser(features, allowed_feature_types=lambda fty: fty.is_discrete())
self.values = values
self.values_column = values_column
self.raster_dtype = raster_dtype
self.rasterio_params = rasterio_params
<|end_body_0|>
<|body_sta... | Task for transforming raster mask feature into vector feature. Each connected component with the same value on the raster mask is turned into a shapely polygon. Polygon are returned as a geometry column in a ``geopandas.GeoDataFrame`` structure together with a column `VALUE` with values of each polygon. If raster mask ... | RasterToVectorTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasterToVectorTask:
"""Task for transforming raster mask feature into vector feature. Each connected component with the same value on the raster mask is turned into a shapely polygon. Polygon are returned as a geometry column in a ``geopandas.GeoDataFrame`` structure together with a column `VALUE... | stack_v2_sparse_classes_36k_train_031196 | 22,267 | permissive | [
{
"docstring": ":param features: One or more raster mask features which will be vectorized together with an optional new name of vector feature. If no new name is given the same name will be used. Examples: - `features=(FeatureType.MASK, 'CLOUD_MASK', 'VECTOR_CLOUD_MASK')` - `features=[(FeatureType.MASK_TIMELES... | 3 | null | Implement the Python class `RasterToVectorTask` described below.
Class description:
Task for transforming raster mask feature into vector feature. Each connected component with the same value on the raster mask is turned into a shapely polygon. Polygon are returned as a geometry column in a ``geopandas.GeoDataFrame`` ... | Implement the Python class `RasterToVectorTask` described below.
Class description:
Task for transforming raster mask feature into vector feature. Each connected component with the same value on the raster mask is turned into a shapely polygon. Polygon are returned as a geometry column in a ``geopandas.GeoDataFrame`` ... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class RasterToVectorTask:
"""Task for transforming raster mask feature into vector feature. Each connected component with the same value on the raster mask is turned into a shapely polygon. Polygon are returned as a geometry column in a ``geopandas.GeoDataFrame`` structure together with a column `VALUE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasterToVectorTask:
"""Task for transforming raster mask feature into vector feature. Each connected component with the same value on the raster mask is turned into a shapely polygon. Polygon are returned as a geometry column in a ``geopandas.GeoDataFrame`` structure together with a column `VALUE` with values... | the_stack_v2_python_sparse | geometry/eolearn/geometry/transformations.py | sentinel-hub/eo-learn | train | 1,072 |
c8c69eeb76a952a5d513aaf6b8cabbfe5803e075 | [
"QUiLoader.__init__(self, baseinstance)\nself.baseinstance = baseinstance\nif customWidgets is None:\n self.customWidgets = {}\nelse:\n self.customWidgets = customWidgets",
"if parent is None and self.baseinstance:\n return self.baseinstance\nelse:\n if class_name in self.availableWidgets() or class_n... | <|body_start_0|>
QUiLoader.__init__(self, baseinstance)
self.baseinstance = baseinstance
if customWidgets is None:
self.customWidgets = {}
else:
self.customWidgets = customWidgets
<|end_body_0|>
<|body_start_1|>
if parent is None and self.baseinstance:
... | Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-level class if needed. This mimics the... | UiLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UiLoader:
"""Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-le... | stack_v2_sparse_classes_36k_train_031197 | 11,582 | permissive | [
{
"docstring": "Create a loader for the given ``baseinstance``. The user interface is created in ``baseinstance``, which must be an instance of the top-level class in the user interface to load, or a subclass thereof. ``customWidgets`` is a dictionary mapping from class name to class object for custom widgets. ... | 2 | stack_v2_sparse_classes_30k_train_011479 | Implement the Python class `UiLoader` described below.
Class description:
Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interfac... | Implement the Python class `UiLoader` described below.
Class description:
Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interfac... | 323c6fef4100220a84daf964ed0b78058862bc29 | <|skeleton|>
class UiLoader:
"""Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-le... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UiLoader:
"""Subclass of :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a base instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-level class if ... | the_stack_v2_python_sparse | winpython/_vendor/qtpy/uic.py | winpython/winpython | train | 1,796 |
e8e9eb5f505df6e09ec40360d3a68d403593d7d1 | [
"self.type = req_type\nself.topic_name = topic_name\nself.tutorials = tutorials\nself.title = title\nself.link = link",
"self.type = metadata['type']\nif self.type == 'internal':\n self.topic_name = metadata['topic_name']\n if 'tutorials' in metadata:\n self.tutorials = metadata['tutorials']\nelse:\n... | <|body_start_0|>
self.type = req_type
self.topic_name = topic_name
self.tutorials = tutorials
self.title = title
self.link = link
<|end_body_0|>
<|body_start_1|>
self.type = metadata['type']
if self.type == 'internal':
self.topic_name = metadata['topi... | Class to describe a training requirement. | Requirement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requirement:
"""Class to describe a training requirement."""
def __init__(self, req_type='internal', topic_name='introduction', title=None, tutorials=None, link=None):
"""Init a Requirement instance."""
<|body_0|>
def init_from_dict(self, metadata):
"""Init from ... | stack_v2_sparse_classes_36k_train_031198 | 2,056 | permissive | [
{
"docstring": "Init a Requirement instance.",
"name": "__init__",
"signature": "def __init__(self, req_type='internal', topic_name='introduction', title=None, tutorials=None, link=None)"
},
{
"docstring": "Init from a dictionary generated by export_to_ordered_dict.",
"name": "init_from_dict... | 3 | null | Implement the Python class `Requirement` described below.
Class description:
Class to describe a training requirement.
Method signatures and docstrings:
- def __init__(self, req_type='internal', topic_name='introduction', title=None, tutorials=None, link=None): Init a Requirement instance.
- def init_from_dict(self, ... | Implement the Python class `Requirement` described below.
Class description:
Class to describe a training requirement.
Method signatures and docstrings:
- def __init__(self, req_type='internal', topic_name='introduction', title=None, tutorials=None, link=None): Init a Requirement instance.
- def init_from_dict(self, ... | 95db94dbd77ab8f273f1fad37fb82c529a94d382 | <|skeleton|>
class Requirement:
"""Class to describe a training requirement."""
def __init__(self, req_type='internal', topic_name='introduction', title=None, tutorials=None, link=None):
"""Init a Requirement instance."""
<|body_0|>
def init_from_dict(self, metadata):
"""Init from ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Requirement:
"""Class to describe a training requirement."""
def __init__(self, req_type='internal', topic_name='introduction', title=None, tutorials=None, link=None):
"""Init a Requirement instance."""
self.type = req_type
self.topic_name = topic_name
self.tutorials = tut... | the_stack_v2_python_sparse | planemo/training/utils.py | galaxyproject/planemo | train | 85 |
47c7c77377fd280e09521a28e89968dd05f3778f | [
"self.width = width\nself.height = height\nself.food = deque(food)\nself.next_food = []\nif self.food:\n self.next_food = self.food.popleft()\nself.curr_pos = [0, 0]\nself.body = deque()\nself.body.append([0, 0])\nself.foods = 0",
"move_dict = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}\nnext_pos = ... | <|body_start_0|>
self.width = width
self.height = height
self.food = deque(food)
self.next_food = []
if self.food:
self.next_food = self.food.popleft()
self.curr_pos = [0, 0]
self.body = deque()
self.body.append([0, 0])
self.foods = 0
<... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k_train_031199 | 1,963 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 31bbbd996d0a9783dc7d516b9af8c0e76792befa | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | design/0353_design_snake_game.py | helenayyan/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.