blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a86aaa32392ebd18a23c7cfbe689989e7dafcb08 | [
"behavior_id = uuid4()\nself.registered_behaviors.append((self.event.create_behavior(json_payload['name'], json_payload['parameters']), self.event.create_criteria(json_payload['criteria']), behavior_id))\nreturn behavior_id",
"for behavior, criteria, _ in self.registered_behaviors:\n if criteria.evaluate(attri... | <|body_start_0|>
behavior_id = uuid4()
self.registered_behaviors.append((self.event.create_behavior(json_payload['name'], json_payload['parameters']), self.event.create_criteria(json_payload['criteria']), behavior_id))
return behavior_id
<|end_body_0|>
<|body_start_1|>
for behavior, cri... | A registry of behavior. :ivar EventDescription event: The event this registry is operating for. :ivar registered_behaviors: The set of criteria and behaviors to use for this event. Currently this is just a list of tuples of (behavior, criteria, and uuid). | BehaviorRegistry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BehaviorRegistry:
"""A registry of behavior. :ivar EventDescription event: The event this registry is operating for. :ivar registered_behaviors: The set of criteria and behaviors to use for this event. Currently this is just a list of tuples of (behavior, criteria, and uuid)."""
def register... | stack_v2_sparse_classes_10k_train_003400 | 13,532 | permissive | [
{
"docstring": "Register a behavior with the given JSON payload from a request.",
"name": "register_from_json",
"signature": "def register_from_json(self, json_payload)"
},
{
"docstring": "Retrive a previously-registered behavior given the set of attributes.",
"name": "behavior_for_attribute... | 3 | stack_v2_sparse_classes_30k_train_002918 | Implement the Python class `BehaviorRegistry` described below.
Class description:
A registry of behavior. :ivar EventDescription event: The event this registry is operating for. :ivar registered_behaviors: The set of criteria and behaviors to use for this event. Currently this is just a list of tuples of (behavior, cr... | Implement the Python class `BehaviorRegistry` described below.
Class description:
A registry of behavior. :ivar EventDescription event: The event this registry is operating for. :ivar registered_behaviors: The set of criteria and behaviors to use for this event. Currently this is just a list of tuples of (behavior, cr... | 8e7eeed84ec5ae97863f9330023298845623c639 | <|skeleton|>
class BehaviorRegistry:
"""A registry of behavior. :ivar EventDescription event: The event this registry is operating for. :ivar registered_behaviors: The set of criteria and behaviors to use for this event. Currently this is just a list of tuples of (behavior, criteria, and uuid)."""
def register... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BehaviorRegistry:
"""A registry of behavior. :ivar EventDescription event: The event this registry is operating for. :ivar registered_behaviors: The set of criteria and behaviors to use for this event. Currently this is just a list of tuples of (behavior, criteria, and uuid)."""
def register_from_json(se... | the_stack_v2_python_sparse | mimic/model/behaviors.py | ranjithpeddi/mimic | train | 1 |
4d20d98aa324aed7861c4a62860a2ec18fbec141 | [
"super(ElaboratedEntireSpaceSupervisedMultiTaskModel, self).__init__()\nself.impress_to_click_pooling = nn.AdaptiveAvgPool1d(1)\nself.click_to_daction_pooling = nn.AdaptiveAvgPool1d(1)\nself.daction_to_buy_pooling = nn.AdaptiveAvgPool1d(1)\nself.oaction_to_buy_pooling = nn.AdaptiveAvgPool1d(1)\nself.impress_to_clic... | <|body_start_0|>
super(ElaboratedEntireSpaceSupervisedMultiTaskModel, self).__init__()
self.impress_to_click_pooling = nn.AdaptiveAvgPool1d(1)
self.click_to_daction_pooling = nn.AdaptiveAvgPool1d(1)
self.daction_to_buy_pooling = nn.AdaptiveAvgPool1d(1)
self.oaction_to_buy_pooling... | Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by adding two more base model to predict the direct CVR (Deterministic Acti... | ElaboratedEntireSpaceSupervisedMultiTaskModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElaboratedEntireSpaceSupervisedMultiTaskModel:
"""Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by... | stack_v2_sparse_classes_10k_train_003401 | 7,284 | permissive | [
{
"docstring": "Initialize ElaboratedEntireSpaceSupervisedMultiTaskModel Args: num_fields (int): Number of inputs' fields layer_sizes (List[int]): Layer sizes of dense network dropout_p (List[float], optional): Probability of Dropout in dense network. Defaults to None. activation (Callable[[T], T], optional): A... | 2 | stack_v2_sparse_classes_30k_train_002179 | Implement the Python class `ElaboratedEntireSpaceSupervisedMultiTaskModel` described below.
Class description:
Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions ... | Implement the Python class `ElaboratedEntireSpaceSupervisedMultiTaskModel` described below.
Class description:
Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions ... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class ElaboratedEntireSpaceSupervisedMultiTaskModel:
"""Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ElaboratedEntireSpaceSupervisedMultiTaskModel:
"""Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2). Elaborated Entire Space Supervised Multi Task Model is a variant of Entire Space Multi Task Model, which is to handle missed actions to order, like cart, wish, like etc, by adding two m... | the_stack_v2_python_sparse | torecsys/models/ctr/elaborated_entire_space_supervised_multi_task.py | zwcdp/torecsys | train | 0 |
1303a02da360a90eefefe6429429b3802c492211 | [
"if self.extra_state.get('matching'):\n return Group.objects.filter(local_site=self.extra_state['local_site'])\nelse:\n request = self.extra_state.get('request')\n assert request is not None\n if 'local_site' in self.extra_state:\n local_site = self.extra_state['local_site']\n else:\n l... | <|body_start_0|>
if self.extra_state.get('matching'):
return Group.objects.filter(local_site=self.extra_state['local_site'])
else:
request = self.extra_state.get('request')
assert request is not None
if 'local_site' in self.extra_state:
loc... | A condition choice for matching review groups. This is used to match a :py:class:`~reviewboard.reviews.models.group.Group` against a list of groups, against no group (empty list), or against a group's public/invite-only state. | ReviewGroupsChoice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewGroupsChoice:
"""A condition choice for matching review groups. This is used to match a :py:class:`~reviewboard.reviews.models.group.Group` against a list of groups, against no group (empty list), or against a group's public/invite-only state."""
def get_queryset(self):
"""Retu... | stack_v2_sparse_classes_10k_train_003402 | 16,348 | permissive | [
{
"docstring": "Return the queryset used to look up review group choices. Returns: django.db.models.query.QuerySet: The queryset for review groups.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Return the review groups used for matching. Args: review_groups (... | 2 | null | Implement the Python class `ReviewGroupsChoice` described below.
Class description:
A condition choice for matching review groups. This is used to match a :py:class:`~reviewboard.reviews.models.group.Group` against a list of groups, against no group (empty list), or against a group's public/invite-only state.
Method ... | Implement the Python class `ReviewGroupsChoice` described below.
Class description:
A condition choice for matching review groups. This is used to match a :py:class:`~reviewboard.reviews.models.group.Group` against a list of groups, against no group (empty list), or against a group's public/invite-only state.
Method ... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class ReviewGroupsChoice:
"""A condition choice for matching review groups. This is used to match a :py:class:`~reviewboard.reviews.models.group.Group` against a list of groups, against no group (empty list), or against a group's public/invite-only state."""
def get_queryset(self):
"""Retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReviewGroupsChoice:
"""A condition choice for matching review groups. This is used to match a :py:class:`~reviewboard.reviews.models.group.Group` against a list of groups, against no group (empty list), or against a group's public/invite-only state."""
def get_queryset(self):
"""Return the querys... | the_stack_v2_python_sparse | reviewboard/reviews/conditions.py | reviewboard/reviewboard | train | 1,141 |
80ee4760bf6f18b6e9079870a9f94db99e4d97d5 | [
"if root is None:\n return False\nif root.val == 1:\n return True\nreturn self.hasOne(root.left) or self.hasOne(root.right)",
"if root is None:\n return root\nif self.hasOne(root.left):\n root.left = self.pruneTree(root.left)\nelse:\n root.left = None\nif self.hasOne(root.right):\n root.right = ... | <|body_start_0|>
if root is None:
return False
if root.val == 1:
return True
return self.hasOne(root.left) or self.hasOne(root.right)
<|end_body_0|>
<|body_start_1|>
if root is None:
return root
if self.hasOne(root.left):
root.left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasOne(self, root):
""":type root: TreeNode :rtype: Boolean"""
<|body_0|>
def pruneTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return False
... | stack_v2_sparse_classes_10k_train_003403 | 1,090 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: Boolean",
"name": "hasOne",
"signature": "def hasOne(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "pruneTree",
"signature": "def pruneTree(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002824 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasOne(self, root): :type root: TreeNode :rtype: Boolean
- def pruneTree(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasOne(self, root): :type root: TreeNode :rtype: Boolean
- def pruneTree(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solution:
def hasOne(self... | f8b35179b980e55f61bbcd2631fa3a9bf30c40ec | <|skeleton|>
class Solution:
def hasOne(self, root):
""":type root: TreeNode :rtype: Boolean"""
<|body_0|>
def pruneTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hasOne(self, root):
""":type root: TreeNode :rtype: Boolean"""
if root is None:
return False
if root.val == 1:
return True
return self.hasOne(root.left) or self.hasOne(root.right)
def pruneTree(self, root):
""":type root: TreeN... | the_stack_v2_python_sparse | Python Solutions/814 Binary Tree Pruning.py | Sue9/Leetcode | train | 0 | |
8d20f4a9c275b515ac04961662973dfb7330ef37 | [
"store = StoreModel.query.filter_by(id=store_id).first()\nif not store or not store:\n store_api.abort(404, \"Store {} doesn't exist\".format(store_id))\nreturn store.products",
"store = StoreModel.query.filter_by(id=store_id).first()\nif not store:\n store_api.abort(404, 'Store {} not found'.format(store_i... | <|body_start_0|>
store = StoreModel.query.filter_by(id=store_id).first()
if not store or not store:
store_api.abort(404, "Store {} doesn't exist".format(store_id))
return store.products
<|end_body_0|>
<|body_start_1|>
store = StoreModel.query.filter_by(id=store_id).first()
... | StoreStockList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreStockList:
def get(self, store_id):
"""List all products given the store relation"""
<|body_0|>
def post(self, store_id):
"""Associate product to the given store with the intermediate table 'stocks'"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003404 | 4,193 | no_license | [
{
"docstring": "List all products given the store relation",
"name": "get",
"signature": "def get(self, store_id)"
},
{
"docstring": "Associate product to the given store with the intermediate table 'stocks'",
"name": "post",
"signature": "def post(self, store_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006066 | Implement the Python class `StoreStockList` described below.
Class description:
Implement the StoreStockList class.
Method signatures and docstrings:
- def get(self, store_id): List all products given the store relation
- def post(self, store_id): Associate product to the given store with the intermediate table 'stoc... | Implement the Python class `StoreStockList` described below.
Class description:
Implement the StoreStockList class.
Method signatures and docstrings:
- def get(self, store_id): List all products given the store relation
- def post(self, store_id): Associate product to the given store with the intermediate table 'stoc... | f380164e92b70874042364ad4b5b20c5793d6921 | <|skeleton|>
class StoreStockList:
def get(self, store_id):
"""List all products given the store relation"""
<|body_0|>
def post(self, store_id):
"""Associate product to the given store with the intermediate table 'stocks'"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StoreStockList:
def get(self, store_id):
"""List all products given the store relation"""
store = StoreModel.query.filter_by(id=store_id).first()
if not store or not store:
store_api.abort(404, "Store {} doesn't exist".format(store_id))
return store.products
de... | the_stack_v2_python_sparse | project/app/main/controllers/store.py | ArielVilleda/docker-flask-postgres | train | 0 | |
e40fbbeb90abfe8662eb148e1475bf7bc8542ee3 | [
"self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"xh = np.concatenate((h_prev, x_t), axis=1)\na_next = np.tanh(np.dot(xh, self.Wh) + self.bh)\ny_pred = np.dot(a_next, self.Wy) + self.by\ny_pred = np.exp(y_pred) / np.sum... | <|body_start_0|>
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
xh = np.concatenate((h_prev, x_t), axis=1)
a_next = np.tanh(np.dot(xh, self.Wh) + se... | RNN cell | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""RNN cell"""
def __init__(self, i, h, o):
"""* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Returns: h_next, y"""
<|body_1|>
<... | stack_v2_sparse_classes_10k_train_003405 | 818 | no_license | [
{
"docstring": "* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Returns: h_next, y",
"name": "forward",
"signature": "def forward(self, h... | 2 | stack_v2_sparse_classes_30k_val_000404 | Implement the Python class `RNNCell` described below.
Class description:
RNN cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros
- def forward(self, h_prev, x_t): Returns: h_next, y | Implement the Python class `RNNCell` described below.
Class description:
RNN cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros
- def forward(self, h_prev, x_t): Returns: h_next, y
<|... | 9ff78818c132d1233c11b8fc8fd469878b23b14e | <|skeleton|>
class RNNCell:
"""RNN cell"""
def __init__(self, i, h, o):
"""* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Returns: h_next, y"""
<|body_1|>
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""RNN cell"""
def __init__(self, i, h, o):
"""* The weights will be used on the right side for matrix multiplication * The biases should be initialized as zeros"""
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.ze... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | Nzparra/holbertonschool-machine_learning | train | 0 |
866d4d13f17b33cf028656e07c3c8a2d55e490c8 | [
"self.sess = sess\nself.model = model\nself.config = config\nself.data_loader = data_loader\nself.cur_iterration = 0\nself.train_writer = tf.summary.FileWriter(self.config.summary_dir, sess.graph)\nself.init = tf.global_variables_initializer()\nself.sess.run(self.init)\nif self.config.load:\n self.model.load(sel... | <|body_start_0|>
self.sess = sess
self.model = model
self.config = config
self.data_loader = data_loader
self.cur_iterration = 0
self.train_writer = tf.summary.FileWriter(self.config.summary_dir, sess.graph)
self.init = tf.global_variables_initializer()
se... | Trainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
def __init__(self, sess, model, data_loader, config, is_training=True):
"""Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]"""
... | stack_v2_sparse_classes_10k_train_003406 | 2,992 | no_license | [
{
"docstring": "Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]",
"name": "__init__",
"signature": "def __init__(self, sess, model, data_loader, config... | 4 | stack_v2_sparse_classes_30k_val_000405 | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, sess, model, data_loader, config, is_training=True): Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[ty... | Implement the Python class `Trainer` described below.
Class description:
Implement the Trainer class.
Method signatures and docstrings:
- def __init__(self, sess, model, data_loader, config, is_training=True): Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[ty... | 6d91ba88c12568cf296d583a2e176f6853961ad6 | <|skeleton|>
class Trainer:
def __init__(self, sess, model, data_loader, config, is_training=True):
"""Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trainer:
def __init__(self, sess, model, data_loader, config, is_training=True):
"""Initilization of train Arguments: sess {[type]} -- [description] model {[type]} -- [description] config {[type]} -- [description] logger {[type]} -- [description] data_loader {[type]} -- [description]"""
self.s... | the_stack_v2_python_sparse | triplet_learning/stage_6/trainer/trainer.py | shangliy/SL_Model_Methods | train | 0 | |
8991b6fadad30d37a7d09b27b490612843014efc | [
"super().__init__(coordinator, device)\nself._mac = device.mac\nself._omada_client = coordinator.omada_client\nself._attr_unique_id = f'{device.mac}_firmware'",
"status = self.coordinator.data[self._mac]\nif status.firmware:\n return status.firmware.release_notes\nreturn None",
"try:\n await self._omada_c... | <|body_start_0|>
super().__init__(coordinator, device)
self._mac = device.mac
self._omada_client = coordinator.omada_client
self._attr_unique_id = f'{device.mac}_firmware'
<|end_body_0|>
<|body_start_1|>
status = self.coordinator.data[self._mac]
if status.firmware:
... | Firmware update status for Omada SDN devices. | OmadaDeviceUpdate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OmadaDeviceUpdate:
"""Firmware update status for Omada SDN devices."""
def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None:
"""Initialize the update entity."""
<|body_0|>
def release_notes(self) -> str | None:
"""Get th... | stack_v2_sparse_classes_10k_train_003407 | 5,250 | permissive | [
{
"docstring": "Initialize the update entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None"
},
{
"docstring": "Get the release notes for the latest update.",
"name": "release_notes",
"signature": "def ... | 4 | null | Implement the Python class `OmadaDeviceUpdate` described below.
Class description:
Firmware update status for Omada SDN devices.
Method signatures and docstrings:
- def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: Initialize the update entity.
- def release_notes(self) ... | Implement the Python class `OmadaDeviceUpdate` described below.
Class description:
Firmware update status for Omada SDN devices.
Method signatures and docstrings:
- def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None: Initialize the update entity.
- def release_notes(self) ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OmadaDeviceUpdate:
"""Firmware update status for Omada SDN devices."""
def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None:
"""Initialize the update entity."""
<|body_0|>
def release_notes(self) -> str | None:
"""Get th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OmadaDeviceUpdate:
"""Firmware update status for Omada SDN devices."""
def __init__(self, coordinator: OmadaFirmwareUpdateCoodinator, device: OmadaListDevice) -> None:
"""Initialize the update entity."""
super().__init__(coordinator, device)
self._mac = device.mac
self._om... | the_stack_v2_python_sparse | homeassistant/components/tplink_omada/update.py | home-assistant/core | train | 35,501 |
80646d2c2036115c8bfaafaa8b73704303b86707 | [
"m, n = (len(matrix), len(matrix[0]))\nfor i in xrange(m / 2):\n tmp1 = [e[n - 1 - i] for e in matrix[i:n - i]]\n tmp2 = matrix[n - 1 - i][i:n - i]\n tmp2.reverse()\n tmp3 = [e[i] for e in matrix[i:n - i]]\n tmp3.reverse()\n tmp4 = matrix[i][i:n - i]\n for j in xrange(i, n - i):\n matrix... | <|body_start_0|>
m, n = (len(matrix), len(matrix[0]))
for i in xrange(m / 2):
tmp1 = [e[n - 1 - i] for e in matrix[i:n - i]]
tmp2 = matrix[n - 1 - i][i:n - i]
tmp2.reverse()
tmp3 = [e[i] for e in matrix[i:n - i]]
tmp3.reverse()
tmp4... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_10k_train_003408 | 3,108 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
... | 3 | stack_v2_sparse_classes_30k_test_000242 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate2(self, matrix): :type matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate2(self, matrix): :type matrix: List[List[... | 4aa3a3a0da8b911e140446352debb9b567b6d78b | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
m, n = (len(matrix), len(matrix[0]))
for i in xrange(m / 2):
tmp1 = [e[n - 1 - i] for e in matrix[i:n - i]]
tmp2 = matrix... | the_stack_v2_python_sparse | rotate_image_48.py | adiggo/leetcode_py | train | 0 | |
114153d53207976669032450fd46630da6b8c20a | [
"assert sampling_type in ['gaussian', 'uniform']\nname_to_transform_func = name_to_transform_func or _NAME_TO_TRANSFORM_FUNC\nlevel_to_arg = level_to_arg or _LEVEL_TO_ARG\ntransform_max_paras = transform_max_paras or _TRANSFORM_MAX_PARAMS\nself.transform_hparas = transform_hparas or TRANSFORM_DEFAULT_HPARAS\nself.s... | <|body_start_0|>
assert sampling_type in ['gaussian', 'uniform']
name_to_transform_func = name_to_transform_func or _NAME_TO_TRANSFORM_FUNC
level_to_arg = level_to_arg or _LEVEL_TO_ARG
transform_max_paras = transform_max_paras or _TRANSFORM_MAX_PARAMS
self.transform_hparas = tran... | AugmentTransform | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugmentTransform:
def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dict[str, Callable]]=None, transform_max_paras: Optional[Dict[str, Tuple]]=None, transform_hparas: Optional[Dict[str, A... | stack_v2_sparse_classes_10k_train_003409 | 17,662 | permissive | [
{
"docstring": "The AugmentTransform composes a video transform that performs augmentation based on a maximum magnitude. AugmentTransform also offers flexible ways to generate augmentation magnitude based on different sampling strategies. Args: transform_name (str): The name of the video transform function. mag... | 3 | stack_v2_sparse_classes_30k_train_000905 | Implement the Python class `AugmentTransform` described below.
Class description:
Implement the AugmentTransform class.
Method signatures and docstrings:
- def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dic... | Implement the Python class `AugmentTransform` described below.
Class description:
Implement the AugmentTransform class.
Method signatures and docstrings:
- def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dic... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class AugmentTransform:
def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dict[str, Callable]]=None, transform_max_paras: Optional[Dict[str, Tuple]]=None, transform_hparas: Optional[Dict[str, A... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AugmentTransform:
def __init__(self, transform_name: str, magnitude: int=10, prob: float=0.5, name_to_transform_func: Optional[Dict[str, Callable]]=None, level_to_arg: Optional[Dict[str, Callable]]=None, transform_max_paras: Optional[Dict[str, Tuple]]=None, transform_hparas: Optional[Dict[str, Any]]=None, sam... | the_stack_v2_python_sparse | pytorchvideo/transforms/augmentations.py | xchani/pytorchvideo | train | 0 | |
8c7cc6e9bd3ee879e0df00a39731e64c622b1bbc | [
"self.backup_run = backup_run\nself.change_event_id = change_event_id\nself.copy_run = copy_run\nself.job_run_id = job_run_id\nself.protection_job_run_uid = protection_job_run_uid\nself.snapshot_target = snapshot_target\nself.snapshot_target_type = snapshot_target_type\nself.task_status = task_status\nself.uuid = u... | <|body_start_0|>
self.backup_run = backup_run
self.change_event_id = change_event_id
self.copy_run = copy_run
self.job_run_id = job_run_id
self.protection_job_run_uid = protection_job_run_uid
self.snapshot_target = snapshot_target
self.snapshot_target_type = snaps... | Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event_id (long|int): Specifies the event id which ca... | LatestProtectionRun | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatestProtectionRun:
"""Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event... | stack_v2_sparse_classes_10k_train_003410 | 4,565 | permissive | [
{
"docstring": "Constructor for the LatestProtectionRun class",
"name": "__init__",
"signature": "def __init__(self, backup_run=None, change_event_id=None, copy_run=None, job_run_id=None, protection_job_run_uid=None, snapshot_target=None, snapshot_target_type=None, task_status=None, uuid=None)"
},
{... | 2 | null | Implement the Python class `LatestProtectionRun` described below.
Class description:
Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local ... | Implement the Python class `LatestProtectionRun` described below.
Class description:
Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LatestProtectionRun:
"""Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LatestProtectionRun:
"""Implementation of the 'LatestProtectionRun' model. Specifies the information about the latest Protection Run. Attributes: backup_run (SourceBackupStatus): Specifies information about the latest successful Protection Job Run for local and replication snapshots. change_event_id (long|int... | the_stack_v2_python_sparse | cohesity_management_sdk/models/latest_protection_run.py | cohesity/management-sdk-python | train | 24 |
7754a3ca009cf3c163986f1c20afdbbf5756bc04 | [
"res = ApiFactory.get_home_api().banner_api()\nlogging.info('请求地址:{}'.format(res.url))\nlogging.info('响应数据:{}'.format(res.json()))\nassert res.status_code == 200\nassert res.json().get('id') == 1 and res.json().get('name') == '首页置顶'\nassert len(res.json().get('items')) > 0",
"res = ApiFactory.get_home_api().theme... | <|body_start_0|>
res = ApiFactory.get_home_api().banner_api()
logging.info('请求地址:{}'.format(res.url))
logging.info('响应数据:{}'.format(res.json()))
assert res.status_code == 200
assert res.json().get('id') == 1 and res.json().get('name') == '首页置顶'
assert len(res.json().get('... | TestHomeApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHomeApi:
def test_home_api(self):
"""轮播图"""
<|body_0|>
def test_theme_api(self):
"""专题栏"""
<|body_1|>
def test_recent_product_api(self):
"""最新新品"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
res = ApiFactory.get_home_api()... | stack_v2_sparse_classes_10k_train_003411 | 1,705 | no_license | [
{
"docstring": "轮播图",
"name": "test_home_api",
"signature": "def test_home_api(self)"
},
{
"docstring": "专题栏",
"name": "test_theme_api",
"signature": "def test_theme_api(self)"
},
{
"docstring": "最新新品",
"name": "test_recent_product_api",
"signature": "def test_recent_prod... | 3 | stack_v2_sparse_classes_30k_train_000633 | Implement the Python class `TestHomeApi` described below.
Class description:
Implement the TestHomeApi class.
Method signatures and docstrings:
- def test_home_api(self): 轮播图
- def test_theme_api(self): 专题栏
- def test_recent_product_api(self): 最新新品 | Implement the Python class `TestHomeApi` described below.
Class description:
Implement the TestHomeApi class.
Method signatures and docstrings:
- def test_home_api(self): 轮播图
- def test_theme_api(self): 专题栏
- def test_recent_product_api(self): 最新新品
<|skeleton|>
class TestHomeApi:
def test_home_api(self):
... | 8c0f3b3b499311f2dc0e2e5a1738476e0af77cac | <|skeleton|>
class TestHomeApi:
def test_home_api(self):
"""轮播图"""
<|body_0|>
def test_theme_api(self):
"""专题栏"""
<|body_1|>
def test_recent_product_api(self):
"""最新新品"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestHomeApi:
def test_home_api(self):
"""轮播图"""
res = ApiFactory.get_home_api().banner_api()
logging.info('请求地址:{}'.format(res.url))
logging.info('响应数据:{}'.format(res.json()))
assert res.status_code == 200
assert res.json().get('id') == 1 and res.json().get('nam... | the_stack_v2_python_sparse | Scripts/testHome.py | yang9801/ego | train | 1 | |
0138a77c06865245c98d99bfcf47fb0b1ce9d11e | [
"super().__init__(device=device)\nxyz = _handle_input(x, y, z, dtype, device, 'scale', allow_singleton=True)\nN = xyz.shape[0]\nmat = torch.eye(4, dtype=dtype, device=device)\nmat = mat.view(1, 4, 4).repeat(N, 1, 1)\nmat[:, 0, 0] = xyz[:, 0]\nmat[:, 1, 1] = xyz[:, 1]\nmat[:, 2, 2] = xyz[:, 2]\nself._matrix = mat",
... | <|body_start_0|>
super().__init__(device=device)
xyz = _handle_input(x, y, z, dtype, device, 'scale', allow_singleton=True)
N = xyz.shape[0]
mat = torch.eye(4, dtype=dtype, device=device)
mat = mat.view(1, 4, 4).repeat(N, 1, 1)
mat[:, 0, 0] = xyz[:, 0]
mat[:, 1, 1... | Scale | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scale:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""A Transform3d representing a scaling operation, with different scale factors along each coordinate axis. Option I: Scale(s, dtype=torch.float32, device='cpu') s can be one of - Python scalar or torch scal... | stack_v2_sparse_classes_10k_train_003412 | 43,607 | permissive | [
{
"docstring": "A Transform3d representing a scaling operation, with different scale factors along each coordinate axis. Option I: Scale(s, dtype=torch.float32, device='cpu') s can be one of - Python scalar or torch scalar: Single uniform scale - 1D torch tensor of shape (N,): A batch of uniform scale - 2D torc... | 2 | stack_v2_sparse_classes_30k_train_003938 | Implement the Python class `Scale` described below.
Class description:
Implement the Scale class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'): A Transform3d representing a scaling operation, with different scale factors along each coordinate axis. Optio... | Implement the Python class `Scale` described below.
Class description:
Implement the Scale class.
Method signatures and docstrings:
- def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'): A Transform3d representing a scaling operation, with different scale factors along each coordinate axis. Optio... | 1d240f60a99682e8409363c5829aba14869ba140 | <|skeleton|>
class Scale:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""A Transform3d representing a scaling operation, with different scale factors along each coordinate axis. Option I: Scale(s, dtype=torch.float32, device='cpu') s can be one of - Python scalar or torch scal... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Scale:
def __init__(self, x, y=None, z=None, dtype=torch.float32, device='cpu'):
"""A Transform3d representing a scaling operation, with different scale factors along each coordinate axis. Option I: Scale(s, dtype=torch.float32, device='cpu') s can be one of - Python scalar or torch scalar: Single uni... | the_stack_v2_python_sparse | soft_intro_vae_3d/datasets/transforms3d.py | LearnerLYH/soft-intro-vae-pytorch | train | 1 | |
be526d189d75c5c7b2352215b2348f3c49e6d51e | [
"result = []\nif root != None:\n if root.left:\n result += self.inorderTraversal(root.left)\n result += [root.val]\n if root.right:\n result += self.inorderTraversal(root.right)\nelse:\n return []\nreturn result",
"result = []\nif root == None:\n return []\nif root == []:\n return ... | <|body_start_0|>
result = []
if root != None:
if root.left:
result += self.inorderTraversal(root.left)
result += [root.val]
if root.right:
result += self.inorderTraversal(root.right)
else:
return []
return re... | recusion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class recusion:
def inorderTraversal(self, root):
"""中序遍历 :type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal(self, root):
"""前序遍历 :type root: TreeNode :rtype: List[int]"""
<|body_1|>
def postorderTraversal(self, root):
"""后序遍历 :... | stack_v2_sparse_classes_10k_train_003413 | 3,316 | no_license | [
{
"docstring": "中序遍历 :type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": "前序遍历 :type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
},
... | 3 | stack_v2_sparse_classes_30k_train_000419 | Implement the Python class `recusion` described below.
Class description:
Implement the recusion class.
Method signatures and docstrings:
- def inorderTraversal(self, root): 中序遍历 :type root: TreeNode :rtype: List[int]
- def preorderTraversal(self, root): 前序遍历 :type root: TreeNode :rtype: List[int]
- def postorderTrav... | Implement the Python class `recusion` described below.
Class description:
Implement the recusion class.
Method signatures and docstrings:
- def inorderTraversal(self, root): 中序遍历 :type root: TreeNode :rtype: List[int]
- def preorderTraversal(self, root): 前序遍历 :type root: TreeNode :rtype: List[int]
- def postorderTrav... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class recusion:
def inorderTraversal(self, root):
"""中序遍历 :type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal(self, root):
"""前序遍历 :type root: TreeNode :rtype: List[int]"""
<|body_1|>
def postorderTraversal(self, root):
"""后序遍历 :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class recusion:
def inorderTraversal(self, root):
"""中序遍历 :type root: TreeNode :rtype: List[int]"""
result = []
if root != None:
if root.left:
result += self.inorderTraversal(root.left)
result += [root.val]
if root.right:
re... | the_stack_v2_python_sparse | BinaryTree_not_recusion.py | NeilWangziyu/Leetcode_py | train | 2 | |
1d8338ec46b2d0a4343c696ab7416899db0f6d88 | [
"if model_name is None:\n if model is None:\n self.model = Defaults.model\n else:\n self.model = model\nelse:\n self.model = Defaults.models[model_name]\nself.scores = []\nfor its in range(len(self.end_sites)):\n if Defaults.model_select:\n self.model = Defaults.model_select(self, i... | <|body_start_0|>
if model_name is None:
if model is None:
self.model = Defaults.model
else:
self.model = model
else:
self.model = Defaults.models[model_name]
self.scores = []
for its in range(len(self.end_sites)):
... | mmModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mmModel:
def eval_score(self, model_name=None, model=None):
"""Computes the *miRmap* score(s). :param model_name: Model name. :type model_name: str :param model: Model with coefficients and intercept as keys. :type model: dict"""
<|body_0|>
def score(self):
"""*miRma... | stack_v2_sparse_classes_10k_train_003414 | 23,750 | permissive | [
{
"docstring": "Computes the *miRmap* score(s). :param model_name: Model name. :type model_name: str :param model: Model with coefficients and intercept as keys. :type model: dict",
"name": "eval_score",
"signature": "def eval_score(self, model_name=None, model=None)"
},
{
"docstring": "*miRmap*... | 2 | stack_v2_sparse_classes_30k_train_003473 | Implement the Python class `mmModel` described below.
Class description:
Implement the mmModel class.
Method signatures and docstrings:
- def eval_score(self, model_name=None, model=None): Computes the *miRmap* score(s). :param model_name: Model name. :type model_name: str :param model: Model with coefficients and in... | Implement the Python class `mmModel` described below.
Class description:
Implement the mmModel class.
Method signatures and docstrings:
- def eval_score(self, model_name=None, model=None): Computes the *miRmap* score(s). :param model_name: Model name. :type model_name: str :param model: Model with coefficients and in... | f608578defb122a1782cff39c5a9a60be0a900df | <|skeleton|>
class mmModel:
def eval_score(self, model_name=None, model=None):
"""Computes the *miRmap* score(s). :param model_name: Model name. :type model_name: str :param model: Model with coefficients and intercept as keys. :type model: dict"""
<|body_0|>
def score(self):
"""*miRma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class mmModel:
def eval_score(self, model_name=None, model=None):
"""Computes the *miRmap* score(s). :param model_name: Model name. :type model_name: str :param model: Model with coefficients and intercept as keys. :type model: dict"""
if model_name is None:
if model is None:
... | the_stack_v2_python_sparse | node/mirmap/model.py | RNAEDITINGPLUS/main | train | 4 | |
c7d64e0427e3b62463bfe7302ece906cd7de6f3b | [
"self.rho = rho\nself.stepSize = alpha_step\nself.stepFactor = alpha_factor",
"direction = state['direction']\nif 'initial_alpha_step' in state:\n alpha = state['initial_alpha_step']\nelse:\n alpha = self.stepSize\nf1temp = function(origin)\ngradient = state['gradient']\nwhile True:\n ftemp = function(or... | <|body_start_0|>
self.rho = rho
self.stepSize = alpha_step
self.stepFactor = alpha_factor
<|end_body_0|>
<|body_start_1|>
direction = state['direction']
if 'initial_alpha_step' in state:
alpha = state['initial_alpha_step']
else:
alpha = self.stepS... | The backtracking algorithm for enforcing Armijo rule | BacktrackingSearch | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BacktrackingSearch:
"""The backtracking algorithm for enforcing Armijo rule"""
def __init__(self, rho=0.1, alpha_step=1.0, alpha_factor=0.5, **kwargs):
"""Can have : - a coefficient for the Armijo rule (rho = 0.1) - an alpha factor to modulate the step (alpha_step = 1.) - an alpha fa... | stack_v2_sparse_classes_10k_train_003415 | 1,202 | permissive | [
{
"docstring": "Can have : - a coefficient for the Armijo rule (rho = 0.1) - an alpha factor to modulate the step (alpha_step = 1.) - an alpha factor < 1 that will decrease the step size until the rule is valid (alpha_factor = 0.5)",
"name": "__init__",
"signature": "def __init__(self, rho=0.1, alpha_st... | 2 | stack_v2_sparse_classes_30k_test_000069 | Implement the Python class `BacktrackingSearch` described below.
Class description:
The backtracking algorithm for enforcing Armijo rule
Method signatures and docstrings:
- def __init__(self, rho=0.1, alpha_step=1.0, alpha_factor=0.5, **kwargs): Can have : - a coefficient for the Armijo rule (rho = 0.1) - an alpha fa... | Implement the Python class `BacktrackingSearch` described below.
Class description:
The backtracking algorithm for enforcing Armijo rule
Method signatures and docstrings:
- def __init__(self, rho=0.1, alpha_step=1.0, alpha_factor=0.5, **kwargs): Can have : - a coefficient for the Armijo rule (rho = 0.1) - an alpha fa... | 3d298e908ff55340cd3612078508be0c791f63a8 | <|skeleton|>
class BacktrackingSearch:
"""The backtracking algorithm for enforcing Armijo rule"""
def __init__(self, rho=0.1, alpha_step=1.0, alpha_factor=0.5, **kwargs):
"""Can have : - a coefficient for the Armijo rule (rho = 0.1) - an alpha factor to modulate the step (alpha_step = 1.) - an alpha fa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BacktrackingSearch:
"""The backtracking algorithm for enforcing Armijo rule"""
def __init__(self, rho=0.1, alpha_step=1.0, alpha_factor=0.5, **kwargs):
"""Can have : - a coefficient for the Armijo rule (rho = 0.1) - an alpha factor to modulate the step (alpha_step = 1.) - an alpha factor < 1 that... | the_stack_v2_python_sparse | PyDSTool/Toolbox/optimizers/line_search/backtracking_search.py | mdlama/pydstool | train | 2 |
8560c0068eff894e5aa1d0788bd9e5ad05c14997 | [
"h = u.planck\nc = u.speed_of_light\npi = np.pi\nreturn 8 * pi / (h * c) ** 3 * ((pi * kT) ** 4 / 15)",
"if kT is not None:\n kT = kT\nelif T is not None:\n kT = u.boltzmann * T\nelse:\n raise Exception('kT or k must be passed to BlackBody')\nenergy_density = BlackBody.compute_energy_density(kT)\nsuper(B... | <|body_start_0|>
h = u.planck
c = u.speed_of_light
pi = np.pi
return 8 * pi / (h * c) ** 3 * ((pi * kT) ** 4 / 15)
<|end_body_0|>
<|body_start_1|>
if kT is not None:
kT = kT
elif T is not None:
kT = u.boltzmann * T
else:
raise ... | BlackBody | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlackBody:
def compute_energy_density(kT):
"""Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi... | stack_v2_sparse_classes_10k_train_003416 | 4,887 | no_license | [
{
"docstring": "Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi*kT)^4/15.",
"name": "compute_energy_density",
... | 2 | stack_v2_sparse_classes_30k_train_001687 | Implement the Python class `BlackBody` described below.
Class description:
Implement the BlackBody class.
Method signatures and docstrings:
- def compute_energy_density(kT): Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*k... | Implement the Python class `BlackBody` described below.
Class description:
Implement the BlackBody class.
Method signatures and docstrings:
- def compute_energy_density(kT): Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*k... | 21d24c0ae70925201b05f73c8044cc39639f8859 | <|skeleton|>
class BlackBody:
def compute_energy_density(kT):
"""Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BlackBody:
def compute_energy_density(kT):
"""Comparing the formula for a blackbody spectrum with prefactor pref = 8pi/(hc)^3 to the fomrula for a general thermal spectrum: pref = 15*U/(pi*kT)^4, we find that for a blackbody spectrum, we have a thermal spectrum with U = (8*pi/(hc)^3)*(pi*kT)^4/15."""
... | the_stack_v2_python_sparse | lande/pysed/sed_thermal.py | zimmerst/PhD-python | train | 0 | |
d5531759c80f209679425418b0f54e56d9709114 | [
"path_sum += triangle[x][y]\nif x == len(triangle) - 1:\n self.res = min(path_sum, self.res)\nelse:\n self.traversal(triangle, x + 1, y, path_sum)\n self.traversal(triangle, x + 1, y + 1, path_sum)",
"self.res = sys.maxsize\nself.traversal(triangle, 0, 0, 0)\nreturn self.res"
] | <|body_start_0|>
path_sum += triangle[x][y]
if x == len(triangle) - 1:
self.res = min(path_sum, self.res)
else:
self.traversal(triangle, x + 1, y, path_sum)
self.traversal(triangle, x + 1, y + 1, path_sum)
<|end_body_0|>
<|body_start_1|>
self.res = sy... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def traversal(self, triangle, x, y, path_sum):
""":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:"""
<|body_0|>
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
... | stack_v2_sparse_classes_10k_train_003417 | 7,199 | no_license | [
{
"docstring": ":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:",
"name": "traversal",
"signature": "def traversal(self, triangle, x, y, path_sum)"
},
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal"... | 2 | stack_v2_sparse_classes_30k_train_006844 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def traversal(self, triangle, x, y, path_sum): :param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:
- def minimumTotal(self, t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def traversal(self, triangle, x, y, path_sum): :param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:
- def minimumTotal(self, t... | bfd16678f179bbfc7564bfc079d2fa4b3e554be6 | <|skeleton|>
class Solution:
def traversal(self, triangle, x, y, path_sum):
""":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:"""
<|body_0|>
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def traversal(self, triangle, x, y, path_sum):
""":param x: the pos x to be visited :param y: the pos y to be visited :param path_sum: sum so far :return:"""
path_sum += triangle[x][y]
if x == len(triangle) - 1:
self.res = min(path_sum, self.res)
else:
... | the_stack_v2_python_sparse | DP/triangle.py | HeliWang/upstream | train | 0 | |
de6d7857c25a32012dd9126a63611e5a27762f95 | [
"if n == 2:\n return 1\nif n == 3:\n return 2\ndp = [0] * 60\ndp[2] = 2\ndp[3] = 3\nfor i in range(4, n + 1):\n dp[i] = max((dp[j] * dp[i - j] for j in range(2, i)))\nreturn dp[n]",
"if n == 2:\n return 1\nif n == 3:\n return 2\nif n % 3 == 0:\n return 3 ** (n // 3)\nif n % 3 == 1:\n return 3... | <|body_start_0|>
if n == 2:
return 1
if n == 3:
return 2
dp = [0] * 60
dp[2] = 2
dp[3] = 3
for i in range(4, n + 1):
dp[i] = max((dp[j] * dp[i - j] for j in range(2, i)))
return dp[n]
<|end_body_0|>
<|body_start_1|>
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerBreak(self, n):
"""dp :type n: int :rtype: int"""
<|body_0|>
def integerBreak2(self, n):
"""找规律发现,尽可能多拆一点3值最大 如果n%3是1,最后的3凑成4 :param n: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 2:
return 1
... | stack_v2_sparse_classes_10k_train_003418 | 1,411 | no_license | [
{
"docstring": "dp :type n: int :rtype: int",
"name": "integerBreak",
"signature": "def integerBreak(self, n)"
},
{
"docstring": "找规律发现,尽可能多拆一点3值最大 如果n%3是1,最后的3凑成4 :param n: :return:",
"name": "integerBreak2",
"signature": "def integerBreak2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerBreak(self, n): dp :type n: int :rtype: int
- def integerBreak2(self, n): 找规律发现,尽可能多拆一点3值最大 如果n%3是1,最后的3凑成4 :param n: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerBreak(self, n): dp :type n: int :rtype: int
- def integerBreak2(self, n): 找规律发现,尽可能多拆一点3值最大 如果n%3是1,最后的3凑成4 :param n: :return:
<|skeleton|>
class Solution:
def i... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def integerBreak(self, n):
"""dp :type n: int :rtype: int"""
<|body_0|>
def integerBreak2(self, n):
"""找规律发现,尽可能多拆一点3值最大 如果n%3是1,最后的3凑成4 :param n: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def integerBreak(self, n):
"""dp :type n: int :rtype: int"""
if n == 2:
return 1
if n == 3:
return 2
dp = [0] * 60
dp[2] = 2
dp[3] = 3
for i in range(4, n + 1):
dp[i] = max((dp[j] * dp[i - j] for j in range(2... | the_stack_v2_python_sparse | 343_整数拆分.py | lovehhf/LeetCode | train | 0 | |
1f1bafd03fb7008d142668e97f1fa466cb0f48a8 | [
"RL_agent.__init__(self)\nself.env = env\nself.actions = env.actions\nself.discount = discount\nself.explore = explore\nself.qinit = qinit\nself.updates_per_step = updates_per_step\nself.label = label\nself.restart()",
"self.acc_rewards = 0\nself.state = self.env.state\nself.q = {}\nself.r = {}\nself.t = {}\nself... | <|body_start_0|>
RL_agent.__init__(self)
self.env = env
self.actions = env.actions
self.discount = discount
self.explore = explore
self.qinit = qinit
self.updates_per_step = updates_per_step
self.label = label
self.restart()
<|end_body_0|>
<|body_... | A Model-based reinforcement learner | Model_based_reinforcement_learner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model_based_reinforcement_learner:
"""A Model-based reinforcement learner"""
def __init__(self, env, discount, explore=0.1, qinit=0, updates_per_step=10, label='MBR_learner'):
"""env is the environment to interact with. discount is the discount factor explore is the proportion of tim... | stack_v2_sparse_classes_10k_train_003419 | 4,177 | no_license | [
{
"docstring": "env is the environment to interact with. discount is the discount factor explore is the proportion of time the agent will explore qinit is the initial value of the Q's updates_per_step is the number of AVI updates per action label is the label for plotting",
"name": "__init__",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_003592 | Implement the Python class `Model_based_reinforcement_learner` described below.
Class description:
A Model-based reinforcement learner
Method signatures and docstrings:
- def __init__(self, env, discount, explore=0.1, qinit=0, updates_per_step=10, label='MBR_learner'): env is the environment to interact with. discoun... | Implement the Python class `Model_based_reinforcement_learner` described below.
Class description:
A Model-based reinforcement learner
Method signatures and docstrings:
- def __init__(self, env, discount, explore=0.1, qinit=0, updates_per_step=10, label='MBR_learner'): env is the environment to interact with. discoun... | 479d6120b75ac0ff602f032474cad440cadd9f31 | <|skeleton|>
class Model_based_reinforcement_learner:
"""A Model-based reinforcement learner"""
def __init__(self, env, discount, explore=0.1, qinit=0, updates_per_step=10, label='MBR_learner'):
"""env is the environment to interact with. discount is the discount factor explore is the proportion of tim... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Model_based_reinforcement_learner:
"""A Model-based reinforcement learner"""
def __init__(self, env, discount, explore=0.1, qinit=0, updates_per_step=10, label='MBR_learner'):
"""env is the environment to interact with. discount is the discount factor explore is the proportion of time the agent w... | the_stack_v2_python_sparse | ass1/aipython/rlModelLearner.py | fckphil/COMP9814 | train | 5 |
02d264799b8f25eda1bd7c799735a4538b695e68 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)",
"query_hash = hash(query)\nzhtmlstring = self._GetRowValue(query_hash, row, 'zhtmlstring')\ntext_extractor = _ZHTMLStringTextExtractor()\ntext = text_e... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
zhtmlstring = self._GetRowValue(query_ha... | SQLite parser plugin for MacOS notes database files. The MacOS Notes database file is typically stored in: test_data/NotesV7.storedata | MacOSNotesPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MacOSNotesPlugin:
"""SQLite parser plugin for MacOS notes database files. The MacOS Notes database file is typically stored in: test_data/NotesV7.storedata"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_has... | stack_v2_sparse_classes_10k_train_003420 | 7,734 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.CocoaTime: date and time value or None if not available.",
"name... | 2 | stack_v2_sparse_classes_30k_test_000139 | Implement the Python class `MacOSNotesPlugin` described below.
Class description:
SQLite parser plugin for MacOS notes database files. The MacOS Notes database file is typically stored in: test_data/NotesV7.storedata
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retr... | Implement the Python class `MacOSNotesPlugin` described below.
Class description:
SQLite parser plugin for MacOS notes database files. The MacOS Notes database file is typically stored in: test_data/NotesV7.storedata
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retr... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class MacOSNotesPlugin:
"""SQLite parser plugin for MacOS notes database files. The MacOS Notes database file is typically stored in: test_data/NotesV7.storedata"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_has... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MacOSNotesPlugin:
"""SQLite parser plugin for MacOS notes database files. The MacOS Notes database file is typically stored in: test_data/NotesV7.storedata"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/macos_notes.py | log2timeline/plaso | train | 1,506 |
50fb49cac282e110febff50f23cc5961885bc2bc | [
"npts = len(pts)\nh = ncfs // 2\ncfs = {}\nfor n in range(-h, h + 1):\n cn = 0\n for iw in range(npts):\n w = iw / npts\n fw = complex(*pts[iw])\n cn += fw * cmath.exp(-1j * n * w * wo)\n cn /= npts\n cfs[n] = cn\nreturn cfs",
"ncfs = len(cfs)\nh = npts // 2\npts = []\nfor it in r... | <|body_start_0|>
npts = len(pts)
h = ncfs // 2
cfs = {}
for n in range(-h, h + 1):
cn = 0
for iw in range(npts):
w = iw / npts
fw = complex(*pts[iw])
cn += fw * cmath.exp(-1j * n * w * wo)
cn /= npts
... | Fourier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fourier:
def transform(pts, ncfs, wo=2 * math.pi):
"""Apply the true fourier transform by returning a dictionary of the coefficients."""
<|body_0|>
def inverseTransform(cfs, npts, wo=2 * math.pi):
"""Apply the true fourier inverse transform by returning the list of t... | stack_v2_sparse_classes_10k_train_003421 | 17,065 | permissive | [
{
"docstring": "Apply the true fourier transform by returning a dictionary of the coefficients.",
"name": "transform",
"signature": "def transform(pts, ncfs, wo=2 * math.pi)"
},
{
"docstring": "Apply the true fourier inverse transform by returning the list of the points.",
"name": "inverseTr... | 3 | stack_v2_sparse_classes_30k_train_002122 | Implement the Python class `Fourier` described below.
Class description:
Implement the Fourier class.
Method signatures and docstrings:
- def transform(pts, ncfs, wo=2 * math.pi): Apply the true fourier transform by returning a dictionary of the coefficients.
- def inverseTransform(cfs, npts, wo=2 * math.pi): Apply t... | Implement the Python class `Fourier` described below.
Class description:
Implement the Fourier class.
Method signatures and docstrings:
- def transform(pts, ncfs, wo=2 * math.pi): Apply the true fourier transform by returning a dictionary of the coefficients.
- def inverseTransform(cfs, npts, wo=2 * math.pi): Apply t... | 61abbbeac0fd351253e06b19736d9939fd5b316e | <|skeleton|>
class Fourier:
def transform(pts, ncfs, wo=2 * math.pi):
"""Apply the true fourier transform by returning a dictionary of the coefficients."""
<|body_0|>
def inverseTransform(cfs, npts, wo=2 * math.pi):
"""Apply the true fourier inverse transform by returning the list of t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Fourier:
def transform(pts, ncfs, wo=2 * math.pi):
"""Apply the true fourier transform by returning a dictionary of the coefficients."""
npts = len(pts)
h = ncfs // 2
cfs = {}
for n in range(-h, h + 1):
cn = 0
for iw in range(npts):
... | the_stack_v2_python_sparse | pygame_geometry/demos/myfouriervf.py | MarcPartensky/Pygame-Geometry | train | 7 | |
1dbea07d24a3dd4cd802ad9c72a117c351f0eb12 | [
"self.template_path = template_path\nfrom qmxgraph.configuration import GraphStyles\nfrom qmxgraph.configuration import GraphOptions\nif options is None:\n options = GraphOptions()\nif styles is None:\n styles = GraphStyles()\nself.options = options\nself.styles = styles\nself.stencils = stencils",
"from qm... | <|body_start_0|>
self.template_path = template_path
from qmxgraph.configuration import GraphStyles
from qmxgraph.configuration import GraphOptions
if options is None:
options = GraphOptions()
if styles is None:
styles = GraphStyles()
self.options =... | A simple page showing a graph drawing widget using mxGraph as its backend. | GraphPage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphPage:
"""A simple page showing a graph drawing widget using mxGraph as its backend."""
def __init__(self, template_path, options=None, styles=None, stencils=tuple()):
""":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options o... | stack_v2_sparse_classes_10k_train_003422 | 7,800 | permissive | [
{
"docstring": ":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options of graph drawing widget, uses default if not given. :param GraphStyles styles: Styles available in graph drawing widget, uses default if not given. :param iterable[str] stencils: Stencils ... | 2 | stack_v2_sparse_classes_30k_train_005801 | Implement the Python class `GraphPage` described below.
Class description:
A simple page showing a graph drawing widget using mxGraph as its backend.
Method signatures and docstrings:
- def __init__(self, template_path, options=None, styles=None, stencils=tuple()): :param str template_path: Path where graph HTML temp... | Implement the Python class `GraphPage` described below.
Class description:
A simple page showing a graph drawing widget using mxGraph as its backend.
Method signatures and docstrings:
- def __init__(self, template_path, options=None, styles=None, stencils=tuple()): :param str template_path: Path where graph HTML temp... | e5dcf6294bd06ed08e61be5ac18a5aaa13613923 | <|skeleton|>
class GraphPage:
"""A simple page showing a graph drawing widget using mxGraph as its backend."""
def __init__(self, template_path, options=None, styles=None, stencils=tuple()):
""":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GraphPage:
"""A simple page showing a graph drawing widget using mxGraph as its backend."""
def __init__(self, template_path, options=None, styles=None, stencils=tuple()):
""":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options of graph drawi... | the_stack_v2_python_sparse | src/qmxgraph/server.py | ESSS/qmxgraph | train | 27 |
55d66298ccb3ecfa1070287fe780bf3563017231 | [
"self.head = ListNode(-1, -1)\nself.tail = self.head\nself.key2node = {}\nself.capacity = capacity\nself.length = 0",
"if key not in self.key2node:\n return -1\nnode = self.key2node[key]\nval = node.val\nif node.next:\n node.prev.next = node.next\n node.next.prev = node.prev\n self.tail.next = node\n ... | <|body_start_0|>
self.head = ListNode(-1, -1)
self.tail = self.head
self.key2node = {}
self.capacity = capacity
self.length = 0
<|end_body_0|>
<|body_start_1|>
if key not in self.key2node:
return -1
node = self.key2node[key]
val = node.val
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_003423 | 2,775 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 5f71ba34f7198841fefaa68eee5b95f2f989296b | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.head = ListNode(-1, -1)
self.tail = self.head
self.key2node = {}
self.capacity = capacity
self.length = 0
def get(self, key):
""":type key: int :rtype: int"""
if key not ... | the_stack_v2_python_sparse | LeetCode/medium/17_LRUcache.py | Kohdz/Algorithms | train | 5 | |
155ffd9468ed73ef0650546a42c046379fc1f75c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.deleteUserFromSharedAppleDeviceActionResult... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | Device action result | DeviceActionResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceActionResult:
"""Device action result"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceActionResult:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimi... | stack_v2_sparse_classes_10k_train_003424 | 6,203 | 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: DeviceActionResult",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_004060 | Implement the Python class `DeviceActionResult` described below.
Class description:
Device action result
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceActionResult: Creates a new instance of the appropriate class based on discriminator value Arg... | Implement the Python class `DeviceActionResult` described below.
Class description:
Device action result
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceActionResult: Creates a new instance of the appropriate class based on discriminator value Arg... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceActionResult:
"""Device action result"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceActionResult:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeviceActionResult:
"""Device action result"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceActionResult:
"""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 a... | the_stack_v2_python_sparse | msgraph/generated/models/device_action_result.py | microsoftgraph/msgraph-sdk-python | train | 135 |
7c6fb64589b773c34f34333e6508acfe1dec1fd9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LifecycleManagementSettings()",
"from ..email_settings import EmailSettings\nfrom ..entity import Entity\nfrom ..email_settings import EmailSettings\nfrom ..entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'emailSettin... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LifecycleManagementSettings()
<|end_body_0|>
<|body_start_1|>
from ..email_settings import EmailSettings
from ..entity import Entity
from ..email_settings import EmailSettings
... | LifecycleManagementSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LifecycleManagementSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings:
"""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 a... | stack_v2_sparse_classes_10k_train_003425 | 2,715 | 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: LifecycleManagementSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_005609 | Implement the Python class `LifecycleManagementSettings` described below.
Class description:
Implement the LifecycleManagementSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings: Creates a new instance of the appr... | Implement the Python class `LifecycleManagementSettings` described below.
Class description:
Implement the LifecycleManagementSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LifecycleManagementSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings:
"""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 a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LifecycleManagementSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings:
"""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 ... | the_stack_v2_python_sparse | msgraph/generated/models/identity_governance/lifecycle_management_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
be1487fca74d04eb7b02fbe16b10309944d14a20 | [
"if not tf.executing_eagerly():\n raise ValueError('Only eager mode is currently supported.')\nself._handle = gen_grpc_ops.grpc_client_resource_handle_op(shared_name=context.shared_name(None))\nself._resource_deleter = resource_variable_ops.EagerResourceDeleter(handle=self._handle, handle_device=context.context(... | <|body_start_0|>
if not tf.executing_eagerly():
raise ValueError('Only eager mode is currently supported.')
self._handle = gen_grpc_ops.grpc_client_resource_handle_op(shared_name=context.shared_name(None))
self._resource_deleter = resource_variable_ops.EagerResourceDeleter(handle=sel... | A TensorFlow gRPC client. | Client | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
"""A TensorFlow gRPC client."""
def __init__(self, server_address):
"""Creates and starts the gRPC client. Args: server_address: A string containing the server address."""
<|body_0|>
def _add_method(self, name, output_specs):
"""Adds a method to the clien... | stack_v2_sparse_classes_10k_train_003426 | 5,903 | permissive | [
{
"docstring": "Creates and starts the gRPC client. Args: server_address: A string containing the server address.",
"name": "__init__",
"signature": "def __init__(self, server_address)"
},
{
"docstring": "Adds a method to the client.",
"name": "_add_method",
"signature": "def _add_method... | 2 | stack_v2_sparse_classes_30k_train_001440 | Implement the Python class `Client` described below.
Class description:
A TensorFlow gRPC client.
Method signatures and docstrings:
- def __init__(self, server_address): Creates and starts the gRPC client. Args: server_address: A string containing the server address.
- def _add_method(self, name, output_specs): Adds ... | Implement the Python class `Client` described below.
Class description:
A TensorFlow gRPC client.
Method signatures and docstrings:
- def __init__(self, server_address): Creates and starts the gRPC client. Args: server_address: A string containing the server address.
- def _add_method(self, name, output_specs): Adds ... | 0e1e0ac9178a670ad1e1463baed92020e88905ec | <|skeleton|>
class Client:
"""A TensorFlow gRPC client."""
def __init__(self, server_address):
"""Creates and starts the gRPC client. Args: server_address: A string containing the server address."""
<|body_0|>
def _add_method(self, name, output_specs):
"""Adds a method to the clien... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Client:
"""A TensorFlow gRPC client."""
def __init__(self, server_address):
"""Creates and starts the gRPC client. Args: server_address: A string containing the server address."""
if not tf.executing_eagerly():
raise ValueError('Only eager mode is currently supported.')
... | the_stack_v2_python_sparse | grpc/python/ops.py | google-research/seed_rl | train | 818 |
ff021c5d7db2117db1fa807d5adebbe737324af0 | [
"tk.Frame.__init__(self, parent)\nself.controller = controller\nlbl_enter_test_type = tk.Label(self, text='Type of test run: ')\nlbl_enter_primary_weight = tk.Label(self, text='CVT primary weight: ')\nlbl_enter_primary_spring = tk.Label(self, text='CVT primary spring: ')\nlbl_enter_secondary_spring = tk.Label(self,... | <|body_start_0|>
tk.Frame.__init__(self, parent)
self.controller = controller
lbl_enter_test_type = tk.Label(self, text='Type of test run: ')
lbl_enter_primary_weight = tk.Label(self, text='CVT primary weight: ')
lbl_enter_primary_spring = tk.Label(self, text='CVT primary spring:... | InputPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputPage:
def __init__(self, parent, controller):
"""Create the input page containing the text fields."""
<|body_0|>
def save_info(self, type_of_run, primary_weight, primary_spring, secondary_spring, secondary_clock, controller):
"""Save the information entered in t... | stack_v2_sparse_classes_10k_train_003427 | 6,622 | no_license | [
{
"docstring": "Create the input page containing the text fields.",
"name": "__init__",
"signature": "def __init__(self, parent, controller)"
},
{
"docstring": "Save the information entered in the Input page.",
"name": "save_info",
"signature": "def save_info(self, type_of_run, primary_w... | 2 | stack_v2_sparse_classes_30k_train_004445 | Implement the Python class `InputPage` described below.
Class description:
Implement the InputPage class.
Method signatures and docstrings:
- def __init__(self, parent, controller): Create the input page containing the text fields.
- def save_info(self, type_of_run, primary_weight, primary_spring, secondary_spring, s... | Implement the Python class `InputPage` described below.
Class description:
Implement the InputPage class.
Method signatures and docstrings:
- def __init__(self, parent, controller): Create the input page containing the text fields.
- def save_info(self, type_of_run, primary_weight, primary_spring, secondary_spring, s... | f03b2ce7e634badb0e55396f3914301def57934c | <|skeleton|>
class InputPage:
def __init__(self, parent, controller):
"""Create the input page containing the text fields."""
<|body_0|>
def save_info(self, type_of_run, primary_weight, primary_spring, secondary_spring, secondary_clock, controller):
"""Save the information entered in t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InputPage:
def __init__(self, parent, controller):
"""Create the input page containing the text fields."""
tk.Frame.__init__(self, parent)
self.controller = controller
lbl_enter_test_type = tk.Label(self, text='Type of test run: ')
lbl_enter_primary_weight = tk.Label(se... | the_stack_v2_python_sparse | GUI/GUI.py | krystal-bc/Senior-Design | train | 0 | |
e249b29ad072651ab373783ea7e7f8af5ad7e4b2 | [
"Idevice.__init__(self, x_(u'Java Applet'), x_(u'University of Auckland'), u'', u'', u'', parentNode)\nself.emphasis = Idevice.NoEmphasis\nself.appletCode = u''\nself._fileInstruc = x_(u'Add all the files provided for the applet\\nexcept the .txt file one at a time using the add files and upload buttons. The \\nfil... | <|body_start_0|>
Idevice.__init__(self, x_(u'Java Applet'), x_(u'University of Auckland'), u'', u'', u'', parentNode)
self.emphasis = Idevice.NoEmphasis
self.appletCode = u''
self._fileInstruc = x_(u'Add all the files provided for the applet\nexcept the .txt file one at a time using the ... | Java Applet Idevice. Enables you to embed java applet in the browser | AppletIdevice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppletIdevice:
"""Java Applet Idevice. Enables you to embed java applet in the browser"""
def __init__(self, parentNode=None):
"""Sets up the idevice title and instructions etc"""
<|body_0|>
def uploadFile(self, filePath):
"""Store the upload files in the package... | stack_v2_sparse_classes_10k_train_003428 | 2,445 | no_license | [
{
"docstring": "Sets up the idevice title and instructions etc",
"name": "__init__",
"signature": "def __init__(self, parentNode=None)"
},
{
"docstring": "Store the upload files in the package Needs to be in a package to work.",
"name": "uploadFile",
"signature": "def uploadFile(self, fi... | 3 | null | Implement the Python class `AppletIdevice` described below.
Class description:
Java Applet Idevice. Enables you to embed java applet in the browser
Method signatures and docstrings:
- def __init__(self, parentNode=None): Sets up the idevice title and instructions etc
- def uploadFile(self, filePath): Store the upload... | Implement the Python class `AppletIdevice` described below.
Class description:
Java Applet Idevice. Enables you to embed java applet in the browser
Method signatures and docstrings:
- def __init__(self, parentNode=None): Sets up the idevice title and instructions etc
- def uploadFile(self, filePath): Store the upload... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class AppletIdevice:
"""Java Applet Idevice. Enables you to embed java applet in the browser"""
def __init__(self, parentNode=None):
"""Sets up the idevice title and instructions etc"""
<|body_0|>
def uploadFile(self, filePath):
"""Store the upload files in the package... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AppletIdevice:
"""Java Applet Idevice. Enables you to embed java applet in the browser"""
def __init__(self, parentNode=None):
"""Sets up the idevice title and instructions etc"""
Idevice.__init__(self, x_(u'Java Applet'), x_(u'University of Auckland'), u'', u'', u'', parentNode)
... | the_stack_v2_python_sparse | eXe/rev2283-2409/base-trunk-2283/exe/idevices/appletidevice.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
39781d0d9c73f7a4cd9c61c994578beffed84f9c | [
"self.modern_dem_name = modern_dem_name\nself.modeled_dem_name = modeled_dem_name\nself.grid, self.z = self.read_topography(modern_dem_name)\nself.grid.set_watershed_boundary_condition_outlet_id(outlet_id, self.z, nodata_value=-9999)\nself.mgrid, self.mz = self.read_topography(modeled_dem_name)\nself.mgrid.set_wate... | <|body_start_0|>
self.modern_dem_name = modern_dem_name
self.modeled_dem_name = modeled_dem_name
self.grid, self.z = self.read_topography(modern_dem_name)
self.grid.set_watershed_boundary_condition_outlet_id(outlet_id, self.z, nodata_value=-9999)
self.mgrid, self.mz = self.read_t... | Calculator for topographic metrics used in sensitivity analysis and model evaluation. | GroupedDifferences | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupedDifferences:
"""Calculator for topographic metrics used in sensitivity analysis and model evaluation."""
def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None):
"""Initialize GroupedDiffe... | stack_v2_sparse_classes_10k_train_003429 | 5,390 | no_license | [
{
"docstring": "Initialize GroupedDifferences with names of postglacial and modern DEMs.",
"name": "__init__",
"signature": "def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None)"
},
{
"docstring": "Read a... | 5 | stack_v2_sparse_classes_30k_train_007187 | Implement the Python class `GroupedDifferences` described below.
Class description:
Calculator for topographic metrics used in sensitivity analysis and model evaluation.
Method signatures and docstrings:
- def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weigh... | Implement the Python class `GroupedDifferences` described below.
Class description:
Calculator for topographic metrics used in sensitivity analysis and model evaluation.
Method signatures and docstrings:
- def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weigh... | 3506ec741a7c8a170ea654d40c6119fefe1b93ba | <|skeleton|>
class GroupedDifferences:
"""Calculator for topographic metrics used in sensitivity analysis and model evaluation."""
def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None):
"""Initialize GroupedDiffe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupedDifferences:
"""Calculator for topographic metrics used in sensitivity analysis and model evaluation."""
def __init__(self, modeled_dem_name, modern_dem_name, outlet_id, category_file=None, category_values=None, weight_file=None, weight_values=None):
"""Initialize GroupedDifferences with n... | the_stack_v2_python_sparse | metric_and_objective_function_calculation/metric_calculator/grouped_differences.py | kbarnhart/inverting_topography_postglacial | train | 4 |
eefa1ffae1934d7a9898f822dcbb07819caa61ed | [
"self.sessionhandler = sessionhandler\nself.url = url\nself.rate = rate\nself.uid = uid\nself.bot = RSSReader(self, url, rate)\nself.task = None",
"def errback(fail):\n logger.log_err(fail.value)\nself.bot.init_session('rssbot', self.url, self.sessionhandler)\nself.bot.uid = self.uid\nself.bot.logged_in = True... | <|body_start_0|>
self.sessionhandler = sessionhandler
self.url = url
self.rate = rate
self.uid = uid
self.bot = RSSReader(self, url, rate)
self.task = None
<|end_body_0|>
<|body_start_1|>
def errback(fail):
logger.log_err(fail.value)
self.bot.... | Initializes new bots. | RSSBotFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSSBotFactory:
"""Initializes new bots."""
def __init__(self, sessionhandler, uid=None, url=None, rate=None):
"""Initialize the bot. Args: sessionhandler (PortalSessionHandler): The main sessionhandler object. uid (int): User id for the bot. url (str): The RSS URL. rate (int): How of... | stack_v2_sparse_classes_10k_train_003430 | 4,450 | permissive | [
{
"docstring": "Initialize the bot. Args: sessionhandler (PortalSessionHandler): The main sessionhandler object. uid (int): User id for the bot. url (str): The RSS URL. rate (int): How often for the RSS to request the latest RSS entries.",
"name": "__init__",
"signature": "def __init__(self, sessionhand... | 2 | stack_v2_sparse_classes_30k_train_007031 | Implement the Python class `RSSBotFactory` described below.
Class description:
Initializes new bots.
Method signatures and docstrings:
- def __init__(self, sessionhandler, uid=None, url=None, rate=None): Initialize the bot. Args: sessionhandler (PortalSessionHandler): The main sessionhandler object. uid (int): User i... | Implement the Python class `RSSBotFactory` described below.
Class description:
Initializes new bots.
Method signatures and docstrings:
- def __init__(self, sessionhandler, uid=None, url=None, rate=None): Initialize the bot. Args: sessionhandler (PortalSessionHandler): The main sessionhandler object. uid (int): User i... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class RSSBotFactory:
"""Initializes new bots."""
def __init__(self, sessionhandler, uid=None, url=None, rate=None):
"""Initialize the bot. Args: sessionhandler (PortalSessionHandler): The main sessionhandler object. uid (int): User id for the bot. url (str): The RSS URL. rate (int): How of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RSSBotFactory:
"""Initializes new bots."""
def __init__(self, sessionhandler, uid=None, url=None, rate=None):
"""Initialize the bot. Args: sessionhandler (PortalSessionHandler): The main sessionhandler object. uid (int): User id for the bot. url (str): The RSS URL. rate (int): How often for the R... | the_stack_v2_python_sparse | evennia/server/portal/rss.py | evennia/evennia | train | 1,781 |
6b7cc16a7991104e38d1c1e741130c2a632399ac | [
"self.trie = collections.defaultdict(list)\nself.length, self.ans = (len(words[0]), [])\nfor word in words:\n prefix = ''\n for letter in word:\n prefix += letter\n self.trie[prefix].append(word)\nfor word in words:\n self.dfs([word])\nreturn self.ans",
"if len(square) == self.length:\n ... | <|body_start_0|>
self.trie = collections.defaultdict(list)
self.length, self.ans = (len(words[0]), [])
for word in words:
prefix = ''
for letter in word:
prefix += letter
self.trie[prefix].append(word)
for word in words:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordSquares(self, words):
""":type words: List[str] :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, square):
""":type square: [[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie = collections.defaultdict(list)
... | stack_v2_sparse_classes_10k_train_003431 | 985 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[List[str]]",
"name": "wordSquares",
"signature": "def wordSquares(self, words)"
},
{
"docstring": ":type square: [[str]]",
"name": "dfs",
"signature": "def dfs(self, square)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007132 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words): :type words: List[str] :rtype: List[List[str]]
- def dfs(self, square): :type square: [[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words): :type words: List[str] :rtype: List[List[str]]
- def dfs(self, square): :type square: [[str]]
<|skeleton|>
class Solution:
def wordSquares(sel... | cc6245c9519d2a249aa469eefc003e340bdbfa7c | <|skeleton|>
class Solution:
def wordSquares(self, words):
""":type words: List[str] :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, square):
""":type square: [[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def wordSquares(self, words):
""":type words: List[str] :rtype: List[List[str]]"""
self.trie = collections.defaultdict(list)
self.length, self.ans = (len(words[0]), [])
for word in words:
prefix = ''
for letter in word:
prefix +... | the_stack_v2_python_sparse | search/hardOnes/word_square.py | LQXshane/leetcode | train | 0 | |
62070fd6e42f8506df69401c77000a1b752d4cd7 | [
"self.is_full_team_required = is_full_team_required\nself.object = object\nself.source_channel_vec = source_channel_vec",
"if dictionary is None:\n return None\nis_full_team_required = dictionary.get('isFullTeamRequired')\nobject = cohesity_management_sdk.models.restore_object.RestoreObject.from_dictionary(dic... | <|body_start_0|>
self.is_full_team_required = is_full_team_required
self.object = object
self.source_channel_vec = source_channel_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_full_team_required = dictionary.get('isFullTeamRequired')
... | Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necessary info. This will store the details of the MS team to be re... | RestoreO365TeamsParams_MSTeamInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necess... | stack_v2_sparse_classes_10k_train_003432 | 2,808 | permissive | [
{
"docstring": "Constructor for the RestoreO365TeamsParams_MSTeamInfo class",
"name": "__init__",
"signature": "def __init__(self, is_full_team_required=None, object=None, source_channel_vec=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionar... | 2 | null | Implement the Python class `RestoreO365TeamsParams_MSTeamInfo` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : ... | Implement the Python class `RestoreO365TeamsParams_MSTeamInfo` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necess... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necessary info. Thi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_teams_params_ms_team_info.py | cohesity/management-sdk-python | train | 24 |
64bdf35534a45a39de93b39983ae1b728e6f6e94 | [
"self.id = id_\nself.log_group_id = log_group_id\nself.user = user\nself.message = message\nself.time = time_",
"with new_session() as session:\n event = models.Log_group_event(log_group_id=log_group_id, user_id=user_id, message=message, time=datetime.utcnow())\n session.add(event)\n return True",
"if ... | <|body_start_0|>
self.id = id_
self.log_group_id = log_group_id
self.user = user
self.message = message
self.time = time_
<|end_body_0|>
<|body_start_1|>
with new_session() as session:
event = models.Log_group_event(log_group_id=log_group_id, user_id=user_id,... | Log_group_event | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log_group_event:
def __init__(self, id_, log_group_id, user, message, time_):
""":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime"""
<|body_0|>
def new(cls, log_group_id, user_id, message):
"""Create... | stack_v2_sparse_classes_10k_train_003433 | 2,347 | no_license | [
{
"docstring": ":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime",
"name": "__init__",
"signature": "def __init__(self, id_, log_group_id, user, message, time_)"
},
{
"docstring": "Creates a new event for a log group. :param log... | 3 | stack_v2_sparse_classes_30k_train_006734 | Implement the Python class `Log_group_event` described below.
Class description:
Implement the Log_group_event class.
Method signatures and docstrings:
- def __init__(self, id_, log_group_id, user, message, time_): :param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param ti... | Implement the Python class `Log_group_event` described below.
Class description:
Implement the Log_group_event class.
Method signatures and docstrings:
- def __init__(self, id_, log_group_id, user, message, time_): :param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param ti... | 3f331c7169c90d1fac0d1922b011b56eebbd086a | <|skeleton|>
class Log_group_event:
def __init__(self, id_, log_group_id, user, message, time_):
""":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime"""
<|body_0|>
def new(cls, log_group_id, user_id, message):
"""Create... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Log_group_event:
def __init__(self, id_, log_group_id, user, message, time_):
""":param id_: int :param log_group_id: int :param user: tlog.base.user.User :param message: str :param time_: Datetime"""
self.id = id_
self.log_group_id = log_group_id
self.user = user
self.... | the_stack_v2_python_sparse | src/tlog/base/event.py | thomaserlang/TLog | train | 2 | |
94f974ef86531298180f8b49834667705da2ae28 | [
"try:\n result = data.DataMaster().create_database(baseid)\n return_data = {'status': '200', 'result': result}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n result = data... | <|body_start_0|>
try:
result = data.DataMaster().create_database(baseid)
return_data = {'status': '200', 'result': result}
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '400', 'result': str(e)}
return ... | 1. POST : 2. PUT : 3. GET : 4. DELETE : | DataFrameSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataFrameSchema:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid):
"""create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result"""
<|body_0|>
def get(self, request):
"""return all ... | stack_v2_sparse_classes_10k_train_003434 | 2,387 | no_license | [
{
"docstring": "create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result",
"name": "post",
"signature": "def post(self, request, baseid)"
},
{
"docstring": "return all databases :param request: Not used :param baseid: schemaId :return: list ... | 4 | stack_v2_sparse_classes_30k_val_000182 | Implement the Python class `DataFrameSchema` described below.
Class description:
1. POST : 2. PUT : 3. GET : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, baseid): create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result
- def get(self, ... | Implement the Python class `DataFrameSchema` described below.
Class description:
1. POST : 2. PUT : 3. GET : 4. DELETE :
Method signatures and docstrings:
- def post(self, request, baseid): create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result
- def get(self, ... | 17216fd58619b56b6a397178d327687c274c238c | <|skeleton|>
class DataFrameSchema:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid):
"""create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result"""
<|body_0|>
def get(self, request):
"""return all ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataFrameSchema:
"""1. POST : 2. PUT : 3. GET : 4. DELETE :"""
def post(self, request, baseid):
"""create data base with given name :param request: Not used :param baseid: schemaId :return: create schema result"""
try:
result = data.DataMaster().create_database(baseid)
... | the_stack_v2_python_sparse | tfmsarest/views/dataframe_base.py | TensorMSA/tensormsa_server_old | train | 0 |
c20b6ca58ce0a13a1ba70c53ee95c7a26c43fe8c | [
"pre = None\ncur = head\nwhile cur:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\nreturn pre",
"p = head\nh = p\ntt = None\nhead = None\nwhile p is not None:\n for _ in range(k - 1):\n if p.next is None:\n if tt is not None:\n tt.next = h\n i... | <|body_start_0|>
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
<|end_body_0|>
<|body_start_1|>
p = head
h = p
tt = None
head = None
while p is not None... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = None
... | stack_v2_sparse_classes_10k_train_003435 | 1,323 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skeleton|>
class Solu... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def reverseKGroup(self, head, k):
... | the_stack_v2_python_sparse | reverse-nodes-in-k-group/solution.py | uxlsl/leetcode_practice | train | 0 | |
498cde9ae6a58951ac49be55226c54d4b7774693 | [
"Parametre.__init__(self, 'éditer', 'edit')\nself.schema = '<texte_libre>'\nself.aide_courte = \"ouvre l'éditeur de modèle de navires\"\nself.aide_longue = \"Cette commande ouvre l'éditeur de prototype de navire. Le terme modèle est également utilisé. Vous devez préciser en paramètre la clé du modèle (par exemple |... | <|body_start_0|>
Parametre.__init__(self, 'éditer', 'edit')
self.schema = '<texte_libre>'
self.aide_courte = "ouvre l'éditeur de modèle de navires"
self.aide_longue = "Cette commande ouvre l'éditeur de prototype de navire. Le terme modèle est également utilisé. Vous devez préciser en par... | Commande 'navire éditer'. | PrmEditer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmEditer:
"""Commande 'navire éditer'."""
def __init__(self):
"""Constructeur de la commande"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
P... | stack_v2_sparse_classes_10k_train_003436 | 3,818 | permissive | [
{
"docstring": "Constructeur de la commande",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmEditer` described below.
Class description:
Commande 'navire éditer'.
Method signatures and docstrings:
- def __init__(self): Constructeur de la commande
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande | Implement the Python class `PrmEditer` described below.
Class description:
Commande 'navire éditer'.
Method signatures and docstrings:
- def __init__(self): Constructeur de la commande
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande
<|skeleton|>
class PrmEditer:
"""Commande... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmEditer:
"""Commande 'navire éditer'."""
def __init__(self):
"""Constructeur de la commande"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmEditer:
"""Commande 'navire éditer'."""
def __init__(self):
"""Constructeur de la commande"""
Parametre.__init__(self, 'éditer', 'edit')
self.schema = '<texte_libre>'
self.aide_courte = "ouvre l'éditeur de modèle de navires"
self.aide_longue = "Cette commande ou... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/navire/editer.py | vincent-lg/tsunami | train | 5 |
357afb0935bf369f97134a252697ba05bb117e23 | [
"if isinstance(value, dict):\n value = json.dumps(value)\nself.map[key] = value",
"try:\n for key_, value_ in keys.items():\n self.map[key_] = str(value_)\n print(key_ + ':' + str(value_))\nexcept BaseException as msg:\n print(msg)\n raise msg",
"try:\n del self.map[key]\n return... | <|body_start_0|>
if isinstance(value, dict):
value = json.dumps(value)
self.map[key] = value
<|end_body_0|>
<|body_start_1|>
try:
for key_, value_ in keys.items():
self.map[key_] = str(value_)
print(key_ + ':' + str(value_))
except... | 拼装成字典构造全局变量 借鉴map 包含变量的增删改查 各参数说明 luaDriver:公共drvier,初始化时创建的driver | GlobalVars | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalVars:
"""拼装成字典构造全局变量 借鉴map 包含变量的增删改查 各参数说明 luaDriver:公共drvier,初始化时创建的driver"""
def set_map(self, key, value):
"""设置单一变量值 :param key:变量名 :param value:变量值 :return:"""
<|body_0|>
def set(self, **keys):
"""设置多个变量 key-value :param keys: :return:"""
<|bod... | stack_v2_sparse_classes_10k_train_003437 | 1,778 | no_license | [
{
"docstring": "设置单一变量值 :param key:变量名 :param value:变量值 :return:",
"name": "set_map",
"signature": "def set_map(self, key, value)"
},
{
"docstring": "设置多个变量 key-value :param keys: :return:",
"name": "set",
"signature": "def set(self, **keys)"
},
{
"docstring": "删除key对应值 :param ke... | 4 | stack_v2_sparse_classes_30k_train_002805 | Implement the Python class `GlobalVars` described below.
Class description:
拼装成字典构造全局变量 借鉴map 包含变量的增删改查 各参数说明 luaDriver:公共drvier,初始化时创建的driver
Method signatures and docstrings:
- def set_map(self, key, value): 设置单一变量值 :param key:变量名 :param value:变量值 :return:
- def set(self, **keys): 设置多个变量 key-value :param keys: :ret... | Implement the Python class `GlobalVars` described below.
Class description:
拼装成字典构造全局变量 借鉴map 包含变量的增删改查 各参数说明 luaDriver:公共drvier,初始化时创建的driver
Method signatures and docstrings:
- def set_map(self, key, value): 设置单一变量值 :param key:变量名 :param value:变量值 :return:
- def set(self, **keys): 设置多个变量 key-value :param keys: :ret... | edc19480c3e94cbcbf004aa9d20099ec6d1b9304 | <|skeleton|>
class GlobalVars:
"""拼装成字典构造全局变量 借鉴map 包含变量的增删改查 各参数说明 luaDriver:公共drvier,初始化时创建的driver"""
def set_map(self, key, value):
"""设置单一变量值 :param key:变量名 :param value:变量值 :return:"""
<|body_0|>
def set(self, **keys):
"""设置多个变量 key-value :param keys: :return:"""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GlobalVars:
"""拼装成字典构造全局变量 借鉴map 包含变量的增删改查 各参数说明 luaDriver:公共drvier,初始化时创建的driver"""
def set_map(self, key, value):
"""设置单一变量值 :param key:变量名 :param value:变量值 :return:"""
if isinstance(value, dict):
value = json.dumps(value)
self.map[key] = value
def set(self, **k... | the_stack_v2_python_sparse | 性能项目/德州-普通场/lua4.0/ali/src/com/globalVars.py | YiFeng0755/testcase | train | 0 |
a305b417802142ddb5444953fad966f1a7e2a30c | [
"self.X = X\nself.Y = pdist(X, metric=options['metric'])\nself.clustering_method = clustering_method\nself.options = options\nself.prototypes = None\nself.clusters = None",
"options = self.options\nif options['use_raw'] == False:\n agglo = AgglomerativeClustering.Agglomerative(self.Y, options['threshold'])\nel... | <|body_start_0|>
self.X = X
self.Y = pdist(X, metric=options['metric'])
self.clustering_method = clustering_method
self.options = options
self.prototypes = None
self.clusters = None
<|end_body_0|>
<|body_start_1|>
options = self.options
if options['use_ra... | Codebook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codebook:
def __init__(self, X, clustering_method='agglomerative', **options):
"""**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_met... | stack_v2_sparse_classes_10k_train_003438 | 4,078 | no_license | [
{
"docstring": "**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_method (optional): default *agglomerative*. Defines the clustering method to be used for find... | 3 | stack_v2_sparse_classes_30k_train_005338 | Implement the Python class `Codebook` described below.
Class description:
Implement the Codebook class.
Method signatures and docstrings:
- def __init__(self, X, clustering_method='agglomerative', **options): **Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Impleme... | Implement the Python class `Codebook` described below.
Class description:
Implement the Codebook class.
Method signatures and docstrings:
- def __init__(self, X, clustering_method='agglomerative', **options): **Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Impleme... | 90531055691a094dd271966b53c40b7a097df375 | <|skeleton|>
class Codebook:
def __init__(self, X, clustering_method='agglomerative', **options):
"""**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_met... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codebook:
def __init__(self, X, clustering_method='agglomerative', **options):
"""**Definition**: Codebook(X, Y, clustering_method = 'agglomerative', **options) Codebook object class. Implementation of codebook generation algorithm. **Inputs**: * X: raw observation data. * clustering_method (optional)... | the_stack_v2_python_sparse | ImageRepresentation/codebook/CodebookGeneration.py | kmakantasis/CV-Tools | train | 0 | |
3cfcee4c5b7fdbea4bc8a26213279457f5ce63e9 | [
"self.num_positions = num_positions\nself.num_trials = num_trials\nself.position_value = 1000 / self.num_positions",
"uniform_list = np.random.uniform(0, 1, self.num_positions)\nresult = np.zeros(self.num_positions)\nfor i in range(self.num_positions):\n if uniform_list[i] <= 0.49:\n result[i] = self.po... | <|body_start_0|>
self.num_positions = num_positions
self.num_trials = num_trials
self.position_value = 1000 / self.num_positions
<|end_body_0|>
<|body_start_1|>
uniform_list = np.random.uniform(0, 1, self.num_positions)
result = np.zeros(self.num_positions)
for i in rang... | The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret. | investment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment:
"""The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret."""
def __init__(self, num_positions, num_trials):
"""Constructor"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_003439 | 2,603 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, num_positions, num_trials)"
},
{
"docstring": "The method returns cumulative return, which is the outcome of simulation of one day's investment for different choice of positions.",
"name": "get_cumu_ret",
... | 3 | null | Implement the Python class `investment` described below.
Class description:
The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret.
Method signatures and docstrings:
- def __init__(self, num_p... | Implement the Python class `investment` described below.
Class description:
The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret.
Method signatures and docstrings:
- def __init__(self, num_p... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment:
"""The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret."""
def __init__(self, num_positions, num_trials):
"""Constructor"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class investment:
"""The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret."""
def __init__(self, num_positions, num_trials):
"""Constructor"""
self.num_positions = num... | the_stack_v2_python_sparse | zg475/investment.py | ds-ga-1007/assignment8 | train | 1 |
618608d8d3ce4767b99323bcb384bd676619e682 | [
"so = cls()\ntry:\n res = func(*args, **kwargs)\nfinally:\n out, err = so.reset()\nreturn (res, out, err)",
"if hasattr(self, '_reset'):\n raise ValueError('was already reset')\nself._reset = True\noutfile, errfile = self.done(save=False)\nout, err = ('', '')\nif outfile and (not outfile.closed):\n ou... | <|body_start_0|>
so = cls()
try:
res = func(*args, **kwargs)
finally:
out, err = so.reset()
return (res, out, err)
<|end_body_0|>
<|body_start_1|>
if hasattr(self, '_reset'):
raise ValueError('was already reset')
self._reset = True
... | Capture | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Capture:
def call(cls, func, *args, **kwargs):
"""return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution."""
<|body_0|>
def reset(sel... | stack_v2_sparse_classes_10k_train_003440 | 11,652 | permissive | [
{
"docstring": "return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution.",
"name": "call",
"signature": "def call(cls, func, *args, **kwargs)"
},
{
"docstr... | 3 | null | Implement the Python class `Capture` described below.
Class description:
Implement the Capture class.
Method signatures and docstrings:
- def call(cls, func, *args, **kwargs): return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with arg... | Implement the Python class `Capture` described below.
Class description:
Implement the Capture class.
Method signatures and docstrings:
- def call(cls, func, *args, **kwargs): return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with arg... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class Capture:
def call(cls, func, *args, **kwargs):
"""return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution."""
<|body_0|>
def reset(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Capture:
def call(cls, func, *args, **kwargs):
"""return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution."""
so = cls()
try:
res = f... | the_stack_v2_python_sparse | contrib/python/py/py/_io/capture.py | catboost/catboost | train | 8,012 | |
066dc967932d8f126c6047804eef3ee16af627e7 | [
"input_cube = self.precip_cube.copy()\ninput_cube.rename('air_temperature')\ninput_cube.units = 'K'\nplugin = CreateExtrapolationForecast(input_cube, self.vel_x, self.vel_y)\nresult = plugin.extrapolate(10)\nexpected_result = np.array([[np.nan, np.nan, np.nan], [np.nan, 1, 2], [np.nan, 1, 1], [np.nan, 0, 2]], dtype... | <|body_start_0|>
input_cube = self.precip_cube.copy()
input_cube.rename('air_temperature')
input_cube.units = 'K'
plugin = CreateExtrapolationForecast(input_cube, self.vel_x, self.vel_y)
result = plugin.extrapolate(10)
expected_result = np.array([[np.nan, np.nan, np.nan],... | Test the extrapolate method. | Test_extrapolate | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_extrapolate:
"""Test the extrapolate method."""
def test_without_orographic_enhancement(self):
"""Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minu... | stack_v2_sparse_classes_10k_train_003441 | 11,800 | permissive | [
{
"docstring": "Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minutes, our precipitation will have moved exactly one grid square along each axis.",
"name": "test_without_orograp... | 2 | stack_v2_sparse_classes_30k_train_006675 | Implement the Python class `Test_extrapolate` described below.
Class description:
Test the extrapolate method.
Method signatures and docstrings:
- def test_without_orographic_enhancement(self): Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advect... | Implement the Python class `Test_extrapolate` described below.
Class description:
Test the extrapolate method.
Method signatures and docstrings:
- def test_without_orographic_enhancement(self): Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advect... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_extrapolate:
"""Test the extrapolate method."""
def test_without_orographic_enhancement(self):
"""Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_extrapolate:
"""Test the extrapolate method."""
def test_without_orographic_enhancement(self):
"""Test plugin returns the correct advected forecast cube. In this case we have 600m grid spacing in our cubes, and 1m/s advection velocities in the x and y direction, so after 10 minutes, our prec... | the_stack_v2_python_sparse | improver_tests/nowcasting/forecasting/test_CreateExtrapolationForecast.py | metoppv/improver | train | 101 |
de1b565ab92f8b99e1e726f62cb4d87d2a621710 | [
"storage = get_storage()\nstorage.add_permission_to_role(role_id, permission_id)\nreturn ('', 204)",
"storage = get_storage()\nstorage.remove_permission_from_role(role_id, permission_id)\nreturn ('', 204)"
] | <|body_start_0|>
storage = get_storage()
storage.add_permission_to_role(role_id, permission_id)
return ('', 204)
<|end_body_0|>
<|body_start_1|>
storage = get_storage()
storage.remove_permission_from_role(role_id, permission_id)
return ('', 204)
<|end_body_1|>
| RolePermissionManagementView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RolePermissionManagementView:
def post(self, role_id, permission_id):
"""--- summary: Add a permission to a role parameters: - role_id - permission_id tags: - Roles - Permissions responses: 204: description: Permission added to role successfully. 400: $ref: '#/components/responses/400-Ba... | stack_v2_sparse_classes_10k_train_003442 | 5,492 | permissive | [
{
"docstring": "--- summary: Add a permission to a role parameters: - role_id - permission_id tags: - Roles - Permissions responses: 204: description: Permission added to role successfully. 400: $ref: '#/components/responses/400-BadRequest' 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/comp... | 2 | stack_v2_sparse_classes_30k_train_000684 | Implement the Python class `RolePermissionManagementView` described below.
Class description:
Implement the RolePermissionManagementView class.
Method signatures and docstrings:
- def post(self, role_id, permission_id): --- summary: Add a permission to a role parameters: - role_id - permission_id tags: - Roles - Perm... | Implement the Python class `RolePermissionManagementView` described below.
Class description:
Implement the RolePermissionManagementView class.
Method signatures and docstrings:
- def post(self, role_id, permission_id): --- summary: Add a permission to a role parameters: - role_id - permission_id tags: - Roles - Perm... | 280800c73eb7cfd49029462b352887e78f1ff91b | <|skeleton|>
class RolePermissionManagementView:
def post(self, role_id, permission_id):
"""--- summary: Add a permission to a role parameters: - role_id - permission_id tags: - Roles - Permissions responses: 204: description: Permission added to role successfully. 400: $ref: '#/components/responses/400-Ba... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RolePermissionManagementView:
def post(self, role_id, permission_id):
"""--- summary: Add a permission to a role parameters: - role_id - permission_id tags: - Roles - Permissions responses: 204: description: Permission added to role successfully. 400: $ref: '#/components/responses/400-BadRequest' 401:... | the_stack_v2_python_sparse | sfa_api/roles.py | SolarArbiter/solarforecastarbiter-api | train | 9 | |
e8dc252f214e13e34c8cf03fddc2823244bd9d03 | [
"super().__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"prev = tf.expand_dims(s_prev, axis=1)\nenco = self.V(tf.nn.tanh(self.W(prev) + self.U(hidden_states)))\nweights = tf.nn.softmax(enco, axis=1)\ncontext = weights * hidden_states\n... | <|body_start_0|>
super().__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
prev = tf.expand_dims(s_prev, axis=1)
enco = self.V(tf.nn.tanh(self.W(prev) + self.U(hidden_s... | Calculate the attention for machine translation | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Calculate the attention for machine translation"""
def __init__(self, units):
"""Units is an integer representing the number of hidden units in the alignment model."""
<|body_0|>
def call(self, s_prev, hidden_states):
"""s_prev is a tensor of sh... | stack_v2_sparse_classes_10k_train_003443 | 1,085 | no_license | [
{
"docstring": "Units is an integer representing the number of hidden units in the alignment model.",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "s_prev is a tensor of shape (batch, units) containing the previous decoder hidden state. hidden_states is a tensor... | 2 | stack_v2_sparse_classes_30k_train_007281 | Implement the Python class `SelfAttention` described below.
Class description:
Calculate the attention for machine translation
Method signatures and docstrings:
- def __init__(self, units): Units is an integer representing the number of hidden units in the alignment model.
- def call(self, s_prev, hidden_states): s_p... | Implement the Python class `SelfAttention` described below.
Class description:
Calculate the attention for machine translation
Method signatures and docstrings:
- def __init__(self, units): Units is an integer representing the number of hidden units in the alignment model.
- def call(self, s_prev, hidden_states): s_p... | b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918 | <|skeleton|>
class SelfAttention:
"""Calculate the attention for machine translation"""
def __init__(self, units):
"""Units is an integer representing the number of hidden units in the alignment model."""
<|body_0|>
def call(self, s_prev, hidden_states):
"""s_prev is a tensor of sh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Calculate the attention for machine translation"""
def __init__(self, units):
"""Units is an integer representing the number of hidden units in the alignment model."""
super().__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | Gaspela/holbertonschool-machine_learning | train | 0 |
ee4d41cd44173eb8bf84b8d711eaad91045a711d | [
"if batch_dims < 0:\n raise ValueError('Batch dims must be non-negative.')\nself._batch_dims = batch_dims\nself._original_tensor_shape = None",
"with tf.name_scope('batch_flatten'):\n if self._batch_dims == 1:\n return tensor\n self._original_tensor_shape = composite.shape(tensor)\n if tensor.s... | <|body_start_0|>
if batch_dims < 0:
raise ValueError('Batch dims must be non-negative.')
self._batch_dims = batch_dims
self._original_tensor_shape = None
<|end_body_0|>
<|body_start_1|>
with tf.name_scope('batch_flatten'):
if self._batch_dims == 1:
... | Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension. | BatchSquash | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchSquash:
"""Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension."""
def __init... | stack_v2_sparse_classes_10k_train_003444 | 9,002 | permissive | [
{
"docstring": "Create two tied ops to flatten and unflatten the front dimensions. Args: batch_dims: Number of batch dimensions the flatten/unflatten ops should handle. Raises: ValueError: if batch dims is negative.",
"name": "__init__",
"signature": "def __init__(self, batch_dims)"
},
{
"docstr... | 3 | null | Implement the Python class `BatchSquash` described below.
Class description:
Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have onl... | Implement the Python class `BatchSquash` described below.
Class description:
Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have onl... | eca1093d3a047e538f17f6ab92ab4d8144284f23 | <|skeleton|>
class BatchSquash:
"""Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension."""
def __init... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchSquash:
"""Facilitates flattening and unflattening batch dims of a tensor. Exposes a pair of matched faltten and unflatten methods. After flattening only 1 batch dimension will be left. This facilitates evaluating networks that expect inputs to have only 1 batch dimension."""
def __init__(self, batc... | the_stack_v2_python_sparse | tf_agents/networks/utils.py | tensorflow/agents | train | 2,755 |
af788f1b33b24a6c2c3e80cb974c69b73c94106a | [
"request_json = request.get_json()\nvalid_format, errors = schema_utils.validate(request_json, 'org')\nif not valid_format:\n return ({'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST)\ntry:\n user = UserService.find_by_jwt_token()\n if user is None:\n response, status = ... | <|body_start_0|>
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'org')
if not valid_format:
return ({'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST)
try:
user = UserService.find_by_jwt_tok... | Resource for managing orgs. | Orgs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Orgs:
"""Resource for managing orgs."""
def post():
"""Post a new org using the request body. If the org already exists, update the attributes."""
<|body_0|>
def get():
"""Search orgs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
request_json... | stack_v2_sparse_classes_10k_train_003445 | 30,185 | permissive | [
{
"docstring": "Post a new org using the request body. If the org already exists, update the attributes.",
"name": "post",
"signature": "def post()"
},
{
"docstring": "Search orgs.",
"name": "get",
"signature": "def get()"
}
] | 2 | null | Implement the Python class `Orgs` described below.
Class description:
Resource for managing orgs.
Method signatures and docstrings:
- def post(): Post a new org using the request body. If the org already exists, update the attributes.
- def get(): Search orgs. | Implement the Python class `Orgs` described below.
Class description:
Resource for managing orgs.
Method signatures and docstrings:
- def post(): Post a new org using the request body. If the org already exists, update the attributes.
- def get(): Search orgs.
<|skeleton|>
class Orgs:
"""Resource for managing or... | 923cb8a3ee88dcbaf0fe800ca70022b3c13c1d01 | <|skeleton|>
class Orgs:
"""Resource for managing orgs."""
def post():
"""Post a new org using the request body. If the org already exists, update the attributes."""
<|body_0|>
def get():
"""Search orgs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Orgs:
"""Resource for managing orgs."""
def post():
"""Post a new org using the request body. If the org already exists, update the attributes."""
request_json = request.get_json()
valid_format, errors = schema_utils.validate(request_json, 'org')
if not valid_format:
... | the_stack_v2_python_sparse | auth-api/src/auth_api/resources/org.py | bcgov/sbc-auth | train | 13 |
b4ce686aabb139152fde70ea6864da507ecbaaa9 | [
"size = len(nums)\nleft = 1\nright = size - 1\nwhile left < right:\n mid = left + (right - left) // 2\n cnt = 0\n for num in nums:\n if num <= mid:\n cnt += 1\n if cnt > mid:\n right = mid\n else:\n left = mid + 1\nreturn left",
"fast = nums[nums[0]]\nslow = nums[0]\... | <|body_start_0|>
size = len(nums)
left = 1
right = size - 1
while left < right:
mid = left + (right - left) // 2
cnt = 0
for num in nums:
if num <= mid:
cnt += 1
if cnt > mid:
right = mid
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""二分查找"""
<|body_0|>
def findDuplicate2(self, nums: List[int]) -> int:
"""快慢指针 wise"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(nums)
left = 1
right = size - ... | stack_v2_sparse_classes_10k_train_003446 | 1,234 | no_license | [
{
"docstring": "二分查找",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums: List[int]) -> int"
},
{
"docstring": "快慢指针 wise",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: 二分查找
- def findDuplicate2(self, nums: List[int]) -> int: 快慢指针 wise | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: 二分查找
- def findDuplicate2(self, nums: List[int]) -> int: 快慢指针 wise
<|skeleton|>
class Solution:
def findDuplicate(self, num... | 40726506802d2d60028fdce206696b1df2f63ece | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""二分查找"""
<|body_0|>
def findDuplicate2(self, nums: List[int]) -> int:
"""快慢指针 wise"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""二分查找"""
size = len(nums)
left = 1
right = size - 1
while left < right:
mid = left + (right - left) // 2
cnt = 0
for num in nums:
if num <= mid:
... | the_stack_v2_python_sparse | 二刷+题解/剑指offer/findDuplicate.py | 1oser5/LeetCode | train | 0 | |
e195f16ebd106c69a875618646cbfb476c7f46d2 | [
"self.root = Path(__file__).parent.absolute()\nif not args:\n return\nself.build = Path(args.build_dir).resolve()\nif args.install_prefix:\n self.installed = Path(args.install_prefix).resolve()\nelse:\n self.installed = self.build.parent / (self.build.stem + '-install')\nif sys.platform == 'win32' and sys.... | <|body_start_0|>
self.root = Path(__file__).parent.absolute()
if not args:
return
self.build = Path(args.build_dir).resolve()
if args.install_prefix:
self.installed = Path(args.install_prefix).resolve()
else:
self.installed = self.build.parent ... | root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a custom prefix, followed by a rela... | Dirs | [
"BSL-1.0",
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Qhull",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dirs:
"""root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a c... | stack_v2_sparse_classes_10k_train_003447 | 49,632 | permissive | [
{
"docstring": ":params args: object like Context(build_dir, install_prefix)",
"name": "__init__",
"signature": "def __init__(self, args=None)"
},
{
"docstring": "Add site dir to sys.path / PYTHONPATH",
"name": "add_sys_path",
"signature": "def add_sys_path(self)"
},
{
"docstring... | 3 | null | Implement the Python class `Dirs` described below.
Class description:
root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built S... | Implement the Python class `Dirs` described below.
Class description:
root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built S... | bae3476b8a245866f5f7f1b824a0a7919f3880a9 | <|skeleton|>
class Dirs:
"""root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dirs:
"""root: Directory where scr, build config and tools are located (and this file) build: Directory where build output files (i.e. *.o) are saved install: Directory where .so from build and .py from src are put together. site: Directory where the built SciPy version was installed. This is a custom prefix,... | the_stack_v2_python_sparse | dev.py | rgommers/scipy | train | 17 |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\noffset = read_fmt('I', fp)[0]\nreturn cls(name, classID, offset)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_fmt(fp, 'I', self.value)\nreturn written"
] | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
offset = read_fmt('I', fp)[0]
return cls(name, classID, offset)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
written += write_length_and_key(fp, self.classI... | Offset structure. .. py:attribute:: value | Offset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_10k_train_003448 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003486 | Implement the Python class `Offset` described below.
Class description:
Offset structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file... | Implement the Python class `Offset` described below.
Class description:
Offset structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
offset = read_fmt('I', fp)[0]
return cls(name, cl... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
f2e803dd230038d8b8d23aeb5ce8df480f6dae8c | [
"super().__init__(model=model, optimizer=optimizer, criterion=criterion, train_mb_size=train_mb_size, train_epochs=train_epochs, eval_mb_size=eval_mb_size, device=device, plugins=plugins, evaluator=evaluator, eval_every=eval_every)\nself._is_fitted = False\nself._experiences: List[TDatasetExperience] = []",
"self... | <|body_start_0|>
super().__init__(model=model, optimizer=optimizer, criterion=criterion, train_mb_size=train_mb_size, train_epochs=train_epochs, eval_mb_size=eval_mb_size, device=device, plugins=plugins, evaluator=evaluator, eval_every=eval_every)
self._is_fitted = False
self._experiences: List[... | Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :py:class:`JointTraining` adapts its own d... | JointTraining | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointTraining:
"""Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :... | stack_v2_sparse_classes_10k_train_003449 | 7,173 | permissive | [
{
"docstring": "Init. :param model: PyTorch model. :param optimizer: PyTorch optimizer. :param criterion: loss function. :param train_mb_size: mini-batch size for training. :param train_epochs: number of training epochs. :param eval_mb_size: mini-batch size for eval. :param device: PyTorch device to run the mod... | 4 | null | Implement the Python class `JointTraining` described below.
Class description:
Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound f... | Implement the Python class `JointTraining` described below.
Class description:
Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound f... | deb2b3e842046f48efc96e55a16d7a566e022c72 | <|skeleton|>
class JointTraining:
"""Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JointTraining:
"""Joint training on the entire stream. JointTraining performs joint training (also called offline training) on the entire stream of data. This means that it is not a continual learning strategy but it can be used as an "offline" upper bound for them. .. warnings also:: Currently :py:class:`Joi... | the_stack_v2_python_sparse | avalanche/training/supervised/joint_training.py | ContinualAI/avalanche | train | 1,424 |
e1652dc5737322ed873006c08e6653036affc57f | [
"if username is None and password is None:\n username = account.username\n password = decrypt_password(account.data['gerrit_http_password'])\nreturn super(GerritClient, self).get_http_credentials(account=account, username=username, password=password)",
"super(GerritClient, self).process_http_error(request, ... | <|body_start_0|>
if username is None and password is None:
username = account.username
password = decrypt_password(account.data['gerrit_http_password'])
return super(GerritClient, self).get_http_credentials(account=account, username=username, password=password)
<|end_body_0|>
<|... | The Gerrit hosting service API client. | GerritClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GerritClient:
"""The Gerrit hosting service API client."""
def get_http_credentials(self, account, username=None, password=None, **kwargs):
"""Return credentials used to authenticate with the service. Unless an explicit username and password is provided, this will use the ones stored... | stack_v2_sparse_classes_10k_train_003450 | 26,166 | permissive | [
{
"docstring": "Return credentials used to authenticate with the service. Unless an explicit username and password is provided, this will use the ones stored for the account. Args: account (reviewboard.hostingsvcs.models.HostingServiceAccount): The stored authentication data for the service. username (unicode, ... | 2 | null | Implement the Python class `GerritClient` described below.
Class description:
The Gerrit hosting service API client.
Method signatures and docstrings:
- def get_http_credentials(self, account, username=None, password=None, **kwargs): Return credentials used to authenticate with the service. Unless an explicit usernam... | Implement the Python class `GerritClient` described below.
Class description:
The Gerrit hosting service API client.
Method signatures and docstrings:
- def get_http_credentials(self, account, username=None, password=None, **kwargs): Return credentials used to authenticate with the service. Unless an explicit usernam... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class GerritClient:
"""The Gerrit hosting service API client."""
def get_http_credentials(self, account, username=None, password=None, **kwargs):
"""Return credentials used to authenticate with the service. Unless an explicit username and password is provided, this will use the ones stored... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GerritClient:
"""The Gerrit hosting service API client."""
def get_http_credentials(self, account, username=None, password=None, **kwargs):
"""Return credentials used to authenticate with the service. Unless an explicit username and password is provided, this will use the ones stored for the acco... | the_stack_v2_python_sparse | reviewboard/hostingsvcs/gerrit.py | reviewboard/reviewboard | train | 1,141 |
2aa8f33a7b50d529928dcfbffb091542bbf2a579 | [
"self.weights = w\nself.sum_weights = [0] * len(w)\nif not w:\n return\nself.sum_weights[0] = w[0]\nfor i in range(1, len(w)):\n self.sum_weights[i] = self.sum_weights[i - 1] + self.weights[i]\nself.total = self.sum_weights[-1]",
"r = randrange(1, self.total + 1)\nlo = 0\nhi = len(self.weights) - 1\nwhile l... | <|body_start_0|>
self.weights = w
self.sum_weights = [0] * len(w)
if not w:
return
self.sum_weights[0] = w[0]
for i in range(1, len(w)):
self.sum_weights[i] = self.sum_weights[i - 1] + self.weights[i]
self.total = self.sum_weights[-1]
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.weights = w
self.sum_weights = [0] * len(w)
if not w:
return
... | stack_v2_sparse_classes_10k_train_003451 | 1,124 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 0da45559271d3dba687858b8945b3e361ecc813c | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.weights = w
self.sum_weights = [0] * len(w)
if not w:
return
self.sum_weights[0] = w[0]
for i in range(1, len(w)):
self.sum_weights[i] = self.sum_weights[i - 1] + self.weights... | the_stack_v2_python_sparse | 528-random-pick-with-weight/solution.py | katryo/leetcode | train | 0 | |
55c8c9412db5ea14ece1d3ff34f511f6f50b6fc6 | [
"super(PartialWriter, self).__init__(cmd_tlm_data, deployment_name, cosmos_directory)\nself.overwrite_destinations = {cosmos_directory + '/config/targets/' + deployment_name.upper() + '/cmd_tlm/channels/_' + deployment_name.lower() + '_tlm_chn_hdr.txt': Partial_Channel.Partial_Channel(), cosmos_directory + '/config... | <|body_start_0|>
super(PartialWriter, self).__init__(cmd_tlm_data, deployment_name, cosmos_directory)
self.overwrite_destinations = {cosmos_directory + '/config/targets/' + deployment_name.upper() + '/cmd_tlm/channels/_' + deployment_name.lower() + '_tlm_chn_hdr.txt': Partial_Channel.Partial_Channel(), ... | This class generates each of the files that the user must input their own data into: _tlm_chn_hdr.txt: Channel header file that contains all shared channel definition fields _cmds_hdr.txt: Command header file that contains all shared command definition fields _tlm_evr_hdr.txt: Event header file that contains all shared... | PartialWriter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartialWriter:
"""This class generates each of the files that the user must input their own data into: _tlm_chn_hdr.txt: Channel header file that contains all shared channel definition fields _cmds_hdr.txt: Command header file that contains all shared command definition fields _tlm_evr_hdr.txt: E... | stack_v2_sparse_classes_10k_train_003452 | 4,229 | permissive | [
{
"docstring": "@param cmd_tlm_data: Tuple containing lists channels [0], commands [1], and events [2] @param deployment_name: name of the COSMOS target @param cosmos_directory: Directory of COSMOS",
"name": "__init__",
"signature": "def __init__(self, cmd_tlm_data, deployment_name, cosmos_directory)"
... | 2 | stack_v2_sparse_classes_30k_train_000314 | Implement the Python class `PartialWriter` described below.
Class description:
This class generates each of the files that the user must input their own data into: _tlm_chn_hdr.txt: Channel header file that contains all shared channel definition fields _cmds_hdr.txt: Command header file that contains all shared comman... | Implement the Python class `PartialWriter` described below.
Class description:
This class generates each of the files that the user must input their own data into: _tlm_chn_hdr.txt: Channel header file that contains all shared channel definition fields _cmds_hdr.txt: Command header file that contains all shared comman... | d19cade2140231b4e0879b2f6ab4a62b25792dea | <|skeleton|>
class PartialWriter:
"""This class generates each of the files that the user must input their own data into: _tlm_chn_hdr.txt: Channel header file that contains all shared channel definition fields _cmds_hdr.txt: Command header file that contains all shared command definition fields _tlm_evr_hdr.txt: E... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PartialWriter:
"""This class generates each of the files that the user must input their own data into: _tlm_chn_hdr.txt: Channel header file that contains all shared channel definition fields _cmds_hdr.txt: Command header file that contains all shared command definition fields _tlm_evr_hdr.txt: Event header f... | the_stack_v2_python_sparse | Autocoders/Python/src/fprime_ac/utils/cosmos/writers/PartialWriter.py | nodcah/fprime | train | 0 |
577eb196c3276f295ebedc1f5c19e609252708f6 | [
"collection = self._get_collection()\nserializer = serializers.CollectionSerializer(collection, context={'request': request})\nreturn Response(serializer.data)",
"pk = self.kwargs.get('pk', None)\nns_name = self.kwargs.get('namespace', None)\nname = self.kwargs.get('name', None)\nif pk:\n return get_object_or_... | <|body_start_0|>
collection = self._get_collection()
serializer = serializers.CollectionSerializer(collection, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
pk = self.kwargs.get('pk', None)
ns_name = self.kwargs.get('namespace', N... | CollectionDetailView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionDetailView:
def get(self, request, *args, **kwargs):
"""Return a collection."""
<|body_0|>
def _get_collection(self):
"""Get collection from either id, or namespace and name."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
collection = sel... | stack_v2_sparse_classes_10k_train_003453 | 9,693 | permissive | [
{
"docstring": "Return a collection.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Get collection from either id, or namespace and name.",
"name": "_get_collection",
"signature": "def _get_collection(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000133 | Implement the Python class `CollectionDetailView` described below.
Class description:
Implement the CollectionDetailView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return a collection.
- def _get_collection(self): Get collection from either id, or namespace and name. | Implement the Python class `CollectionDetailView` described below.
Class description:
Implement the CollectionDetailView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return a collection.
- def _get_collection(self): Get collection from either id, or namespace and name.
<|skelet... | 6a374cacdf0f04de94486913bba5285e24e178d3 | <|skeleton|>
class CollectionDetailView:
def get(self, request, *args, **kwargs):
"""Return a collection."""
<|body_0|>
def _get_collection(self):
"""Get collection from either id, or namespace and name."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CollectionDetailView:
def get(self, request, *args, **kwargs):
"""Return a collection."""
collection = self._get_collection()
serializer = serializers.CollectionSerializer(collection, context={'request': request})
return Response(serializer.data)
def _get_collection(self):... | the_stack_v2_python_sparse | galaxy/api/v2/views/collection.py | ansible/galaxy | train | 972 | |
ea168550fdbb5510f0f0b37717f140602a6b6961 | [
"self.time = 0\nself.tweets = {}\nself.follows = {}",
"if userId in self.tweets:\n self.tweets[userId].append([-self.time, tweetId])\nelse:\n self.tweets[userId] = [[-self.time, tweetId]]\nself.time += 1",
"users = list(self.follows.get(userId, set()) | set([userId]))\npointers = [len(self.tweets.get(u, [... | <|body_start_0|>
self.time = 0
self.tweets = {}
self.follows = {}
<|end_body_0|>
<|body_start_1|>
if userId in self.tweets:
self.tweets[userId].append([-self.time, tweetId])
else:
self.tweets[userId] = [[-self.time, tweetId]]
self.time += 1
<|end_... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_10k_train_003454 | 2,393 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. :type userId: int :type tweetId: int :rtype: void",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"... | 5 | stack_v2_sparse_classes_30k_train_002169 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: void
- def getNew... | 616939d1599b5a135747b0c4dd1f989974835f40 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.time = 0
self.tweets = {}
self.follows = {}
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: void"""
if userId in self.twe... | the_stack_v2_python_sparse | 355. Design Twitter.py | BITMystery/leetcode-journey | train | 0 | |
fb6f485fb920eaac93d34bfdccb8ecab1a99840f | [
"logger.debug('---------- workbench application ----------')\ngui = self.gui\nif self.start():\n window = self.workbench.create_window(position=self.window_position, size=self.window_size)\n window.open()\n self.workbench.on_trait_change(self._on_workbench_exited, 'exited')\n if self.start_gui_event_loo... | <|body_start_0|>
logger.debug('---------- workbench application ----------')
gui = self.gui
if self.start():
window = self.workbench.create_window(position=self.window_position, size=self.window_size)
window.open()
self.workbench.on_trait_change(self._on_workb... | The mayavi application. | MayaviWorkbenchApplication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MayaviWorkbenchApplication:
"""The mayavi application."""
def run(self):
"""Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When the event loop termi... | stack_v2_sparse_classes_10k_train_003455 | 4,424 | no_license | [
{
"docstring": "Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When the event loop terminates, stops the application This particular method is overridden from the parent class ... | 3 | null | Implement the Python class `MayaviWorkbenchApplication` described below.
Class description:
The mayavi application.
Method signatures and docstrings:
- def run(self): Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if s... | Implement the Python class `MayaviWorkbenchApplication` described below.
Class description:
The mayavi application.
Method signatures and docstrings:
- def run(self): Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if s... | 5466f5858dbd2f1f082fa0d7417b57c8fb068fad | <|skeleton|>
class MayaviWorkbenchApplication:
"""The mayavi application."""
def run(self):
"""Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When the event loop termi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MayaviWorkbenchApplication:
"""The mayavi application."""
def run(self):
"""Run the application. This does the following: 1) Starts the application 2) Creates and opens a workbench window 3) Starts the GUI event loop (only if start_gui_event_loop is True) 4) When the event loop terminates, stops ... | the_stack_v2_python_sparse | maps/build/mayavi/enthought/mayavi/plugins/mayavi_workbench_application.py | m-elhussieny/code | train | 0 |
2a22bd6a49c9a3be956d1ebdbc54ee73840c14f8 | [
"self.dataset = dataset\nself.kwargs = kwargs\nself.logger = logger",
"if batch_sampler:\n self.logger.get_log().info('this case sets the batch_sampler')\nelse:\n self.logger.get_log().info('this case has no batch_sampler')\ndataloader = paddle.io.DataLoader(self.dataset, batch_sampler=batch_sampler, **self... | <|body_start_0|>
self.dataset = dataset
self.kwargs = kwargs
self.logger = logger
<|end_body_0|>
<|body_start_1|>
if batch_sampler:
self.logger.get_log().info('this case sets the batch_sampler')
else:
self.logger.get_log().info('this case has no batch_sam... | generate DataLoader class | GenDataLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenDataLoader:
"""generate DataLoader class"""
def __init__(self, dataset, **kwargs):
"""init"""
<|body_0|>
def exec(self, batch_sampler):
"""execute"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dataset = dataset
self.kwargs = kw... | stack_v2_sparse_classes_10k_train_003456 | 765 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, dataset, **kwargs)"
},
{
"docstring": "execute",
"name": "exec",
"signature": "def exec(self, batch_sampler)"
}
] | 2 | null | Implement the Python class `GenDataLoader` described below.
Class description:
generate DataLoader class
Method signatures and docstrings:
- def __init__(self, dataset, **kwargs): init
- def exec(self, batch_sampler): execute | Implement the Python class `GenDataLoader` described below.
Class description:
generate DataLoader class
Method signatures and docstrings:
- def __init__(self, dataset, **kwargs): init
- def exec(self, batch_sampler): execute
<|skeleton|>
class GenDataLoader:
"""generate DataLoader class"""
def __init__(sel... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class GenDataLoader:
"""generate DataLoader class"""
def __init__(self, dataset, **kwargs):
"""init"""
<|body_0|>
def exec(self, batch_sampler):
"""execute"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GenDataLoader:
"""generate DataLoader class"""
def __init__(self, dataset, **kwargs):
"""init"""
self.dataset = dataset
self.kwargs = kwargs
self.logger = logger
def exec(self, batch_sampler):
"""execute"""
if batch_sampler:
self.logger.get... | the_stack_v2_python_sparse | framework/e2e/io/io_loader.py | PaddlePaddle/PaddleTest | train | 42 |
8d3fbc72f95891fe45b86724380600c7616d8be8 | [
"super(Critic, self).__init__()\nself.hidden = nn.Linear(in_dim, 64)\nself.out = nn.Linear(64, 1)\nself.out = init_layer_uniform(self.out)",
"x = F.relu(self.hidden(state))\nvalue = self.out(x)\nreturn value"
] | <|body_start_0|>
super(Critic, self).__init__()
self.hidden = nn.Linear(in_dim, 64)
self.out = nn.Linear(64, 1)
self.out = init_layer_uniform(self.out)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.hidden(state))
value = self.out(x)
return value
<|end_body_1|>
| Critic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
def __init__(self, in_dim: int):
"""Initialize."""
<|body_0|>
def forward(self, state: torch.Tensor) -> torch.Tensor:
"""Forward method implementation."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Critic, self).__init__()
se... | stack_v2_sparse_classes_10k_train_003457 | 13,315 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, in_dim: int)"
},
{
"docstring": "Forward method implementation.",
"name": "forward",
"signature": "def forward(self, state: torch.Tensor) -> torch.Tensor"
}
] | 2 | stack_v2_sparse_classes_30k_train_000199 | Implement the Python class `Critic` described below.
Class description:
Implement the Critic class.
Method signatures and docstrings:
- def __init__(self, in_dim: int): Initialize.
- def forward(self, state: torch.Tensor) -> torch.Tensor: Forward method implementation. | Implement the Python class `Critic` described below.
Class description:
Implement the Critic class.
Method signatures and docstrings:
- def __init__(self, in_dim: int): Initialize.
- def forward(self, state: torch.Tensor) -> torch.Tensor: Forward method implementation.
<|skeleton|>
class Critic:
def __init__(se... | 14ddfb81295c349acc2ede7588ebc73c235246c0 | <|skeleton|>
class Critic:
def __init__(self, in_dim: int):
"""Initialize."""
<|body_0|>
def forward(self, state: torch.Tensor) -> torch.Tensor:
"""Forward method implementation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Critic:
def __init__(self, in_dim: int):
"""Initialize."""
super(Critic, self).__init__()
self.hidden = nn.Linear(in_dim, 64)
self.out = nn.Linear(64, 1)
self.out = init_layer_uniform(self.out)
def forward(self, state: torch.Tensor) -> torch.Tensor:
"""Forw... | the_stack_v2_python_sparse | PPO_GAE_TEST/PPO_gae_test2.py | namjiwon1023/Reinforcement_learning | train | 2 | |
f0fdc703bec438b7888bd3eda6197aa328da1791 | [
"models = registry.models.values()\nmodels = sorted(models, key=lambda x: x.label)\nserializer = ModelSerializer(models, many=True)\nreturn Response(serializer.data)",
"model = registry.models.get(pk)\nif model is None:\n raise Http404\nserializer = ModelSerializer(model)\nreturn Response(serializer.data)"
] | <|body_start_0|>
models = registry.models.values()
models = sorted(models, key=lambda x: x.label)
serializer = ModelSerializer(models, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
model = registry.models.get(pk)
if model is None:
... | Viewset around model information. | ModelViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelViewSet:
"""Viewset around model information."""
def list(self, request):
"""Get a list of models."""
<|body_0|>
def retrieve(self, request, pk=None):
"""Get a specific model."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
models = registr... | stack_v2_sparse_classes_10k_train_003458 | 9,625 | permissive | [
{
"docstring": "Get a list of models.",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Get a specific model.",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006533 | Implement the Python class `ModelViewSet` described below.
Class description:
Viewset around model information.
Method signatures and docstrings:
- def list(self, request): Get a list of models.
- def retrieve(self, request, pk=None): Get a specific model. | Implement the Python class `ModelViewSet` described below.
Class description:
Viewset around model information.
Method signatures and docstrings:
- def list(self, request): Get a list of models.
- def retrieve(self, request, pk=None): Get a specific model.
<|skeleton|>
class ModelViewSet:
"""Viewset around model... | aaab76706c8268d3ff3e87c275baee9dd4714314 | <|skeleton|>
class ModelViewSet:
"""Viewset around model information."""
def list(self, request):
"""Get a list of models."""
<|body_0|>
def retrieve(self, request, pk=None):
"""Get a specific model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelViewSet:
"""Viewset around model information."""
def list(self, request):
"""Get a list of models."""
models = registry.models.values()
models = sorted(models, key=lambda x: x.label)
serializer = ModelSerializer(models, many=True)
return Response(serializer.da... | the_stack_v2_python_sparse | web/api/views.py | rcbops/FleetDeploymentReporting | train | 1 |
aa880751c64ad6161f08f7a9b461cd8ed30f9a25 | [
"self.is_installed = is_installed\nself.reboot_status = reboot_status\nself.service_state = service_state",
"if dictionary is None:\n return None\nis_installed = dictionary.get('isInstalled')\nreboot_status = dictionary.get('rebootStatus')\nservice_state = dictionary.get('serviceState')\nreturn cls(is_installe... | <|body_start_0|>
self.is_installed = is_installed
self.reboot_status = reboot_status
self.service_state = service_state
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_installed = dictionary.get('isInstalled')
reboot_status = dictionary.... | Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver installation. Only applicable for volc... | CbtInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CbtInfo:
"""Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver ins... | stack_v2_sparse_classes_10k_train_003459 | 2,799 | permissive | [
{
"docstring": "Constructor for the CbtInfo class",
"name": "__init__",
"signature": "def __init__(self, is_installed=None, reboot_status=None, service_state=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | null | Implement the Python class `CbtInfo` described below.
Class description:
Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot... | Implement the Python class `CbtInfo` described below.
Class description:
Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CbtInfo:
"""Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver ins... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CbtInfo:
"""Implementation of the 'CbtInfo' model. Specifies information about the Cbt Driver associated with agent. Attributes: is_installed (bool): Specifies whether the cbt driver is installed or not. reboot_status (RebootStatusEnum): Specifies the reboot status of the host post cbt driver installation. On... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cbt_info.py | cohesity/management-sdk-python | train | 24 |
0fe37c756cd200db2ee834e9a214df84833e0b27 | [
"self.hass = hass\nself.config_entry = config_entry\nself.api = api\nself.servers: dict[str, dict] = {DEFAULT_SERVER: {}}\nsuper().__init__(self.hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=DEFAULT_SCAN_INTERVAL))",
"test_servers = self.api.get_servers()\ntest_servers_list = []\nfor servers in te... | <|body_start_0|>
self.hass = hass
self.config_entry = config_entry
self.api = api
self.servers: dict[str, dict] = {DEFAULT_SERVER: {}}
super().__init__(self.hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=DEFAULT_SCAN_INTERVAL))
<|end_body_0|>
<|body_start_1|>
... | Get the latest data from speedtest.net. | SpeedTestDataCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeedTestDataCoordinator:
"""Get the latest data from speedtest.net."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None:
"""Initialize the data object."""
<|body_0|>
def update_servers(self) -> None:
"""Update ... | stack_v2_sparse_classes_10k_train_003460 | 2,772 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None"
},
{
"docstring": "Update list of test servers.",
"name": "update_servers",
"signature": "def update_serve... | 4 | stack_v2_sparse_classes_30k_train_001718 | Implement the Python class `SpeedTestDataCoordinator` described below.
Class description:
Get the latest data from speedtest.net.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None: Initialize the data object.
- def update_servers(s... | Implement the Python class `SpeedTestDataCoordinator` described below.
Class description:
Get the latest data from speedtest.net.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None: Initialize the data object.
- def update_servers(s... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SpeedTestDataCoordinator:
"""Get the latest data from speedtest.net."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None:
"""Initialize the data object."""
<|body_0|>
def update_servers(self) -> None:
"""Update ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpeedTestDataCoordinator:
"""Get the latest data from speedtest.net."""
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry, api: speedtest.Speedtest) -> None:
"""Initialize the data object."""
self.hass = hass
self.config_entry = config_entry
self.api = api
... | the_stack_v2_python_sparse | homeassistant/components/speedtestdotnet/coordinator.py | home-assistant/core | train | 35,501 |
f55a9e9b1450b6336add72e8bc38bb2163c22517 | [
"data = np.zeros((2, 3, 3), dtype=np.float32)\npercentiles = np.array([50.0, 90.0], dtype=np.float32)\nself.cube_wg = set_up_percentile_cube(data, percentiles)",
"perc_coord = find_percentile_coordinate(self.cube_wg)\nself.assertIsInstance(perc_coord, iris.coords.Coord)\nself.assertEqual(perc_coord.name(), 'perce... | <|body_start_0|>
data = np.zeros((2, 3, 3), dtype=np.float32)
percentiles = np.array([50.0, 90.0], dtype=np.float32)
self.cube_wg = set_up_percentile_cube(data, percentiles)
<|end_body_0|>
<|body_start_1|>
perc_coord = find_percentile_coordinate(self.cube_wg)
self.assertIsInstan... | Test whether the cube has a percentile coordinate. | Test_find_percentile_coordinate | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_find_percentile_coordinate:
"""Test whether the cube has a percentile coordinate."""
def setUp(self):
"""Create a wind-speed and wind-gust cube with percentile coord."""
<|body_0|>
def test_basic(self):
"""Test that the function returns a Coord."""
<... | stack_v2_sparse_classes_10k_train_003461 | 19,394 | permissive | [
{
"docstring": "Create a wind-speed and wind-gust cube with percentile coord.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the function returns a Coord.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test it raises... | 5 | null | Implement the Python class `Test_find_percentile_coordinate` described below.
Class description:
Test whether the cube has a percentile coordinate.
Method signatures and docstrings:
- def setUp(self): Create a wind-speed and wind-gust cube with percentile coord.
- def test_basic(self): Test that the function returns ... | Implement the Python class `Test_find_percentile_coordinate` described below.
Class description:
Test whether the cube has a percentile coordinate.
Method signatures and docstrings:
- def setUp(self): Create a wind-speed and wind-gust cube with percentile coord.
- def test_basic(self): Test that the function returns ... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_find_percentile_coordinate:
"""Test whether the cube has a percentile coordinate."""
def setUp(self):
"""Create a wind-speed and wind-gust cube with percentile coord."""
<|body_0|>
def test_basic(self):
"""Test that the function returns a Coord."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_find_percentile_coordinate:
"""Test whether the cube has a percentile coordinate."""
def setUp(self):
"""Create a wind-speed and wind-gust cube with percentile coord."""
data = np.zeros((2, 3, 3), dtype=np.float32)
percentiles = np.array([50.0, 90.0], dtype=np.float32)
... | the_stack_v2_python_sparse | improver_tests/metadata/test_probabilistic.py | metoppv/improver | train | 101 |
a54acbcfe9c3cbafee7e711c1d7b541651a65def | [
"if not matrix or not matrix[0]:\n return\nm, n = (len(matrix), len(matrix[0]))\nrow_ind, col_ind = (set(), set())\nfor i in xrange(m):\n for j in xrange(n):\n if not matrix[i][j]:\n row_ind.add(i)\n col_ind.add(j)\nfor i in row_ind:\n matrix[i] = [0] * n\nfor j in col_ind:\n ... | <|body_start_0|>
if not matrix or not matrix[0]:
return
m, n = (len(matrix), len(matrix[0]))
row_ind, col_ind = (set(), set())
for i in xrange(m):
for j in xrange(n):
if not matrix[i][j]:
row_ind.add(i)
col_i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_10k_train_003462 | 2,424 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instea... | 2 | stack_v2_sparse_classes_30k_train_005627 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes2(self, matrix): :type matrix: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes2(self, matrix): :type matrix: List... | 18ed31a3edf20a3e5a0b7a0b56acca5b98939693 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
if not matrix or not matrix[0]:
return
m, n = (len(matrix), len(matrix[0]))
row_ind, col_ind = (set(), set())
for ... | the_stack_v2_python_sparse | exercises/array/set_zeros.py | nahgnaw/data-structure | train | 0 | |
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9 | [
"if not is_string(field):\n raise TypeError('Field name must be a string')\nfield = field.strip()\nif not field or ' ' in field:\n raise ValueError(\"Empty or invalid property field name '{0}'\".format(field))\nif name is not None:\n if not is_string(name):\n raise TypeError('Property name must be a... | <|body_start_0|>
if not is_string(field):
raise TypeError('Field name must be a string')
field = field.strip()
if not field or ' ' in field:
raise ValueError("Empty or invalid property field name '{0}'".format(field))
if name is not None:
if not is_str... | @Property decorator Defines a component property. | Property | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Property:
"""@Property decorator Defines a component property."""
def __init__(self, field=None, name=None, value=None):
"""Sets up the property :param field: The property field in the class (can't be None nor empty) :param name: The property name (if None, this will be the field nam... | stack_v2_sparse_classes_10k_train_003463 | 41,418 | permissive | [
{
"docstring": "Sets up the property :param field: The property field in the class (can't be None nor empty) :param name: The property name (if None, this will be the field name) :param value: The property value :raise TypeError: Invalid argument type :raise ValueError: If the name or the name is None or empty"... | 2 | stack_v2_sparse_classes_30k_train_000216 | Implement the Python class `Property` described below.
Class description:
@Property decorator Defines a component property.
Method signatures and docstrings:
- def __init__(self, field=None, name=None, value=None): Sets up the property :param field: The property field in the class (can't be None nor empty) :param nam... | Implement the Python class `Property` described below.
Class description:
@Property decorator Defines a component property.
Method signatures and docstrings:
- def __init__(self, field=None, name=None, value=None): Sets up the property :param field: The property field in the class (can't be None nor empty) :param nam... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class Property:
"""@Property decorator Defines a component property."""
def __init__(self, field=None, name=None, value=None):
"""Sets up the property :param field: The property field in the class (can't be None nor empty) :param name: The property name (if None, this will be the field nam... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Property:
"""@Property decorator Defines a component property."""
def __init__(self, field=None, name=None, value=None):
"""Sets up the property :param field: The property field in the class (can't be None nor empty) :param name: The property name (if None, this will be the field name) :param val... | the_stack_v2_python_sparse | python/src/lib/python/pelix/ipopo/decorators.py | cohorte/cohorte-runtime | train | 3 |
ae3019448dfa736f92c19dfb7aa45a343b497dd8 | [
"num = 0\ni = 0\nwhile i < len(A):\n j = i\n temp = 0\n for k in range(j, len(A)):\n temp += A[k]\n if temp == S:\n num += 1\n elif temp > S:\n break\n i += 1\nreturn num",
"indexes = [-1] + [ix for ix, v in enumerate(A) if v] + [len(A)]\nans = 0\nif S == 0:\... | <|body_start_0|>
num = 0
i = 0
while i < len(A):
j = i
temp = 0
for k in range(j, len(A)):
temp += A[k]
if temp == S:
num += 1
elif temp > S:
break
i += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarraysWithSum(self, A, S):
""":type A: List[int] :type S: int :rtype: int"""
<|body_0|>
def numSubarraysWithSum1(self, A, S):
"""Approach 1: Index of Ones"""
<|body_1|>
def numSubarraysWithSum2(self, A, S):
"""Approach 2: Pref... | stack_v2_sparse_classes_10k_train_003464 | 1,998 | no_license | [
{
"docstring": ":type A: List[int] :type S: int :rtype: int",
"name": "numSubarraysWithSum",
"signature": "def numSubarraysWithSum(self, A, S)"
},
{
"docstring": "Approach 1: Index of Ones",
"name": "numSubarraysWithSum1",
"signature": "def numSubarraysWithSum1(self, A, S)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_000668 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarraysWithSum(self, A, S): :type A: List[int] :type S: int :rtype: int
- def numSubarraysWithSum1(self, A, S): Approach 1: Index of Ones
- def numSubarraysWithSum2(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarraysWithSum(self, A, S): :type A: List[int] :type S: int :rtype: int
- def numSubarraysWithSum1(self, A, S): Approach 1: Index of Ones
- def numSubarraysWithSum2(self... | 5674024fd179120134ab0588e499a5bace2469e2 | <|skeleton|>
class Solution:
def numSubarraysWithSum(self, A, S):
""":type A: List[int] :type S: int :rtype: int"""
<|body_0|>
def numSubarraysWithSum1(self, A, S):
"""Approach 1: Index of Ones"""
<|body_1|>
def numSubarraysWithSum2(self, A, S):
"""Approach 2: Pref... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarraysWithSum(self, A, S):
""":type A: List[int] :type S: int :rtype: int"""
num = 0
i = 0
while i < len(A):
j = i
temp = 0
for k in range(j, len(A)):
temp += A[k]
if temp == S:
... | the_stack_v2_python_sparse | leetcode solution in python/BinarySubarraysWithSum.py | shengchaohua/leetcode-solution | train | 3 | |
a57569ae9ac57c61fa2158334fdb18211286783b | [
"window = SortedList(key=lambda x: -x)\nres = 0\nleft = 0\ncurSum = 0\nfor right, num in enumerate(nums):\n curSum += num\n window.add(num)\n while window and (right - left + 1) * window[0] - curSum > k:\n curSum -= nums[left]\n window.discard(nums[left])\n left += 1\n res = max(res... | <|body_start_0|>
window = SortedList(key=lambda x: -x)
res = 0
left = 0
curSum = 0
for right, num in enumerate(nums):
curSum += num
window.add(num)
while window and (right - left + 1) * window[0] - curSum > k:
curSum -= nums[lef... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve1(self, nums: List[int], k: int):
"""sortedList TLE"""
<|body_0|>
def solve(self, nums: List[int], k: int):
"""monoQueue AC"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
window = SortedList(key=lambda x: -x)
res = 0
... | stack_v2_sparse_classes_10k_train_003465 | 1,897 | no_license | [
{
"docstring": "sortedList TLE",
"name": "solve1",
"signature": "def solve1(self, nums: List[int], k: int)"
},
{
"docstring": "monoQueue AC",
"name": "solve",
"signature": "def solve(self, nums: List[int], k: int)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve1(self, nums: List[int], k: int): sortedList TLE
- def solve(self, nums: List[int], k: int): monoQueue AC | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve1(self, nums: List[int], k: int): sortedList TLE
- def solve(self, nums: List[int], k: int): monoQueue AC
<|skeleton|>
class Solution:
def solve1(self, nums: List[... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def solve1(self, nums: List[int], k: int):
"""sortedList TLE"""
<|body_0|>
def solve(self, nums: List[int], k: int):
"""monoQueue AC"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def solve1(self, nums: List[int], k: int):
"""sortedList TLE"""
window = SortedList(key=lambda x: -x)
res = 0
left = 0
curSum = 0
for right, num in enumerate(nums):
curSum += num
window.add(num)
while window and (rig... | the_stack_v2_python_sparse | 22_专题/前缀与差分/差分数组/区间操作/Longest Equivalent Sublist After K Increments-双指针.py | 981377660LMT/algorithm-study | train | 225 | |
98c257929487290b4af7a5e9f824f0a14554f2b4 | [
"p2c, c2p = ({}, {})\nfor edge in edges:\n p, c = edge\n p2c[p] = p2c.get(p, [])\n p2c[p].append(c)\n c2p[c] = p\np2c_dist = {}\nfor p in p2c:\n p2c_dist[p] = []\n stack = [(c, 1) for c in p2c[p]]\n while stack:\n node, depth = stack.pop()\n p2c_dist[p].append((node, depth))\n ... | <|body_start_0|>
p2c, c2p = ({}, {})
for edge in edges:
p, c = edge
p2c[p] = p2c.get(p, [])
p2c[p].append(c)
c2p[c] = p
p2c_dist = {}
for p in p2c:
p2c_dist[p] = []
stack = [(c, 1) for c in p2c[p]]
while ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfDistancesInTree(self, N, edges):
"""Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def sumOfDistancesInTree2(self, N, edges):
"""Brute force, TLE Time: O(N^2) Space: O(N) :type N: int :type edges: List[List... | stack_v2_sparse_classes_10k_train_003466 | 4,875 | no_license | [
{
"docstring": "Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]",
"name": "sumOfDistancesInTree",
"signature": "def sumOfDistancesInTree(self, N, edges)"
},
{
"docstring": "Brute force, TLE Time: O(N^2) Space: O(N) :type N: int :type edges: List[List[int]] :rtype: List... | 4 | stack_v2_sparse_classes_30k_train_004828 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfDistancesInTree(self, N, edges): Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]
- def sumOfDistancesInTree2(self, N, edges): Brute force, TLE... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfDistancesInTree(self, N, edges): Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]
- def sumOfDistancesInTree2(self, N, edges): Brute force, TLE... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def sumOfDistancesInTree(self, N, edges):
"""Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def sumOfDistancesInTree2(self, N, edges):
"""Brute force, TLE Time: O(N^2) Space: O(N) :type N: int :type edges: List[List... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sumOfDistancesInTree(self, N, edges):
"""Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]"""
p2c, c2p = ({}, {})
for edge in edges:
p, c = edge
p2c[p] = p2c.get(p, [])
p2c[p].append(c)
c2p[c] = p
... | the_stack_v2_python_sparse | py/leetcode_py/834.py | imsure/tech-interview-prep | train | 0 | |
6899a1784fea90a7f2afd9071e9d56a95e8dde55 | [
"super(GaussianFilterNd, self).__init__()\nself.dims = dims\nself.sigma = nn.Parameter(torch.tensor(sigma, dtype=torch.float32), requires_grad=trainable)\nself.truncate = truncate\nself.kernel_size = kernel_size\nself.padding_mode = padding_mode\nself.padding_value = padding_value",
"for dim in self.dims:\n te... | <|body_start_0|>
super(GaussianFilterNd, self).__init__()
self.dims = dims
self.sigma = nn.Parameter(torch.tensor(sigma, dtype=torch.float32), requires_grad=trainable)
self.truncate = truncate
self.kernel_size = kernel_size
self.padding_mode = padding_mode
self.pa... | A differentiable gaussian filter | GaussianFilterNd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianFilterNd:
"""A differentiable gaussian filter"""
def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False):
"""Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is app... | stack_v2_sparse_classes_10k_train_003467 | 8,932 | permissive | [
{
"docstring": "Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is applied. Negative values won't work sigma (float): standard deviation of the gaussian filter (blur size) truncate (float, optional): truncate the filter at this many standard deviations (default: 4.0)... | 2 | stack_v2_sparse_classes_30k_train_005854 | Implement the Python class `GaussianFilterNd` described below.
Class description:
A differentiable gaussian filter
Method signatures and docstrings:
- def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False): Creates a 1d gaussian filter Args: dims ([... | Implement the Python class `GaussianFilterNd` described below.
Class description:
A differentiable gaussian filter
Method signatures and docstrings:
- def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False): Creates a 1d gaussian filter Args: dims ([... | 0664dba9b637f64b089b3a44b191dd24da84a30e | <|skeleton|>
class GaussianFilterNd:
"""A differentiable gaussian filter"""
def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False):
"""Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is app... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GaussianFilterNd:
"""A differentiable gaussian filter"""
def __init__(self, dims, sigma, truncate=4, kernel_size=None, padding_mode='replicate', padding_value=0.0, trainable=False):
"""Creates a 1d gaussian filter Args: dims ([int]): the dimensions to which the gaussian filter is applied. Negativ... | the_stack_v2_python_sparse | pysaliency/torch_utils.py | matthias-k/pysaliency | train | 142 |
44d160bd335180af752386c8ffa6662bacf81c5c | [
"self._dbg = debug\nself._log = get_logger(self.__class__.__name__, self._dbg)\nself._log.debug('server_host:server_port=%s:%s', server_host, server_port)\nself._log.debug('cmd=%s', cmd)\nself._server_host = server_host\nself._server_port = server_port\nself._cmd = cmd\nself._client = WsClientHostPort(self._server_... | <|body_start_0|>
self._dbg = debug
self._log = get_logger(self.__class__.__name__, self._dbg)
self._log.debug('server_host:server_port=%s:%s', server_host, server_port)
self._log.debug('cmd=%s', cmd)
self._server_host = server_host
self._server_port = server_port
... | Music Box Websocket Client App for simple command | WsCmdApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WsCmdApp:
"""Music Box Websocket Client App for simple command"""
def __init__(self, server_host, server_port, cmd, debug=False):
"""Constructor Parameters ---------- server_host: str server_port: int cmd: str"""
<|body_0|>
def main(self):
"""main"""
<|bo... | stack_v2_sparse_classes_10k_train_003468 | 25,197 | no_license | [
{
"docstring": "Constructor Parameters ---------- server_host: str server_port: int cmd: str",
"name": "__init__",
"signature": "def __init__(self, server_host, server_port, cmd, debug=False)"
},
{
"docstring": "main",
"name": "main",
"signature": "def main(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001888 | Implement the Python class `WsCmdApp` described below.
Class description:
Music Box Websocket Client App for simple command
Method signatures and docstrings:
- def __init__(self, server_host, server_port, cmd, debug=False): Constructor Parameters ---------- server_host: str server_port: int cmd: str
- def main(self):... | Implement the Python class `WsCmdApp` described below.
Class description:
Music Box Websocket Client App for simple command
Method signatures and docstrings:
- def __init__(self, server_host, server_port, cmd, debug=False): Constructor Parameters ---------- server_host: str server_port: int cmd: str
- def main(self):... | b8264118d19c7f6c6be9b11f18c890c598eb1295 | <|skeleton|>
class WsCmdApp:
"""Music Box Websocket Client App for simple command"""
def __init__(self, server_host, server_port, cmd, debug=False):
"""Constructor Parameters ---------- server_host: str server_port: int cmd: str"""
<|body_0|>
def main(self):
"""main"""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WsCmdApp:
"""Music Box Websocket Client App for simple command"""
def __init__(self, server_host, server_port, cmd, debug=False):
"""Constructor Parameters ---------- server_host: str server_port: int cmd: str"""
self._dbg = debug
self._log = get_logger(self.__class__.__name__, se... | the_stack_v2_python_sparse | musicbox/__main__.py | ytani01/MusicBox | train | 1 |
57be4b5e99f737b889427350d5a8620cbb852957 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ParticipantInfo()",
"from .endpoint_type import EndpointType\nfrom .identity_set import IdentitySet\nfrom .endpoint_type import EndpointType\nfrom .identity_set import IdentitySet\nfields: Dict[str, Callable[[Any], None]] = {'countryCo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ParticipantInfo()
<|end_body_0|>
<|body_start_1|>
from .endpoint_type import EndpointType
from .identity_set import IdentitySet
from .endpoint_type import EndpointType
fr... | ParticipantInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo:
"""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 Ret... | stack_v2_sparse_classes_10k_train_003469 | 4,296 | 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: ParticipantInfo",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `ParticipantInfo` described below.
Class description:
Implement the ParticipantInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `ParticipantInfo` described below.
Class description:
Implement the ParticipantInfo class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo:
"""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 Ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParticipantInfo:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ParticipantInfo:
"""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: Particip... | the_stack_v2_python_sparse | msgraph/generated/models/participant_info.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4c308c06c751e5f143037c31c71b45ff8c37d022 | [
"array = self.format_and_eval_string(self.target_array)\nif self.column_name:\n array = array[self.column_name]\nval = self.format_and_eval_string(self.value)\ntry:\n ind = np.where(np.abs(array - val) < 1e-12)[0][0]\nexcept IndexError as e:\n msg = 'Could not find {} in array {} ({})'\n raise ValueErro... | <|body_start_0|>
array = self.format_and_eval_string(self.target_array)
if self.column_name:
array = array[self.column_name]
val = self.format_and_eval_string(self.value)
try:
ind = np.where(np.abs(array - val) < 1e-12)[0][0]
except IndexError as e:
... | Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution. | ArrayFindValueTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayFindValueTask:
"""Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find index of value array and store index in database."""
<|body_0|>
def check(self, *args, **kwargs):
... | stack_v2_sparse_classes_10k_train_003470 | 6,289 | permissive | [
{
"docstring": "Find index of value array and store index in database.",
"name": "perform",
"signature": "def perform(self)"
},
{
"docstring": "Check the target array can be found and has the right column.",
"name": "check",
"signature": "def check(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000598 | Implement the Python class `ArrayFindValueTask` described below.
Class description:
Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.
Method signatures and docstrings:
- def perform(self): Find index of value array and store index in database.
- def check... | Implement the Python class `ArrayFindValueTask` described below.
Class description:
Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.
Method signatures and docstrings:
- def perform(self): Find index of value array and store index in database.
- def check... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class ArrayFindValueTask:
"""Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find index of value array and store index in database."""
<|body_0|>
def check(self, *args, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArrayFindValueTask:
"""Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find index of value array and store index in database."""
array = self.format_and_eval_string(self.target_array)
if self... | the_stack_v2_python_sparse | exopy_hqc_legacy/tasks/tasks/util/array_tasks.py | Exopy/exopy_hqc_legacy | train | 0 |
3fdb029283a1a664f8a6e0d3a973069fb07cc16e | [
"l, r = (0, len(nums) - 1)\nif nums[l] < nums[r] or len(nums) == 1:\n return nums[l]\nif len(nums) == 2:\n return min(nums[0], nums[1])\nwhile l < r:\n m = (l + r) // 2\n if m + 1 < len(nums) and nums[m] > nums[m + 1]:\n return nums[m + 1]\n if m - 1 >= 0 and nums[m - 1] > nums[m]:\n re... | <|body_start_0|>
l, r = (0, len(nums) - 1)
if nums[l] < nums[r] or len(nums) == 1:
return nums[l]
if len(nums) == 2:
return min(nums[0], nums[1])
while l < r:
m = (l + r) // 2
if m + 1 < len(nums) and nums[m] > nums[m + 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int [3,4,5,5,5,6,6,1,1,2,3,3] [3,3,3,1] [1] [1,1] [2,2,2,0,1,2] [10,1,10,10,10]"""
<|body_0|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_003471 | 2,046 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int [3,4,5,5,5,6,6,1,1,2,3,3] [3,3,3,1] [1] [1,1] [2,2,2,0,1,2] [10,1,10,10,10]",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin2",
"signature": "def findMin2(... | 2 | stack_v2_sparse_classes_30k_train_000239 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int [3,4,5,5,5,6,6,1,1,2,3,3] [3,3,3,1] [1] [1,1] [2,2,2,0,1,2] [10,1,10,10,10]
- def findMin2(self, nums): :type nums: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int [3,4,5,5,5,6,6,1,1,2,3,3] [3,3,3,1] [1] [1,1] [2,2,2,0,1,2] [10,1,10,10,10]
- def findMin2(self, nums): :type nums: Lis... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int [3,4,5,5,5,6,6,1,1,2,3,3] [3,3,3,1] [1] [1,1] [2,2,2,0,1,2] [10,1,10,10,10]"""
<|body_0|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int [3,4,5,5,5,6,6,1,1,2,3,3] [3,3,3,1] [1] [1,1] [2,2,2,0,1,2] [10,1,10,10,10]"""
l, r = (0, len(nums) - 1)
if nums[l] < nums[r] or len(nums) == 1:
return nums[l]
if len(nums) == 2:
ret... | the_stack_v2_python_sparse | src/Find Minimum in Rotated Sorted Array II.py | jsdiuf/leetcode | train | 1 | |
3539fe6196ff26c70e775659deea8c40b007165b | [
"self.bgcolor = bgcolor\nself.size = size\nself.scale_mode = scale_mode\nself.colormap = colormap\nself.mode = mode\nself.scale_factor = scale_factor\nself.show_axes = show_axes\nself.show_outline = show_outline\nself.show_colorbar = show_colorbar\nself.show_fig = show_fig\nself.view = view\nself.gpu = gpu\nself.fi... | <|body_start_0|>
self.bgcolor = bgcolor
self.size = size
self.scale_mode = scale_mode
self.colormap = colormap
self.mode = mode
self.scale_factor = scale_factor
self.show_axes = show_axes
self.show_outline = show_outline
self.show_colorbar = show_c... | 三维quiver图,需要确定画图的文件夹 | quiver3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class quiver3D:
"""三维quiver图,需要确定画图的文件夹"""
def __init__(self, bgcolor=None, size=(1080, 720), scale_mode='vector', colormap='bwr', mode='arrow', scale_factor=1e-09, show_outline=False, show_axes=False, show_colorbar=True, show_fig=True, view=np.array([[90, 180]]), gpu=False, fig_format='.png', sav... | stack_v2_sparse_classes_10k_train_003472 | 5,858 | no_license | [
{
"docstring": "bgcolor:tuple,背景颜色:(1,1,1) size:tuple,图片大小 (1080,720) scale_mode:str,颜色模式:scalar/vector colormap:str,'bwr','coolwarm' mode:str,arrow,cone,cube.... scale_factor:float,缩放 show_outline:bool,显示外框 show_axes:bool,显示坐标轴 view:array,视图 gpu:bool fig_format:str,图片格式",
"name": "__init__",
"signature... | 2 | stack_v2_sparse_classes_30k_test_000356 | Implement the Python class `quiver3D` described below.
Class description:
三维quiver图,需要确定画图的文件夹
Method signatures and docstrings:
- def __init__(self, bgcolor=None, size=(1080, 720), scale_mode='vector', colormap='bwr', mode='arrow', scale_factor=1e-09, show_outline=False, show_axes=False, show_colorbar=True, show_fig... | Implement the Python class `quiver3D` described below.
Class description:
三维quiver图,需要确定画图的文件夹
Method signatures and docstrings:
- def __init__(self, bgcolor=None, size=(1080, 720), scale_mode='vector', colormap='bwr', mode='arrow', scale_factor=1e-09, show_outline=False, show_axes=False, show_colorbar=True, show_fig... | b851c5988c8abcfdc911cb84f3290e849e83a9f6 | <|skeleton|>
class quiver3D:
"""三维quiver图,需要确定画图的文件夹"""
def __init__(self, bgcolor=None, size=(1080, 720), scale_mode='vector', colormap='bwr', mode='arrow', scale_factor=1e-09, show_outline=False, show_axes=False, show_colorbar=True, show_fig=True, view=np.array([[90, 180]]), gpu=False, fig_format='.png', sav... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class quiver3D:
"""三维quiver图,需要确定画图的文件夹"""
def __init__(self, bgcolor=None, size=(1080, 720), scale_mode='vector', colormap='bwr', mode='arrow', scale_factor=1e-09, show_outline=False, show_axes=False, show_colorbar=True, show_fig=True, view=np.array([[90, 180]]), gpu=False, fig_format='.png', save_path=os.get... | the_stack_v2_python_sparse | mpy0.1/tool/quiver3d.py | plenari/omfPython | train | 5 |
4812224be3f79bdeb9b29422ef2e3aded8352afc | [
"self.clear_table()\nself.unhinge_db()\nself.logger.info('Vacuum analyzing tables now that db is unhinged')\nself.execute('VACUUM ANALYZE;')\nself.logger.info('Creating mrt_w_roas')\nsql = 'CREATE UNLOGGED TABLE IF NOT EXISTS\\n mrt_w_roas AS (\\n SELECT DISTINCT ON (m.prefix, m.as_path, m... | <|body_start_0|>
self.clear_table()
self.unhinge_db()
self.logger.info('Vacuum analyzing tables now that db is unhinged')
self.execute('VACUUM ANALYZE;')
self.logger.info('Creating mrt_w_roas')
sql = 'CREATE UNLOGGED TABLE IF NOT EXISTS\n mrt_w_roas AS (\n ... | Announcements table class | MRT_W_Roas_Table | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRT_W_Roas_Table:
"""Announcements table class"""
def _create_tables(self):
"""Creates tables if they do not exist"""
<|body_0|>
def clear_table(self):
"""Clears the tables. Should be called at the start of every run"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_003473 | 2,215 | permissive | [
{
"docstring": "Creates tables if they do not exist",
"name": "_create_tables",
"signature": "def _create_tables(self)"
},
{
"docstring": "Clears the tables. Should be called at the start of every run",
"name": "clear_table",
"signature": "def clear_table(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000667 | Implement the Python class `MRT_W_Roas_Table` described below.
Class description:
Announcements table class
Method signatures and docstrings:
- def _create_tables(self): Creates tables if they do not exist
- def clear_table(self): Clears the tables. Should be called at the start of every run | Implement the Python class `MRT_W_Roas_Table` described below.
Class description:
Announcements table class
Method signatures and docstrings:
- def _create_tables(self): Creates tables if they do not exist
- def clear_table(self): Clears the tables. Should be called at the start of every run
<|skeleton|>
class MRT_W... | 91c92584b31bd128d818c7fee86c738367c0712e | <|skeleton|>
class MRT_W_Roas_Table:
"""Announcements table class"""
def _create_tables(self):
"""Creates tables if they do not exist"""
<|body_0|>
def clear_table(self):
"""Clears the tables. Should be called at the start of every run"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MRT_W_Roas_Table:
"""Announcements table class"""
def _create_tables(self):
"""Creates tables if they do not exist"""
self.clear_table()
self.unhinge_db()
self.logger.info('Vacuum analyzing tables now that db is unhinged')
self.execute('VACUUM ANALYZE;')
se... | the_stack_v2_python_sparse | lib_bgp_data/forecast/tables.py | jfuruness/lib_bgp_data | train | 16 |
dd2e26be4e72fcb5d389e063df358567e9682624 | [
"super().default_login()\nleaguer_level_page = Leaguer_Level_Page(self.base, test_data)\nleaguer_level_page.switch_in_leaguer_level_menu()\nleaguer_level_page.click_add_btn()\nleaguer_level_page.input_add_info()\nleaguer_level_page.click_save_btn()\nleaguer_level_page.assert_add_result()",
"super().default_login(... | <|body_start_0|>
super().default_login()
leaguer_level_page = Leaguer_Level_Page(self.base, test_data)
leaguer_level_page.switch_in_leaguer_level_menu()
leaguer_level_page.click_add_btn()
leaguer_level_page.input_add_info()
leaguer_level_page.click_save_btn()
leag... | Leaguer_Level_Case | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Leaguer_Level_Case:
def test_001_leaguer_level_add(self):
"""新增会员"""
<|body_0|>
def test_002_leaguer_level_query(self):
"""查询会员"""
<|body_1|>
def test_003_leaguer_level_del(self):
"""删除会员"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003474 | 1,873 | no_license | [
{
"docstring": "新增会员",
"name": "test_001_leaguer_level_add",
"signature": "def test_001_leaguer_level_add(self)"
},
{
"docstring": "查询会员",
"name": "test_002_leaguer_level_query",
"signature": "def test_002_leaguer_level_query(self)"
},
{
"docstring": "删除会员",
"name": "test_003... | 3 | stack_v2_sparse_classes_30k_train_006848 | Implement the Python class `Leaguer_Level_Case` described below.
Class description:
Implement the Leaguer_Level_Case class.
Method signatures and docstrings:
- def test_001_leaguer_level_add(self): 新增会员
- def test_002_leaguer_level_query(self): 查询会员
- def test_003_leaguer_level_del(self): 删除会员 | Implement the Python class `Leaguer_Level_Case` described below.
Class description:
Implement the Leaguer_Level_Case class.
Method signatures and docstrings:
- def test_001_leaguer_level_add(self): 新增会员
- def test_002_leaguer_level_query(self): 查询会员
- def test_003_leaguer_level_del(self): 删除会员
<|skeleton|>
class Lea... | 94875917afb222cadcf6b4fde391e44cfbc9d199 | <|skeleton|>
class Leaguer_Level_Case:
def test_001_leaguer_level_add(self):
"""新增会员"""
<|body_0|>
def test_002_leaguer_level_query(self):
"""查询会员"""
<|body_1|>
def test_003_leaguer_level_del(self):
"""删除会员"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Leaguer_Level_Case:
def test_001_leaguer_level_add(self):
"""新增会员"""
super().default_login()
leaguer_level_page = Leaguer_Level_Page(self.base, test_data)
leaguer_level_page.switch_in_leaguer_level_menu()
leaguer_level_page.click_add_btn()
leaguer_level_page.inp... | the_stack_v2_python_sparse | test_case/leaguer_case/test_leaguer_level_case.py | goodboyxzmkk/youlebao | train | 5 | |
143758b7a4c3091ebe280a532eb9e012acd08437 | [
"obj = super().__new__(cls, _str_)\nobj.if_empty = if_empty\nobj.separator = s\nobj.quote_args = quote_args\nreturn obj",
"tovar: Callable[[Any], Var] = _tovar\nif self.quote_args:\n tovar = lambda var: Var(repr(str(_tovar(var))))\nif args:\n args = tuple((tovar(arg) for arg in args if arg))\n if self ==... | <|body_start_0|>
obj = super().__new__(cls, _str_)
obj.if_empty = if_empty
obj.separator = s
obj.quote_args = quote_args
return obj
<|end_body_0|>
<|body_start_1|>
tovar: Callable[[Any], Var] = _tovar
if self.quote_args:
tovar = lambda var: Var(repr(s... | ``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, all occurrences of `` or `` presen... | AtRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtRule:
"""``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, ... | stack_v2_sparse_classes_10k_train_003475 | 44,402 | permissive | [
{
"docstring": "Create the ``AtRule`` and save parameters. Parameters ---------- _str_ : str The string of the current ``Var`` For the other parameters, see the class docstring (``if_empty`` and ``quote_args`` have the same name as the arguments to ``__new__`, but ``separator`` comes from the ``s`` argument. Re... | 2 | stack_v2_sparse_classes_30k_train_003462 | Implement the Python class `AtRule` described below.
Class description:
``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args pa... | Implement the Python class `AtRule` described below.
Class description:
``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args pa... | adeff652784f0d814835fd16a8cacab09f426922 | <|skeleton|>
class AtRule:
"""``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AtRule:
"""``Var`` that, when called, allows to define a CSS '@-rule'. Attributes ---------- if_empty : str A string to use if there is no args passed to ``__call__``. separator : str Default to `` or ``, it is the string that will join the different args passed to ``__call__``. If not `` or ``, all occurrenc... | the_stack_v2_python_sparse | src/mixt/contrib/css/vars.py | twidi/mixt | train | 37 |
2419187dafbed75331e4d65d60f87d3c8d36386c | [
"QWidget.__init__(self, flags=Qt.Widget)\nself.te_1 = QTextEdit()\nself.te_2 = QTextEdit()\nself.te_3 = QTextEdit()\nself.split_1 = QSplitter()\nself.split_2 = QSplitter()\nself.vbox = QVBoxLayout()\nself.container_vbox = QVBoxLayout()\nself.init_widget()",
"self.setWindowTitle('Hello World')\nself.split_1.addWid... | <|body_start_0|>
QWidget.__init__(self, flags=Qt.Widget)
self.te_1 = QTextEdit()
self.te_2 = QTextEdit()
self.te_3 = QTextEdit()
self.split_1 = QSplitter()
self.split_2 = QSplitter()
self.vbox = QVBoxLayout()
self.container_vbox = QVBoxLayout()
sel... | 만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성. | Form | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Form:
"""만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성."""
def __init__(self):
"""보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다."""
<|body_0|>
def init_widget(self):
"""현재 위젯의 모양등을 초기화"""
... | stack_v2_sparse_classes_10k_train_003476 | 1,815 | no_license | [
{
"docstring": "보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "현재 위젯의 모양등을 초기화",
"name": "init_widget",
"signature": "def init_widget(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000071 | Implement the Python class `Form` described below.
Class description:
만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성.
Method signatures and docstrings:
- def __init__(self): 보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.
- def init_widget(self): 현재 위젯의... | Implement the Python class `Form` described below.
Class description:
만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성.
Method signatures and docstrings:
- def __init__(self): 보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다.
- def init_widget(self): 현재 위젯의... | 559ad5618eb99368b4da140cb78609bce2d5da71 | <|skeleton|>
class Form:
"""만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성."""
def __init__(self):
"""보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다."""
<|body_0|>
def init_widget(self):
"""현재 위젯의 모양등을 초기화"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Form:
"""만들고자 하는 프로그램의 기본이 되는 창 또는 폼 위젯. 본 위젯 위에 다른 위젯을 올려서 모양을 만든다. QWidget을 상속받아서 필요한 메소드를 작성."""
def __init__(self):
"""보통 __init__ (생성자)에서 필요한 것들을 다를 위젯들을 선언해줘도 되지만 init_widget을 따로 만들어서 호출한다."""
QWidget.__init__(self, flags=Qt.Widget)
self.te_1 = QTextEdit()
self.te_2 ... | the_stack_v2_python_sparse | Python/pyqt5/OpenTutorials_PyQt/QtFramework/QtWidgets/QSplitter/QSplitter_00_basic.py | ghdic/marinelifeirony | train | 6 |
358854b669c0f977b5d61976991de31126240edf | [
"inter.MNADevice.__init__(self, nodes, 0, **parameters)\nself.subckt = subckt\nself.parameters = parameters",
"self.port2node = {}\nfor p, n in zip(self.netlist.subckts[self.subckt].ports, self.nodes):\n self.port2node[p] = n"
] | <|body_start_0|>
inter.MNADevice.__init__(self, nodes, 0, **parameters)
self.subckt = subckt
self.parameters = parameters
<|end_body_0|>
<|body_start_1|>
self.port2node = {}
for p, n in zip(self.netlist.subckts[self.subckt].ports, self.nodes):
self.port2node[p] = n
<... | Subckt instance device (SPICE X) | X | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class X:
"""Subckt instance device (SPICE X)"""
def __init__(self, nodes, subckt, **parameters):
"""Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New s... | stack_v2_sparse_classes_10k_train_003477 | 3,583 | permissive | [
{
"docstring": "Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New subckt instance device",
"name": "__init__",
"signature": "def __init__(self, nodes, subckt, **para... | 2 | stack_v2_sparse_classes_30k_train_004109 | Implement the Python class `X` described below.
Class description:
Subckt instance device (SPICE X)
Method signatures and docstrings:
- def __init__(self, nodes, subckt, **parameters): Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary... | Implement the Python class `X` described below.
Class description:
Subckt instance device (SPICE X)
Method signatures and docstrings:
- def __init__(self, nodes, subckt, **parameters): Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary... | 0097735f71b19a4d3f95696d3af0a3df4a620e25 | <|skeleton|>
class X:
"""Subckt instance device (SPICE X)"""
def __init__(self, nodes, subckt, **parameters):
"""Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class X:
"""Subckt instance device (SPICE X)"""
def __init__(self, nodes, subckt, **parameters):
"""Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New subckt instanc... | the_stack_v2_python_sparse | subcircuit/devices/x.py | joehood/SubCircuit | train | 7 |
e4cc33506d25199ec4ff9b06c754c21f23f5143b | [
"maxSumList = [0] * len(array)\nfor i in range(len(array)):\n maxSum = 0\n sum_ = 0\n for j in range(i, len(array)):\n sum_ += array[j]\n if maxSum < sum_:\n maxSum = sum_\n maxSumList[i] = maxSum\nreturn max(maxSumList)",
"tmp = nums[0]\nmax_ = tmp\nfor i in range(1, len(nums... | <|body_start_0|>
maxSumList = [0] * len(array)
for i in range(len(array)):
maxSum = 0
sum_ = 0
for j in range(i, len(array)):
sum_ += array[j]
if maxSum < sum_:
maxSum = sum_
maxSumList[i] = maxSum
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, array):
"""暴力求解法"""
<|body_0|>
def maxSubArray(self, nums) -> int:
"""动态规划法DP"""
<|body_1|>
def maxSubArray3(self, nums) -> int:
"""分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_003478 | 2,930 | no_license | [
{
"docstring": "暴力求解法",
"name": "maxSubArray",
"signature": "def maxSubArray(self, array)"
},
{
"docstring": "动态规划法DP",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums) -> int"
},
{
"docstring": "分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解",
"name": "maxSubArray3",
"s... | 3 | stack_v2_sparse_classes_30k_train_003002 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, array): 暴力求解法
- def maxSubArray(self, nums) -> int: 动态规划法DP
- def maxSubArray3(self, nums) -> int: 分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, array): 暴力求解法
- def maxSubArray(self, nums) -> int: 动态规划法DP
- def maxSubArray3(self, nums) -> int: 分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解
<|skeleton|>
class Solut... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def maxSubArray(self, array):
"""暴力求解法"""
<|body_0|>
def maxSubArray(self, nums) -> int:
"""动态规划法DP"""
<|body_1|>
def maxSubArray3(self, nums) -> int:
"""分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, array):
"""暴力求解法"""
maxSumList = [0] * len(array)
for i in range(len(array)):
maxSum = 0
sum_ = 0
for j in range(i, len(array)):
sum_ += array[j]
if maxSum < sum_:
ma... | the_stack_v2_python_sparse | leetcode/53.最大子序和(动态规划).py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
51159822727d1eef0074618b80366d8c8ae8d915 | [
"group = Group.objects.filter(name='teachers')\nusers = User.objects.filter(groups__in=group)\nif obj in users:\n return 'teachers'\nelse:\n return 'students'",
"exams = []\nqueryset = ExamSheet.objects.filter(owner=obj)\nfor q in queryset:\n exams.append(q.title)\nreturn exams"
] | <|body_start_0|>
group = Group.objects.filter(name='teachers')
users = User.objects.filter(groups__in=group)
if obj in users:
return 'teachers'
else:
return 'students'
<|end_body_0|>
<|body_start_1|>
exams = []
queryset = ExamSheet.objects.filter(... | UserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
def get_group(self, obj):
"""Simply returns a groups name to which user belongs"""
<|body_0|>
def get_owned_exams(self, obj):
"""Get exams owned by teacher"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
group = Group.objects.filter(... | stack_v2_sparse_classes_10k_train_003479 | 3,922 | no_license | [
{
"docstring": "Simply returns a groups name to which user belongs",
"name": "get_group",
"signature": "def get_group(self, obj)"
},
{
"docstring": "Get exams owned by teacher",
"name": "get_owned_exams",
"signature": "def get_owned_exams(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005266 | Implement the Python class `UserSerializer` described below.
Class description:
Implement the UserSerializer class.
Method signatures and docstrings:
- def get_group(self, obj): Simply returns a groups name to which user belongs
- def get_owned_exams(self, obj): Get exams owned by teacher | Implement the Python class `UserSerializer` described below.
Class description:
Implement the UserSerializer class.
Method signatures and docstrings:
- def get_group(self, obj): Simply returns a groups name to which user belongs
- def get_owned_exams(self, obj): Get exams owned by teacher
<|skeleton|>
class UserSeri... | 2651ac12078c7d5435d1fb23585bb275c974ce30 | <|skeleton|>
class UserSerializer:
def get_group(self, obj):
"""Simply returns a groups name to which user belongs"""
<|body_0|>
def get_owned_exams(self, obj):
"""Get exams owned by teacher"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserSerializer:
def get_group(self, obj):
"""Simply returns a groups name to which user belongs"""
group = Group.objects.filter(name='teachers')
users = User.objects.filter(groups__in=group)
if obj in users:
return 'teachers'
else:
return 'studen... | the_stack_v2_python_sparse | ExamAPI/Sheets/serializers.py | mtyton/ExamSheetEvaluator-API | train | 0 | |
7a02d49108d79b2075ab25f1edbb3626dee48182 | [
"super().__init__(parent)\nself.items = items\nself.initUi()",
"width = 150\nheight = 70\nroundness = 20\ncolor = qRgb(154, 179, 174)\nstyle = '\\n QLabel {\\n color: black;\\n font-weight: bold;\\n font-size: 30pt;\\n font-family: Asap;\\n ... | <|body_start_0|>
super().__init__(parent)
self.items = items
self.initUi()
<|end_body_0|>
<|body_start_1|>
width = 150
height = 70
roundness = 20
color = qRgb(154, 179, 174)
style = '\n QLabel {\n color: black;\n f... | Food Menu widget. | Tabs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tabs:
"""Food Menu widget."""
def __init__(self, items, parent=None):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(parent)
self.items = items
self.initUi()... | stack_v2_sparse_classes_10k_train_003480 | 2,585 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, items, parent=None)"
},
{
"docstring": "Ui Setup.",
"name": "initUi",
"signature": "def initUi(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005444 | Implement the Python class `Tabs` described below.
Class description:
Food Menu widget.
Method signatures and docstrings:
- def __init__(self, items, parent=None): Init.
- def initUi(self): Ui Setup. | Implement the Python class `Tabs` described below.
Class description:
Food Menu widget.
Method signatures and docstrings:
- def __init__(self, items, parent=None): Init.
- def initUi(self): Ui Setup.
<|skeleton|>
class Tabs:
"""Food Menu widget."""
def __init__(self, items, parent=None):
"""Init."""... | a5d18593e689123cac34af552628ed2818ca5d59 | <|skeleton|>
class Tabs:
"""Food Menu widget."""
def __init__(self, items, parent=None):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tabs:
"""Food Menu widget."""
def __init__(self, items, parent=None):
"""Init."""
super().__init__(parent)
self.items = items
self.initUi()
def initUi(self):
"""Ui Setup."""
width = 150
height = 70
roundness = 20
color = qRgb(15... | the_stack_v2_python_sparse | Menu.py | edgary777/lonchepos | train | 0 |
d9d3eaa9d356f048e0815dc6e82d2cdfb377e3a3 | [
"self.trainloader = trainloader\nself.N_trn = len(trainloader.sampler.data_source)\nself.online = online\nself.indices = None\nself.gammas = None",
"if self.online or self.indices is None:\n self.indices = np.random.choice(self.N_trn, size=budget, replace=False)\n self.gammas = torch.ones(budget)\nreturn (s... | <|body_start_0|>
self.trainloader = trainloader
self.N_trn = len(trainloader.sampler.data_source)
self.online = online
self.indices = None
self.gammas = None
<|end_body_0|>
<|body_start_1|>
if self.online or self.indices is None:
self.indices = np.random.choi... | This is the Random Selection Strategy class where we select a set of random points as a datasubset and often acts as baselines to compare other subset selection strategies. Parameters ---------- trainloader: class Loading the training data using pytorch DataLoader | RandomStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomStrategy:
"""This is the Random Selection Strategy class where we select a set of random points as a datasubset and often acts as baselines to compare other subset selection strategies. Parameters ---------- trainloader: class Loading the training data using pytorch DataLoader"""
def _... | stack_v2_sparse_classes_10k_train_003481 | 1,305 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, trainloader, online=False)"
},
{
"docstring": "Perform random sampling of indices of size budget. Parameters ---------- budget: int The number of data points to be selected Returns ---------- indices: ndarr... | 2 | stack_v2_sparse_classes_30k_val_000372 | Implement the Python class `RandomStrategy` described below.
Class description:
This is the Random Selection Strategy class where we select a set of random points as a datasubset and often acts as baselines to compare other subset selection strategies. Parameters ---------- trainloader: class Loading the training data... | Implement the Python class `RandomStrategy` described below.
Class description:
This is the Random Selection Strategy class where we select a set of random points as a datasubset and often acts as baselines to compare other subset selection strategies. Parameters ---------- trainloader: class Loading the training data... | 8d10c7f5d96e071f98c20e4e9ff4c41c2c4ea2af | <|skeleton|>
class RandomStrategy:
"""This is the Random Selection Strategy class where we select a set of random points as a datasubset and often acts as baselines to compare other subset selection strategies. Parameters ---------- trainloader: class Loading the training data using pytorch DataLoader"""
def _... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomStrategy:
"""This is the Random Selection Strategy class where we select a set of random points as a datasubset and often acts as baselines to compare other subset selection strategies. Parameters ---------- trainloader: class Loading the training data using pytorch DataLoader"""
def __init__(self,... | the_stack_v2_python_sparse | cords/selectionstrategies/SSL/randomstrategy.py | decile-team/cords | train | 289 |
c7062b2fedb190599f2b5b302aeeeae054d3a9ba | [
"super().__init__()\nif type(uni_prob) == int:\n self.class_weights = Variable(torch.ones(uni_prob)).cuda()\nelif self.samp_prob is not None:\n usamp = uni_prob.pow(0.75)\n self.samp_prob = usamp / usamp.sum()\n assert self.samp_prob.sum().data == 1.0\nelse:\n self.samp_prob = Variable(torch.ones(uni... | <|body_start_0|>
super().__init__()
if type(uni_prob) == int:
self.class_weights = Variable(torch.ones(uni_prob)).cuda()
elif self.samp_prob is not None:
usamp = uni_prob.pow(0.75)
self.samp_prob = usamp / usamp.sum()
assert self.samp_prob.sum().da... | This criterion (`BinaryCrossEntropyLoss`) combines `LogSigmoid` and `NLLLoss` in one single class. Therefore, no Softmax used, but instead a Sigmoid for each unit in the output. NOTE: Computes per-element losses for a mini-batch (instead of the average loss over the entire mini-batch). | BinaryCrossEntropyLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryCrossEntropyLoss:
"""This criterion (`BinaryCrossEntropyLoss`) combines `LogSigmoid` and `NLLLoss` in one single class. Therefore, no Softmax used, but instead a Sigmoid for each unit in the output. NOTE: Computes per-element losses for a mini-batch (instead of the average loss over the ent... | stack_v2_sparse_classes_10k_train_003482 | 9,463 | permissive | [
{
"docstring": ":param class_weights: weights certain classes more than others :param uni_prob: counts for getting negative samples OR an int that is the length of the vocabulary :param num_neighbors:",
"name": "__init__",
"signature": "def __init__(self, uni_prob, num_neighbors=10)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_003351 | Implement the Python class `BinaryCrossEntropyLoss` described below.
Class description:
This criterion (`BinaryCrossEntropyLoss`) combines `LogSigmoid` and `NLLLoss` in one single class. Therefore, no Softmax used, but instead a Sigmoid for each unit in the output. NOTE: Computes per-element losses for a mini-batch (i... | Implement the Python class `BinaryCrossEntropyLoss` described below.
Class description:
This criterion (`BinaryCrossEntropyLoss`) combines `LogSigmoid` and `NLLLoss` in one single class. Therefore, no Softmax used, but instead a Sigmoid for each unit in the output. NOTE: Computes per-element losses for a mini-batch (i... | 99cba1030ed8c012a453bc7715830fc99fb980dc | <|skeleton|>
class BinaryCrossEntropyLoss:
"""This criterion (`BinaryCrossEntropyLoss`) combines `LogSigmoid` and `NLLLoss` in one single class. Therefore, no Softmax used, but instead a Sigmoid for each unit in the output. NOTE: Computes per-element losses for a mini-batch (instead of the average loss over the ent... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BinaryCrossEntropyLoss:
"""This criterion (`BinaryCrossEntropyLoss`) combines `LogSigmoid` and `NLLLoss` in one single class. Therefore, no Softmax used, but instead a Sigmoid for each unit in the output. NOTE: Computes per-element losses for a mini-batch (instead of the average loss over the entire mini-batc... | the_stack_v2_python_sparse | models/loss/ce.py | jamesoneill12/LayerFusion | train | 2 |
3c0a68e399548287377fbf4f5d4e646524722057 | [
"if not kwargs.get('auth_plugin') and (not kwargs.get('session')):\n kwargs['auth_plugin'] = monitoringclient.get_auth_plugin(*args, **kwargs)\nself.auth_plugin = kwargs.get('auth_plugin')\nself.http_client = monitoringclient._construct_http_client(**kwargs)\nself.alarm_client = self._get_alarm_client(**kwargs)\... | <|body_start_0|>
if not kwargs.get('auth_plugin') and (not kwargs.get('session')):
kwargs['auth_plugin'] = monitoringclient.get_auth_plugin(*args, **kwargs)
self.auth_plugin = kwargs.get('auth_plugin')
self.http_client = monitoringclient._construct_http_client(**kwargs)
self.... | Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The default interface for URL discove... | Client | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
"""Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The... | stack_v2_sparse_classes_10k_train_003483 | 5,420 | permissive | [
{
"docstring": "Initialize a new client for the Ceilometer v2 API.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get client for alarm manager that redirect to aodh.",
"name": "_get_alarm_client",
"signature": "def _get_alarm_client(**ceilo_kw... | 2 | stack_v2_sparse_classes_30k_train_002843 | Implement the Python class `Client` described below.
Class description:
Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for ... | Implement the Python class `Client` described below.
Class description:
Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for ... | 5e88cf438b4d24b92f996ae31907d44bd736c7f1 | <|skeleton|>
class Client:
"""Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Client:
"""Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The default inte... | the_stack_v2_python_sparse | eclcli/monitoring/monitoringclient/v2/client.py | nttcom/eclcli | train | 32 |
08de3526ea79539fce720dde3fe7c09374fb47b4 | [
"if len(self.required_tasks) == 0:\n return True\ntask_query = self.storage_socket.get_procedures(id=list(self.required_tasks.values()), include=['status', 'error'])\nstatus_values = set((x['status'] for x in task_query['data']))\nif status_values == {'COMPLETE'}:\n return True\nelif 'ERROR' in status_values:... | <|body_start_0|>
if len(self.required_tasks) == 0:
return True
task_query = self.storage_socket.get_procedures(id=list(self.required_tasks.values()), include=['status', 'error'])
status_values = set((x['status'] for x in task_query['data']))
if status_values == {'COMPLETE'}:
... | TaskManager | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskManager:
def done(self) -> bool:
"""Check if requested tasks are complete."""
<|body_0|>
def get_tasks(self) -> Dict[str, Any]:
"""Pulls currently held tasks."""
<|body_1|>
def submit_tasks(self, procedure_type: str, tasks: Dict[str, Any]) -> bool:
... | stack_v2_sparse_classes_10k_train_003484 | 6,231 | permissive | [
{
"docstring": "Check if requested tasks are complete.",
"name": "done",
"signature": "def done(self) -> bool"
},
{
"docstring": "Pulls currently held tasks.",
"name": "get_tasks",
"signature": "def get_tasks(self) -> Dict[str, Any]"
},
{
"docstring": "Submits new tasks to the qu... | 3 | stack_v2_sparse_classes_30k_train_006514 | Implement the Python class `TaskManager` described below.
Class description:
Implement the TaskManager class.
Method signatures and docstrings:
- def done(self) -> bool: Check if requested tasks are complete.
- def get_tasks(self) -> Dict[str, Any]: Pulls currently held tasks.
- def submit_tasks(self, procedure_type:... | Implement the Python class `TaskManager` described below.
Class description:
Implement the TaskManager class.
Method signatures and docstrings:
- def done(self) -> bool: Check if requested tasks are complete.
- def get_tasks(self) -> Dict[str, Any]: Pulls currently held tasks.
- def submit_tasks(self, procedure_type:... | e48ac2fd5e0bfde56ada9520db64bcc2cb8d8c0d | <|skeleton|>
class TaskManager:
def done(self) -> bool:
"""Check if requested tasks are complete."""
<|body_0|>
def get_tasks(self) -> Dict[str, Any]:
"""Pulls currently held tasks."""
<|body_1|>
def submit_tasks(self, procedure_type: str, tasks: Dict[str, Any]) -> bool:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TaskManager:
def done(self) -> bool:
"""Check if requested tasks are complete."""
if len(self.required_tasks) == 0:
return True
task_query = self.storage_socket.get_procedures(id=list(self.required_tasks.values()), include=['status', 'error'])
status_values = set((x... | the_stack_v2_python_sparse | qcfractal/services/service_util.py | ahurta92/QCFractal | train | 0 | |
679483262ef9e854746428f03c0310c0aae11700 | [
"if update_info.get('data_truncate', {}).get('enable', False):\n instalog_config['buffer']['args']['truncate_interval'] = 86400\nthreshold = update_info.get('input_http', {}).get('log_level_threshold', logging.NOTSET)\ninstalog_config['input']['http_in']['args']['log_level_threshold'] = threshold\nif update_info... | <|body_start_0|>
if update_info.get('data_truncate', {}).get('enable', False):
instalog_config['buffer']['args']['truncate_interval'] = 86400
threshold = update_info.get('input_http', {}).get('log_level_threshold', logging.NOTSET)
instalog_config['input']['http_in']['args']['log_leve... | Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs) | InstalogService | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstalogService:
"""Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)"""
def UpdateConfig(self, instalog_config, update_info, env):
"""Updates Instalog plugin config based on Umpire config. Arg... | stack_v2_sparse_classes_10k_train_003485 | 6,051 | permissive | [
{
"docstring": "Updates Instalog plugin config based on Umpire config. Args: instalog_config: Original Instalog configuration. update_info: The Umpire configuration used to update instalog_config. env: UmpireEnv object.",
"name": "UpdateConfig",
"signature": "def UpdateConfig(self, instalog_config, upda... | 3 | stack_v2_sparse_classes_30k_train_002809 | Implement the Python class `InstalogService` described below.
Class description:
Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)
Method signatures and docstrings:
- def UpdateConfig(self, instalog_config, update_info, env): U... | Implement the Python class `InstalogService` described below.
Class description:
Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)
Method signatures and docstrings:
- def UpdateConfig(self, instalog_config, update_info, env): U... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class InstalogService:
"""Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)"""
def UpdateConfig(self, instalog_config, update_info, env):
"""Updates Instalog plugin config based on Umpire config. Arg... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InstalogService:
"""Instalog service. Example: svc = GetServiceInstance('instalog') procs = svc.CreateProcesses(umpire_config_dict, umpire_env) svc.Start(procs)"""
def UpdateConfig(self, instalog_config, update_info, env):
"""Updates Instalog plugin config based on Umpire config. Args: instalog_c... | the_stack_v2_python_sparse | py/umpire/server/service/instalog.py | bridder/factory | train | 0 |
5493ad710279bda247a961503a88a92787165840 | [
"parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('Specific GitHub account users to reset. If not provided, all users will be reset.'))\nparser.add_argument('--yes', action='store_true', default=False, dest='force_yes', help=_('Answer yes to all questions'))\nparser.add_argument('--local-sites... | <|body_start_0|>
parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('Specific GitHub account users to reset. If not provided, all users will be reset.'))
parser.add_argument('--yes', action='store_true', default=False, dest='force_yes', help=_('Answer yes to all questions'))
... | Management command for resetting GitHub auth tokens. | Command | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Management command for resetting GitHub auth tokens."""
def add_arguments(self, parser):
"""Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command."""
<|body_0|>
def handle(self, *usernames, **options):
... | stack_v2_sparse_classes_10k_train_003486 | 4,284 | permissive | [
{
"docstring": "Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Handle the command. Args: *usernames (tuple): A list of usernames containing tok... | 3 | stack_v2_sparse_classes_30k_train_002572 | Implement the Python class `Command` described below.
Class description:
Management command for resetting GitHub auth tokens.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.
- def handle(sel... | Implement the Python class `Command` described below.
Class description:
Management command for resetting GitHub auth tokens.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.
- def handle(sel... | 563c1e8d4dfd860f372281dc0f380a0809f6ae15 | <|skeleton|>
class Command:
"""Management command for resetting GitHub auth tokens."""
def add_arguments(self, parser):
"""Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command."""
<|body_0|>
def handle(self, *usernames, **options):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Command:
"""Management command for resetting GitHub auth tokens."""
def add_arguments(self, parser):
"""Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command."""
parser.add_argument('usernames', metavar='USERNAME', nargs='*', help=_('Spe... | the_stack_v2_python_sparse | reviewboard/hostingsvcs/management/commands/reset-github-tokens.py | LloydFinch/reviewboard | train | 2 |
cc878044d30b3563836322d6f429d72294c9dd17 | [
"from facebook import GraphAPI, GraphAPIError\nself.GraphAPI = GraphAPI\nself.GraphAPIError = GraphAPIError\nrequest = current.request\nsettings = current.deployment_settings\nscope = 'email,user_about_me,user_location,user_photos,user_relationships,user_birthday,user_website,create_event,user_events,publish_stream... | <|body_start_0|>
from facebook import GraphAPI, GraphAPIError
self.GraphAPI = GraphAPI
self.GraphAPIError = GraphAPIError
request = current.request
settings = current.deployment_settings
scope = 'email,user_about_me,user_location,user_photos,user_relationships,user_birthd... | OAuth implementation for FaceBook | FaceBookAccount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceBookAccount:
"""OAuth implementation for FaceBook"""
def __init__(self, channel):
"""Constructor @param channel: Facebook channel (Row) with API credentials: {app_id=clientID, app_secret=clientSecret}"""
<|body_0|>
def login_url(self, next='/'):
"""Overriding... | stack_v2_sparse_classes_10k_train_003487 | 31,965 | permissive | [
{
"docstring": "Constructor @param channel: Facebook channel (Row) with API credentials: {app_id=clientID, app_secret=clientSecret}",
"name": "__init__",
"signature": "def __init__(self, channel)"
},
{
"docstring": "Overriding to produce a different redirect_uri",
"name": "login_url",
"s... | 3 | null | Implement the Python class `FaceBookAccount` described below.
Class description:
OAuth implementation for FaceBook
Method signatures and docstrings:
- def __init__(self, channel): Constructor @param channel: Facebook channel (Row) with API credentials: {app_id=clientID, app_secret=clientSecret}
- def login_url(self, ... | Implement the Python class `FaceBookAccount` described below.
Class description:
OAuth implementation for FaceBook
Method signatures and docstrings:
- def __init__(self, channel): Constructor @param channel: Facebook channel (Row) with API credentials: {app_id=clientID, app_secret=clientSecret}
- def login_url(self, ... | 7ec4b959d009daf26d5ca6ce91dd9c3c0bd978d6 | <|skeleton|>
class FaceBookAccount:
"""OAuth implementation for FaceBook"""
def __init__(self, channel):
"""Constructor @param channel: Facebook channel (Row) with API credentials: {app_id=clientID, app_secret=clientSecret}"""
<|body_0|>
def login_url(self, next='/'):
"""Overriding... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FaceBookAccount:
"""OAuth implementation for FaceBook"""
def __init__(self, channel):
"""Constructor @param channel: Facebook channel (Row) with API credentials: {app_id=clientID, app_secret=clientSecret}"""
from facebook import GraphAPI, GraphAPIError
self.GraphAPI = GraphAPI
... | the_stack_v2_python_sparse | modules/core/aaa/oauth.py | nursix/drkcm | train | 3 |
e9999c112fed2aa27840f65a0c410a5206c026c7 | [
"res = []\nnums.sort()\ni = 0\nfor n in range(1, len(nums) + 1):\n if i < len(nums) and n < nums[i] or (i == len(nums) and n > nums[-1]):\n res.append(n)\n while i < len(nums) and n >= nums[i]:\n i += 1\nreturn res",
"if len(nums) < 2:\n return []\nresult = []\nfor i in range(len(nums)):\n ... | <|body_start_0|>
res = []
nums.sort()
i = 0
for n in range(1, len(nums) + 1):
if i < len(nums) and n < nums[i] or (i == len(nums) and n > nums[-1]):
res.append(n)
while i < len(nums) and n >= nums[i]:
i += 1
return res
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def findDisappearedNumbers(self, nums):
""... | stack_v2_sparse_classes_10k_train_003488 | 1,946 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbers",
"signature": "def findDisappearedNumbers(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbers",
"signature": "def findDisappearedNumbers(self, ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisapp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisapp... | f3fc71f344cd758cfce77f16ab72992c99ab288e | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def findDisappearedNumbers(self, nums):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
res = []
nums.sort()
i = 0
for n in range(1, len(nums) + 1):
if i < len(nums) and n < nums[i] or (i == len(nums) and n > nums[-1]):
res.append(n)
... | the_stack_v2_python_sparse | 448_findDisappearedNumbers.py | jennyChing/leetCode | train | 2 | |
6c1b57c9b3387e879699050202c6fb6b02662782 | [
"sys.stdout.write('\\nDownloading the repository of soletta...')\nsys.stdout.flush()\nsoletta_url = 'https://github.com/solettaproject/soletta.git'\nget_test_module_repo(soletta_url, 'soletta')\nsys.stdout.write('\\nCopying necessary files to target device...')\nsys.stdout.flush()\nbinding = 'i2c'\ncopy_test_files(... | <|body_start_0|>
sys.stdout.write('\nDownloading the repository of soletta...')
sys.stdout.flush()
soletta_url = 'https://github.com/solettaproject/soletta.git'
get_test_module_repo(soletta_url, 'soletta')
sys.stdout.write('\nCopying necessary files to target device...')
... | @class solettai2cApiTest Update suite.js for testing | solettai2cApiTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class solettai2cApiTest:
"""@class solettai2cApiTest Update suite.js for testing"""
def setUp(self):
"""Copy all files related to testing to device @fn setup @param self"""
<|body_0|>
def test_sol_i2c_api(self):
"""Execute the soletta upstream test cases. @fn test_sol_... | stack_v2_sparse_classes_10k_train_003489 | 2,887 | permissive | [
{
"docstring": "Copy all files related to testing to device @fn setup @param self",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Execute the soletta upstream test cases. @fn test_sol_platform_service_api @param self",
"name": "test_sol_i2c_api",
"signature": "def te... | 3 | stack_v2_sparse_classes_30k_train_006585 | Implement the Python class `solettai2cApiTest` described below.
Class description:
@class solettai2cApiTest Update suite.js for testing
Method signatures and docstrings:
- def setUp(self): Copy all files related to testing to device @fn setup @param self
- def test_sol_i2c_api(self): Execute the soletta upstream test... | Implement the Python class `solettai2cApiTest` described below.
Class description:
@class solettai2cApiTest Update suite.js for testing
Method signatures and docstrings:
- def setUp(self): Copy all files related to testing to device @fn setup @param self
- def test_sol_i2c_api(self): Execute the soletta upstream test... | e7f0006b7549907671be82a3b1f6b743217b1a90 | <|skeleton|>
class solettai2cApiTest:
"""@class solettai2cApiTest Update suite.js for testing"""
def setUp(self):
"""Copy all files related to testing to device @fn setup @param self"""
<|body_0|>
def test_sol_i2c_api(self):
"""Execute the soletta upstream test cases. @fn test_sol_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class solettai2cApiTest:
"""@class solettai2cApiTest Update suite.js for testing"""
def setUp(self):
"""Copy all files related to testing to device @fn setup @param self"""
sys.stdout.write('\nDownloading the repository of soletta...')
sys.stdout.flush()
soletta_url = 'https://g... | the_stack_v2_python_sparse | lib/oeqa/runtime/nodejs/soletta_i2c_api_upstream.py | ostroproject/meta-iotqa | train | 1 |
311ebc902bf5f7729c3ad898f353e3e7bf855b5a | [
"func = self._module.locally_linear_embedding\ny, squared_error = func(self._data.values, n_neighbors, n_components, *args, **kwargs)\ny = self._constructor(y, index=self._df.index)\nreturn (y, squared_error)",
"func = self._module.spectral_embedding\ndata = self._data\nembedding = func(data.values, *args, **kwar... | <|body_start_0|>
func = self._module.locally_linear_embedding
y, squared_error = func(self._data.values, n_neighbors, n_components, *args, **kwargs)
y = self._constructor(y, index=self._df.index)
return (y, squared_error)
<|end_body_0|>
<|body_start_1|>
func = self._module.spect... | Accessor to ``sklearn.manifold``. | ManifoldMethods | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManifoldMethods:
"""Accessor to ``sklearn.manifold``."""
def locally_linear_embedding(self, n_neighbors, n_components, *args, **kwargs):
"""Call ``sklearn.manifold.locally_linear_embedding`` using automatic mapping. - ``X``: ``ModelFrame.data``"""
<|body_0|>
def spectral... | stack_v2_sparse_classes_10k_train_003490 | 1,167 | permissive | [
{
"docstring": "Call ``sklearn.manifold.locally_linear_embedding`` using automatic mapping. - ``X``: ``ModelFrame.data``",
"name": "locally_linear_embedding",
"signature": "def locally_linear_embedding(self, n_neighbors, n_components, *args, **kwargs)"
},
{
"docstring": "Call ``sklearn.manifold.... | 2 | null | Implement the Python class `ManifoldMethods` described below.
Class description:
Accessor to ``sklearn.manifold``.
Method signatures and docstrings:
- def locally_linear_embedding(self, n_neighbors, n_components, *args, **kwargs): Call ``sklearn.manifold.locally_linear_embedding`` using automatic mapping. - ``X``: ``... | Implement the Python class `ManifoldMethods` described below.
Class description:
Accessor to ``sklearn.manifold``.
Method signatures and docstrings:
- def locally_linear_embedding(self, n_neighbors, n_components, *args, **kwargs): Call ``sklearn.manifold.locally_linear_embedding`` using automatic mapping. - ``X``: ``... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class ManifoldMethods:
"""Accessor to ``sklearn.manifold``."""
def locally_linear_embedding(self, n_neighbors, n_components, *args, **kwargs):
"""Call ``sklearn.manifold.locally_linear_embedding`` using automatic mapping. - ``X``: ``ModelFrame.data``"""
<|body_0|>
def spectral... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ManifoldMethods:
"""Accessor to ``sklearn.manifold``."""
def locally_linear_embedding(self, n_neighbors, n_components, *args, **kwargs):
"""Call ``sklearn.manifold.locally_linear_embedding`` using automatic mapping. - ``X``: ``ModelFrame.data``"""
func = self._module.locally_linear_embedd... | the_stack_v2_python_sparse | lib/python2.7/site-packages/pandas_ml/skaccessors/manifold.py | wangyum/Anaconda | train | 11 |
6985fbcc9d3f5a87986d7c327d6f9d9a1bf6859a | [
"self.model = torch_model.to(device)\nself.model.eval()\nself.dev = device\nself.transform = x_transform",
"arm_dataset = data_utils.DatasetNumpy(np_x, np_y, transform=self.transform)\narm_loader = torch.utils.data.DataLoader(arm_dataset, batch_size=128)\nreturn train_utils.evaluate(self.model, arm_loader, self.d... | <|body_start_0|>
self.model = torch_model.to(device)
self.model.eval()
self.dev = device
self.transform = x_transform
<|end_body_0|>
<|body_start_1|>
arm_dataset = data_utils.DatasetNumpy(np_x, np_y, transform=self.transform)
arm_loader = torch.utils.data.DataLoader(arm_... | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def __init__(self, torch_model, device, x_transform=None):
""":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions."""
<|body_0|>
def evaluate(self, np... | stack_v2_sparse_classes_10k_train_003491 | 5,605 | no_license | [
{
"docstring": ":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions.",
"name": "__init__",
"signature": "def __init__(self, torch_model, device, x_transform=None)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_006787 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, torch_model, device, x_transform=None): :args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any n... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, torch_model, device, x_transform=None): :args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any n... | 9782f6705a779d20323eb5a0132aeabffa5fbf92 | <|skeleton|>
class Model:
def __init__(self, torch_model, device, x_transform=None):
""":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions."""
<|body_0|>
def evaluate(self, np... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Model:
def __init__(self, torch_model, device, x_transform=None):
""":args: Torch model and device, the forward of model should give logits(classification)/scalar(regression) :x_transform: Any needed transform before we obtain predictions."""
self.model = torch_model.to(device)
self.mo... | the_stack_v2_python_sparse | src/dataset.py | vihari/AAA | train | 3 | |
b1a4a7a04e6869c2cebf9c0df40c341a272a1505 | [
"wb = load_workbook(excel_path)\nsheetnames = wb.get_sheet_names()\nself.ws = wb.get_sheet_by_name(sheetnames[0])",
"id_list = []\nfor i in range(2, self.ws.max_row + 1):\n if self.ws.cell(i, 1).value not in id_list:\n if i - 1 != self.ws.cell(i, 1).value:\n print('ID自增错误!! 行数:{}'.format(i + ... | <|body_start_0|>
wb = load_workbook(excel_path)
sheetnames = wb.get_sheet_names()
self.ws = wb.get_sheet_by_name(sheetnames[0])
<|end_body_0|>
<|body_start_1|>
id_list = []
for i in range(2, self.ws.max_row + 1):
if self.ws.cell(i, 1).value not in id_list:
... | Csvcheck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Csvcheck:
def __init__(self, excel_path: str):
"""打开一个excel文件 :param excel_path: :return:"""
<|body_0|>
def check_id(self):
"""检查ID是否重复 是否连续 默认ID在第一列 默认ID从1开始自增 :return:"""
<|body_1|>
def check_lua(self, column_num: int):
"""检查lua数据列 是否存在中文标点符号 是... | stack_v2_sparse_classes_10k_train_003492 | 1,513 | permissive | [
{
"docstring": "打开一个excel文件 :param excel_path: :return:",
"name": "__init__",
"signature": "def __init__(self, excel_path: str)"
},
{
"docstring": "检查ID是否重复 是否连续 默认ID在第一列 默认ID从1开始自增 :return:",
"name": "check_id",
"signature": "def check_id(self)"
},
{
"docstring": "检查lua数据列 是否存在中... | 3 | stack_v2_sparse_classes_30k_train_006085 | Implement the Python class `Csvcheck` described below.
Class description:
Implement the Csvcheck class.
Method signatures and docstrings:
- def __init__(self, excel_path: str): 打开一个excel文件 :param excel_path: :return:
- def check_id(self): 检查ID是否重复 是否连续 默认ID在第一列 默认ID从1开始自增 :return:
- def check_lua(self, column_num: in... | Implement the Python class `Csvcheck` described below.
Class description:
Implement the Csvcheck class.
Method signatures and docstrings:
- def __init__(self, excel_path: str): 打开一个excel文件 :param excel_path: :return:
- def check_id(self): 检查ID是否重复 是否连续 默认ID在第一列 默认ID从1开始自增 :return:
- def check_lua(self, column_num: in... | 9d9ff9fb0dc4f1b63cdd31d6bbc12f9cd467eb81 | <|skeleton|>
class Csvcheck:
def __init__(self, excel_path: str):
"""打开一个excel文件 :param excel_path: :return:"""
<|body_0|>
def check_id(self):
"""检查ID是否重复 是否连续 默认ID在第一列 默认ID从1开始自增 :return:"""
<|body_1|>
def check_lua(self, column_num: int):
"""检查lua数据列 是否存在中文标点符号 是... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Csvcheck:
def __init__(self, excel_path: str):
"""打开一个excel文件 :param excel_path: :return:"""
wb = load_workbook(excel_path)
sheetnames = wb.get_sheet_names()
self.ws = wb.get_sheet_by_name(sheetnames[0])
def check_id(self):
"""检查ID是否重复 是否连续 默认ID在第一列 默认ID从1开始自增 :ret... | the_stack_v2_python_sparse | code/kagamimoe/008/csv_check.py | jianbing/python-practice-for-game-tester | train | 42 | |
38628210514547e37e6b3fe73a5a6c75ab68fd98 | [
"self.num_failed = num_failed\nself.num_objects = num_objects\nself.size_bytes = size_bytes",
"if dictionary is None:\n return None\nnum_failed = dictionary.get('numFailed')\nnum_objects = dictionary.get('numObjects')\nsize_bytes = dictionary.get('sizeBytes')\nreturn cls(num_failed, num_objects, size_bytes)"
] | <|body_start_0|>
self.num_failed = num_failed
self.num_objects = num_objects
self.size_bytes = size_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
num_failed = dictionary.get('numFailed')
num_objects = dictionary.get('numObjects')
... | Implementation of the 'ProtectionStats' model. Protection Statistics. Attributes: num_failed (int): Number of Failed Objects. num_objects (int): Number of Objects. size_bytes (long|int): Size in Bytes. | ProtectionStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionStats:
"""Implementation of the 'ProtectionStats' model. Protection Statistics. Attributes: num_failed (int): Number of Failed Objects. num_objects (int): Number of Objects. size_bytes (long|int): Size in Bytes."""
def __init__(self, num_failed=None, num_objects=None, size_bytes=No... | stack_v2_sparse_classes_10k_train_003493 | 1,756 | permissive | [
{
"docstring": "Constructor for the ProtectionStats class",
"name": "__init__",
"signature": "def __init__(self, num_failed=None, num_objects=None, size_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation ... | 2 | null | Implement the Python class `ProtectionStats` described below.
Class description:
Implementation of the 'ProtectionStats' model. Protection Statistics. Attributes: num_failed (int): Number of Failed Objects. num_objects (int): Number of Objects. size_bytes (long|int): Size in Bytes.
Method signatures and docstrings:
-... | Implement the Python class `ProtectionStats` described below.
Class description:
Implementation of the 'ProtectionStats' model. Protection Statistics. Attributes: num_failed (int): Number of Failed Objects. num_objects (int): Number of Objects. size_bytes (long|int): Size in Bytes.
Method signatures and docstrings:
-... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionStats:
"""Implementation of the 'ProtectionStats' model. Protection Statistics. Attributes: num_failed (int): Number of Failed Objects. num_objects (int): Number of Objects. size_bytes (long|int): Size in Bytes."""
def __init__(self, num_failed=None, num_objects=None, size_bytes=No... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProtectionStats:
"""Implementation of the 'ProtectionStats' model. Protection Statistics. Attributes: num_failed (int): Number of Failed Objects. num_objects (int): Number of Objects. size_bytes (long|int): Size in Bytes."""
def __init__(self, num_failed=None, num_objects=None, size_bytes=None):
... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_stats.py | cohesity/management-sdk-python | train | 24 |
4dc032b772ae863399a6b8ff20a932cdbf18783a | [
"args = self.parser.parse_args()\ndata = self.build_data(args=args, collection='asset_site')\nreturn data",
"args = self.parse_args(add_site_fields)\nsite = args.pop('site')\nscope_id = args.pop('scope_id')\nurl = utils.normal_url(site).strip('/')\nif not url:\n return utils.build_ret(ErrorMsg.DomainInvalid, {... | <|body_start_0|>
args = self.parser.parse_args()
data = self.build_data(args=args, collection='asset_site')
return data
<|end_body_0|>
<|body_start_1|>
args = self.parse_args(add_site_fields)
site = args.pop('site')
scope_id = args.pop('scope_id')
url = utils.nor... | ARLAssetSite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ARLAssetSite:
def get(self):
"""资产站点信息查询"""
<|body_0|>
def post(self):
"""添加站点到资产组中"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = self.parser.parse_args()
data = self.build_data(args=args, collection='asset_site')
return dat... | stack_v2_sparse_classes_10k_train_003494 | 8,529 | no_license | [
{
"docstring": "资产站点信息查询",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "添加站点到资产组中",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002453 | Implement the Python class `ARLAssetSite` described below.
Class description:
Implement the ARLAssetSite class.
Method signatures and docstrings:
- def get(self): 资产站点信息查询
- def post(self): 添加站点到资产组中 | Implement the Python class `ARLAssetSite` described below.
Class description:
Implement the ARLAssetSite class.
Method signatures and docstrings:
- def get(self): 资产站点信息查询
- def post(self): 添加站点到资产组中
<|skeleton|>
class ARLAssetSite:
def get(self):
"""资产站点信息查询"""
<|body_0|>
def post(self):
... | 5ca64806252b9e7e6d2b31a6bfaeecbfdc4baf06 | <|skeleton|>
class ARLAssetSite:
def get(self):
"""资产站点信息查询"""
<|body_0|>
def post(self):
"""添加站点到资产组中"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ARLAssetSite:
def get(self):
"""资产站点信息查询"""
args = self.parser.parse_args()
data = self.build_data(args=args, collection='asset_site')
return data
def post(self):
"""添加站点到资产组中"""
args = self.parse_args(add_site_fields)
site = args.pop('site')
... | the_stack_v2_python_sparse | app/routes/assetSite.py | QmF0c3UK/ARL | train | 0 | |
e9e3dd408401d510c3d2c1e1f4c7c3365c941e34 | [
"page = self.client.get('/')\nself.assertEqual(page.status_code, 200)\nself.assertTemplateUsed(page, 'index.html')",
"page = self.client.get('/about/')\nself.assertEqual(page.status_code, 200)\nself.assertTemplateUsed(page, 'about.html')",
"user = User.objects.create_user('TestingUser', 'testing@test.com', 'tes... | <|body_start_0|>
page = self.client.get('/')
self.assertEqual(page.status_code, 200)
self.assertTemplateUsed(page, 'index.html')
<|end_body_0|>
<|body_start_1|>
page = self.client.get('/about/')
self.assertEqual(page.status_code, 200)
self.assertTemplateUsed(page, 'about... | TestHomeViews | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHomeViews:
def test_get_index_page(self):
"""Testing index view which is the first page user sees"""
<|body_0|>
def test_get_about_page(self):
"""Testing about view"""
<|body_1|>
def test_get_faq_page(self):
"""Testing faq view"""
<|b... | stack_v2_sparse_classes_10k_train_003495 | 1,202 | no_license | [
{
"docstring": "Testing index view which is the first page user sees",
"name": "test_get_index_page",
"signature": "def test_get_index_page(self)"
},
{
"docstring": "Testing about view",
"name": "test_get_about_page",
"signature": "def test_get_about_page(self)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_test_000078 | Implement the Python class `TestHomeViews` described below.
Class description:
Implement the TestHomeViews class.
Method signatures and docstrings:
- def test_get_index_page(self): Testing index view which is the first page user sees
- def test_get_about_page(self): Testing about view
- def test_get_faq_page(self): T... | Implement the Python class `TestHomeViews` described below.
Class description:
Implement the TestHomeViews class.
Method signatures and docstrings:
- def test_get_index_page(self): Testing index view which is the first page user sees
- def test_get_about_page(self): Testing about view
- def test_get_faq_page(self): T... | b28b2254b81c5edf4db68056aeaecffbc7a56ab5 | <|skeleton|>
class TestHomeViews:
def test_get_index_page(self):
"""Testing index view which is the first page user sees"""
<|body_0|>
def test_get_about_page(self):
"""Testing about view"""
<|body_1|>
def test_get_faq_page(self):
"""Testing faq view"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestHomeViews:
def test_get_index_page(self):
"""Testing index view which is the first page user sees"""
page = self.client.get('/')
self.assertEqual(page.status_code, 200)
self.assertTemplateUsed(page, 'index.html')
def test_get_about_page(self):
"""Testing about ... | the_stack_v2_python_sparse | home/test_views.py | kimpea/us-issue-tracker | train | 0 | |
6a3a666b24d670f02713c86e1d51973ca7a4def9 | [
"super(QNetwork, self).__init__()\nif norm_in:\n self.in_fn = nn.BatchNorm1d(state_size)\n self.in_fn.weight.data.fill_(1)\n self.in_fn.bias.data.fill_(0)\nelse:\n self.in_fn = lambda x: x\nself.fc1 = nn.Linear(state_size, hidden_dim)\nself.fc2 = nn.Linear(hidden_dim, hidden_dim)\nself.fc3 = nn.Linear(h... | <|body_start_0|>
super(QNetwork, self).__init__()
if norm_in:
self.in_fn = nn.BatchNorm1d(state_size)
self.in_fn.weight.data.fill_(1)
self.in_fn.bias.data.fill_(0)
else:
self.in_fn = lambda x: x
self.fc1 = nn.Linear(state_size, hidden_dim)
... | Deep Q-Network | QNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNetwork:
"""Deep Q-Network"""
def __init__(self, state_size, action_size, hidden_dim, dropout_p=0.0, nonlin=F.relu, norm_in=True):
"""Initialize parameters and build model. :param state_size: Dimension of each state :param action_size: Dimension of each action :param hidden_dim: dim... | stack_v2_sparse_classes_10k_train_003496 | 1,565 | no_license | [
{
"docstring": "Initialize parameters and build model. :param state_size: Dimension of each state :param action_size: Dimension of each action :param hidden_dim: dimension of hidden layers :param dropout_p: dropout probability :param nonlin: nonlinearity to use :param norm_in: normalise input first",
"name"... | 2 | stack_v2_sparse_classes_30k_train_002019 | Implement the Python class `QNetwork` described below.
Class description:
Deep Q-Network
Method signatures and docstrings:
- def __init__(self, state_size, action_size, hidden_dim, dropout_p=0.0, nonlin=F.relu, norm_in=True): Initialize parameters and build model. :param state_size: Dimension of each state :param act... | Implement the Python class `QNetwork` described below.
Class description:
Deep Q-Network
Method signatures and docstrings:
- def __init__(self, state_size, action_size, hidden_dim, dropout_p=0.0, nonlin=F.relu, norm_in=True): Initialize parameters and build model. :param state_size: Dimension of each state :param act... | 2afa0a9d83bd66a151c1a19242c5ef22cf4eb1f6 | <|skeleton|>
class QNetwork:
"""Deep Q-Network"""
def __init__(self, state_size, action_size, hidden_dim, dropout_p=0.0, nonlin=F.relu, norm_in=True):
"""Initialize parameters and build model. :param state_size: Dimension of each state :param action_size: Dimension of each action :param hidden_dim: dim... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QNetwork:
"""Deep Q-Network"""
def __init__(self, state_size, action_size, hidden_dim, dropout_p=0.0, nonlin=F.relu, norm_in=True):
"""Initialize parameters and build model. :param state_size: Dimension of each state :param action_size: Dimension of each action :param hidden_dim: dimension of hid... | the_stack_v2_python_sparse | marl_algorithms/iql/model.py | Jarvis-K/MSc_Curiosity_MARL | train | 0 |
34ce94b4488517cf866c95e2e2b2fd21f00fe6b8 | [
"while True:\n result = 0\n while num != 0:\n ind = num % 10\n num = num // 10\n result += ind\n if result < 10:\n break\n else:\n num = result\nreturn result",
"while num >= 10:\n num = sum(map(int, str(num)))\nreturn num",
"if num == 0:\n return 0\nelse:\n ... | <|body_start_0|>
while True:
result = 0
while num != 0:
ind = num % 10
num = num // 10
result += ind
if result < 10:
break
else:
num = result
return result
<|end_body_0|>
<|bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_1|>
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_003497 | 969 | no_license | [
{
"docstring": ":type num: int :rtype: int",
"name": "addDigits",
"signature": "def addDigits(self, num)"
},
{
"docstring": ":type num: int :rtype: int",
"name": "addDigits",
"signature": "def addDigits(self, num)"
},
{
"docstring": ":type num: int :rtype: int",
"name": "addD... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addDigits(self, num): :type num: int :rtype: int
- def addDigits(self, num): :type num: int :rtype: int
- def addDigits(self, num): :type num: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addDigits(self, num): :type num: int :rtype: int
- def addDigits(self, num): :type num: int :rtype: int
- def addDigits(self, num): :type num: int :rtype: int
<|skeleton|>
c... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_1|>
def addDigits(self, num):
""":type num: int :rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def addDigits(self, num):
""":type num: int :rtype: int"""
while True:
result = 0
while num != 0:
ind = num % 10
num = num // 10
result += ind
if result < 10:
break
else:
... | the_stack_v2_python_sparse | code/258#Add Digits.py | EachenKuang/LeetCode | train | 28 | |
067ed5baa300e1f69d74d4c22d1583fe8aafdfa1 | [
"self.iter1 = iter(v1)\nself.iter2 = iter(v2)\nself.ind1 = len(v1)\nself.ind2 = len(v2)\nself.flag = True",
"if self.ind1 > 0 and self.ind2 > 0:\n if self.flag:\n self.flag = False\n self.ind1 -= 1\n return next(self.iter1)\n else:\n self.flag = True\n self.ind2 -= 1\n ... | <|body_start_0|>
self.iter1 = iter(v1)
self.iter2 = iter(v2)
self.ind1 = len(v1)
self.ind2 = len(v2)
self.flag = True
<|end_body_0|>
<|body_start_1|>
if self.ind1 > 0 and self.ind2 > 0:
if self.flag:
self.flag = False
self.ind1... | ZigzagIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_10k_train_003498 | 1,240 | permissive | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_003132 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | e7a6906ecc5bce665dec5d0f057b302a64d50f40 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.iter1 = iter(v1)
self.iter2 = iter(v2)
self.ind1 = len(v1)
self.ind2 = len(v2)
self.flag = True
def next(self):
""":r... | the_stack_v2_python_sparse | design/ZigzagIterator.py | mengyangbai/leetcode | train | 0 | |
f16a4c9924ac8328b019dd8caf797ae878c956a1 | [
"ans: List[str] = []\nlevel: Set[str] = {s}\nwhile True:\n for sub_str in level:\n if self.is_valid(sub_str):\n ans.append(sub_str)\n if len(ans) > 0:\n return ans\n next_level: Set[str] = set()\n for sub_str in level:\n for i in range(len(sub_str)):\n if sub_s... | <|body_start_0|>
ans: List[str] = []
level: Set[str] = {s}
while True:
for sub_str in level:
if self.is_valid(sub_str):
ans.append(sub_str)
if len(ans) > 0:
return ans
next_level: Set[str] = set()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def remove_invalid_parentheses(self, s: str) -> List[str]:
"""BFS。"""
<|body_0|>
def is_valid(self, s: str) -> bool:
"""判断字符串括号是否有效。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans: List[str] = []
level: Set[str] = {s}
... | stack_v2_sparse_classes_10k_train_003499 | 3,194 | no_license | [
{
"docstring": "BFS。",
"name": "remove_invalid_parentheses",
"signature": "def remove_invalid_parentheses(self, s: str) -> List[str]"
},
{
"docstring": "判断字符串括号是否有效。",
"name": "is_valid",
"signature": "def is_valid(self, s: str) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def remove_invalid_parentheses(self, s: str) -> List[str]: BFS。
- def is_valid(self, s: str) -> bool: 判断字符串括号是否有效。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def remove_invalid_parentheses(self, s: str) -> List[str]: BFS。
- def is_valid(self, s: str) -> bool: 判断字符串括号是否有效。
<|skeleton|>
class Solution:
def remove_invalid_parenthes... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def remove_invalid_parentheses(self, s: str) -> List[str]:
"""BFS。"""
<|body_0|>
def is_valid(self, s: str) -> bool:
"""判断字符串括号是否有效。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def remove_invalid_parentheses(self, s: str) -> List[str]:
"""BFS。"""
ans: List[str] = []
level: Set[str] = {s}
while True:
for sub_str in level:
if self.is_valid(sub_str):
ans.append(sub_str)
if len(ans) > 0... | the_stack_v2_python_sparse | 0301_remove-invalid-parentheses.py | Nigirimeshi/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.