blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
47e7b338024ef97cdc18c802c2a78541bc48b14e | [
"super().__init__()\nself.reduction = reduction\nself.axis = axis",
"if not isinstance(y_true, Tensor):\n y_true = y_true.class_id\nif not isinstance(y_pred, Tensor):\n y_pred = y_pred.class_id\npred_class = y_pred.argmax(dim=self.axis)\ntrue_class = y_true.long()\ncorrect_predictions = pred_class == true_c... | <|body_start_0|>
super().__init__()
self.reduction = reduction
self.axis = axis
<|end_body_0|>
<|body_start_1|>
if not isinstance(y_true, Tensor):
y_true = y_true.class_id
if not isinstance(y_pred, Tensor):
y_pred = y_pred.class_id
pred_class = y_... | SparseCategoricalAccuracy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseCategoricalAccuracy:
def __init__(self, model=None, reduction: str='mean', axis=-1):
"""Compute the sparse mean squared error. Sparse means that the targets are not one hot encoded. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'n... | stack_v2_sparse_classes_36k_train_034300 | 4,640 | permissive | [
{
"docstring": "Compute the sparse mean squared error. Sparse means that the targets are not one hot encoded. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no reduction will be applied, `'mean'`: the sum of the output will be divided by the number of ... | 2 | stack_v2_sparse_classes_30k_train_021381 | Implement the Python class `SparseCategoricalAccuracy` described below.
Class description:
Implement the SparseCategoricalAccuracy class.
Method signatures and docstrings:
- def __init__(self, model=None, reduction: str='mean', axis=-1): Compute the sparse mean squared error. Sparse means that the targets are not one... | Implement the Python class `SparseCategoricalAccuracy` described below.
Class description:
Implement the SparseCategoricalAccuracy class.
Method signatures and docstrings:
- def __init__(self, model=None, reduction: str='mean', axis=-1): Compute the sparse mean squared error. Sparse means that the targets are not one... | 0c7fb170d62f193dbbb2018f7b8d42f713178bb8 | <|skeleton|>
class SparseCategoricalAccuracy:
def __init__(self, model=None, reduction: str='mean', axis=-1):
"""Compute the sparse mean squared error. Sparse means that the targets are not one hot encoded. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseCategoricalAccuracy:
def __init__(self, model=None, reduction: str='mean', axis=-1):
"""Compute the sparse mean squared error. Sparse means that the targets are not one hot encoded. :param reduction: Specifies the reduction to apply to the output: `'none'` | `'mean'` | `'sum'`. `'none'`: no redu... | the_stack_v2_python_sparse | deeptech/training/losses/classification.py | penguinmenac3/deeptech | train | 1 | |
9944980640cc5987ae4144412582e21fdbcd4fea | [
"settings.addListsToRepository('skeinforge_tools.craft_plugins.unpause.html', '', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Unpause', self, '')\nself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://ww... | <|body_start_0|>
settings.addListsToRepository('skeinforge_tools.craft_plugins.unpause.html', '', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Unpause', self, '')
self.openWikiManualHelpPage = settings.HelpPag... | A class to handle the unpause settings. | UnpauseRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnpauseRepository:
"""A class to handle the unpause settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Unpause button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_034301 | 9,096 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Unpause button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | null | Implement the Python class `UnpauseRepository` described below.
Class description:
A class to handle the unpause settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Unpause button has been clicked. | Implement the Python class `UnpauseRepository` described below.
Class description:
A class to handle the unpause settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Unpause button has been clicked.
<|skeleton|>
class Unpa... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class UnpauseRepository:
"""A class to handle the unpause settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Unpause button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnpauseRepository:
"""A class to handle the unpause settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
settings.addListsToRepository('skeinforge_tools.craft_plugins.unpause.html', '', self)
self.fileNameInput = settings.FileNameInpu... | the_stack_v2_python_sparse | skeinforge_tools/craft_plugins/unpause.py | bmander/skeinforge | train | 34 |
fc13fb90aeacfb49408fa5be62d18df023ce82d4 | [
"if isinstance(value, (Long,)):\n return ColumnValue.fromLong(Long(value))\nelif isinstance(value, (int,)):\n return ColumnValue.fromLong(int(value).longValue())\nelif isinstance(value, (Double,)):\n return ColumnValue.fromDouble(Double(value))\nelif isinstance(value, (str,)):\n return ColumnValue.fromS... | <|body_start_0|>
if isinstance(value, (Long,)):
return ColumnValue.fromLong(Long(value))
elif isinstance(value, (int,)):
return ColumnValue.fromLong(int(value).longValue())
elif isinstance(value, (Double,)):
return ColumnValue.fromDouble(Double(value))
... | generated source for class ValueUtil | ValueUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueUtil:
"""generated source for class ValueUtil"""
def toColumnValue(cls, value):
"""generated source for method toColumnValue"""
<|body_0|>
def toObject(cls, value):
"""generated source for method toObject"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_034302 | 1,578 | no_license | [
{
"docstring": "generated source for method toColumnValue",
"name": "toColumnValue",
"signature": "def toColumnValue(cls, value)"
},
{
"docstring": "generated source for method toObject",
"name": "toObject",
"signature": "def toObject(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020644 | Implement the Python class `ValueUtil` described below.
Class description:
generated source for class ValueUtil
Method signatures and docstrings:
- def toColumnValue(cls, value): generated source for method toColumnValue
- def toObject(cls, value): generated source for method toObject | Implement the Python class `ValueUtil` described below.
Class description:
generated source for class ValueUtil
Method signatures and docstrings:
- def toColumnValue(cls, value): generated source for method toColumnValue
- def toObject(cls, value): generated source for method toObject
<|skeleton|>
class ValueUtil:
... | 39ec7fc72b63482032e3febfcaabae272f662ecc | <|skeleton|>
class ValueUtil:
"""generated source for class ValueUtil"""
def toColumnValue(cls, value):
"""generated source for method toColumnValue"""
<|body_0|>
def toObject(cls, value):
"""generated source for method toObject"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueUtil:
"""generated source for class ValueUtil"""
def toColumnValue(cls, value):
"""generated source for method toColumnValue"""
if isinstance(value, (Long,)):
return ColumnValue.fromLong(Long(value))
elif isinstance(value, (int,)):
return ColumnValue.f... | the_stack_v2_python_sparse | tablestore/grid/utils/ValueUtil.py | leetcode-xu/tablestore-grid | train | 0 |
5b08bd32f6843c2a5eb398330af3ad1ff11a44e9 | [
"super(PreprocessorSupervised, self).__init__(root_dir=root_dir, patch_size=patch_size, pad_type=pad_type, look_for_labels=look_for_labels, crop=crop, spacing=spacing)\nself.transforms = [{'name': 'Mirroring', 'execution_probability': 0.5}, {'name': 'Rotate', 'execution_probability': 0.5}, {'name': 'ElasticDeformat... | <|body_start_0|>
super(PreprocessorSupervised, self).__init__(root_dir=root_dir, patch_size=patch_size, pad_type=pad_type, look_for_labels=look_for_labels, crop=crop, spacing=spacing)
self.transforms = [{'name': 'Mirroring', 'execution_probability': 0.5}, {'name': 'Rotate', 'execution_probability': 0.5}... | PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data. | PreprocessorSupervised | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessorSupervised:
"""PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data."""
def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=True, spacing=(0.8, 0.8, 0.8), **... | stack_v2_sparse_classes_36k_train_034303 | 19,145 | no_license | [
{
"docstring": "PreprocessorSupervised constructor, extending the Preprocessor constructor by defining augumentations and level of supervision. Args: root_dir (string): path to folder containing raw data. Defaults to '../raw'. patch_size (tuple of ints): patch size for padding and croping calculation. Defaults ... | 2 | stack_v2_sparse_classes_30k_train_017104 | Implement the Python class `PreprocessorSupervised` described below.
Class description:
PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data.
Method signatures and docstrings:
- def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pa... | Implement the Python class `PreprocessorSupervised` described below.
Class description:
PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data.
Method signatures and docstrings:
- def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pa... | d89f696a1404f5793b71ca46261055a7f4575497 | <|skeleton|>
class PreprocessorSupervised:
"""PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data."""
def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=True, spacing=(0.8, 0.8, 0.8), **... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreprocessorSupervised:
"""PreprocessorSupervised class. Extends the original class by additionaly processing labels and saving the processed data."""
def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=True, spacing=(0.8, 0.8, 0.8), **kwargs):
... | the_stack_v2_python_sparse | source/dataset/preprocessor.py | BereznyMatej/IBT | train | 0 |
499ecc88ba26f0c714486f120de0965c72f87935 | [
"if not root:\n return []\nqueue = [root]\nresult = []\nwhile queue:\n next_queue = []\n result.append([node.val for node in queue])\n for cur in queue:\n if cur.left:\n next_queue.append(cur.left)\n if cur.right:\n next_queue.append(cur.right)\n queue = next_queue... | <|body_start_0|>
if not root:
return []
queue = [root]
result = []
while queue:
next_queue = []
result.append([node.val for node in queue])
for cur in queue:
if cur.left:
next_queue.append(cur.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderWithoutLevelInfo(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not ro... | stack_v2_sparse_classes_36k_train_034304 | 1,858 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrderWithoutLevelInfo",
"signature": "def levelOrderWithoutLevelInfo(self, root)"... | 2 | stack_v2_sparse_classes_30k_train_019115 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderWithoutLevelInfo(self, root): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrderWithoutLevelInfo(self, root): :type root: TreeNode :rtype: List[List[int]]
<|skeleton|>
... | ca95110b77152258573b6f1d43e39a316cdcb459 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrderWithoutLevelInfo(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
if not root:
return []
queue = [root]
result = []
while queue:
next_queue = []
result.append([node.val for node in queue])
for cur in... | the_stack_v2_python_sparse | algo/bfs/_0102_BinaryTreeLevelOrderTraversal.py | ianlai/Note-Python | train | 0 | |
512d69ee6c2a2a2f21f98a19ae5c79817d0053b8 | [
"super(TFResidualStack, self).__init__()\nself.block = [getattr(tf.keras.layers, nonlinear_activation)(**nonlinear_activation_params), TFReflectionPad1d(dilation), tf.keras.layers.Conv2D(filters=channels, kernel_size=(kernel_size, 1), dilation_rate=(dilation, 1), use_bias=bias, padding='valid'), getattr(tf.keras.la... | <|body_start_0|>
super(TFResidualStack, self).__init__()
self.block = [getattr(tf.keras.layers, nonlinear_activation)(**nonlinear_activation_params), TFReflectionPad1d(dilation), tf.keras.layers.Conv2D(filters=channels, kernel_size=(kernel_size, 1), dilation_rate=(dilation, 1), use_bias=bias, padding='v... | Tensorflow ResidualStack module. | TFResidualStack | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFResidualStack:
"""Tensorflow ResidualStack module."""
def __init__(self, kernel_size, channels, dilation, bias, nonlinear_activation, nonlinear_activation_params, padding):
"""Initialize TFResidualStack module. Args: kernel_size (int): Kernel size. channles (int): Number of channel... | stack_v2_sparse_classes_36k_train_034305 | 3,916 | permissive | [
{
"docstring": "Initialize TFResidualStack module. Args: kernel_size (int): Kernel size. channles (int): Number of channels. dilation (int): Dilation ine. bias (bool): Whether to add bias parameter in convolution layers. nonlinear_activation (str): Activation function module name. nonlinear_activation_params (d... | 2 | stack_v2_sparse_classes_30k_train_015517 | Implement the Python class `TFResidualStack` described below.
Class description:
Tensorflow ResidualStack module.
Method signatures and docstrings:
- def __init__(self, kernel_size, channels, dilation, bias, nonlinear_activation, nonlinear_activation_params, padding): Initialize TFResidualStack module. Args: kernel_s... | Implement the Python class `TFResidualStack` described below.
Class description:
Tensorflow ResidualStack module.
Method signatures and docstrings:
- def __init__(self, kernel_size, channels, dilation, bias, nonlinear_activation, nonlinear_activation_params, padding): Initialize TFResidualStack module. Args: kernel_s... | c68b4590ab20eaf55e0b96b82325a90177fffd5c | <|skeleton|>
class TFResidualStack:
"""Tensorflow ResidualStack module."""
def __init__(self, kernel_size, channels, dilation, bias, nonlinear_activation, nonlinear_activation_params, padding):
"""Initialize TFResidualStack module. Args: kernel_size (int): Kernel size. channles (int): Number of channel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFResidualStack:
"""Tensorflow ResidualStack module."""
def __init__(self, kernel_size, channels, dilation, bias, nonlinear_activation, nonlinear_activation_params, padding):
"""Initialize TFResidualStack module. Args: kernel_size (int): Kernel size. channles (int): Number of channels. dilation (... | the_stack_v2_python_sparse | parallel_wavegan/layers/tf_layers.py | kan-bayashi/ParallelWaveGAN | train | 1,405 |
3fbf5264f47bbbf66f114c12799ef205d5e02ea5 | [
"returned = Vacancy.get_weekdays()\nexpected = ['MO', 'TU', 'WE', 'TH', 'FR']\nself.assertEqual(returned, expected)",
"returned = Vacancy.get_weekends()\nexpected = ['SA', 'SU']\nself.assertEqual(returned, expected)"
] | <|body_start_0|>
returned = Vacancy.get_weekdays()
expected = ['MO', 'TU', 'WE', 'TH', 'FR']
self.assertEqual(returned, expected)
<|end_body_0|>
<|body_start_1|>
returned = Vacancy.get_weekends()
expected = ['SA', 'SU']
self.assertEqual(returned, expected)
<|end_body_1|>... | All tests of the Vacancy model.- | VacancyTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VacancyTest:
"""All tests of the Vacancy model.-"""
def test_get_weekdays(self):
"""The week days returned should be valid.-"""
<|body_0|>
def test_get_weekends(self):
"""The weekend days returned should be valid.-"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_034306 | 640 | no_license | [
{
"docstring": "The week days returned should be valid.-",
"name": "test_get_weekdays",
"signature": "def test_get_weekdays(self)"
},
{
"docstring": "The weekend days returned should be valid.-",
"name": "test_get_weekends",
"signature": "def test_get_weekends(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008566 | Implement the Python class `VacancyTest` described below.
Class description:
All tests of the Vacancy model.-
Method signatures and docstrings:
- def test_get_weekdays(self): The week days returned should be valid.-
- def test_get_weekends(self): The weekend days returned should be valid.- | Implement the Python class `VacancyTest` described below.
Class description:
All tests of the Vacancy model.-
Method signatures and docstrings:
- def test_get_weekdays(self): The week days returned should be valid.-
- def test_get_weekends(self): The weekend days returned should be valid.-
<|skeleton|>
class Vacancy... | 4d26e2cf1557d49a91d76dad196b89f9d933a012 | <|skeleton|>
class VacancyTest:
"""All tests of the Vacancy model.-"""
def test_get_weekdays(self):
"""The week days returned should be valid.-"""
<|body_0|>
def test_get_weekends(self):
"""The weekend days returned should be valid.-"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VacancyTest:
"""All tests of the Vacancy model.-"""
def test_get_weekdays(self):
"""The week days returned should be valid.-"""
returned = Vacancy.get_weekdays()
expected = ['MO', 'TU', 'WE', 'TH', 'FR']
self.assertEqual(returned, expected)
def test_get_weekends(self)... | the_stack_v2_python_sparse | players/tests.py | lichinka/ht | train | 0 |
0df548a48599da159de5122ebd75a9386a710e64 | [
"self.mask = None\nself.mode = None\nself.prob = kwargs.get('prob', 0)\nself.seed = kwargs.get('seed', None)",
"self.mode = mode\nif self.seed is not None:\n np.random.seed(self.seed)\nif self.mode == 'train':\n self.mask = np.ones(x.shape)\n prob_arr = np.random.random(x.shape)\n self.mask[prob_arr <... | <|body_start_0|>
self.mask = None
self.mode = None
self.prob = kwargs.get('prob', 0)
self.seed = kwargs.get('seed', None)
<|end_body_0|>
<|body_start_1|>
self.mode = mode
if self.seed is not None:
np.random.seed(self.seed)
if self.mode == 'train':
... | Dropout implements a network layer that performs drop out regularization | Dropout | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dropout:
"""Dropout implements a network layer that performs drop out regularization"""
def __init__(self, **kwargs):
"""Keyword args: prob: Probability for each neuron to drop out seed: Seeding integer for random generator"""
<|body_0|>
def forward_pass(self, x, mode='t... | stack_v2_sparse_classes_36k_train_034307 | 1,752 | no_license | [
{
"docstring": "Keyword args: prob: Probability for each neuron to drop out seed: Seeding integer for random generator",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Args: x: Input of any shape mode: 'test' or 'train', optional Returns: out: Output of the sa... | 3 | null | Implement the Python class `Dropout` described below.
Class description:
Dropout implements a network layer that performs drop out regularization
Method signatures and docstrings:
- def __init__(self, **kwargs): Keyword args: prob: Probability for each neuron to drop out seed: Seeding integer for random generator
- d... | Implement the Python class `Dropout` described below.
Class description:
Dropout implements a network layer that performs drop out regularization
Method signatures and docstrings:
- def __init__(self, **kwargs): Keyword args: prob: Probability for each neuron to drop out seed: Seeding integer for random generator
- d... | 7da789ef34d5e5bcf9033cfbe0ff5df607b2437a | <|skeleton|>
class Dropout:
"""Dropout implements a network layer that performs drop out regularization"""
def __init__(self, **kwargs):
"""Keyword args: prob: Probability for each neuron to drop out seed: Seeding integer for random generator"""
<|body_0|>
def forward_pass(self, x, mode='t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dropout:
"""Dropout implements a network layer that performs drop out regularization"""
def __init__(self, **kwargs):
"""Keyword args: prob: Probability for each neuron to drop out seed: Seeding integer for random generator"""
self.mask = None
self.mode = None
self.prob = ... | the_stack_v2_python_sparse | convolutional_neural_networks/conv_net/layer/dropout.py | calvinfeng/machine-learning-notebook | train | 38 |
851652ea115121fcddd91f2a4be2e727e4d46c4c | [
"virtual = self._ledfx.virtuals.get(virtual_id)\nif virtual is None:\n response = {'status': 'failed', 'reason': f'Virtual with ID {virtual_id} not found'}\n return web.json_response(data=response, status=404)\nresponse = {'status': 'success', 'virtual': virtual_id, 'Data': 'No current tools supported'}\nretu... | <|body_start_0|>
virtual = self._ledfx.virtuals.get(virtual_id)
if virtual is None:
response = {'status': 'failed', 'reason': f'Virtual with ID {virtual_id} not found'}
return web.json_response(data=response, status=404)
response = {'status': 'success', 'virtual': virtual... | api for individual virtual tools | VirtualsToolsEndpoint | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only",
"GPL-3.0-or-later",
"LGPL-2.1-or-later",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualsToolsEndpoint:
"""api for individual virtual tools"""
async def get(self, virtual_id) -> web.Response:
"""Get presets for active effect of a virtual"""
<|body_0|>
async def put(self, virtual_id, request) -> web.Response:
"""Extensible tools support"""
... | stack_v2_sparse_classes_36k_train_034308 | 2,794 | permissive | [
{
"docstring": "Get presets for active effect of a virtual",
"name": "get",
"signature": "async def get(self, virtual_id) -> web.Response"
},
{
"docstring": "Extensible tools support",
"name": "put",
"signature": "async def put(self, virtual_id, request) -> web.Response"
}
] | 2 | null | Implement the Python class `VirtualsToolsEndpoint` described below.
Class description:
api for individual virtual tools
Method signatures and docstrings:
- async def get(self, virtual_id) -> web.Response: Get presets for active effect of a virtual
- async def put(self, virtual_id, request) -> web.Response: Extensible... | Implement the Python class `VirtualsToolsEndpoint` described below.
Class description:
api for individual virtual tools
Method signatures and docstrings:
- async def get(self, virtual_id) -> web.Response: Get presets for active effect of a virtual
- async def put(self, virtual_id, request) -> web.Response: Extensible... | 3146ba9e9d10a2d01cdd4cb15ea37fc0c7bd020f | <|skeleton|>
class VirtualsToolsEndpoint:
"""api for individual virtual tools"""
async def get(self, virtual_id) -> web.Response:
"""Get presets for active effect of a virtual"""
<|body_0|>
async def put(self, virtual_id, request) -> web.Response:
"""Extensible tools support"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VirtualsToolsEndpoint:
"""api for individual virtual tools"""
async def get(self, virtual_id) -> web.Response:
"""Get presets for active effect of a virtual"""
virtual = self._ledfx.virtuals.get(virtual_id)
if virtual is None:
response = {'status': 'failed', 'reason': ... | the_stack_v2_python_sparse | ledfx/api/virtuals_tools.py | THATDONFC/LedFx | train | 0 |
28658cda49c965f5add0ab92473812c45c28d8e7 | [
"self.label = label\nself.paths = paths\nif self.paths is None:\n self.paths = {}\nself.reset()",
"str_ = \"Vertex '{label}' - visited: {visited}, parent: {parent}, cost: {cost}\\n\"\nstr_ += ' paths: {paths}'\nreturn str_.format(**self.__dict__)",
"self.visited = False\nself.parent = None\nself.cost = No... | <|body_start_0|>
self.label = label
self.paths = paths
if self.paths is None:
self.paths = {}
self.reset()
<|end_body_0|>
<|body_start_1|>
str_ = "Vertex '{label}' - visited: {visited}, parent: {parent}, cost: {cost}\n"
str_ += ' paths: {paths}'
re... | A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex also has the 'visited', 'parent' ... | Vertex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vertex:
"""A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex... | stack_v2_sparse_classes_36k_train_034309 | 15,275 | no_license | [
{
"docstring": "Create a new vertex.",
"name": "__init__",
"signature": "def __init__(self, label, paths=None)"
},
{
"docstring": "Format the vertex as a string.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Reset the vertex to its default values. This ... | 3 | stack_v2_sparse_classes_30k_train_004904 | Implement the Python class `Vertex` described below.
Class description:
A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any ve... | Implement the Python class `Vertex` described below.
Class description:
A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any ve... | c80ea145c758f3b392f956e4311f11cfc099a149 | <|skeleton|>
class Vertex:
"""A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vertex:
"""A graph vertex with a set of paths to other vertices. A vertex is characterized by a label (or name) and a dictionary of paths from the vertex to other vertices. For application of Dijkstra's algorithm for calculating the shortest path from any vertex to all other vertices, each vertex also has the... | the_stack_v2_python_sparse | dailyprogrammer/challenges/038e.py | UltimateTimmeh/r-daily-programmer | train | 0 |
b39341b902ff92afbaadc95987a667ef7fd4c042 | [
"if not root:\n return 0\nself.ans = 0\n\ndef dfs(cur):\n if cur.right:\n nxt = dfs(cur.right)\n if nxt:\n dfs(cur.left)\n elif cur.left:\n dfs(cur.left)\n return 1\n else:\n self.ans = max(self.ans, cur.val)\n return 1\ndfs(root)\nreturn self.ans",
... | <|body_start_0|>
if not root:
return 0
self.ans = 0
def dfs(cur):
if cur.right:
nxt = dfs(cur.right)
if nxt:
dfs(cur.left)
elif cur.left:
dfs(cur.left)
return 1
el... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNodesWA(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def countNodes(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
self.... | stack_v2_sparse_classes_36k_train_034310 | 2,238 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "countNodesWA",
"signature": "def countNodesWA(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "countNodes",
"signature": "def countNodes(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodesWA(self, root): :type root: TreeNode :rtype: int
- def countNodes(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodesWA(self, root): :type root: TreeNode :rtype: int
- def countNodes(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def countNodesWA(... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def countNodesWA(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def countNodes(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countNodesWA(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
self.ans = 0
def dfs(cur):
if cur.right:
nxt = dfs(cur.right)
if nxt:
dfs(cur.left)
elif... | the_stack_v2_python_sparse | python/leetcode.222.py | CalvinNeo/LeetCode | train | 3 | |
d2aa9d87684016a838a94d31b3035bce137ec945 | [
"if not self.config.discovery_region:\n if not self.default_region:\n raise ConfigMismatchError('Failed to determine default discovery region; please provide an explicit discovery_region')\n self.config.discovery_region = self.default_region",
"_key_id = to_str(key_id)\narn = arn_from_str(_key_id)\ni... | <|body_start_0|>
if not self.config.discovery_region:
if not self.default_region:
raise ConfigMismatchError('Failed to determine default discovery region; please provide an explicit discovery_region')
self.config.discovery_region = self.default_region
<|end_body_0|>
<|bo... | Discovery Master Key Provider for KMS that has smarts for handling Multi-Region keys TODO MORE .. note:: If no botocore_session is provided, the default botocore session will be used. :param config: Configuration object (optional) :type config: aws_encryption_sdk.key_providers.kms.KMSMasterKeyProviderConfig :param boto... | MRKAwareDiscoveryAwsKmsMasterKeyProvider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRKAwareDiscoveryAwsKmsMasterKeyProvider:
"""Discovery Master Key Provider for KMS that has smarts for handling Multi-Region keys TODO MORE .. note:: If no botocore_session is provided, the default botocore session will be used. :param config: Configuration object (optional) :type config: aws_enc... | stack_v2_sparse_classes_36k_train_034311 | 49,646 | permissive | [
{
"docstring": "Validates the provided configuration.",
"name": "validate_config",
"signature": "def validate_config(self)"
},
{
"docstring": "Creation of new master keys. Compared to the base class, this class has smarts to use either the configured discovery region or, if not present, the defa... | 2 | stack_v2_sparse_classes_30k_train_008749 | Implement the Python class `MRKAwareDiscoveryAwsKmsMasterKeyProvider` described below.
Class description:
Discovery Master Key Provider for KMS that has smarts for handling Multi-Region keys TODO MORE .. note:: If no botocore_session is provided, the default botocore session will be used. :param config: Configuration ... | Implement the Python class `MRKAwareDiscoveryAwsKmsMasterKeyProvider` described below.
Class description:
Discovery Master Key Provider for KMS that has smarts for handling Multi-Region keys TODO MORE .. note:: If no botocore_session is provided, the default botocore session will be used. :param config: Configuration ... | 3ba8019681ed95c41bb9448f0c3897d1aecc7559 | <|skeleton|>
class MRKAwareDiscoveryAwsKmsMasterKeyProvider:
"""Discovery Master Key Provider for KMS that has smarts for handling Multi-Region keys TODO MORE .. note:: If no botocore_session is provided, the default botocore session will be used. :param config: Configuration object (optional) :type config: aws_enc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MRKAwareDiscoveryAwsKmsMasterKeyProvider:
"""Discovery Master Key Provider for KMS that has smarts for handling Multi-Region keys TODO MORE .. note:: If no botocore_session is provided, the default botocore session will be used. :param config: Configuration object (optional) :type config: aws_encryption_sdk.k... | the_stack_v2_python_sparse | src/aws_encryption_sdk/key_providers/kms.py | aws/aws-encryption-sdk-python | train | 137 |
549081a87fb69983154dbeb9aaf3037dfe836497 | [
"super(Ipconfig, self).__init__()\nself.connection = connection\nself.interface = interface\nself.not_available = not_available\nself.timeout = timeout\nself._ip_expression = None\nself._address = None\nreturn",
"if self._ip_expression is None:\n self._ip_expression = re.compile(oatbran.SPACES + 'IPv4' + oatbr... | <|body_start_0|>
super(Ipconfig, self).__init__()
self.connection = connection
self.interface = interface
self.not_available = not_available
self.timeout = timeout
self._ip_expression = None
self._address = None
return
<|end_body_0|>
<|body_start_1|>
... | A class to interpret the `ipconfig` output | Ipconfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ipconfig:
"""A class to interpret the `ipconfig` output"""
def __init__(self, connection, interface='Wireless LAN adapter', not_available='NA', timeout=30):
""":param: - `connection`: a connection to the device - `interface`: The name of the interface to check - `not_available`: The ... | stack_v2_sparse_classes_36k_train_034312 | 2,627 | permissive | [
{
"docstring": ":param: - `connection`: a connection to the device - `interface`: The name of the interface to check - `not_available`: The token to use if the information isn't found - `timeout`: The amount of time to wait for the command before giving up.",
"name": "__init__",
"signature": "def __init... | 3 | null | Implement the Python class `Ipconfig` described below.
Class description:
A class to interpret the `ipconfig` output
Method signatures and docstrings:
- def __init__(self, connection, interface='Wireless LAN adapter', not_available='NA', timeout=30): :param: - `connection`: a connection to the device - `interface`: T... | Implement the Python class `Ipconfig` described below.
Class description:
A class to interpret the `ipconfig` output
Method signatures and docstrings:
- def __init__(self, connection, interface='Wireless LAN adapter', not_available='NA', timeout=30): :param: - `connection`: a connection to the device - `interface`: T... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class Ipconfig:
"""A class to interpret the `ipconfig` output"""
def __init__(self, connection, interface='Wireless LAN adapter', not_available='NA', timeout=30):
""":param: - `connection`: a connection to the device - `interface`: The name of the interface to check - `not_available`: The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ipconfig:
"""A class to interpret the `ipconfig` output"""
def __init__(self, connection, interface='Wireless LAN adapter', not_available='NA', timeout=30):
""":param: - `connection`: a connection to the device - `interface`: The name of the interface to check - `not_available`: The token to use ... | the_stack_v2_python_sparse | apetools/commands/ipconfig.py | russell-n/oldape | train | 0 |
1eae3ce8ad70a92cf051e1ed8bc11a106e0287f2 | [
"new_library = Library()\nnew_library.title = request.data['title']\nnew_library.link = request.data['link']\nnew_library.image = request.data['image']\nnew_library.image_title = request.data['image_title']\nnew_library.parent_library_id = request.data['parent_library_id']\nnew_library.library_type_id = request.dat... | <|body_start_0|>
new_library = Library()
new_library.title = request.data['title']
new_library.link = request.data['link']
new_library.image = request.data['image']
new_library.image_title = request.data['image_title']
new_library.parent_library_id = request.data['parent_... | Libraries for codeArchive | Libraries | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Libraries:
"""Libraries for codeArchive"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized Library instance"""
<|body_0|>
def destroy(self, request, pk=None):
"""Handle DELETE requests for a single library Returns: Respon... | stack_v2_sparse_classes_36k_train_034313 | 4,662 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized Library instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle DELETE requests for a single library Returns: Response -- 200, 404, or 500 status code",
"name": "destroy",
... | 5 | stack_v2_sparse_classes_30k_train_006263 | Implement the Python class `Libraries` described below.
Class description:
Libraries for codeArchive
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized Library instance
- def destroy(self, request, pk=None): Handle DELETE requests for a single li... | Implement the Python class `Libraries` described below.
Class description:
Libraries for codeArchive
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized Library instance
- def destroy(self, request, pk=None): Handle DELETE requests for a single li... | 2bd984d13baaa9e12bba63a3bf39c2ff93619e59 | <|skeleton|>
class Libraries:
"""Libraries for codeArchive"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized Library instance"""
<|body_0|>
def destroy(self, request, pk=None):
"""Handle DELETE requests for a single library Returns: Respon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Libraries:
"""Libraries for codeArchive"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized Library instance"""
new_library = Library()
new_library.title = request.data['title']
new_library.link = request.data['link']
new_li... | the_stack_v2_python_sparse | codearchiveAPIapp/views/library_view.py | shanemiller89/codeArchive_API | train | 0 |
62da1c75cfc3b08a5c306e4bee070e1e3de30cf2 | [
"self.foodIndex = 0\nself.snake = collections.deque()\nself.snake.append((0, 0))\nself.body = {(0, 0)}\nself.foods = food\nself.width = width\nself.height = height\nself.moves = {'U': (0, -1), 'L': (-1, 0), 'R': (1, 0), 'D': (0, 1)}",
"tail = self.snake.popleft()\nself.body.remove(tail)\nif not self.snake:\n h... | <|body_start_0|>
self.foodIndex = 0
self.snake = collections.deque()
self.snake.append((0, 0))
self.body = {(0, 0)}
self.foods = food
self.width = width
self.height = height
self.moves = {'U': (0, -1), 'L': (-1, 0), 'R': (1, 0), 'D': (0, 1)}
<|end_body_0|>... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k_train_034314 | 15,245 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_005564 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | leetcode_python/Design/design-snake-game.py | yennanliu/CS_basics | train | 64 | |
548afeb111dd06882184d21a0a5fcdbf416e5825 | [
"if not nums or len(nums) == 1:\n return 0\nif nums[0] + 1 >= len(nums):\n return 1\nmemo = [float('inf') for _ in range(len(nums))]\nmemo[0] = 0\nm = 1\nfor i, n in enumerate(nums):\n for j in range(m, min(len(nums), i + n + 1)):\n memo[j] = min(memo[j], memo[i] + 1)\n m = max(m, i + n)\nreturn ... | <|body_start_0|>
if not nums or len(nums) == 1:
return 0
if nums[0] + 1 >= len(nums):
return 1
memo = [float('inf') for _ in range(len(nums))]
memo[0] = 0
m = 1
for i, n in enumerate(nums):
for j in range(m, min(len(nums), i + n + 1)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
"""08/07/2018 06:05"""
<|body_0|>
def jump(self, nums):
"""08/10/2018 18:13"""
<|body_1|>
def jump(self, nums: List[int]) -> int:
"""DP Time complexity: O(n*m) Space complexity: O(n)"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k_train_034315 | 4,016 | no_license | [
{
"docstring": "08/07/2018 06:05",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": "08/10/2018 18:13",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": "DP Time complexity: O(n*m) Space complexity: O(n)",
"name": "jump",
"signatu... | 6 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): 08/07/2018 06:05
- def jump(self, nums): 08/10/2018 18:13
- def jump(self, nums: List[int]) -> int: DP Time complexity: O(n*m) Space complexity: O(n)
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): 08/07/2018 06:05
- def jump(self, nums): 08/10/2018 18:13
- def jump(self, nums: List[int]) -> int: DP Time complexity: O(n*m) Space complexity: O(n)
- def ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def jump(self, nums):
"""08/07/2018 06:05"""
<|body_0|>
def jump(self, nums):
"""08/10/2018 18:13"""
<|body_1|>
def jump(self, nums: List[int]) -> int:
"""DP Time complexity: O(n*m) Space complexity: O(n)"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums):
"""08/07/2018 06:05"""
if not nums or len(nums) == 1:
return 0
if nums[0] + 1 >= len(nums):
return 1
memo = [float('inf') for _ in range(len(nums))]
memo[0] = 0
m = 1
for i, n in enumerate(nums):
... | the_stack_v2_python_sparse | leetcode/solved/45_Jump_Game_II/solution.py | sungminoh/algorithms | train | 0 | |
b3adee9fa96d4afd7a0c0c39c73b34a3f8e49d4c | [
"runner = m.group('run') or ''\nindent = len(m.group('%sindent' % runner))\nsource_lines = m.group('%ssource' % runner).split('\\n')\nif runner:\n self._check_prefix(source_lines[1:], ' ' * indent, name, lineno)\nelse:\n self._check_prompt_blank(source_lines, indent, name, lineno)\n self._check_prefix(sour... | <|body_start_0|>
runner = m.group('run') or ''
indent = len(m.group('%sindent' % runner))
source_lines = m.group('%ssource' % runner).split('\n')
if runner:
self._check_prefix(source_lines[1:], ' ' * indent, name, lineno)
else:
self._check_prompt_blank(sou... | This parser recognizes some reST comments as commands, without prompts or expected output, like: .. run: do_this(... ...) | LongFormDocTestParser | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongFormDocTestParser:
"""This parser recognizes some reST comments as commands, without prompts or expected output, like: .. run: do_this(... ...)"""
def _parse_example(self, m, name, lineno):
"""Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want... | stack_v2_sparse_classes_36k_train_034316 | 14,923 | permissive | [
{
"docstring": "Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `linen... | 2 | null | Implement the Python class `LongFormDocTestParser` described below.
Class description:
This parser recognizes some reST comments as commands, without prompts or expected output, like: .. run: do_this(... ...)
Method signatures and docstrings:
- def _parse_example(self, m, name, lineno): Given a regular expression mat... | Implement the Python class `LongFormDocTestParser` described below.
Class description:
This parser recognizes some reST comments as commands, without prompts or expected output, like: .. run: do_this(... ...)
Method signatures and docstrings:
- def _parse_example(self, m, name, lineno): Given a regular expression mat... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class LongFormDocTestParser:
"""This parser recognizes some reST comments as commands, without prompts or expected output, like: .. run: do_this(... ...)"""
def _parse_example(self, m, name, lineno):
"""Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LongFormDocTestParser:
"""This parser recognizes some reST comments as commands, without prompts or expected output, like: .. run: do_this(... ...)"""
def _parse_example(self, m, name, lineno):
"""Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `so... | the_stack_v2_python_sparse | third_party/Paste/paste/debug/doctest_webapp.py | catapult-project/catapult | train | 2,032 |
a2796351de78a282c6999edd4f2b1726072060ec | [
"p = 0\nif len(nums) == 0:\n return []\nif k >= len(nums):\n return [max(nums)]\nresult = []\nwhile p + k <= len(nums):\n result.append(max(nums[p:p + k]))\n p += 1\nreturn result",
"if len(nums) == 0:\n return []\nif k >= len(nums):\n return [max(nums)]\nresult = []\nmaxValue = max(nums[0:k])\n... | <|body_start_0|>
p = 0
if len(nums) == 0:
return []
if k >= len(nums):
return [max(nums)]
result = []
while p + k <= len(nums):
result.append(max(nums[p:p + k]))
p += 1
return result
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_034317 | 859 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow2",
"signature": "def maxSlidingWindow2... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[... | 0fddcc61923d760faa5fc60311861cbe89a54ba9 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
p = 0
if len(nums) == 0:
return []
if k >= len(nums):
return [max(nums)]
result = []
while p + k <= len(nums):
result.ap... | the_stack_v2_python_sparse | 239.py | zenmeder/leetcode | train | 0 | |
a186e8da1375d1029138099a7dda9fd5b19df958 | [
"if not (datasource or table or column):\n raise Exception('Either a datasource, table, or column must be provided.')\ntypes = [constants.USER_SPECIFIED_TYPE_DASHBOARD, constants.USER_SPECIFIED_TYPE_WIDGET]\nquery = self._make_query(types, datasource=datasource, table=table, column=column)\nentry_names = self._s... | <|body_start_0|>
if not (datasource or table or column):
raise Exception('Either a datasource, table, or column must be provided.')
types = [constants.USER_SPECIFIED_TYPE_DASHBOARD, constants.USER_SPECIFIED_TYPE_WIDGET]
query = self._make_query(types, datasource=datasource, table=tab... | Count on Google Data Catalog search capabilities to find ElastiCube-related dependencies using specific Tag fields. The public methods are intended to provide clients a simplified interface for Data Catalog search and results handling. | TagBasedFinder | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagBasedFinder:
"""Count on Google Data Catalog search capabilities to find ElastiCube-related dependencies using specific Tag fields. The public methods are intended to provide clients a simplified interface for Data Catalog search and results handling."""
def find(self, datasource: Optiona... | stack_v2_sparse_classes_36k_train_034318 | 7,374 | permissive | [
{
"docstring": "Orchestrate actions that comprise: - generating a query string to search Google Data Catalog; - performing a catalog search operation; - getting Entries and Tags based on search results; - filtering Tags that contain Entry enrichment metadata or match the table/column search criteria; - assembli... | 5 | null | Implement the Python class `TagBasedFinder` described below.
Class description:
Count on Google Data Catalog search capabilities to find ElastiCube-related dependencies using specific Tag fields. The public methods are intended to provide clients a simplified interface for Data Catalog search and results handling.
Me... | Implement the Python class `TagBasedFinder` described below.
Class description:
Count on Google Data Catalog search capabilities to find ElastiCube-related dependencies using specific Tag fields. The public methods are intended to provide clients a simplified interface for Data Catalog search and results handling.
Me... | 58cc57e12632cbd1e237b3d6930e519333c51f4e | <|skeleton|>
class TagBasedFinder:
"""Count on Google Data Catalog search capabilities to find ElastiCube-related dependencies using specific Tag fields. The public methods are intended to provide clients a simplified interface for Data Catalog search and results handling."""
def find(self, datasource: Optiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagBasedFinder:
"""Count on Google Data Catalog search capabilities to find ElastiCube-related dependencies using specific Tag fields. The public methods are intended to provide clients a simplified interface for Data Catalog search and results handling."""
def find(self, datasource: Optional[str]=None, ... | the_stack_v2_python_sparse | google-datacatalog-sisense-connector/src/google/datacatalog_connectors/sisense/addons/tag_based_finder.py | GoogleCloudPlatform/datacatalog-connectors-bi | train | 34 |
948ca04775b1e11d44e89c34b75ef1c8a266b830 | [
"obj_api = api()\ntoken = request.session['token']\nmessages = None\nparameters = {'page_size': 0}\ndata_messages = obj_api.get(slug='queries/categories/' + pk, token=token, arg=parameters)\nesp = Category.objects.get(pk=pk)\nform = QueryForm()\nif data_messages:\n messages = sorted(data_messages, key=itemgetter... | <|body_start_0|>
obj_api = api()
token = request.session['token']
messages = None
parameters = {'page_size': 0}
data_messages = obj_api.get(slug='queries/categories/' + pk, token=token, arg=parameters)
esp = Category.objects.get(pk=pk)
form = QueryForm()
i... | Client | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
def chat(self, request, pk):
"""Chat por Especialidad."""
<|body_0|>
def send_query(self, request):
"""Enviar data de consulta."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj_api = api()
token = request.session['token']
... | stack_v2_sparse_classes_36k_train_034319 | 3,271 | no_license | [
{
"docstring": "Chat por Especialidad.",
"name": "chat",
"signature": "def chat(self, request, pk)"
},
{
"docstring": "Enviar data de consulta.",
"name": "send_query",
"signature": "def send_query(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015169 | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def chat(self, request, pk): Chat por Especialidad.
- def send_query(self, request): Enviar data de consulta. | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def chat(self, request, pk): Chat por Especialidad.
- def send_query(self, request): Enviar data de consulta.
<|skeleton|>
class Client:
def chat(self, request, pk):
""... | 20f40ff3d0eeb2ea0d9a4001555238f346f85dc7 | <|skeleton|>
class Client:
def chat(self, request, pk):
"""Chat por Especialidad."""
<|body_0|>
def send_query(self, request):
"""Enviar data de consulta."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Client:
def chat(self, request, pk):
"""Chat por Especialidad."""
obj_api = api()
token = request.session['token']
messages = None
parameters = {'page_size': 0}
data_messages = obj_api.get(slug='queries/categories/' + pk, token=token, arg=parameters)
esp... | the_stack_v2_python_sparse | frontend/views/chat.py | darwinv/web-chat-lnk | train | 0 | |
b73a2f24673e974ab8e021b90ba818c8c2915a69 | [
"sample = self.get_object()\nif SampleLike.objects.filter(sample=sample).filter(user=request.user).exists():\n return JsonResponse({'liked': True}, status=status.HTTP_200_OK)\nreturn JsonResponse({'liked': False}, status=status.HTTP_200_OK)",
"sample = self.get_object()\nSampleLike.objects.get_or_create(user=r... | <|body_start_0|>
sample = self.get_object()
if SampleLike.objects.filter(sample=sample).filter(user=request.user).exists():
return JsonResponse({'liked': True}, status=status.HTTP_200_OK)
return JsonResponse({'liked': False}, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|... | SampleLikeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleLikeView:
def get(self, request, *args, **kwargs):
"""Overridden get method in order to return whether the given sample belongs to the authenticated user samples likes or not."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Overridden post method in ... | stack_v2_sparse_classes_36k_train_034320 | 1,984 | no_license | [
{
"docstring": "Overridden get method in order to return whether the given sample belongs to the authenticated user samples likes or not.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Overridden post method in order to add the given sample to the auth... | 3 | stack_v2_sparse_classes_30k_train_002877 | Implement the Python class `SampleLikeView` described below.
Class description:
Implement the SampleLikeView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Overridden get method in order to return whether the given sample belongs to the authenticated user samples likes or not.
- d... | Implement the Python class `SampleLikeView` described below.
Class description:
Implement the SampleLikeView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Overridden get method in order to return whether the given sample belongs to the authenticated user samples likes or not.
- d... | 94810e2e0bddd98ec9f3bd44c2f9f5f3f166bb08 | <|skeleton|>
class SampleLikeView:
def get(self, request, *args, **kwargs):
"""Overridden get method in order to return whether the given sample belongs to the authenticated user samples likes or not."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Overridden post method in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleLikeView:
def get(self, request, *args, **kwargs):
"""Overridden get method in order to return whether the given sample belongs to the authenticated user samples likes or not."""
sample = self.get_object()
if SampleLike.objects.filter(sample=sample).filter(user=request.user).exis... | the_stack_v2_python_sparse | src/safm_api/views/sample_like.py | HE-Arc/social-audio-free-market | train | 4 | |
ff21bf1c59cb7523843b45f4343513b56199d36a | [
"self.storage = storage\nself.output_dataset_name = output_dataset_name\nself.hash_function = hash_function or md5",
"logging.info('Converting ONET %s to pandas', filename)\nfiletext = OnetToMemoryDownloader().download(filename)\nonet = [row for row in csv.DictReader(io.StringIO(filetext), delimiter='\\t')]\nonet... | <|body_start_0|>
self.storage = storage
self.output_dataset_name = output_dataset_name
self.hash_function = hash_function or md5
<|end_body_0|>
<|body_start_1|>
logging.info('Converting ONET %s to pandas', filename)
filetext = OnetToMemoryDownloader().download(filename)
... | An object that creates a skills importance CSV based on ONET data Originally written by Kwame Porter Robinson | OnetSkillImportanceExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnetSkillImportanceExtractor:
"""An object that creates a skills importance CSV based on ONET data Originally written by Kwame Porter Robinson"""
def __init__(self, storage, output_dataset_name, hash_function=None):
"""Args: output_dataset_name: A filename to write the final dataset ... | stack_v2_sparse_classes_36k_train_034321 | 2,780 | permissive | [
{
"docstring": "Args: output_dataset_name: A filename to write the final dataset onet_source: An object that is able to fetch ONET files by name hash_function: A function that can hash a given string",
"name": "__init__",
"signature": "def __init__(self, storage, output_dataset_name, hash_function=None)... | 3 | stack_v2_sparse_classes_30k_train_006096 | Implement the Python class `OnetSkillImportanceExtractor` described below.
Class description:
An object that creates a skills importance CSV based on ONET data Originally written by Kwame Porter Robinson
Method signatures and docstrings:
- def __init__(self, storage, output_dataset_name, hash_function=None): Args: ou... | Implement the Python class `OnetSkillImportanceExtractor` described below.
Class description:
An object that creates a skills importance CSV based on ONET data Originally written by Kwame Porter Robinson
Method signatures and docstrings:
- def __init__(self, storage, output_dataset_name, hash_function=None): Args: ou... | feffead90815ccdecf24bf1a995f79683442b046 | <|skeleton|>
class OnetSkillImportanceExtractor:
"""An object that creates a skills importance CSV based on ONET data Originally written by Kwame Porter Robinson"""
def __init__(self, storage, output_dataset_name, hash_function=None):
"""Args: output_dataset_name: A filename to write the final dataset ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnetSkillImportanceExtractor:
"""An object that creates a skills importance CSV based on ONET data Originally written by Kwame Porter Robinson"""
def __init__(self, storage, output_dataset_name, hash_function=None):
"""Args: output_dataset_name: A filename to write the final dataset onet_source: ... | the_stack_v2_python_sparse | skills_ml/datasets/skill_importances/onet.py | workforce-data-initiative/skills-ml | train | 164 |
1e023cefc27669de2717b7a35d426c2ec757767d | [
"if matrix == [[]] or matrix == []:\n return False\nrow_index = self.bin_search_row(0, len(matrix) - 1, matrix, target)\nif row_index == -1:\n return False\nreturn self.bin_search_column(0, len(matrix[row_index]) - 1, matrix[row_index], target)",
"if start > end:\n return -1\nmid = (start + end) // 2\nif... | <|body_start_0|>
if matrix == [[]] or matrix == []:
return False
row_index = self.bin_search_row(0, len(matrix) - 1, matrix, target)
if row_index == -1:
return False
return self.bin_search_column(0, len(matrix[row_index]) - 1, matrix[row_index], target)
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def bin_search_row(self, start, end, matrix, target) -> int:
""":type start: int :type end: int :type matrix: List[List[int]] :type target:... | stack_v2_sparse_classes_36k_train_034322 | 2,192 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type start: int :type end: int :type matrix: List[List[int]] :type target: int :rtype: int",
"name": "bin_search_ro... | 3 | stack_v2_sparse_classes_30k_train_018338 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def bin_search_row(self, start, end, matrix, target) -> int: :type start: i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def bin_search_row(self, start, end, matrix, target) -> int: :type start: i... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def bin_search_row(self, start, end, matrix, target) -> int:
""":type start: int :type end: int :type matrix: List[List[int]] :type target:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if matrix == [[]] or matrix == []:
return False
row_index = self.bin_search_row(0, len(matrix) - 1, matrix, target)
if row_index == -1:
r... | the_stack_v2_python_sparse | 74.py | Gackle/leetcode_practice | train | 0 | |
7d4f19f701039bf1fcc4de68707c3eea68e01540 | [
"self.stack = []\nself.length = len(self.stack)\nself.current_min = 0",
"print('Pushing', item)\ncurrent_min = self.getMin()\nif current_min is None or item < current_min:\n self.current_min = item\nself.stack.append(item)\nself.length = len(self.stack)",
"popped = self.stack[-1]\nprint('Popping', popped)\ns... | <|body_start_0|>
self.stack = []
self.length = len(self.stack)
self.current_min = 0
<|end_body_0|>
<|body_start_1|>
print('Pushing', item)
current_min = self.getMin()
if current_min is None or item < current_min:
self.current_min = item
self.stack.app... | A simple Min Stack implementation: push(item) pop() top() getMin() | MinStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinStack:
"""A simple Min Stack implementation: push(item) pop() top() getMin()"""
def __init__(self):
"""Initializes the stack and maintains a length value for navigation."""
<|body_0|>
def push(self, item):
"""Pushes an arg value on to the stack. :type x: int :... | stack_v2_sparse_classes_36k_train_034323 | 2,513 | no_license | [
{
"docstring": "Initializes the stack and maintains a length value for navigation.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Pushes an arg value on to the stack. :type x: int :rtype: void",
"name": "push",
"signature": "def push(self, item)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_009330 | Implement the Python class `MinStack` described below.
Class description:
A simple Min Stack implementation: push(item) pop() top() getMin()
Method signatures and docstrings:
- def __init__(self): Initializes the stack and maintains a length value for navigation.
- def push(self, item): Pushes an arg value on to the ... | Implement the Python class `MinStack` described below.
Class description:
A simple Min Stack implementation: push(item) pop() top() getMin()
Method signatures and docstrings:
- def __init__(self): Initializes the stack and maintains a length value for navigation.
- def push(self, item): Pushes an arg value on to the ... | c701657046f0fa767c5a2ee3468ed4747a32c523 | <|skeleton|>
class MinStack:
"""A simple Min Stack implementation: push(item) pop() top() getMin()"""
def __init__(self):
"""Initializes the stack and maintains a length value for navigation."""
<|body_0|>
def push(self, item):
"""Pushes an arg value on to the stack. :type x: int :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinStack:
"""A simple Min Stack implementation: push(item) pop() top() getMin()"""
def __init__(self):
"""Initializes the stack and maintains a length value for navigation."""
self.stack = []
self.length = len(self.stack)
self.current_min = 0
def push(self, item):
... | the_stack_v2_python_sparse | Min Stack/min_stack.py | bknie1/Code-Challenges | train | 0 |
df4b3f6f33d1a0afa81b2aac8e36fcc0e572a0af | [
"LDC_Info.__init__(self)\nself.setTitle(self.name)\nself.status = compat_res[0]\nui = Ui_videoFrame()\nui.setupUi(self.frame)\nself.__fill_frame(ui, info_res, compat_res, diag_res)",
"ui.productLineEdit.setText(QtGui.QApplication.translate('videoFrame', self._check_invalid_values(info_res.model[1]), None, QtGui.Q... | <|body_start_0|>
LDC_Info.__init__(self)
self.setTitle(self.name)
self.status = compat_res[0]
ui = Ui_videoFrame()
ui.setupUi(self.frame)
self.__fill_frame(ui, info_res, compat_res, diag_res)
<|end_body_0|>
<|body_start_1|>
ui.productLineEdit.setText(QtGui.QAppli... | Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo. | GUIVideo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUIVideo:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo."""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_r... | stack_v2_sparse_classes_36k_train_034324 | 4,657 | no_license | [
{
"docstring": "Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista com as tuples de resultados de compatibilidade [(True, msg)] diag_res -- Lista com os resultados do diagn�stico (lista de 'DaigResSound')",
"name": "__init__",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_003925 | Implement the Python class `GUIVideo` described below.
Class description:
Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo.
Method signatures and docstrings:
- def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os ... | Implement the Python class `GUIVideo` described below.
Class description:
Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo.
Method signatures and docstrings:
- def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os ... | bda0c2c8977dd1246339f1f0f4718d29e8795f21 | <|skeleton|>
class GUIVideo:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo."""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GUIVideo:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de vídeo."""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista c... | the_stack_v2_python_sparse | src/libs/video/gui_video.py | adrianomelo/ldc-desktop | train | 1 |
bbd19f88c3fe72762ed8e1e1d7ac4397f4119243 | [
"if not head or not head.next:\n return head\nfirst_node = head\nsecond_node = head.next\nfirst_node.next = self.swapPairs_1(second_node.next)\nsecond_node.next = first_node\nreturn second_node",
"dummy = ListNode(-1)\ndummy.next = head\nprev_node = dummy\nwhile head and head.next:\n first_node = head\n ... | <|body_start_0|>
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swapPairs_1(second_node.next)
second_node.next = first_node
return second_node
<|end_body_0|>
<|body_start_1|>
dummy = ListNode... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs_1(self, head: ListNode) -> ListNode:
"""方法一:递归 时间复杂度:O(N),其中 N 指的是链表的节点数量。 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :return:"""
<|body_0|>
def swapPairs_2(self, head: ListNode) -> ListNode:
""":type head: ListNode :rtype: ListNode"""
<|bod... | stack_v2_sparse_classes_36k_train_034325 | 2,240 | no_license | [
{
"docstring": "方法一:递归 时间复杂度:O(N),其中 N 指的是链表的节点数量。 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :return:",
"name": "swapPairs_1",
"signature": "def swapPairs_1(self, head: ListNode) -> ListNode"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs_2",
"signature": "def s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs_1(self, head: ListNode) -> ListNode: 方法一:递归 时间复杂度:O(N),其中 N 指的是链表的节点数量。 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :return:
- def swapPairs_2(self, head: ListNode) -> Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs_1(self, head: ListNode) -> ListNode: 方法一:递归 时间复杂度:O(N),其中 N 指的是链表的节点数量。 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :return:
- def swapPairs_2(self, head: ListNode) -> Lis... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def swapPairs_1(self, head: ListNode) -> ListNode:
"""方法一:递归 时间复杂度:O(N),其中 N 指的是链表的节点数量。 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :return:"""
<|body_0|>
def swapPairs_2(self, head: ListNode) -> ListNode:
""":type head: ListNode :rtype: ListNode"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs_1(self, head: ListNode) -> ListNode:
"""方法一:递归 时间复杂度:O(N),其中 N 指的是链表的节点数量。 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :return:"""
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swa... | the_stack_v2_python_sparse | 软件开发岗刷题(华为笔试准备)/递归/swapPairs.py | MaoningGuan/LeetCode | train | 3 | |
33c1ab9403515cafa2a6f7d3c2dc9d6adcda58cc | [
"if 'GLOBAL' not in PATH:\n raise ParameterError(PATH, 'GLOBAL')\nif 'OUTPUT' not in PATH:\n raise ParameterError(PATH, 'OUTPUT')\nif 'DATA' not in PATH:\n setattr(PATH, 'DATA', None)\nif 'MODEL' not in PATH:\n raise ParameterError(PATH, 'MODEL')\nif 'PERTURB' not in PATH:\n raise ParameterError(PATH... | <|body_start_0|>
if 'GLOBAL' not in PATH:
raise ParameterError(PATH, 'GLOBAL')
if 'OUTPUT' not in PATH:
raise ParameterError(PATH, 'OUTPUT')
if 'DATA' not in PATH:
setattr(PATH, 'DATA', None)
if 'MODEL' not in PATH:
raise ParameterError(PAT... | Following the methodologies of Fichtner & Trampert 2011b, this class calculates Point Spread Functions using approximate Hessians derived by a finite difference calculation of gradients. These kernels can be used as a form of resolution testing during adjoint tomography inversions. | PointSpreadFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointSpreadFunction:
"""Following the methodologies of Fichtner & Trampert 2011b, this class calculates Point Spread Functions using approximate Hessians derived by a finite difference calculation of gradients. These kernels can be used as a form of resolution testing during adjoint tomography in... | stack_v2_sparse_classes_36k_train_034326 | 5,423 | no_license | [
{
"docstring": "Checks parameters and paths",
"name": "check",
"signature": "def check(self)"
},
{
"docstring": "Compute a point spread from a given perturbation 'dm' with respect to a reference model 'm'",
"name": "main",
"signature": "def main(self)"
},
{
"docstring": "One-time... | 4 | null | Implement the Python class `PointSpreadFunction` described below.
Class description:
Following the methodologies of Fichtner & Trampert 2011b, this class calculates Point Spread Functions using approximate Hessians derived by a finite difference calculation of gradients. These kernels can be used as a form of resoluti... | Implement the Python class `PointSpreadFunction` described below.
Class description:
Following the methodologies of Fichtner & Trampert 2011b, this class calculates Point Spread Functions using approximate Hessians derived by a finite difference calculation of gradients. These kernels can be used as a form of resoluti... | 0af2d61a84c8f529da968ae72418ebebda89f068 | <|skeleton|>
class PointSpreadFunction:
"""Following the methodologies of Fichtner & Trampert 2011b, this class calculates Point Spread Functions using approximate Hessians derived by a finite difference calculation of gradients. These kernels can be used as a form of resolution testing during adjoint tomography in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointSpreadFunction:
"""Following the methodologies of Fichtner & Trampert 2011b, this class calculates Point Spread Functions using approximate Hessians derived by a finite difference calculation of gradients. These kernels can be used as a form of resolution testing during adjoint tomography inversions."""
... | the_stack_v2_python_sparse | seisflows/workflows/point_spread_function.py | bch0w/simutils | train | 0 |
0d9c4334fc53e39470fd64725f5aff4c93626e94 | [
"config = Configuration()\nconfig.DEFAULT['localhost'] = '192.168.0.1'\nconfig.DEFAULT['port'] = 8080\nconfig.DEFAULT['connection_timeout'] = 60\nconfig.add_section('Test')\nconfig.Test['key1'] = 100\nconfig.Test['key2'] = 123.456\nconfig.Test['key3'] = 'True'\nconfig.Test['key4'] = '123'\nconfig.Test['key5'] = 'C:... | <|body_start_0|>
config = Configuration()
config.DEFAULT['localhost'] = '192.168.0.1'
config.DEFAULT['port'] = 8080
config.DEFAULT['connection_timeout'] = 60
config.add_section('Test')
config.Test['key1'] = 100
config.Test['key2'] = 123.456
config.Test['ke... | ConfigurationUnittest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationUnittest:
def setUp(self):
"""从config dump到本地文件, 以供检视"""
<|body_0|>
def test_load(self):
"""测试Configuration.load()方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
config = Configuration()
config.DEFAULT['localhost'] = '192.168... | stack_v2_sparse_classes_36k_train_034327 | 16,385 | no_license | [
{
"docstring": "从config dump到本地文件, 以供检视",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "测试Configuration.load()方法",
"name": "test_load",
"signature": "def test_load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015608 | Implement the Python class `ConfigurationUnittest` described below.
Class description:
Implement the ConfigurationUnittest class.
Method signatures and docstrings:
- def setUp(self): 从config dump到本地文件, 以供检视
- def test_load(self): 测试Configuration.load()方法 | Implement the Python class `ConfigurationUnittest` described below.
Class description:
Implement the ConfigurationUnittest class.
Method signatures and docstrings:
- def setUp(self): 从config dump到本地文件, 以供检视
- def test_load(self): 测试Configuration.load()方法
<|skeleton|>
class ConfigurationUnittest:
def setUp(self)... | e4db975abf8566074cd610b1f026f858db047a9e | <|skeleton|>
class ConfigurationUnittest:
def setUp(self):
"""从config dump到本地文件, 以供检视"""
<|body_0|>
def test_load(self):
"""测试Configuration.load()方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigurationUnittest:
def setUp(self):
"""从config dump到本地文件, 以供检视"""
config = Configuration()
config.DEFAULT['localhost'] = '192.168.0.1'
config.DEFAULT['port'] = 8080
config.DEFAULT['connection_timeout'] = 60
config.add_section('Test')
config.Test['key... | the_stack_v2_python_sparse | angora/GADGET/configuration.py | MacHu-GWU/Angora | train | 0 | |
070083b455a5de1bd498dbbaf9ee619796450eb4 | [
"super().__init__()\nself.c_in = c_in\nself.c_out = c_out\nself.A = A\nself.conv = nn.Conv2d(self.c_in, self.c_out, kernel_size=(1, 1))\nself.activation = getattr(nn, activation)()",
"if A is None:\n A = self.A\nX = self.conv(X)\nX = torch.einsum('nctv,vw->nctw', (X, A))\nreturn X.contiguous()"
] | <|body_start_0|>
super().__init__()
self.c_in = c_in
self.c_out = c_out
self.A = A
self.conv = nn.Conv2d(self.c_in, self.c_out, kernel_size=(1, 1))
self.activation = getattr(nn, activation)()
<|end_body_0|>
<|body_start_1|>
if A is None:
A = self.A
... | Implementation of the spectral convolution. | SpectralConvolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectralConvolution:
"""Implementation of the spectral convolution."""
def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None):
"""Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation functio... | stack_v2_sparse_classes_36k_train_034328 | 12,878 | no_license | [
{
"docstring": "Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation function for the final output. Not used yet. A: torch.Tensor Adjacency matrix.",
"name": "__init__",
"signature": "def __init__(self, c_in: int, c_out: int=2, activation: str='Leaky... | 2 | stack_v2_sparse_classes_30k_train_013447 | Implement the Python class `SpectralConvolution` described below.
Class description:
Implementation of the spectral convolution.
Method signatures and docstrings:
- def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None): Args: c_in: int Number of input channels. c_out: int Numb... | Implement the Python class `SpectralConvolution` described below.
Class description:
Implementation of the spectral convolution.
Method signatures and docstrings:
- def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None): Args: c_in: int Number of input channels. c_out: int Numb... | 1bdfe7eabcdff257524ae773bcb806ca33700372 | <|skeleton|>
class SpectralConvolution:
"""Implementation of the spectral convolution."""
def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None):
"""Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpectralConvolution:
"""Implementation of the spectral convolution."""
def __init__(self, c_in: int, c_out: int=2, activation: str='LeakyReLU', A: torch.Tensor=None):
"""Args: c_in: int Number of input channels. c_out: int Number of output channels. activation: str Activation function for the fin... | the_stack_v2_python_sparse | model/tig.py | j-huthmacher/Temporal-Info-Graph | train | 0 |
49e6a6285e2d95853bee5f190084e9ed25364795 | [
"measurement_model = self._check_measurement_model(measurement_model)\npred_meas = measurement_model.matrix(**kwargs) @ prediction.state_vector\nreturn MeasurementPrediction.from_state(prediction, pred_meas)",
"out_statevector = hypothesis.prediction.state_vector.copy()\nmeasurement_model = hypothesis.measurement... | <|body_start_0|>
measurement_model = self._check_measurement_model(measurement_model)
pred_meas = measurement_model.matrix(**kwargs) @ prediction.state_vector
return MeasurementPrediction.from_state(prediction, pred_meas)
<|end_body_0|>
<|body_start_1|>
out_statevector = hypothesis.pred... | Conceptually, the :math:`\\alpha-\\beta` filter is similar to its Kalman cousins in that it operates recursively over predict and update steps. It assumes that a state vector is decomposable into quantities and the rates of change of those quantities. We refer to these as position :math:`p` and velocity :math:`v` respe... | AlphaBetaUpdater | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-secret-labs-2011"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlphaBetaUpdater:
"""Conceptually, the :math:`\\alpha-\\beta` filter is similar to its Kalman cousins in that it operates recursively over predict and update steps. It assumes that a state vector is decomposable into quantities and the rates of change of those quantities. We refer to these as pos... | stack_v2_sparse_classes_36k_train_034329 | 5,425 | permissive | [
{
"docstring": "Return the predicted measurement Parameters ---------- prediction : :class:`~.StatePrediction` The state prediction Returns ------- : :class:`~.StateVector` The predicted measurement",
"name": "predict_measurement",
"signature": "def predict_measurement(self, prediction, measurement_mode... | 2 | stack_v2_sparse_classes_30k_train_006812 | Implement the Python class `AlphaBetaUpdater` described below.
Class description:
Conceptually, the :math:`\\alpha-\\beta` filter is similar to its Kalman cousins in that it operates recursively over predict and update steps. It assumes that a state vector is decomposable into quantities and the rates of change of tho... | Implement the Python class `AlphaBetaUpdater` described below.
Class description:
Conceptually, the :math:`\\alpha-\\beta` filter is similar to its Kalman cousins in that it operates recursively over predict and update steps. It assumes that a state vector is decomposable into quantities and the rates of change of tho... | f24090cc919b3b590b84f965a3884ed1293d181d | <|skeleton|>
class AlphaBetaUpdater:
"""Conceptually, the :math:`\\alpha-\\beta` filter is similar to its Kalman cousins in that it operates recursively over predict and update steps. It assumes that a state vector is decomposable into quantities and the rates of change of those quantities. We refer to these as pos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlphaBetaUpdater:
"""Conceptually, the :math:`\\alpha-\\beta` filter is similar to its Kalman cousins in that it operates recursively over predict and update steps. It assumes that a state vector is decomposable into quantities and the rates of change of those quantities. We refer to these as position :math:`... | the_stack_v2_python_sparse | stonesoup/updater/alphabeta.py | dstl/Stone-Soup | train | 315 |
11a72443dfdce4db6dd71ccd35e37422d9a7c62d | [
"if value:\n return ['selected']\nreturn []",
"if value and value[0] == 'selected':\n return True\nreturn False"
] | <|body_start_0|>
if value:
return ['selected']
return []
<|end_body_0|>
<|body_start_1|>
if value and value[0] == 'selected':
return True
return False
<|end_body_1|>
| A special converter between boolean fields and single checkbox widgets. | BoolSingleCheckboxDataConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoolSingleCheckboxDataConverter:
"""A special converter between boolean fields and single checkbox widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.I... | stack_v2_sparse_classes_36k_train_034330 | 16,755 | permissive | [
{
"docstring": "Convert from Python bool to HTML representation.",
"name": "to_widget_value",
"signature": "def to_widget_value(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "to_field_value",
"signature": "def to_field_value(self, value)"
}
] | 2 | null | Implement the Python class `BoolSingleCheckboxDataConverter` described below.
Class description:
A special converter between boolean fields and single checkbox widgets.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, val... | Implement the Python class `BoolSingleCheckboxDataConverter` described below.
Class description:
A special converter between boolean fields and single checkbox widgets.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, val... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class BoolSingleCheckboxDataConverter:
"""A special converter between boolean fields and single checkbox widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoolSingleCheckboxDataConverter:
"""A special converter between boolean fields and single checkbox widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
if value:
return ['selected']
return []
def to_field_value(self,... | the_stack_v2_python_sparse | src/pyams_form/converter.py | Py-AMS/pyams-form | train | 0 |
2fa417d4d0364590e2fedc09ccc1400d746d34ad | [
"super().__init__()\nself.enc_hidden_size = enc_hidden_size\nself.dec_hidden_size = dec_hidden_size\nself.rnn_type = rnn_type\nself.W = nn.Linear(enc_hidden_size + dec_hidden_size + embed_size, 1)\nself.sigmoid = nn.Sigmoid()",
"p_gen = self.W(torch.cat([context, decoder_state, decoder_input], dim=1))\np_gen = se... | <|body_start_0|>
super().__init__()
self.enc_hidden_size = enc_hidden_size
self.dec_hidden_size = dec_hidden_size
self.rnn_type = rnn_type
self.W = nn.Linear(enc_hidden_size + dec_hidden_size + embed_size, 1)
self.sigmoid = nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
... | PointerGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointerGenerator:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'):
"""Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k_train_034331 | 49,575 | no_license | [
{
"docstring": "Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)",
"name": "__init__",
"signature": "def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM')"
},
{
"docstring": "... | 2 | null | Implement the Python class `PointerGenerator` described below.
Class description:
Implement the PointerGenerator class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'): Estimation of Word Generation (vs Copying) Probability Get To The P... | Implement the Python class `PointerGenerator` described below.
Class description:
Implement the PointerGenerator class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'): Estimation of Word Generation (vs Copying) Probability Get To The P... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class PointerGenerator:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'):
"""Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointerGenerator:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, embed_size=128, rnn_type='LSTM'):
"""Estimation of Word Generation (vs Copying) Probability Get To The Point: Summarization with Pointer-Generator Networks (ACL 2017)"""
super().__init__()
self.enc_hidden_si... | the_stack_v2_python_sparse | generated/test_clovaai_FocusSeq2Seq.py | jansel/pytorch-jit-paritybench | train | 35 | |
6466bc8b6b9c9df8277539a269711649b5410501 | [
"response = self.client.get(reverse('index'))\nself.assertEqual(response.status_code, 200)\nself.assertQuerysetEqual(response.context['listings'], [])",
"listing = Listing.objects.create()\nresponse = self.client.get(reverse('index'))\nself.assertQuerysetEqual(response.context['listings'], [listing])"
] | <|body_start_0|>
response = self.client.get(reverse('index'))
self.assertEqual(response.status_code, 200)
self.assertQuerysetEqual(response.context['listings'], [])
<|end_body_0|>
<|body_start_1|>
listing = Listing.objects.create()
response = self.client.get(reverse('index'))
... | IndexViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexViewTests:
def test_no_listings(self):
"""If no listings exist, none are displayed on the index page."""
<|body_0|>
def test_display_listings(self):
"""Index view displays all created listings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
re... | stack_v2_sparse_classes_36k_train_034332 | 1,005 | no_license | [
{
"docstring": "If no listings exist, none are displayed on the index page.",
"name": "test_no_listings",
"signature": "def test_no_listings(self)"
},
{
"docstring": "Index view displays all created listings.",
"name": "test_display_listings",
"signature": "def test_display_listings(self... | 2 | stack_v2_sparse_classes_30k_train_000095 | Implement the Python class `IndexViewTests` described below.
Class description:
Implement the IndexViewTests class.
Method signatures and docstrings:
- def test_no_listings(self): If no listings exist, none are displayed on the index page.
- def test_display_listings(self): Index view displays all created listings. | Implement the Python class `IndexViewTests` described below.
Class description:
Implement the IndexViewTests class.
Method signatures and docstrings:
- def test_no_listings(self): If no listings exist, none are displayed on the index page.
- def test_display_listings(self): Index view displays all created listings.
... | 3e5394d4c54188aa371c46a112be7791d829dc7e | <|skeleton|>
class IndexViewTests:
def test_no_listings(self):
"""If no listings exist, none are displayed on the index page."""
<|body_0|>
def test_display_listings(self):
"""Index view displays all created listings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexViewTests:
def test_no_listings(self):
"""If no listings exist, none are displayed on the index page."""
response = self.client.get(reverse('index'))
self.assertEqual(response.status_code, 200)
self.assertQuerysetEqual(response.context['listings'], [])
def test_displa... | the_stack_v2_python_sparse | auctions/tests.py | andkerr/mytoyauctionsite | train | 0 | |
3b712ab8074120d6a1c6f48660e9c86e5c337f51 | [
"app = TaskGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('task_genomic_file', kf_id))\nreturn TaskGenomicFileSchema().jsonify(app)",
"app = TaskGenomicFile.query.get(kf_id)\nif app is None:\n abort(404, 'could not find {} `{}`'.format('task_genomic_file', kf_id))... | <|body_start_0|>
app = TaskGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.format('task_genomic_file', kf_id))
return TaskGenomicFileSchema().jsonify(app)
<|end_body_0|>
<|body_start_1|>
app = TaskGenomicFile.query.get(kf_id)
if app i... | TaskGenomicFile API | TaskGenomicFileAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGenomicFileAPI:
"""TaskGenomicFile API"""
def get(self, kf_id):
"""Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing task_genomic_file. Allows part... | stack_v2_sparse_classes_36k_train_034333 | 5,124 | permissive | [
{
"docstring": "Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing task_genomic_file. Allows partial update --- template: path: update_by_id.yml propertie... | 3 | null | Implement the Python class `TaskGenomicFileAPI` described below.
Class description:
TaskGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile
- def patch(self, kf_id): Update an existing task_geno... | Implement the Python class `TaskGenomicFileAPI` described below.
Class description:
TaskGenomicFile API
Method signatures and docstrings:
- def get(self, kf_id): Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile
- def patch(self, kf_id): Update an existing task_geno... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class TaskGenomicFileAPI:
"""TaskGenomicFile API"""
def get(self, kf_id):
"""Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing task_genomic_file. Allows part... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskGenomicFileAPI:
"""TaskGenomicFile API"""
def get(self, kf_id):
"""Get a task_genomic_file by id --- template: path: get_by_id.yml properties: resource: TaskGenomicFile"""
app = TaskGenomicFile.query.get(kf_id)
if app is None:
abort(404, 'could not find {} `{}`'.fo... | the_stack_v2_python_sparse | dataservice/api/task_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
ec350f2fc5388fd89478bc0155447bc9bc8d6bed | [
"ZIP_FILEPATH = 'temp/new.zip'\nwith zipfile.ZipFile(str(ZIP_FILEPATH), 'w', compression=zipfile.ZIP_DEFLATED) as zfile:\n zfile.write('data/file_a.txt')\n zfile.write('data/file_b.txt')",
"ZIP_FILEPATH = 'temp/new.zip'\nEXPAND_DIR = 'temp/expand'\nwith zipfile.ZipFile(str(ZIP_FILEPATH)) as zfile:\n zfil... | <|body_start_0|>
ZIP_FILEPATH = 'temp/new.zip'
with zipfile.ZipFile(str(ZIP_FILEPATH), 'w', compression=zipfile.ZIP_DEFLATED) as zfile:
zfile.write('data/file_a.txt')
zfile.write('data/file_b.txt')
<|end_body_0|>
<|body_start_1|>
ZIP_FILEPATH = 'temp/new.zip'
EXP... | TestZip | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestZip:
def test_zip(self) -> None:
"""指定したファイルを zip ファイルに圧縮する。"""
<|body_0|>
def test_unzip(self) -> None:
"""zipファイル中の全てのデータを解凍"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ZIP_FILEPATH = 'temp/new.zip'
with zipfile.ZipFile(str(ZIP_FIL... | stack_v2_sparse_classes_36k_train_034334 | 762 | permissive | [
{
"docstring": "指定したファイルを zip ファイルに圧縮する。",
"name": "test_zip",
"signature": "def test_zip(self) -> None"
},
{
"docstring": "zipファイル中の全てのデータを解凍",
"name": "test_unzip",
"signature": "def test_unzip(self) -> None"
}
] | 2 | null | Implement the Python class `TestZip` described below.
Class description:
Implement the TestZip class.
Method signatures and docstrings:
- def test_zip(self) -> None: 指定したファイルを zip ファイルに圧縮する。
- def test_unzip(self) -> None: zipファイル中の全てのデータを解凍 | Implement the Python class `TestZip` described below.
Class description:
Implement the TestZip class.
Method signatures and docstrings:
- def test_zip(self) -> None: 指定したファイルを zip ファイルに圧縮する。
- def test_unzip(self) -> None: zipファイル中の全てのデータを解凍
<|skeleton|>
class TestZip:
def test_zip(self) -> None:
"""指定し... | a3994d272d812261ba694954554cfa213dfe795e | <|skeleton|>
class TestZip:
def test_zip(self) -> None:
"""指定したファイルを zip ファイルに圧縮する。"""
<|body_0|>
def test_unzip(self) -> None:
"""zipファイル中の全てのデータを解凍"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestZip:
def test_zip(self) -> None:
"""指定したファイルを zip ファイルに圧縮する。"""
ZIP_FILEPATH = 'temp/new.zip'
with zipfile.ZipFile(str(ZIP_FILEPATH), 'w', compression=zipfile.ZIP_DEFLATED) as zfile:
zfile.write('data/file_a.txt')
zfile.write('data/file_b.txt')
def test... | the_stack_v2_python_sparse | python/zipfile/test_zip.py | samsgood0310/til | train | 0 | |
bb0c5155111e0c6ad0be0dcc95af68e9fde7e24b | [
"response = self.client.get(reverse('education:index'))\nself.assertEqual(response.status_code, 200)\nself.assertEqual(response.context.get('json_data'), None)\nself.assertContains(response, 'High School Graduation')\nself.assertContains(response, 'How Rates Were Calculated')\nself.assertContains(response, 'Home')\... | <|body_start_0|>
response = self.client.get(reverse('education:index'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context.get('json_data'), None)
self.assertContains(response, 'High School Graduation')
self.assertContains(response, 'How Rates Were Calc... | EducationIndexViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationIndexViewTests:
def test_no_data(self):
"""If no data is in the database, no content is displayed but there is no map of graudation rates."""
<|body_0|>
def test_with_data(self):
"""If state data is in the database, make sure the conents renders and a graph ... | stack_v2_sparse_classes_36k_train_034335 | 9,266 | no_license | [
{
"docstring": "If no data is in the database, no content is displayed but there is no map of graudation rates.",
"name": "test_no_data",
"signature": "def test_no_data(self)"
},
{
"docstring": "If state data is in the database, make sure the conents renders and a graph of the graudation rates i... | 2 | stack_v2_sparse_classes_30k_val_001014 | Implement the Python class `EducationIndexViewTests` described below.
Class description:
Implement the EducationIndexViewTests class.
Method signatures and docstrings:
- def test_no_data(self): If no data is in the database, no content is displayed but there is no map of graudation rates.
- def test_with_data(self): ... | Implement the Python class `EducationIndexViewTests` described below.
Class description:
Implement the EducationIndexViewTests class.
Method signatures and docstrings:
- def test_no_data(self): If no data is in the database, no content is displayed but there is no map of graudation rates.
- def test_with_data(self): ... | 2a8e2dc4e9b3cb92d4d437b37e61940a9486b81f | <|skeleton|>
class EducationIndexViewTests:
def test_no_data(self):
"""If no data is in the database, no content is displayed but there is no map of graudation rates."""
<|body_0|>
def test_with_data(self):
"""If state data is in the database, make sure the conents renders and a graph ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationIndexViewTests:
def test_no_data(self):
"""If no data is in the database, no content is displayed but there is no map of graudation rates."""
response = self.client.get(reverse('education:index'))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.co... | the_stack_v2_python_sparse | education/tests.py | smeds1/mysite | train | 1 | |
8e52e48fc9e5bd4deb0a2a7f33481e16a68ef013 | [
"super().__init__()\nself.player = player\nself.spawnTime = 0\nself.disappear = False\npygame.sprite.Sprite.__init__(self)\nsprite_sheet = SpriteSheet('Golem.png')\nimage = sprite_sheet.get_image(29, 11, 101, 319)\nself.image = image\nself.rect = self.image.get_rect()\nself.rect.x = player.rect.x\nself.rect.y = -31... | <|body_start_0|>
super().__init__()
self.player = player
self.spawnTime = 0
self.disappear = False
pygame.sprite.Sprite.__init__(self)
sprite_sheet = SpriteSheet('Golem.png')
image = sprite_sheet.get_image(29, 11, 101, 319)
self.image = image
self.... | Punch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Punch:
def __init__(self, player):
""":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet t... | stack_v2_sparse_classes_36k_train_034336 | 2,449 | no_license | [
{
"docstring": ":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet to where the custom spries came from image: Hol... | 2 | null | Implement the Python class `Punch` described below.
Class description:
Implement the Punch class.
Method signatures and docstrings:
- def __init__(self, player): :param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay ... | Implement the Python class `Punch` described below.
Class description:
Implement the Punch class.
Method signatures and docstrings:
- def __init__(self, player): :param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay ... | 56fbcfc786dfc373f477270468f06e31b6271749 | <|skeleton|>
class Punch:
def __init__(self, player):
""":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Punch:
def __init__(self, player):
""":param player: The player object This initializes the punch Variables: self.player: The player object self.spawnTime: The amout of time the punch will stay on screen self.disappear: True to allow the punch to disappear sprite_sheet: The spritesheet to where the cu... | the_stack_v2_python_sparse | Doki Doki Island/bossAttacks/golem/golAttack3.py | cashpop5000/DokiProject | train | 0 | |
835c6a48b1e3ec48fba6dc1e46224544165a4300 | [
"if not root or not root.left:\n return root\npre = root\nwhile pre.left:\n cur = pre\n while cur:\n cur.left.next = cur.right\n if cur.next:\n cur.right.next = cur.next.left\n cur = cur.next\n pre = pre.left\nreturn root",
"if not root:\n return root\nqueue = [(root... | <|body_start_0|>
if not root or not root.left:
return root
pre = root
while pre.left:
cur = pre
while cur:
cur.left.next = cur.right
if cur.next:
cur.right.next = cur.next.left
cur = cur.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
"""' 修已改版bfs 只使用常数项空间 经有上一层的next了,所以就不需要队列来存储了 :type root: Node :rtype: Node"""
<|body_0|>
def connect2(self, root):
"""bfs遍历每一层 下一个节点在同一个节点的时候next指向下一个节点 不符合常数空间要求 :type root: Node :rtype: Node"""
<|body_1|>
def connec... | stack_v2_sparse_classes_36k_train_034337 | 3,426 | no_license | [
{
"docstring": "' 修已改版bfs 只使用常数项空间 经有上一层的next了,所以就不需要队列来存储了 :type root: Node :rtype: Node",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": "bfs遍历每一层 下一个节点在同一个节点的时候next指向下一个节点 不符合常数空间要求 :type root: Node :rtype: Node",
"name": "connect2",
"signature": "def conn... | 3 | stack_v2_sparse_classes_30k_train_001566 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): ' 修已改版bfs 只使用常数项空间 经有上一层的next了,所以就不需要队列来存储了 :type root: Node :rtype: Node
- def connect2(self, root): bfs遍历每一层 下一个节点在同一个节点的时候next指向下一个节点 不符合常数空间要求 :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): ' 修已改版bfs 只使用常数项空间 经有上一层的next了,所以就不需要队列来存储了 :type root: Node :rtype: Node
- def connect2(self, root): bfs遍历每一层 下一个节点在同一个节点的时候next指向下一个节点 不符合常数空间要求 :type ... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def connect(self, root):
"""' 修已改版bfs 只使用常数项空间 经有上一层的next了,所以就不需要队列来存储了 :type root: Node :rtype: Node"""
<|body_0|>
def connect2(self, root):
"""bfs遍历每一层 下一个节点在同一个节点的时候next指向下一个节点 不符合常数空间要求 :type root: Node :rtype: Node"""
<|body_1|>
def connec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root):
"""' 修已改版bfs 只使用常数项空间 经有上一层的next了,所以就不需要队列来存储了 :type root: Node :rtype: Node"""
if not root or not root.left:
return root
pre = root
while pre.left:
cur = pre
while cur:
cur.left.next = cur.r... | the_stack_v2_python_sparse | 116_填充每个节点的下一个右侧节点指针.py | lovehhf/LeetCode | train | 0 | |
48527f61f2e2a9312a47290e480f96ce410dad3c | [
"url = kwargs['url']\naccount_code = kwargs['serial']\nagent_id = kwargs['agentID']\nwechat_controllers = WechatControllers()\nauth_config = json.loads(wechat_controllers.auth_config(url, account_code, agent_id))\nauth_config['corpId'] = auth_config.pop('appId')\nauth_config['nonceStr'] = auth_config.pop('noncestr'... | <|body_start_0|>
url = kwargs['url']
account_code = kwargs['serial']
agent_id = kwargs['agentID']
wechat_controllers = WechatControllers()
auth_config = json.loads(wechat_controllers.auth_config(url, account_code, agent_id))
auth_config['corpId'] = auth_config.pop('appId'... | MobileControllers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MobileControllers:
def api_sign(self, **kwargs):
"""移动端获取签名 :param kwargs: url: 本地url, serial: 企业编号, agentID: 应用id :return:"""
<|body_0|>
def api_login(self, **kwargs):
"""移动端登录 :param kwargs: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_034338 | 9,700 | no_license | [
{
"docstring": "移动端获取签名 :param kwargs: url: 本地url, serial: 企业编号, agentID: 应用id :return:",
"name": "api_sign",
"signature": "def api_sign(self, **kwargs)"
},
{
"docstring": "移动端登录 :param kwargs: :return:",
"name": "api_login",
"signature": "def api_login(self, **kwargs)"
}
] | 2 | null | Implement the Python class `MobileControllers` described below.
Class description:
Implement the MobileControllers class.
Method signatures and docstrings:
- def api_sign(self, **kwargs): 移动端获取签名 :param kwargs: url: 本地url, serial: 企业编号, agentID: 应用id :return:
- def api_login(self, **kwargs): 移动端登录 :param kwargs: :ret... | Implement the Python class `MobileControllers` described below.
Class description:
Implement the MobileControllers class.
Method signatures and docstrings:
- def api_sign(self, **kwargs): 移动端获取签名 :param kwargs: url: 本地url, serial: 企业编号, agentID: 应用id :return:
- def api_login(self, **kwargs): 移动端登录 :param kwargs: :ret... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class MobileControllers:
def api_sign(self, **kwargs):
"""移动端获取签名 :param kwargs: url: 本地url, serial: 企业编号, agentID: 应用id :return:"""
<|body_0|>
def api_login(self, **kwargs):
"""移动端登录 :param kwargs: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MobileControllers:
def api_sign(self, **kwargs):
"""移动端获取签名 :param kwargs: url: 本地url, serial: 企业编号, agentID: 应用id :return:"""
url = kwargs['url']
account_code = kwargs['serial']
agent_id = kwargs['agentID']
wechat_controllers = WechatControllers()
auth_config =... | the_stack_v2_python_sparse | mdias_addons/funenc_wechat/controllers/controllers.py | rezaghanimi/main_mdias | train | 0 | |
f4428aebd34569c6ad3347bcfc05b7b4d4df778f | [
"self.head = None\nself.tail = None\nreturn",
"currentNode = self.head\nwhile currentNode is not None:\n print(currentNode.getData())\n currentNode = currentNode.getNext()\nreturn",
"if isinstance(item, ListNode):\n if self.head is None:\n self.head = item\n else:\n tail = self.tail\n ... | <|body_start_0|>
self.head = None
self.tail = None
return
<|end_body_0|>
<|body_start_1|>
currentNode = self.head
while currentNode is not None:
print(currentNode.getData())
currentNode = currentNode.getNext()
return
<|end_body_1|>
<|body_start_2... | SingleLinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleLinkedList:
def __init__(self):
"""constructor to initiate this object"""
<|body_0|>
def outputList(self):
"""outputs the list (the value of the node, actually)"""
<|body_1|>
def addListitem(self, item):
"""add an item at the end of the lis... | stack_v2_sparse_classes_36k_train_034339 | 1,208 | no_license | [
{
"docstring": "constructor to initiate this object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "outputs the list (the value of the node, actually)",
"name": "outputList",
"signature": "def outputList(self)"
},
{
"docstring": "add an item at the end ... | 4 | stack_v2_sparse_classes_30k_train_000417 | Implement the Python class `SingleLinkedList` described below.
Class description:
Implement the SingleLinkedList class.
Method signatures and docstrings:
- def __init__(self): constructor to initiate this object
- def outputList(self): outputs the list (the value of the node, actually)
- def addListitem(self, item): ... | Implement the Python class `SingleLinkedList` described below.
Class description:
Implement the SingleLinkedList class.
Method signatures and docstrings:
- def __init__(self): constructor to initiate this object
- def outputList(self): outputs the list (the value of the node, actually)
- def addListitem(self, item): ... | f4c08170bef3b841f3dac7a1a05c741ccfe8cfb9 | <|skeleton|>
class SingleLinkedList:
def __init__(self):
"""constructor to initiate this object"""
<|body_0|>
def outputList(self):
"""outputs the list (the value of the node, actually)"""
<|body_1|>
def addListitem(self, item):
"""add an item at the end of the lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleLinkedList:
def __init__(self):
"""constructor to initiate this object"""
self.head = None
self.tail = None
return
def outputList(self):
"""outputs the list (the value of the node, actually)"""
currentNode = self.head
while currentNode is not ... | the_stack_v2_python_sparse | listen/einfacheliste.py | hofmannedv/python-kurs-gfn | train | 1 | |
161e8dd021bb3290747b53ca54dc2d0e8836e90f | [
"self.portdb = portdb\nself.qatracker = qatracker\nself.repo_settings = repo_settings\nself.repoman_settings = repoman_settings\nself.vcs_settings = vcs_settings",
"for y_file in checkdirlist:\n index = self.repo_settings.repo_config.find_invalid_path_char(y_file)\n if index != -1:\n y_relative = os.... | <|body_start_0|>
self.portdb = portdb
self.qatracker = qatracker
self.repo_settings = repo_settings
self.repoman_settings = repoman_settings
self.vcs_settings = vcs_settings
<|end_body_0|>
<|body_start_1|>
for y_file in checkdirlist:
index = self.repo_setting... | FileChecks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileChecks:
def __init__(self, qatracker, repoman_settings, repo_settings, portdb, vcs_settings):
"""@param qatracker: QATracker instance @param repoman_settings: settings instance @param repo_settings: repository settings instance @param portdb: portdb instance"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_034340 | 2,285 | no_license | [
{
"docstring": "@param qatracker: QATracker instance @param repoman_settings: settings instance @param repo_settings: repository settings instance @param portdb: portdb instance",
"name": "__init__",
"signature": "def __init__(self, qatracker, repoman_settings, repo_settings, portdb, vcs_settings)"
},... | 2 | stack_v2_sparse_classes_30k_train_009867 | Implement the Python class `FileChecks` described below.
Class description:
Implement the FileChecks class.
Method signatures and docstrings:
- def __init__(self, qatracker, repoman_settings, repo_settings, portdb, vcs_settings): @param qatracker: QATracker instance @param repoman_settings: settings instance @param r... | Implement the Python class `FileChecks` described below.
Class description:
Implement the FileChecks class.
Method signatures and docstrings:
- def __init__(self, qatracker, repoman_settings, repo_settings, portdb, vcs_settings): @param qatracker: QATracker instance @param repoman_settings: settings instance @param r... | e4a2a2279955e37973b848c2495ca7a54d63f51a | <|skeleton|>
class FileChecks:
def __init__(self, qatracker, repoman_settings, repo_settings, portdb, vcs_settings):
"""@param qatracker: QATracker instance @param repoman_settings: settings instance @param repo_settings: repository settings instance @param portdb: portdb instance"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileChecks:
def __init__(self, qatracker, repoman_settings, repo_settings, portdb, vcs_settings):
"""@param qatracker: QATracker instance @param repoman_settings: settings instance @param repo_settings: repository settings instance @param portdb: portdb instance"""
self.portdb = portdb
... | the_stack_v2_python_sparse | backend/zobcs/pym/repoman/checks/directories/files.py | zorry/zobsc | train | 0 | |
0ff40cbf2ac376f4e94e8977b6616fdf70826b82 | [
"self.n_head = n_head\nself.d_k = self.d_v = d_k = d_v = d_model // n_head\nself.dropout = dropout\nself.seed = seed\nself.qs_layers = []\nself.ks_layers = []\nself.vs_layers = []\nvs_layer = Dense(d_v, use_bias=False)\nfor _ in range(n_head):\n self.qs_layers.append(Dense(d_k, use_bias=False))\n self.ks_laye... | <|body_start_0|>
self.n_head = n_head
self.d_k = self.d_v = d_k = d_v = d_model // n_head
self.dropout = dropout
self.seed = seed
self.qs_layers = []
self.ks_layers = []
self.vs_layers = []
vs_layer = Dense(d_v, use_bias=False)
for _ in range(n_hea... | Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs_layers: List of values across heads attention: Scaled dot ... | InterpretableMultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs... | stack_v2_sparse_classes_36k_train_034341 | 13,910 | permissive | [
{
"docstring": "Initialises layer. Args: n_head: Number of heads d_model: TFT state dimensionality dropout: Dropout discard rate",
"name": "__init__",
"signature": "def __init__(self, n_head, d_model, dropout, seed=313, **kwargs)"
},
{
"docstring": "Applies interpretable multihead attention. Usi... | 2 | stack_v2_sparse_classes_30k_train_016064 | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ... | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ... | ec2a4a426673b11e3589b64cef9d7160b1de28d4 | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs_layers: List... | the_stack_v2_python_sparse | ai4water/models/_tensorflow/utils.py | AtrCheema/AI4Water | train | 47 |
8a982a0f10b674c316a354fb7b8c85459aaeea5c | [
"self.stopping_criterion = stopping_criterion\nself.integrand = integrand\nself.measure = self.integrand.measure\nself.distribution = self.measure.distribution\nself.replications = replications\nself.muhat_r = zeros(int(self.replications))\nself.solution = nan\nself.muhat = inf\nself.sighat = inf\nself.t_eval = 0\n... | <|body_start_0|>
self.stopping_criterion = stopping_criterion
self.integrand = integrand
self.measure = self.integrand.measure
self.distribution = self.measure.distribution
self.replications = replications
self.muhat_r = zeros(int(self.replications))
self.solution... | Update and store mean and variance estimates with repliations. See the stopping criterion that utilize this object for references. | MeanVarDataRep | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanVarDataRep:
"""Update and store mean and variance estimates with repliations. See the stopping criterion that utilize this object for references."""
def __init__(self, stopping_criterion, integrand, n_init, replications):
"""Args: stopping_criterion (StoppingCriterion): a Stoppin... | stack_v2_sparse_classes_36k_train_034342 | 2,622 | permissive | [
{
"docstring": "Args: stopping_criterion (StoppingCriterion): a StoppingCriterion instance integrand (Integrand): an Integrand instance n_init (int): initial number of samples replications (int): number of replications",
"name": "__init__",
"signature": "def __init__(self, stopping_criterion, integrand,... | 2 | stack_v2_sparse_classes_30k_train_012807 | Implement the Python class `MeanVarDataRep` described below.
Class description:
Update and store mean and variance estimates with repliations. See the stopping criterion that utilize this object for references.
Method signatures and docstrings:
- def __init__(self, stopping_criterion, integrand, n_init, replications)... | Implement the Python class `MeanVarDataRep` described below.
Class description:
Update and store mean and variance estimates with repliations. See the stopping criterion that utilize this object for references.
Method signatures and docstrings:
- def __init__(self, stopping_criterion, integrand, n_init, replications)... | 0ed9da2f10b9ac0004c993c01392b4c86002954c | <|skeleton|>
class MeanVarDataRep:
"""Update and store mean and variance estimates with repliations. See the stopping criterion that utilize this object for references."""
def __init__(self, stopping_criterion, integrand, n_init, replications):
"""Args: stopping_criterion (StoppingCriterion): a Stoppin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeanVarDataRep:
"""Update and store mean and variance estimates with repliations. See the stopping criterion that utilize this object for references."""
def __init__(self, stopping_criterion, integrand, n_init, replications):
"""Args: stopping_criterion (StoppingCriterion): a StoppingCriterion in... | the_stack_v2_python_sparse | qmcpy/accumulate_data/mean_var_data_rep.py | kachiann/QMCSoftware | train | 1 |
0dac62f7942734b8c8c410b2045bf1102e43f782 | [
"node_set = set()\nwhile head:\n if head in node_set:\n return True\n else:\n node_set.add(head)\n head = head.next\nreturn False",
"if head == None or head.next == None:\n return False\nfast = head.next\nslow = head\nwhile slow != fast:\n if head == None or head.next == None:\n ... | <|body_start_0|>
node_set = set()
while head:
if head in node_set:
return True
else:
node_set.add(head)
head = head.next
return False
<|end_body_0|>
<|body_start_1|>
if head == None or head.next == None:
ret... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def has_cycle_1(self, head: ListNode) -> ListNode:
"""寻找链表里面的环 Args: head: 头结点 Returns: bool"""
<|body_0|>
def has_cycle_2(self, head: ListNode) -> ListNode:
"""寻找链表里面的环 Args: head: 头结点 Returns: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_034343 | 2,294 | permissive | [
{
"docstring": "寻找链表里面的环 Args: head: 头结点 Returns: bool",
"name": "has_cycle_1",
"signature": "def has_cycle_1(self, head: ListNode) -> ListNode"
},
{
"docstring": "寻找链表里面的环 Args: head: 头结点 Returns: bool",
"name": "has_cycle_2",
"signature": "def has_cycle_2(self, head: ListNode) -> ListN... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def has_cycle_1(self, head: ListNode) -> ListNode: 寻找链表里面的环 Args: head: 头结点 Returns: bool
- def has_cycle_2(self, head: ListNode) -> ListNode: 寻找链表里面的环 Args: head: 头结点 Returns: b... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def has_cycle_1(self, head: ListNode) -> ListNode: 寻找链表里面的环 Args: head: 头结点 Returns: bool
- def has_cycle_2(self, head: ListNode) -> ListNode: 寻找链表里面的环 Args: head: 头结点 Returns: b... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def has_cycle_1(self, head: ListNode) -> ListNode:
"""寻找链表里面的环 Args: head: 头结点 Returns: bool"""
<|body_0|>
def has_cycle_2(self, head: ListNode) -> ListNode:
"""寻找链表里面的环 Args: head: 头结点 Returns: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def has_cycle_1(self, head: ListNode) -> ListNode:
"""寻找链表里面的环 Args: head: 头结点 Returns: bool"""
node_set = set()
while head:
if head in node_set:
return True
else:
node_set.add(head)
head = head.next
... | the_stack_v2_python_sparse | src/leetcodepython/list/linked_list_cycle_141.py | zhangyu345293721/leetcode | train | 101 | |
bcf1b9c13fa954c345b9ae9778b1cea8e402d049 | [
"super(EinsteinMidpoint, self).__init__()\nself.to_klein = ToKlein(min_norm)\nself.lorentz_factors = LorentzFactors(min_norm)\nself.sum = ReduceSum(keep_dims=True)\nself.unsqueeze = ExpandDims()\nself.sumFalse = ReduceSum(keep_dims=False)\nself.klein_constraint = KleinConstraint(min_norm)\nself.klein_to_poincare = ... | <|body_start_0|>
super(EinsteinMidpoint, self).__init__()
self.to_klein = ToKlein(min_norm)
self.lorentz_factors = LorentzFactors(min_norm)
self.sum = ReduceSum(keep_dims=True)
self.unsqueeze = ExpandDims()
self.sumFalse = ReduceSum(keep_dims=False)
self.klein_con... | einstein mindpoint class | EinsteinMidpoint | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EinsteinMidpoint:
"""einstein mindpoint class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, x, c):
"""class construction"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(EinsteinMidpoint, self).__init__()
... | stack_v2_sparse_classes_36k_train_034344 | 8,596 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, min_norm)"
},
{
"docstring": "class construction",
"name": "construct",
"signature": "def construct(self, x, c)"
}
] | 2 | null | Implement the Python class `EinsteinMidpoint` described below.
Class description:
einstein mindpoint class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, x, c): class construction | Implement the Python class `EinsteinMidpoint` described below.
Class description:
einstein mindpoint class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, x, c): class construction
<|skeleton|>
class EinsteinMidpoint:
"""einstein mindpoint class"""
def __init... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class EinsteinMidpoint:
"""einstein mindpoint class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, x, c):
"""class construction"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EinsteinMidpoint:
"""einstein mindpoint class"""
def __init__(self, min_norm):
"""init fun"""
super(EinsteinMidpoint, self).__init__()
self.to_klein = ToKlein(min_norm)
self.lorentz_factors = LorentzFactors(min_norm)
self.sum = ReduceSum(keep_dims=True)
sel... | the_stack_v2_python_sparse | research/nlp/hypertext/src/poincare.py | mindspore-ai/models | train | 301 |
147726cb2dbbf0d7f211e519ca599ebd3c360140 | [
"if not head:\n return head\ncount = 0\ndummy = ListNode(0)\ndummy.next = head\ncur = dummy\nwhile cur.next:\n count += 1\n cur = cur.next\nk %= count\nif k == 0:\n return head\ncur = dummy\nfor _ in range(count - k):\n cur = cur.next\nnew_head = cur.next\ncur.next = None\ndummy.next = new_head\nwhil... | <|body_start_0|>
if not head:
return head
count = 0
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next:
count += 1
cur = cur.next
k %= count
if k == 0:
return head
cur = dummy
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n... | stack_v2_sparse_classes_36k_train_034345 | 1,706 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight1",
"signature": "def rotateRight1(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight(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 rotateRight1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skelet... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
if not head:
return head
count = 0
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next:
count += 1
cur = ... | the_stack_v2_python_sparse | LinkedList/q061_rotate_list.py | sevenhe716/LeetCode | train | 0 | |
7d7bdccc4bd70b6cf6830b6d0d9fafa1fdcbdc5b | [
"self.nc_file = nc_file\nxr_variables, global_attributes = self._readXarrayFile(var_ids, exclude_vars)\nsuper().__init__(xr_variables, global_attributes=global_attributes, na_items_to_override=na_items_to_override, only_return_file_names=only_return_file_names, requested_ffi=requested_ffi)",
"exclude_vars = exclu... | <|body_start_0|>
self.nc_file = nc_file
xr_variables, global_attributes = self._readXarrayFile(var_ids, exclude_vars)
super().__init__(xr_variables, global_attributes=global_attributes, na_items_to_override=na_items_to_override, only_return_file_names=only_return_file_names, requested_ffi=reques... | Converts a NetCDF file to one or more NASA Ames files. | NCToNA | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NCToNA:
"""Converts a NetCDF file to one or more NASA Ames files."""
def __init__(self, nc_file, var_ids=None, na_items_to_override=None, only_return_file_names=False, exclude_vars=None, requested_ffi=None):
"""Sets up instance variables. Typical usage is: >>> import nappy.nc_interfa... | stack_v2_sparse_classes_36k_train_034346 | 3,661 | permissive | [
{
"docstring": "Sets up instance variables. Typical usage is: >>> import nappy.nc_interface.nc_to_na as nc_to_na >>> c = nc_to_na.NCToNA(\"old_file.nc\") >>> c.convert() >>> c.writeNAFiles(\"new_file.na\", delimiter=\",\") OR: >>> c = nc_to_na.NCToNA(\"old_file.nc\") >>> file_names = c.constructNAFileNames()",
... | 2 | stack_v2_sparse_classes_30k_train_015897 | Implement the Python class `NCToNA` described below.
Class description:
Converts a NetCDF file to one or more NASA Ames files.
Method signatures and docstrings:
- def __init__(self, nc_file, var_ids=None, na_items_to_override=None, only_return_file_names=False, exclude_vars=None, requested_ffi=None): Sets up instance... | Implement the Python class `NCToNA` described below.
Class description:
Converts a NetCDF file to one or more NASA Ames files.
Method signatures and docstrings:
- def __init__(self, nc_file, var_ids=None, na_items_to_override=None, only_return_file_names=False, exclude_vars=None, requested_ffi=None): Sets up instance... | 71e42a91112f52eef86183e35129b9ee2019e55b | <|skeleton|>
class NCToNA:
"""Converts a NetCDF file to one or more NASA Ames files."""
def __init__(self, nc_file, var_ids=None, na_items_to_override=None, only_return_file_names=False, exclude_vars=None, requested_ffi=None):
"""Sets up instance variables. Typical usage is: >>> import nappy.nc_interfa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NCToNA:
"""Converts a NetCDF file to one or more NASA Ames files."""
def __init__(self, nc_file, var_ids=None, na_items_to_override=None, only_return_file_names=False, exclude_vars=None, requested_ffi=None):
"""Sets up instance variables. Typical usage is: >>> import nappy.nc_interface.nc_to_na a... | the_stack_v2_python_sparse | nappy/nc_interface/nc_to_na.py | cedadev/nappy | train | 9 |
ccfa549c203e6aaa51d5e12d24543cdf770eefdf | [
"def check_supported_spec(spec):\n if tensor_spec.is_discrete(spec):\n assert len(spec.shape) == 0 or (len(spec.shape) == 1 and spec.shape[0] == 1)\n else:\n assert len(spec.shape) == 1\ntf.nest.map_structure(check_supported_spec, action_spec)\nself._action_spec = action_spec",
"tf.nest.assert... | <|body_start_0|>
def check_supported_spec(spec):
if tensor_spec.is_discrete(spec):
assert len(spec.shape) == 0 or (len(spec.shape) == 1 and spec.shape[0] == 1)
else:
assert len(spec.shape) == 1
tf.nest.map_structure(check_supported_spec, action_spe... | A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them | SimpleActionEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleActionEncoder:
"""A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them"""
def __init__(self, action_spec):
"""Create Simpl... | stack_v2_sparse_classes_36k_train_034347 | 2,438 | permissive | [
{
"docstring": "Create SimpleActionEncoder. Args: action_spec (nested BoundedTensorSpec): spec for actions",
"name": "__init__",
"signature": "def __init__(self, action_spec)"
},
{
"docstring": "Generate encoded actions. Args: inputs (nested Tensor): action tensors. Returns: nested Tensor with t... | 2 | stack_v2_sparse_classes_30k_train_019917 | Implement the Python class `SimpleActionEncoder` described below.
Class description:
A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them
Method signatures and do... | Implement the Python class `SimpleActionEncoder` described below.
Class description:
A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them
Method signatures and do... | 38a3621337a030f74bb3944d7695e7642e777e10 | <|skeleton|>
class SimpleActionEncoder:
"""A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them"""
def __init__(self, action_spec):
"""Create Simpl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleActionEncoder:
"""A simple encoder for action. Only supports one action (discrete or continuous). If encode discrete action to one hot representation and use the original continous actions. And output the concat of all of them"""
def __init__(self, action_spec):
"""Create SimpleActionEncode... | the_stack_v2_python_sparse | alf/utils/action_encoder.py | Haichao-Zhang/alf | train | 1 |
f26481e17e7159c0c1ec4d349b75a06c4b8ae204 | [
"payload = {'resource_path': resource_path, 'alias': alias}\nendpoint = url_path_join(LINKS_RESOURCE_URL, self.owner)\nr = self.request('post', endpoint, payload=payload)\nself.check_and_raise(r)\ndata = self.get_json(r)\nreturn data['resource_link']",
"endpoint = url_path_join(LINKS_RESOURCE_URL, self.owner)\nr ... | <|body_start_0|>
payload = {'resource_path': resource_path, 'alias': alias}
endpoint = url_path_join(LINKS_RESOURCE_URL, self.owner)
r = self.request('post', endpoint, payload=payload)
self.check_and_raise(r)
data = self.get_json(r)
return data['resource_link']
<|end_body... | LinksClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinksClient:
def create_link(self, resource_path, alias):
"""Create a soft link to a resource. Keyword arguments: resource_path -- a single file or a directory, relative path alias -- name of the symlink to be created, pointing to resource_path Returns: a dictionary with the following ke... | stack_v2_sparse_classes_36k_train_034348 | 2,623 | no_license | [
{
"docstring": "Create a soft link to a resource. Keyword arguments: resource_path -- a single file or a directory, relative path alias -- name of the symlink to be created, pointing to resource_path Returns: a dictionary with the following keys: \"resource_path\" (path of the created link), \"alias\" (alias of... | 4 | stack_v2_sparse_classes_30k_train_019109 | Implement the Python class `LinksClient` described below.
Class description:
Implement the LinksClient class.
Method signatures and docstrings:
- def create_link(self, resource_path, alias): Create a soft link to a resource. Keyword arguments: resource_path -- a single file or a directory, relative path alias -- name... | Implement the Python class `LinksClient` described below.
Class description:
Implement the LinksClient class.
Method signatures and docstrings:
- def create_link(self, resource_path, alias): Create a soft link to a resource. Keyword arguments: resource_path -- a single file or a directory, relative path alias -- name... | 3aa64414c47534534bc6063185e3e6692a97e8a5 | <|skeleton|>
class LinksClient:
def create_link(self, resource_path, alias):
"""Create a soft link to a resource. Keyword arguments: resource_path -- a single file or a directory, relative path alias -- name of the symlink to be created, pointing to resource_path Returns: a dictionary with the following ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinksClient:
def create_link(self, resource_path, alias):
"""Create a soft link to a resource. Keyword arguments: resource_path -- a single file or a directory, relative path alias -- name of the symlink to be created, pointing to resource_path Returns: a dictionary with the following keys: "resource_... | the_stack_v2_python_sparse | env/Lib/site-packages/spell/api/links_client.py | Kendubu1/NLP-Flask-Website | train | 0 | |
acc865a3a0ec80a751079a782dea10b74220cf4d | [
"kwargs.setdefault('max_length', 1000)\nsuper().__init__(*args, **kwargs)\nself.validators.append(link_validator)",
"super().contribute_to_class(cls, name)\n\ndef get_XXX_resolved(self):\n link = getattr(self, name, '')\n if link:\n try:\n link = resolve_link(link)\n except LinkReso... | <|body_start_0|>
kwargs.setdefault('max_length', 1000)
super().__init__(*args, **kwargs)
self.validators.append(link_validator)
<|end_body_0|>
<|body_start_1|>
super().contribute_to_class(cls, name)
def get_XXX_resolved(self):
link = getattr(self, name, '')
... | A field that contains an internal or external link. | LinkField | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkField:
"""A field that contains an internal or external link."""
def __init__(self, *args, **kwargs):
"""Initializes the LinkField."""
<|body_0|>
def contribute_to_class(self, cls, name):
"""Adds in an accessor for the resolved link."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_034349 | 2,581 | permissive | [
{
"docstring": "Initializes the LinkField.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Adds in an accessor for the resolved link.",
"name": "contribute_to_class",
"signature": "def contribute_to_class(self, cls, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013151 | Implement the Python class `LinkField` described below.
Class description:
A field that contains an internal or external link.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the LinkField.
- def contribute_to_class(self, cls, name): Adds in an accessor for the resolved link. | Implement the Python class `LinkField` described below.
Class description:
A field that contains an internal or external link.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the LinkField.
- def contribute_to_class(self, cls, name): Adds in an accessor for the resolved link.
<|s... | 23ab6216e2580bd9b91dbf5c087973bce98f6b5e | <|skeleton|>
class LinkField:
"""A field that contains an internal or external link."""
def __init__(self, *args, **kwargs):
"""Initializes the LinkField."""
<|body_0|>
def contribute_to_class(self, cls, name):
"""Adds in an accessor for the resolved link."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkField:
"""A field that contains an internal or external link."""
def __init__(self, *args, **kwargs):
"""Initializes the LinkField."""
kwargs.setdefault('max_length', 1000)
super().__init__(*args, **kwargs)
self.validators.append(link_validator)
def contribute_to_... | the_stack_v2_python_sparse | cms/models/fields.py | onespacemedia/cms | train | 13 |
7078778ad392c891856029547eea3ae920d2b953 | [
"errors: dict = {}\nif user_input is None:\n return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_SCHEMA, errors=errors)\ntry:\n info = await validate_input(self.hass, user_input)\nexcept DeviceNotFound:\n errors['base'] = 'cannot_connect'\nexcept Exception:\n _LOGGER.exception('Unexpe... | <|body_start_0|>
errors: dict = {}
if user_input is None:
return self.async_show_form(step_id='user', data_schema=STEP_USER_DATA_SCHEMA, errors=errors)
try:
info = await validate_input(self.hass, user_input)
except DeviceNotFound:
errors['base'] = 'can... | Handle a config flow for devolo Home Network. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for devolo Home Network."""
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle the initial step."""
<|body_0|>
async def async_step_zeroconf(self, discovery_info: zeroconf.ZeroconfServiceIn... | stack_v2_sparse_classes_36k_train_034350 | 5,348 | permissive | [
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult"
},
{
"docstring": "Handle zeroconf discovery.",
"name": "async_step_zeroconf",
"signature": "async def async_step_zer... | 5 | null | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for devolo Home Network.
Method signatures and docstrings:
- async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step.
- async def async_step_zeroconf(self, discovery_... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for devolo Home Network.
Method signatures and docstrings:
- async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step.
- async def async_step_zeroconf(self, discovery_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for devolo Home Network."""
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle the initial step."""
<|body_0|>
async def async_step_zeroconf(self, discovery_info: zeroconf.ZeroconfServiceIn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle a config flow for devolo Home Network."""
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle the initial step."""
errors: dict = {}
if user_input is None:
return self.async_show_form(step_id='user', da... | the_stack_v2_python_sparse | homeassistant/components/devolo_home_network/config_flow.py | home-assistant/core | train | 35,501 |
3f3fc88d845948a9a5a8b18518fab01e5bfbca6f | [
"super().__init__(log_root=log_root)\nlog = self.log\nlog.debug(f'In {__name__}')\nself.config = config\nself.out = out\nself.csv = csv\nself.generate_config(get_element)\nself.write_csv()",
"log = self.log\nnew_config: Dict = {}\nfor section in ['Parameter', 'Dimension', 'Paths', 'Model']:\n new_config[sectio... | <|body_start_0|>
super().__init__(log_root=log_root)
log = self.log
log.debug(f'In {__name__}')
self.config = config
self.out = out
self.csv = csv
self.generate_config(get_element)
self.write_csv()
<|end_body_0|>
<|body_start_1|>
log = self.log
... | Creates an output object. Supply a callback that provides each model element in turn since we we cannot pass it. For while mutual import fails so instead we need a callback so that output and run through all the elements of model. http://effbot.org/pyfaq/how-can-i-have-modules-that-mutually-import-each-other.htm | Output | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Output:
"""Creates an output object. Supply a callback that provides each model element in turn since we we cannot pass it. For while mutual import fails so instead we need a callback so that output and run through all the elements of model. http://effbot.org/pyfaq/how-can-i-have-modules-that-mut... | stack_v2_sparse_classes_36k_train_034351 | 2,525 | no_license | [
{
"docstring": "Do the initializing. Generate the config files",
"name": "__init__",
"signature": "def __init__(self, get_element: Callable, config: confuse.Configuration, log_root: Log=None, out: str=None, csv: str=None)"
},
{
"docstring": "Generate a new config yaml.",
"name": "generate_co... | 4 | stack_v2_sparse_classes_30k_train_000522 | Implement the Python class `Output` described below.
Class description:
Creates an output object. Supply a callback that provides each model element in turn since we we cannot pass it. For while mutual import fails so instead we need a callback so that output and run through all the elements of model. http://effbot.or... | Implement the Python class `Output` described below.
Class description:
Creates an output object. Supply a callback that provides each model element in turn since we we cannot pass it. For while mutual import fails so instead we need a callback so that output and run through all the elements of model. http://effbot.or... | 93b0ddddd872f953feec46025aef80a990e6bbeb | <|skeleton|>
class Output:
"""Creates an output object. Supply a callback that provides each model element in turn since we we cannot pass it. For while mutual import fails so instead we need a callback so that output and run through all the elements of model. http://effbot.org/pyfaq/how-can-i-have-modules-that-mut... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Output:
"""Creates an output object. Supply a callback that provides each model element in turn since we we cannot pass it. For while mutual import fails so instead we need a callback so that output and run through all the elements of model. http://effbot.org/pyfaq/how-can-i-have-modules-that-mutually-import-... | the_stack_v2_python_sparse | restart/output.py | dcaseykc/restart | train | 0 |
5ffc959115321fbbab316a6d3398e0f8118ef98c | [
"source_cnt, target_cnt = (Counter(nums), Counter(target))\nif source_cnt == target_cnt:\n return 0\nret = 0\nsource_list, target_list = (sorted(source_cnt.keys()), sorted(target_cnt, reverse=True))\nodd, even = ([], [])\nfor num in source_list:\n if num & 1:\n odd.append(num)\n else:\n even.... | <|body_start_0|>
source_cnt, target_cnt = (Counter(nums), Counter(target))
if source_cnt == target_cnt:
return 0
ret = 0
source_list, target_list = (sorted(source_cnt.keys()), sorted(target_cnt, reverse=True))
odd, even = ([], [])
for num in source_list:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def makeSimilar(self, nums: List[int], target: List[int]) -> int:
"""Runtime: 1406 ms, faster than 75.00% Memory Usage: 43.1 MB, less than 8.33% n == nums.length == target.length 1 <= n <= 10^5 1 <= nums[i], target[i] <= 10^6 It is possible to make nums similar to target."""
... | stack_v2_sparse_classes_36k_train_034352 | 2,434 | permissive | [
{
"docstring": "Runtime: 1406 ms, faster than 75.00% Memory Usage: 43.1 MB, less than 8.33% n == nums.length == target.length 1 <= n <= 10^5 1 <= nums[i], target[i] <= 10^6 It is possible to make nums similar to target.",
"name": "makeSimilar",
"signature": "def makeSimilar(self, nums: List[int], target... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeSimilar(self, nums: List[int], target: List[int]) -> int: Runtime: 1406 ms, faster than 75.00% Memory Usage: 43.1 MB, less than 8.33% n == nums.length == target.length 1 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makeSimilar(self, nums: List[int], target: List[int]) -> int: Runtime: 1406 ms, faster than 75.00% Memory Usage: 43.1 MB, less than 8.33% n == nums.length == target.length 1 ... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def makeSimilar(self, nums: List[int], target: List[int]) -> int:
"""Runtime: 1406 ms, faster than 75.00% Memory Usage: 43.1 MB, less than 8.33% n == nums.length == target.length 1 <= n <= 10^5 1 <= nums[i], target[i] <= 10^6 It is possible to make nums similar to target."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def makeSimilar(self, nums: List[int], target: List[int]) -> int:
"""Runtime: 1406 ms, faster than 75.00% Memory Usage: 43.1 MB, less than 8.33% n == nums.length == target.length 1 <= n <= 10^5 1 <= nums[i], target[i] <= 10^6 It is possible to make nums similar to target."""
source_c... | the_stack_v2_python_sparse | src/2449-MinimumNumberOfOperationsToMakeArraysSimilar.py | Jiezhi/myleetcode | train | 1 | |
9487d5b97337717032a17dc1528f74a871178691 | [
"l = len(nums)\nremove_nums = []\nfor i in range(len(nums)):\n if i > 0 and nums[i] == nums[i - 1]:\n l -= 1\n remove_nums.append(nums[i])\nfor i in remove_nums:\n nums.remove(i)\nreturn l",
"i1, i2 = (0, 1)\nwhile i2 < len(nums):\n if nums[i1] == nums[i2]:\n nums.pop(i2)\n else:\... | <|body_start_0|>
l = len(nums)
remove_nums = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
l -= 1
remove_nums.append(nums[i])
for i in remove_nums:
nums.remove(i)
return l
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates1(self, nums):
""":type nums: List[int] :rtype: int # 暴力求解"""
<|body_0|>
def removeDuplicates2(self, nums):
"""双指针 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = len(nums)
remove_nums ... | stack_v2_sparse_classes_36k_train_034353 | 2,441 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int # 暴力求解",
"name": "removeDuplicates1",
"signature": "def removeDuplicates1(self, nums)"
},
{
"docstring": "双指针 :param nums: :return:",
"name": "removeDuplicates2",
"signature": "def removeDuplicates2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005661 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates1(self, nums): :type nums: List[int] :rtype: int # 暴力求解
- def removeDuplicates2(self, nums): 双指针 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates1(self, nums): :type nums: List[int] :rtype: int # 暴力求解
- def removeDuplicates2(self, nums): 双指针 :param nums: :return:
<|skeleton|>
class Solution:
def ... | 60e9ef1051a1d0441ab1c5484a51ab77a306bf5b | <|skeleton|>
class Solution:
def removeDuplicates1(self, nums):
""":type nums: List[int] :rtype: int # 暴力求解"""
<|body_0|>
def removeDuplicates2(self, nums):
"""双指针 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates1(self, nums):
""":type nums: List[int] :rtype: int # 暴力求解"""
l = len(nums)
remove_nums = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
l -= 1
remove_nums.append(nums[i])
for ... | the_stack_v2_python_sparse | Week 1/id_040/LeetCode_26_040.py | chenlei65368/algorithm004-05 | train | 1 | |
ae27651030ffafda2ce526a54c26b95238f148eb | [
"self.item_freq = fi\nself.item_values = pv\nself.target = Select(fi)\nself.impulse = np.argsort(np.random.random(len(fi)))[:3]\nwhile self.target in self.impulse:\n self.impulse = np.argsort(np.random.random(len(fi)))[:3]",
"spent = 0.0\nfor p in products:\n if p == self.target:\n spent += self.item... | <|body_start_0|>
self.item_freq = fi
self.item_values = pv
self.target = Select(fi)
self.impulse = np.argsort(np.random.random(len(fi)))[:3]
while self.target in self.impulse:
self.impulse = np.argsort(np.random.random(len(fi)))[:3]
<|end_body_0|>
<|body_start_1|>
... | Represent a single shopper | Shopper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shopper:
"""Represent a single shopper"""
def __init__(self, fi, pv):
"""Constructor"""
<|body_0|>
def GoShopping(self, products):
"""Go shopping and return the amount spent"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.item_freq = fi
... | stack_v2_sparse_classes_36k_train_034354 | 6,050 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, fi, pv)"
},
{
"docstring": "Go shopping and return the amount spent",
"name": "GoShopping",
"signature": "def GoShopping(self, products)"
}
] | 2 | null | Implement the Python class `Shopper` described below.
Class description:
Represent a single shopper
Method signatures and docstrings:
- def __init__(self, fi, pv): Constructor
- def GoShopping(self, products): Go shopping and return the amount spent | Implement the Python class `Shopper` described below.
Class description:
Represent a single shopper
Method signatures and docstrings:
- def __init__(self, fi, pv): Constructor
- def GoShopping(self, products): Go shopping and return the amount spent
<|skeleton|>
class Shopper:
"""Represent a single shopper"""
... | 5445b6f90ab49339ca0fdb71e98d44e6827c95a8 | <|skeleton|>
class Shopper:
"""Represent a single shopper"""
def __init__(self, fi, pv):
"""Constructor"""
<|body_0|>
def GoShopping(self, products):
"""Go shopping and return the amount spent"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shopper:
"""Represent a single shopper"""
def __init__(self, fi, pv):
"""Constructor"""
self.item_freq = fi
self.item_values = pv
self.target = Select(fi)
self.impulse = np.argsort(np.random.random(len(fi)))[:3]
while self.target in self.impulse:
... | the_stack_v2_python_sparse | store/store.py | dayoladejo/SwarmOptimization | train | 0 |
d8511d383996cf7221d95f5083db567872bd5bf4 | [
"n = len(arr)\nans = 0\nMOD = 10 ** 9 + 7\nm = {}\nfor i in range(n - 1):\n for j in range(i + 1, n):\n if target - arr[j] - arr[i] in m:\n ans += m[target - arr[j] - arr[i]]\n m[arr[i]] = m.setdefault(arr[i], 0) + 1\nreturn ans % MOD",
"n = len(arr)\narr.sort()\nans = 0\nMOD = 10 ** 9 + 7... | <|body_start_0|>
n = len(arr)
ans = 0
MOD = 10 ** 9 + 7
m = {}
for i in range(n - 1):
for j in range(i + 1, n):
if target - arr[j] - arr[i] in m:
ans += m[target - arr[j] - arr[i]]
m[arr[i]] = m.setdefault(arr[i], 0) + 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSumMulti(self, arr, target):
""":type arr: List[int] :type target: int :rtype: int"""
<|body_0|>
def threeSumMultiTwoPointers(self, arr, target):
""":type arr: List[int] :type target: int :rtype: int"""
<|body_1|>
def threeSumMultiUsin... | stack_v2_sparse_classes_36k_train_034355 | 3,256 | no_license | [
{
"docstring": ":type arr: List[int] :type target: int :rtype: int",
"name": "threeSumMulti",
"signature": "def threeSumMulti(self, arr, target)"
},
{
"docstring": ":type arr: List[int] :type target: int :rtype: int",
"name": "threeSumMultiTwoPointers",
"signature": "def threeSumMultiTwo... | 3 | stack_v2_sparse_classes_30k_train_020361 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumMulti(self, arr, target): :type arr: List[int] :type target: int :rtype: int
- def threeSumMultiTwoPointers(self, arr, target): :type arr: List[int] :type target: int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumMulti(self, arr, target): :type arr: List[int] :type target: int :rtype: int
- def threeSumMultiTwoPointers(self, arr, target): :type arr: List[int] :type target: int... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def threeSumMulti(self, arr, target):
""":type arr: List[int] :type target: int :rtype: int"""
<|body_0|>
def threeSumMultiTwoPointers(self, arr, target):
""":type arr: List[int] :type target: int :rtype: int"""
<|body_1|>
def threeSumMultiUsin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSumMulti(self, arr, target):
""":type arr: List[int] :type target: int :rtype: int"""
n = len(arr)
ans = 0
MOD = 10 ** 9 + 7
m = {}
for i in range(n - 1):
for j in range(i + 1, n):
if target - arr[j] - arr[i] in m:
... | the_stack_v2_python_sparse | 3/3SumWithMultiplicity.py | bssrdf/pyleet | train | 2 | |
0739f4322856affff3ddd86bebaec1f11caa1bc7 | [
"extent_raw_geom = obj['extent']\nif extent_raw_geom is not None:\n extent_geometry = GEOSGeometry(extent_raw_geom)\n return extent_geometry.extent\nreturn None",
"ret = super().to_representation(instance)\nret['id'] = instance['aquifer_id']\nret['name'] = instance['aquifer_name']\nif instance['area']:\n ... | <|body_start_0|>
extent_raw_geom = obj['extent']
if extent_raw_geom is not None:
extent_geometry = GEOSGeometry(extent_raw_geom)
return extent_geometry.extent
return None
<|end_body_0|>
<|body_start_1|>
ret = super().to_representation(instance)
ret['id'] ... | Serialize an aquifer list | AquiferSerializerV2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AquiferSerializerV2:
"""Serialize an aquifer list"""
def get_extent(self, obj):
"""Gets a GeoJSON extent"""
<|body_0|>
def to_representation(self, instance):
"""Rather the declare serializer fields, we must reference them here because they are queried as a `dict`... | stack_v2_sparse_classes_36k_train_034356 | 12,484 | permissive | [
{
"docstring": "Gets a GeoJSON extent",
"name": "get_extent",
"signature": "def get_extent(self, obj)"
},
{
"docstring": "Rather the declare serializer fields, we must reference them here because they are queried as a `dict`, which dramatically improves performance due to the high number of join... | 2 | stack_v2_sparse_classes_30k_train_018501 | Implement the Python class `AquiferSerializerV2` described below.
Class description:
Serialize an aquifer list
Method signatures and docstrings:
- def get_extent(self, obj): Gets a GeoJSON extent
- def to_representation(self, instance): Rather the declare serializer fields, we must reference them here because they ar... | Implement the Python class `AquiferSerializerV2` described below.
Class description:
Serialize an aquifer list
Method signatures and docstrings:
- def get_extent(self, obj): Gets a GeoJSON extent
- def to_representation(self, instance): Rather the declare serializer fields, we must reference them here because they ar... | 6be3701a8e0085d0c6fa199b2672b7f9f1266a03 | <|skeleton|>
class AquiferSerializerV2:
"""Serialize an aquifer list"""
def get_extent(self, obj):
"""Gets a GeoJSON extent"""
<|body_0|>
def to_representation(self, instance):
"""Rather the declare serializer fields, we must reference them here because they are queried as a `dict`... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AquiferSerializerV2:
"""Serialize an aquifer list"""
def get_extent(self, obj):
"""Gets a GeoJSON extent"""
extent_raw_geom = obj['extent']
if extent_raw_geom is not None:
extent_geometry = GEOSGeometry(extent_raw_geom)
return extent_geometry.extent
... | the_stack_v2_python_sparse | app/backend/aquifers/serializers_v2.py | bcgov/gwells | train | 39 |
a7af196c40923c3f22ed2facd7df2162b85ffe15 | [
"super().__init__()\nself.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1)\nself.conv2 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1)\nself.relu = nn.ReLU(inplace=True)",
"out = self.relu(x)\nout = self.conv1(out)\nout = self.relu(out)\nout = self.conv2(out)\nreturn o... | <|body_start_0|>
super().__init__()
self.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU(inplace=True)
<|end_body_0|>
<|body_start_1|>
out = self.relu(x)
... | Residual convolution module. | ResidualConvUnit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_034357 | 7,931 | permissive | [
{
"docstring": "Init. Args: features (int): number of features",
"name": "__init__",
"signature": "def __init__(self, features)"
},
{
"docstring": "Forward pass. Args: x (tensor): input Returns: tensor: output",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `ResidualConvUnit` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: tensor: output | Implement the Python class `ResidualConvUnit` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: tensor: output
<|skele... | b402610a6f0b382a978e82473b541ea1fc6cf09a | <|skeleton|>
class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResidualConvUnit:
"""Residual convolution module."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
super().__init__()
self.conv1 = nn.Conv2D(features, features, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2D(features, featur... | the_stack_v2_python_sparse | modules/image/semantic_segmentation/lseg/models/scratch.py | PaddlePaddle/PaddleHub | train | 12,914 |
ace94eee74d1e597d12c17a09cb675d6899aee62 | [
"self.n = len(nums)\nself.tree = nums + nums\nfor i in range(self.n - 1, 0, -1):\n self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]",
"tree = self.tree\ni += self.n\ntree[i] = val\nwhile i > 0:\n left = right = i\n if i % 2 == 1:\n left -= 1\n else:\n right += 1\n tree[i / 2] = ... | <|body_start_0|>
self.n = len(nums)
self.tree = nums + nums
for i in range(self.n - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
<|end_body_0|>
<|body_start_1|>
tree = self.tree
i += self.n
tree[i] = val
while i > 0:
l... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k_train_034358 | 1,416 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: int",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "sum o... | 3 | stack_v2_sparse_classes_30k_train_004517 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | 036a29d681cc91f2317d454e04530d7375d55478 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.n = len(nums)
self.tree = nums + nums
for i in range(self.n - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def update(self, i, val):
... | the_stack_v2_python_sparse | leetcode/range_sum_query_mutable_v1.py | myliu/python-algorithm | train | 0 | |
3f4e613387c8c936554c09b5c9ef126ccd459886 | [
"d = {}\nfor i, num in enumerate(nums):\n if num in d:\n return [d[num], i]\n d[target - num] = i",
"for i, num in enumerate(nums):\n if target - num in nums[i + 1:]:\n return [i, len(nums) - 1 - nums[::-1].index(target - num)]"
] | <|body_start_0|>
d = {}
for i, num in enumerate(nums):
if num in d:
return [d[num], i]
d[target - num] = i
<|end_body_0|>
<|body_start_1|>
for i, num in enumerate(nums):
if target - num in nums[i + 1:]:
return [i, len(nums) - 1... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""hash table"""
<|body_0|>
def twoSum2(self, nums, target):
"""first try"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = {}
for i, num in enumerate(nums):
if num in d:
... | stack_v2_sparse_classes_36k_train_034359 | 887 | permissive | [
{
"docstring": "hash table",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": "first try",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): hash table
- def twoSum2(self, nums, target): first try | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): hash table
- def twoSum2(self, nums, target): first try
<|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""hash table""... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""hash table"""
<|body_0|>
def twoSum2(self, nums, target):
"""first try"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
"""hash table"""
d = {}
for i, num in enumerate(nums):
if num in d:
return [d[num], i]
d[target - num] = i
def twoSum2(self, nums, target):
"""first try"""
for i, num in enumerate(num... | the_stack_v2_python_sparse | leetcode/0001_two_sum.py | chaosWsF/Python-Practice | train | 1 | |
6713abb09de37e0f79ed7dc0233161525f0f5698 | [
"try:\n data = PolicyManager.get_action_assignments(user_id=user_id, policy_id=uuid, action_id=perimeter_id, category_id=category_id)\nexcept Exception as e:\n LOG.error(e, exc_info=True)\n return ({'result': False, 'error': str(e)}, 500)\nreturn {'action_assignments': data}",
"try:\n data_id = reques... | <|body_start_0|>
try:
data = PolicyManager.get_action_assignments(user_id=user_id, policy_id=uuid, action_id=perimeter_id, category_id=category_id)
except Exception as e:
LOG.error(e, exc_info=True)
return ({'result': False, 'error': str(e)}, 500)
return {'act... | Endpoint for action assignment requests | ActionAssignments | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionAssignments:
"""Endpoint for action assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all action assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid... | stack_v2_sparse_classes_36k_train_034360 | 14,093 | permissive | [
{
"docstring": "Retrieve all action assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid of the action :param category_id: uuid of the action category :param data_id: uuid of the action scope :param user_id: user ID who do the request :return: { \"action_data... | 3 | stack_v2_sparse_classes_30k_train_003009 | Implement the Python class `ActionAssignments` described below.
Class description:
Endpoint for action assignment requests
Method signatures and docstrings:
- def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): Retrieve all action assignment or a specific one for a given policy ... | Implement the Python class `ActionAssignments` described below.
Class description:
Endpoint for action assignment requests
Method signatures and docstrings:
- def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): Retrieve all action assignment or a specific one for a given policy ... | daaba34fa2ed4426bc0fde359e54a5e1b872208c | <|skeleton|>
class ActionAssignments:
"""Endpoint for action assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all action assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionAssignments:
"""Endpoint for action assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all action assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid of the actio... | the_stack_v2_python_sparse | moonv4/moon_manager/moon_manager/api/assignments.py | hashnfv/hashnfv-moon | train | 0 |
2ff57a5f8ed4312dbbe3f742094472ff93e8cb0e | [
"if not nums:\n return False\nfor i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] == nums[j] and abs(j - i) <= k:\n return True\nreturn False",
"record = set()\nfor i, num in enumerate(nums):\n if num in record:\n return True\n record.add(num)\n prin... | <|body_start_0|>
if not nums:
return False
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j] and abs(j - i) <= k:
return True
return False
<|end_body_0|>
<|body_start_1|>
record = set()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_034361 | 1,650 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate2",
"signature": "def contai... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | f022677c042db3598003df1a320a70f0edc4f870 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
if not nums:
return False
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j] and abs(j - i) <= k:
... | the_stack_v2_python_sparse | ArrayDeal/cunzaichongfuyuansu2.py | daisyzl/program-exercise-python | train | 0 | |
affb9f2df666928742fb99fae67a15df05a78f37 | [
"xml_ele = ET.fromstring(serialized_str)\ncls._remove_xml_etree_namespace(xml_ele, Constants.XML_API_NAMESPACE)\ngroups = []\nfor group in xml_ele.findall('security_group'):\n groups.append(SecurityGroup._xml_ele_to_obj(group))\nreturn groups",
"ret = []\njson_dict = json.loads(serialized_str)\ngroups = json_d... | <|body_start_0|>
xml_ele = ET.fromstring(serialized_str)
cls._remove_xml_etree_namespace(xml_ele, Constants.XML_API_NAMESPACE)
groups = []
for group in xml_ele.findall('security_group'):
groups.append(SecurityGroup._xml_ele_to_obj(group))
return groups
<|end_body_0|>
... | SecurityGroups | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityGroups:
def _xml_to_obj(cls, serialized_str):
"""@summary: Returns a list of a SecurityGroup based on the xml serialized_str passed in. @param serialized_str: xml serialized string. @type serialized_str: String. @return: List. @rtype: List."""
<|body_0|>
def _json_to... | stack_v2_sparse_classes_36k_train_034362 | 5,294 | permissive | [
{
"docstring": "@summary: Returns a list of a SecurityGroup based on the xml serialized_str passed in. @param serialized_str: xml serialized string. @type serialized_str: String. @return: List. @rtype: List.",
"name": "_xml_to_obj",
"signature": "def _xml_to_obj(cls, serialized_str)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_014626 | Implement the Python class `SecurityGroups` described below.
Class description:
Implement the SecurityGroups class.
Method signatures and docstrings:
- def _xml_to_obj(cls, serialized_str): @summary: Returns a list of a SecurityGroup based on the xml serialized_str passed in. @param serialized_str: xml serialized str... | Implement the Python class `SecurityGroups` described below.
Class description:
Implement the SecurityGroups class.
Method signatures and docstrings:
- def _xml_to_obj(cls, serialized_str): @summary: Returns a list of a SecurityGroup based on the xml serialized_str passed in. @param serialized_str: xml serialized str... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class SecurityGroups:
def _xml_to_obj(cls, serialized_str):
"""@summary: Returns a list of a SecurityGroup based on the xml serialized_str passed in. @param serialized_str: xml serialized string. @type serialized_str: String. @return: List. @rtype: List."""
<|body_0|>
def _json_to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecurityGroups:
def _xml_to_obj(cls, serialized_str):
"""@summary: Returns a list of a SecurityGroup based on the xml serialized_str passed in. @param serialized_str: xml serialized string. @type serialized_str: String. @return: List. @rtype: List."""
xml_ele = ET.fromstring(serialized_str)
... | the_stack_v2_python_sparse | cloudcafe/compute/extensions/security_groups_api/models/security_group.py | kurhula/cloudcafe | train | 0 | |
eae7ac88e46f75de4c199d987fdaf0a2f82a4945 | [
"object.__init__(self)\nself.where_arguments = (int(obj1[bacula_tools.ID]), obj1.IDTAG, int(obj2[bacula_tools.ID]), obj2.IDTAG)\nself.load()\nreturn",
"if director_type:\n sql = 'SELECT obj_id, obj_type from %s where director_id = %%s and director_type = %%s'\nelse:\n sql = 'SELECT director_id, director_typ... | <|body_start_0|>
object.__init__(self)
self.where_arguments = (int(obj1[bacula_tools.ID]), obj1.IDTAG, int(obj2[bacula_tools.ID]), obj2.IDTAG)
self.load()
return
<|end_body_0|>
<|body_start_1|>
if director_type:
sql = 'SELECT obj_id, obj_type from %s where director_i... | Client resources have passwords associated. This class helps manage that. Instantiate with two objects: a Client/Storage and a Director/Console. | PasswordStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordStore:
"""Client resources have passwords associated. This class helps manage that. Instantiate with two objects: a Client/Storage and a Director/Console."""
def __init__(self, obj1, obj2):
"""Store references to the two objects associated with this password"""
<|body... | stack_v2_sparse_classes_36k_train_034363 | 32,892 | permissive | [
{
"docstring": "Store references to the two objects associated with this password",
"name": "__init__",
"signature": "def __init__(self, obj1, obj2)"
},
{
"docstring": "Find all of the password related to a particular object.",
"name": "Find",
"signature": "def Find(kls, obj, director_ty... | 4 | stack_v2_sparse_classes_30k_train_011753 | Implement the Python class `PasswordStore` described below.
Class description:
Client resources have passwords associated. This class helps manage that. Instantiate with two objects: a Client/Storage and a Director/Console.
Method signatures and docstrings:
- def __init__(self, obj1, obj2): Store references to the tw... | Implement the Python class `PasswordStore` described below.
Class description:
Client resources have passwords associated. This class helps manage that. Instantiate with two objects: a Client/Storage and a Director/Console.
Method signatures and docstrings:
- def __init__(self, obj1, obj2): Store references to the tw... | 026c9403e80edd78f3c9198e97f196d62e81a53a | <|skeleton|>
class PasswordStore:
"""Client resources have passwords associated. This class helps manage that. Instantiate with two objects: a Client/Storage and a Director/Console."""
def __init__(self, obj1, obj2):
"""Store references to the two objects associated with this password"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordStore:
"""Client resources have passwords associated. This class helps manage that. Instantiate with two objects: a Client/Storage and a Director/Console."""
def __init__(self, obj1, obj2):
"""Store references to the two objects associated with this password"""
object.__init__(sel... | the_stack_v2_python_sparse | bacula_tools/util.py | BrianGallew/bacula_configuration | train | 8 |
cbf8ec50e9b5ce6696ff171e776cbc03089f07f5 | [
"self.index = index\nself.id = unicode(index) + 'q' + questionId\nself.question = question\nself.questionId = questionId\nself.option = option\nself.answerId = 'optionAnswer' + unicode(index) + 'q' + questionId\nself.keyId = 'key' + questionId\nself.idevice = idevice",
"log.debug('process ' + repr(request.args))\... | <|body_start_0|>
self.index = index
self.id = unicode(index) + 'q' + questionId
self.question = question
self.questionId = questionId
self.option = option
self.answerId = 'optionAnswer' + unicode(index) + 'q' + questionId
self.keyId = 'key' + questionId
se... | TestOptionElement is responsible for a block of option. Used by TestquestionElement. | TestoptionElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestoptionElement:
"""TestOptionElement is responsible for a block of option. Used by TestquestionElement."""
def __init__(self, index, question, questionId, option, idevice):
"""Initialize"""
<|body_0|>
def process(self, request):
"""Process arguments from the w... | stack_v2_sparse_classes_36k_train_034364 | 2,670 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, index, question, questionId, option, idevice)"
},
{
"docstring": "Process arguments from the web server. Return any which apply to this element.",
"name": "process",
"signature": "def process(self, request)... | 4 | stack_v2_sparse_classes_30k_train_003451 | Implement the Python class `TestoptionElement` described below.
Class description:
TestOptionElement is responsible for a block of option. Used by TestquestionElement.
Method signatures and docstrings:
- def __init__(self, index, question, questionId, option, idevice): Initialize
- def process(self, request): Process... | Implement the Python class `TestoptionElement` described below.
Class description:
TestOptionElement is responsible for a block of option. Used by TestquestionElement.
Method signatures and docstrings:
- def __init__(self, index, question, questionId, option, idevice): Initialize
- def process(self, request): Process... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class TestoptionElement:
"""TestOptionElement is responsible for a block of option. Used by TestquestionElement."""
def __init__(self, index, question, questionId, option, idevice):
"""Initialize"""
<|body_0|>
def process(self, request):
"""Process arguments from the w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestoptionElement:
"""TestOptionElement is responsible for a block of option. Used by TestquestionElement."""
def __init__(self, index, question, questionId, option, idevice):
"""Initialize"""
self.index = index
self.id = unicode(index) + 'q' + questionId
self.question = q... | the_stack_v2_python_sparse | eXe/rev2283-2409/right-branch-2409/exe/idevices/testoptionelement.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
b8d8f360dde40768c170c436ee4ea0a7ae438233 | [
"maxarea = 0\nstk = []\nheights.append(0)\nfor i, h in enumerate(heights):\n while stk and stk[-1] > h:\n i_top = stk.pop()\n maxarea = max(maxarea, heights[i_top] * (i if not stk else i - stk[-1] - 1))\n stk.append(i)\nheights.pop()\nreturn maxarea",
"maxarea = 0\nstk = [-1]\nheights.append(0... | <|body_start_0|>
maxarea = 0
stk = []
heights.append(0)
for i, h in enumerate(heights):
while stk and stk[-1] > h:
i_top = stk.pop()
maxarea = max(maxarea, heights[i_top] * (i if not stk else i - stk[-1] - 1))
stk.append(i)
... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
maxarea = 0
... | stack_v2_sparse_classes_36k_train_034365 | 2,242 | no_license | [
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
},
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea2",
"signature": "def largestRectangleArea2(self, heights)"... | 2 | null | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def largestRectangleArea2(self, heights): :type heights: List[int] :rtype: int | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def largestRectangleArea2(self, heights): :type heights: List[int] :rtype: int
<|skeleton|>
cla... | fa6504cb5145d10952f4615478fa745f4b35ba13 | <|skeleton|>
class Solution2:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution2:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
maxarea = 0
stk = []
heights.append(0)
for i, h in enumerate(heights):
while stk and stk[-1] > h:
i_top = stk.pop()
maxarea = max(m... | the_stack_v2_python_sparse | Algorithms/challenges/lc084_largest_rectangle_in_histogram.py | snowdj/cs_course | train | 0 | |
eae4089a43a2dcbe6b7c68a01ce7d96711c48aba | [
"self.bit = x\nfor i in range(len(x)):\n j = i | i + 1\n if j < len(x):\n x[j] += x[i]",
"while idx < len(self.bit):\n self.bit[idx] += x\n idx |= idx + 1",
"x = 0\nwhile end:\n x += self.bit[end - 1]\n end &= end - 1\nreturn x",
"idx = -1\nfor d in reversed(range(len(self.bit).bit_le... | <|body_start_0|>
self.bit = x
for i in range(len(x)):
j = i | i + 1
if j < len(x):
x[j] += x[i]
<|end_body_0|>
<|body_start_1|>
while idx < len(self.bit):
self.bit[idx] += x
idx |= idx + 1
<|end_body_1|>
<|body_start_2|>
x... | FenwickTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
<|body_0|>
def update(self, idx, x):
"""updates bit[idx] += x"""
<|body_1|>
def query(self, end):
"""calc sum(bit[:end])"""
<|body_2|>
def find_kth_smallest(self, k):
... | stack_v2_sparse_classes_36k_train_034366 | 2,618 | no_license | [
{
"docstring": "transform list into BIT",
"name": "__init__",
"signature": "def __init__(self, x)"
},
{
"docstring": "updates bit[idx] += x",
"name": "update",
"signature": "def update(self, idx, x)"
},
{
"docstring": "calc sum(bit[:end])",
"name": "query",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_007825 | Implement the Python class `FenwickTree` described below.
Class description:
Implement the FenwickTree class.
Method signatures and docstrings:
- def __init__(self, x): transform list into BIT
- def update(self, idx, x): updates bit[idx] += x
- def query(self, end): calc sum(bit[:end])
- def find_kth_smallest(self, k... | Implement the Python class `FenwickTree` described below.
Class description:
Implement the FenwickTree class.
Method signatures and docstrings:
- def __init__(self, x): transform list into BIT
- def update(self, idx, x): updates bit[idx] += x
- def query(self, end): calc sum(bit[:end])
- def find_kth_smallest(self, k... | 57f473ca84735f9312913967e20a3ac0da32baa8 | <|skeleton|>
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
<|body_0|>
def update(self, idx, x):
"""updates bit[idx] += x"""
<|body_1|>
def query(self, end):
"""calc sum(bit[:end])"""
<|body_2|>
def find_kth_smallest(self, k):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
self.bit = x
for i in range(len(x)):
j = i | i + 1
if j < len(x):
x[j] += x[i]
def update(self, idx, x):
"""updates bit[idx] += x"""
while idx < len(self.bit):... | the_stack_v2_python_sparse | codeforces/current/c1354d/task.py | x3mka/code-contests-python | train | 0 | |
95d8e10a5402d86b8f68971096a5a6098ff52214 | [
"from sims4communitylib.utils.sims.common_age_utils import CommonAgeUtils\nif CommonAgeUtils.is_baby(sim_info):\n return CommonAge.BABY\nelif CommonAgeUtils.is_toddler(sim_info):\n return CommonAge.TODDLER\nelif CommonAgeUtils.is_child(sim_info):\n return CommonAge.CHILD\nelif CommonAgeUtils.is_teen(sim_in... | <|body_start_0|>
from sims4communitylib.utils.sims.common_age_utils import CommonAgeUtils
if CommonAgeUtils.is_baby(sim_info):
return CommonAge.BABY
elif CommonAgeUtils.is_toddler(sim_info):
return CommonAge.TODDLER
elif CommonAgeUtils.is_child(sim_info):
... | Custom Age enum containing all ages, because there have been too many problems when referencing the vanilla Age in various places. | CommonAge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonAge:
"""Custom Age enum containing all ages, because there have been too many problems when referencing the vanilla Age in various places."""
def get_age(sim_info: SimInfo) -> 'CommonAge':
"""get_age(sim_info) Retrieve the CommonAge of a Sim. :param sim_info: An instance of a S... | stack_v2_sparse_classes_36k_train_034367 | 3,948 | permissive | [
{
"docstring": "get_age(sim_info) Retrieve the CommonAge of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonAge that represents what age a Sim is or CommonAge.INVALID if their age cannot be determined. :rtype: CommonAge",
"name": "get_age",
"signature": "def get_... | 3 | null | Implement the Python class `CommonAge` described below.
Class description:
Custom Age enum containing all ages, because there have been too many problems when referencing the vanilla Age in various places.
Method signatures and docstrings:
- def get_age(sim_info: SimInfo) -> 'CommonAge': get_age(sim_info) Retrieve th... | Implement the Python class `CommonAge` described below.
Class description:
Custom Age enum containing all ages, because there have been too many problems when referencing the vanilla Age in various places.
Method signatures and docstrings:
- def get_age(sim_info: SimInfo) -> 'CommonAge': get_age(sim_info) Retrieve th... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonAge:
"""Custom Age enum containing all ages, because there have been too many problems when referencing the vanilla Age in various places."""
def get_age(sim_info: SimInfo) -> 'CommonAge':
"""get_age(sim_info) Retrieve the CommonAge of a Sim. :param sim_info: An instance of a S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonAge:
"""Custom Age enum containing all ages, because there have been too many problems when referencing the vanilla Age in various places."""
def get_age(sim_info: SimInfo) -> 'CommonAge':
"""get_age(sim_info) Retrieve the CommonAge of a Sim. :param sim_info: An instance of a Sim. :type sim... | the_stack_v2_python_sparse | src/sims4communitylib/enums/common_age.py | velocist/TS4CheatsInfo | train | 1 |
4cf6b2cf2af79f78d078e16810cd2c856a6c769e | [
"def mid_recur(root):\n nonlocal recorder\n if root:\n if not mid_recur(root.left):\n return False\n if recorder is not None and root.val <= recorder:\n return False\n else:\n recorder = root.val\n if not mid_recur(root.right):\n return F... | <|body_start_0|>
def mid_recur(root):
nonlocal recorder
if root:
if not mid_recur(root.left):
return False
if recorder is not None and root.val <= recorder:
return False
else:
reco... | BSTTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTTree:
def isValidBST(root):
"""98.mid_验证二叉搜索树.py 判断是否合法二叉树(中序遍历,必须是递增序列!)"""
<|body_0|>
def isSameTree(p, q):
"""100.easy_相同的树.py 判断两个树是否完全一样"""
<|body_1|>
def searchBST(root, val):
"""700.easy_二叉搜索树中的搜索.py 在二叉树中搜索某个值 ,若不存在返回None"""
<|... | stack_v2_sparse_classes_36k_train_034368 | 3,601 | no_license | [
{
"docstring": "98.mid_验证二叉搜索树.py 判断是否合法二叉树(中序遍历,必须是递增序列!)",
"name": "isValidBST",
"signature": "def isValidBST(root)"
},
{
"docstring": "100.easy_相同的树.py 判断两个树是否完全一样",
"name": "isSameTree",
"signature": "def isSameTree(p, q)"
},
{
"docstring": "700.easy_二叉搜索树中的搜索.py 在二叉树中搜索某个值 ,... | 5 | stack_v2_sparse_classes_30k_train_005104 | Implement the Python class `BSTTree` described below.
Class description:
Implement the BSTTree class.
Method signatures and docstrings:
- def isValidBST(root): 98.mid_验证二叉搜索树.py 判断是否合法二叉树(中序遍历,必须是递增序列!)
- def isSameTree(p, q): 100.easy_相同的树.py 判断两个树是否完全一样
- def searchBST(root, val): 700.easy_二叉搜索树中的搜索.py 在二叉树中搜索某个值 ,... | Implement the Python class `BSTTree` described below.
Class description:
Implement the BSTTree class.
Method signatures and docstrings:
- def isValidBST(root): 98.mid_验证二叉搜索树.py 判断是否合法二叉树(中序遍历,必须是递增序列!)
- def isSameTree(p, q): 100.easy_相同的树.py 判断两个树是否完全一样
- def searchBST(root, val): 700.easy_二叉搜索树中的搜索.py 在二叉树中搜索某个值 ,... | 576de9b993f7763789d25a995702b40c9bc6fa57 | <|skeleton|>
class BSTTree:
def isValidBST(root):
"""98.mid_验证二叉搜索树.py 判断是否合法二叉树(中序遍历,必须是递增序列!)"""
<|body_0|>
def isSameTree(p, q):
"""100.easy_相同的树.py 判断两个树是否完全一样"""
<|body_1|>
def searchBST(root, val):
"""700.easy_二叉搜索树中的搜索.py 在二叉树中搜索某个值 ,若不存在返回None"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSTTree:
def isValidBST(root):
"""98.mid_验证二叉搜索树.py 判断是否合法二叉树(中序遍历,必须是递增序列!)"""
def mid_recur(root):
nonlocal recorder
if root:
if not mid_recur(root.left):
return False
if recorder is not None and root.val <= recorder... | the_stack_v2_python_sparse | 0.leetcode/3.刷题/1.数据结构系列/2.树形结构/1.二叉查找树/bsttree.py | GMwang550146647/network | train | 0 | |
089fb1df46a34b3bd5e74344f1261c07a33fe870 | [
"if isinstance(cls, six.class_types):\n init = cls.__init__\n\n def wrapped(*args, **kwargs):\n try:\n warp_self = args[0]\n warp_self.df = None\n init(*args, **kwargs)\n symbol = args[1]\n self._gen_warp_df(warp_self, symbol)\n except Excep... | <|body_start_0|>
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
warp_self.df = None
init(*args, **kwargs)
symbol = args[1]
... | 做为类装饰器封装替换解析数据统一操作,装饰替换init | HSDataParseWrap | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HSDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:""... | stack_v2_sparse_classes_36k_train_034369 | 9,806 | permissive | [
{
"docstring": "只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程",
"name": "__call__",
"signature": "def __call__(self, cls)"
},
{
"docstring": "封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:",
"name": "_gen_warp_df",
"signature": "def _gen_warp_df(self, warp_s... | 2 | stack_v2_sparse_classes_30k_train_017777 | Implement the Python class `HSDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的sy... | Implement the Python class `HSDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的sy... | f8841331022e8844537a5c5b08d047e2cc328856 | <|skeleton|>
class HSDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HSDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
... | the_stack_v2_python_sparse | hsstock/service/tx_service.py | hsstock/hsstock | train | 2 |
d9af9ade7ca949b474b107f1120b00e38e2f9c53 | [
"cmd = '{executable} {argstr}'\nif params.get('stdout'):\n cmd += ' >{stdout}'\nif params.get('stderr'):\n cmd += ' 2>{stderr}'\nreturn cmd.format(**params)",
"cmd = self.cmdline(**params)\nif not cmd:\n raise ValueError('No executable')\nparams['cmdline'] = cmd\nself.exec(cmd)"
] | <|body_start_0|>
cmd = '{executable} {argstr}'
if params.get('stdout'):
cmd += ' >{stdout}'
if params.get('stderr'):
cmd += ' 2>{stderr}'
return cmd.format(**params)
<|end_body_0|>
<|body_start_1|>
cmd = self.cmdline(**params)
if not cmd:
... | A DirectRunner runs a program directly. | DirectRunner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectRunner:
"""A DirectRunner runs a program directly."""
def cmdline(self, **params):
"""Build a command line from `executable` and `argstr` and redirect output if `stdout` or `stderr` is given."""
<|body_0|>
def run(self, cmd, **params):
"""Run command built ... | stack_v2_sparse_classes_36k_train_034370 | 13,942 | no_license | [
{
"docstring": "Build a command line from `executable` and `argstr` and redirect output if `stdout` or `stderr` is given.",
"name": "cmdline",
"signature": "def cmdline(self, **params)"
},
{
"docstring": "Run command built from `cmdline()` but first save param set file given by `paramfile` so th... | 2 | stack_v2_sparse_classes_30k_train_020967 | Implement the Python class `DirectRunner` described below.
Class description:
A DirectRunner runs a program directly.
Method signatures and docstrings:
- def cmdline(self, **params): Build a command line from `executable` and `argstr` and redirect output if `stdout` or `stderr` is given.
- def run(self, cmd, **params... | Implement the Python class `DirectRunner` described below.
Class description:
A DirectRunner runs a program directly.
Method signatures and docstrings:
- def cmdline(self, **params): Build a command line from `executable` and `argstr` and redirect output if `stdout` or `stderr` is given.
- def run(self, cmd, **params... | 50bf5ccc9ea9527d4032e0992fb70f598c236d37 | <|skeleton|>
class DirectRunner:
"""A DirectRunner runs a program directly."""
def cmdline(self, **params):
"""Build a command line from `executable` and `argstr` and redirect output if `stdout` or `stderr` is given."""
<|body_0|>
def run(self, cmd, **params):
"""Run command built ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectRunner:
"""A DirectRunner runs a program directly."""
def cmdline(self, **params):
"""Build a command line from `executable` and `argstr` and redirect output if `stdout` or `stderr` is given."""
cmd = '{executable} {argstr}'
if params.get('stdout'):
cmd += ' >{st... | the_stack_v2_python_sparse | femb_python/runpolicy.py | DUNE/femb_python | train | 3 |
ce56b63eb2d8d75c306523c569e343ad3fed1332 | [
"def dfs(node, is_left_branch):\n if node == None:\n return 0\n if node.left == None and node.right == None:\n if is_left_branch:\n return node.val\n else:\n return 0\n else:\n left = dfs(node.left, True)\n right = dfs(node.right, False)\n ret... | <|body_start_0|>
def dfs(node, is_left_branch):
if node == None:
return 0
if node.left == None and node.right == None:
if is_left_branch:
return node.val
else:
return 0
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(node, is_left_branch):
... | stack_v2_sparse_classes_36k_train_034371 | 1,660 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves",
"signature": "def sumOfLeftLeaves(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumOfLeftLeaves",
"signature": "def sumOfLeftLeaves(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
- def sumOfLeftLeaves(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumOf... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumOfLeftLeaves(self, root):
""":type root: TreeNode :rtype: int"""
def dfs(node, is_left_branch):
if node == None:
return 0
if node.left == None and node.right == None:
if is_left_branch:
return node.val... | the_stack_v2_python_sparse | 404-sum_of_left_leaves.py | stevestar888/leetcode-problems | train | 2 | |
9632bd3eb41ac33d43e35e5e9c91a8f52d15d5ff | [
"self.paths_images = paths_images\nself.labels = labels\nself.args = args",
"full_data = list(zip(self.paths_images, self.labels))\nrandom.shuffle(full_data)\nself.paths_images, self.labels = zip(*full_data)\nbatch_im_generator = TrainGenerator(self.paths_images, self.labels, 32, self.args)\nlogging.info(' Model ... | <|body_start_0|>
self.paths_images = paths_images
self.labels = labels
self.args = args
<|end_body_0|>
<|body_start_1|>
full_data = list(zip(self.paths_images, self.labels))
random.shuffle(full_data)
self.paths_images, self.labels = zip(*full_data)
batch_im_gener... | Operate training with the full dataset Methods ------- launching_steps | FullRun | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullRun:
"""Operate training with the full dataset Methods ------- launching_steps"""
def __init__(self, paths_images: list, labels: list, args):
"""Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str) corr... | stack_v2_sparse_classes_36k_train_034372 | 4,620 | no_license | [
{
"docstring": "Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str) corresponding to the images paths args : arguments parser list of user arguments",
"name": "__init__",
"signature": "def __init__(self, paths_images: list, l... | 2 | null | Implement the Python class `FullRun` described below.
Class description:
Operate training with the full dataset Methods ------- launching_steps
Method signatures and docstrings:
- def __init__(self, paths_images: list, labels: list, args): Class initialisation Parameters ---------- paths_images : list list of paths t... | Implement the Python class `FullRun` described below.
Class description:
Operate training with the full dataset Methods ------- launching_steps
Method signatures and docstrings:
- def __init__(self, paths_images: list, labels: list, args): Class initialisation Parameters ---------- paths_images : list list of paths t... | 227641cc02f5c3aef04f3c27cbfc316382041ae0 | <|skeleton|>
class FullRun:
"""Operate training with the full dataset Methods ------- launching_steps"""
def __init__(self, paths_images: list, labels: list, args):
"""Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str) corr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullRun:
"""Operate training with the full dataset Methods ------- launching_steps"""
def __init__(self, paths_images: list, labels: list, args):
"""Class initialisation Parameters ---------- paths_images : list list of paths to selected images labels : list list of labels (str) corresponding to ... | the_stack_v2_python_sparse | yotta_p2/bj-computer-vision/masked_face/domain/run_selection.py | j-bd/various_exs | train | 0 |
5506856d790b0315ee9a2092553d08dae7830412 | [
"self._options = options\nself._preMessage = preMessage\nself._postMessage = postMessage\nself._selected = 0\nself._result = None",
"self._selected = 0\nself._show()\nreturn self._handleKeypresses()",
"combinedUpKeys = Constants.UP_KEYS + Constants.LEFT_KEYS\ncombinedDownKeys = Constants.DOWN_KEYS + Constants.R... | <|body_start_0|>
self._options = options
self._preMessage = preMessage
self._postMessage = postMessage
self._selected = 0
self._result = None
<|end_body_0|>
<|body_start_1|>
self._selected = 0
self._show()
return self._handleKeypresses()
<|end_body_1|>
<... | A menu (list of options) for a terminal interface | TerminalMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TerminalMenu:
"""A menu (list of options) for a terminal interface"""
def __init__(self, options, preMessage=None, postMessage=None):
"""Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) p... | stack_v2_sparse_classes_36k_train_034373 | 7,322 | no_license | [
{
"docstring": "Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) postMessage -- the message to show below the menu (optional)",
"name": "__init__",
"signature": "def __init__(self, options, preMessage=None, ... | 5 | stack_v2_sparse_classes_30k_train_021089 | Implement the Python class `TerminalMenu` described below.
Class description:
A menu (list of options) for a terminal interface
Method signatures and docstrings:
- def __init__(self, options, preMessage=None, postMessage=None): Arguments: options -- the options the user can choose from as a collection of strings preM... | Implement the Python class `TerminalMenu` described below.
Class description:
A menu (list of options) for a terminal interface
Method signatures and docstrings:
- def __init__(self, options, preMessage=None, postMessage=None): Arguments: options -- the options the user can choose from as a collection of strings preM... | 46b7e084234227f925a24ea2eb41ed5d9ac14b7a | <|skeleton|>
class TerminalMenu:
"""A menu (list of options) for a terminal interface"""
def __init__(self, options, preMessage=None, postMessage=None):
"""Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TerminalMenu:
"""A menu (list of options) for a terminal interface"""
def __init__(self, options, preMessage=None, postMessage=None):
"""Arguments: options -- the options the user can choose from as a collection of strings preMessage -- the message to show above the menu (optional) postMessage --... | the_stack_v2_python_sparse | Source/TerminalMenu.py | csahmad/291-Mini-Project-1 | train | 0 |
d85591ecfb44339c6069d32396bda9e7ff54ef1a | [
"if 'formatter' not in overrides:\n overrides['formatter'] = TimeFormatter(rounding=ROUNDING.HALFUP)\nsuper().__init__(**overrides)",
"start, end = (self.start, self.end)\ndomain = abs(end - start)\nmajor_step = self.major_step\nif major_step is UNDEF:\n major_step = self._calc_step(domain, self.major_count... | <|body_start_0|>
if 'formatter' not in overrides:
overrides['formatter'] = TimeFormatter(rounding=ROUNDING.HALFUP)
super().__init__(**overrides)
<|end_body_0|>
<|body_start_1|>
start, end = (self.start, self.end)
domain = abs(end - start)
major_step = self.major_step... | This type of ticker generates nice looking ticks and labels for time data assuming all given data are in seconds. The major and the minor steps are calculated automatically according to current range, however, both can be specified if needed. The label 'formatter' is by default set to pero.TimeFormatter, but can be cha... | TimeTicker | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeTicker:
"""This type of ticker generates nice looking ticks and labels for time data assuming all given data are in seconds. The major and the minor steps are calculated automatically according to current range, however, both can be specified if needed. The label 'formatter' is by default set... | stack_v2_sparse_classes_36k_train_034374 | 4,476 | permissive | [
{
"docstring": "Initializes a new instance of TimeTicker.",
"name": "__init__",
"signature": "def __init__(self, **overrides)"
},
{
"docstring": "Generates ticks according to current settings. Returns: (float,), (float,) Generated major and minor ticks.",
"name": "make_ticks",
"signature... | 4 | stack_v2_sparse_classes_30k_train_014713 | Implement the Python class `TimeTicker` described below.
Class description:
This type of ticker generates nice looking ticks and labels for time data assuming all given data are in seconds. The major and the minor steps are calculated automatically according to current range, however, both can be specified if needed. ... | Implement the Python class `TimeTicker` described below.
Class description:
This type of ticker generates nice looking ticks and labels for time data assuming all given data are in seconds. The major and the minor steps are calculated automatically according to current range, however, both can be specified if needed. ... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class TimeTicker:
"""This type of ticker generates nice looking ticks and labels for time data assuming all given data are in seconds. The major and the minor steps are calculated automatically according to current range, however, both can be specified if needed. The label 'formatter' is by default set... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeTicker:
"""This type of ticker generates nice looking ticks and labels for time data assuming all given data are in seconds. The major and the minor steps are calculated automatically according to current range, however, both can be specified if needed. The label 'formatter' is by default set to pero.Time... | the_stack_v2_python_sparse | pero/tickers/timed.py | xxao/pero | train | 31 |
ad8081c71254dbe7cc8f30c7de420865a1b38c87 | [
"matrix.reverse()\nfor i in range(len(matrix)):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])",
"low, high = (0, len(matrix) - 1)\nwhile low < high:\n for i in range(low, high):\n matrix[low][i], matrix[i][high] = (matrix[i][high], matrix[low][i])\n ma... | <|body_start_0|>
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
<|end_body_0|>
<|body_start_1|>
low, high = (0, len(matrix) - 1)
while low < high:
for i in range(low, high... | RotateImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotateImage:
def rotate(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate2(self, matrix: 'List[List[int]]') -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body... | stack_v2_sparse_classes_36k_train_034375 | 899 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotate2",
"signature": "def rotate2(self, mat... | 2 | null | Implement the Python class `RotateImage` described below.
Class description:
Implement the RotateImage class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def rotate2(self, matrix: 'List[List[int]]') -> None: Do not re... | Implement the Python class `RotateImage` described below.
Class description:
Implement the RotateImage class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def rotate2(self, matrix: 'List[List[int]]') -> None: Do not re... | e7f486114df17918e49d6452c7047c9d90e8aef2 | <|skeleton|>
class RotateImage:
def rotate(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate2(self, matrix: 'List[List[int]]') -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RotateImage:
def rotate(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
def ... | the_stack_v2_python_sparse | tranquil-beach/arrays_strings/rotate_image.py | yokolet/tranquil-beach-python | train | 0 | |
bd723686feb9e1dbfee3b2dc61244ec117c43a2c | [
"PROVIDER_ID = kwargs.get('id')\nCONTRACT_ADDRESS = 'address'\nprovider = providerModel.ProviderModel.get_by_id(self.db.session, PROVIDER_ID)\nif not provider:\n raise HTTPNotFound(description='Entry not found', code=5)\npricingContract_list = pricingContractModel.PricingContractModel.get_generic(self.db.session... | <|body_start_0|>
PROVIDER_ID = kwargs.get('id')
CONTRACT_ADDRESS = 'address'
provider = providerModel.ProviderModel.get_by_id(self.db.session, PROVIDER_ID)
if not provider:
raise HTTPNotFound(description='Entry not found', code=5)
pricingContract_list = pricingContrac... | API Resource to set and get prices for each provider. This resource exposes an Option, GET, PATCH methods. This converts contracts data into/from DB models. All methods translate keystone URI to internal URI. | PriceRateResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceRateResource:
"""API Resource to set and get prices for each provider. This resource exposes an Option, GET, PATCH methods. This converts contracts data into/from DB models. All methods translate keystone URI to internal URI."""
def on_get(self, req, resp, **kwargs):
"""Get rate... | stack_v2_sparse_classes_36k_train_034376 | 6,049 | permissive | [
{
"docstring": "Get rate of provider's id --- summary: Fetches a rate practiced by provider's ID description: Endpoint that retrieves rate parameters: - in: path name: id description: id of provider schema: type: integer tags: - price_rate responses: 200: description: OK 404: description: Not found",
"name"... | 2 | stack_v2_sparse_classes_30k_train_002317 | Implement the Python class `PriceRateResource` described below.
Class description:
API Resource to set and get prices for each provider. This resource exposes an Option, GET, PATCH methods. This converts contracts data into/from DB models. All methods translate keystone URI to internal URI.
Method signatures and docs... | Implement the Python class `PriceRateResource` described below.
Class description:
API Resource to set and get prices for each provider. This resource exposes an Option, GET, PATCH methods. This converts contracts data into/from DB models. All methods translate keystone URI to internal URI.
Method signatures and docs... | e2c74c36d5eb8492764205fe99558b0818473cb7 | <|skeleton|>
class PriceRateResource:
"""API Resource to set and get prices for each provider. This resource exposes an Option, GET, PATCH methods. This converts contracts data into/from DB models. All methods translate keystone URI to internal URI."""
def on_get(self, req, resp, **kwargs):
"""Get rate... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriceRateResource:
"""API Resource to set and get prices for each provider. This resource exposes an Option, GET, PATCH methods. This converts contracts data into/from DB models. All methods translate keystone URI to internal URI."""
def on_get(self, req, resp, **kwargs):
"""Get rate of provider'... | the_stack_v2_python_sparse | mobility-service-provider---service/msp/resources/pricerate.py | vicinityh2020/vicinity-vas-dreven | train | 0 |
f22429484a731bfe74b2f57634f10f7ed7eb4cb0 | [
"self.http = http\nself.srp = auth_handler\nself._atv_salt = None\nself._atv_pub_key = None",
"self.srp.initialize()\nawait self.http.post('/pair-pin-start', headers=_AIRPLAY_HEADERS)\ndata = {hap_tlv8.TlvValue.Method: b'\\x00', hap_tlv8.TlvValue.SeqNo: b'\\x01'}\nresp = await self.http.post('/pair-setup', body=h... | <|body_start_0|>
self.http = http
self.srp = auth_handler
self._atv_salt = None
self._atv_pub_key = None
<|end_body_0|>
<|body_start_1|>
self.srp.initialize()
await self.http.post('/pair-pin-start', headers=_AIRPLAY_HEADERS)
data = {hap_tlv8.TlvValue.Method: b'\x... | Authenticate a device for AirPlay playback. | AirPlayHapPairSetupProcedure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirPlayHapPairSetupProcedure:
"""Authenticate a device for AirPlay playback."""
def __init__(self, http: HttpConnection, auth_handler: SRPAuthHandler):
"""Initialize a new DeviceAuthenticator."""
<|body_0|>
async def start_pairing(self) -> None:
"""Start the auth... | stack_v2_sparse_classes_36k_train_034377 | 4,929 | permissive | [
{
"docstring": "Initialize a new DeviceAuthenticator.",
"name": "__init__",
"signature": "def __init__(self, http: HttpConnection, auth_handler: SRPAuthHandler)"
},
{
"docstring": "Start the authentication process. This method will show the expected PIN on screen.",
"name": "start_pairing",
... | 3 | stack_v2_sparse_classes_30k_train_011728 | Implement the Python class `AirPlayHapPairSetupProcedure` described below.
Class description:
Authenticate a device for AirPlay playback.
Method signatures and docstrings:
- def __init__(self, http: HttpConnection, auth_handler: SRPAuthHandler): Initialize a new DeviceAuthenticator.
- async def start_pairing(self) ->... | Implement the Python class `AirPlayHapPairSetupProcedure` described below.
Class description:
Authenticate a device for AirPlay playback.
Method signatures and docstrings:
- def __init__(self, http: HttpConnection, auth_handler: SRPAuthHandler): Initialize a new DeviceAuthenticator.
- async def start_pairing(self) ->... | 05ca46d2a8bbc8e725ad63794d14b2d1fb9913fa | <|skeleton|>
class AirPlayHapPairSetupProcedure:
"""Authenticate a device for AirPlay playback."""
def __init__(self, http: HttpConnection, auth_handler: SRPAuthHandler):
"""Initialize a new DeviceAuthenticator."""
<|body_0|>
async def start_pairing(self) -> None:
"""Start the auth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AirPlayHapPairSetupProcedure:
"""Authenticate a device for AirPlay playback."""
def __init__(self, http: HttpConnection, auth_handler: SRPAuthHandler):
"""Initialize a new DeviceAuthenticator."""
self.http = http
self.srp = auth_handler
self._atv_salt = None
self._... | the_stack_v2_python_sparse | pyatv/protocols/airplay/auth/hap.py | postlund/pyatv | train | 749 |
d5b373d174cf734feb92cb9706b8d3e661712219 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), is_active=is_active)\nuser.set_password(password)\nuser.save()\nreturn user",
"user = self.create_user(email, password=password)\nuser.is_staff = True\nuser.is_superuser = True\nuser.save... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), is_active=is_active)
user.set_password(password)
user.save()
return user
<|end_body_0|>
<|body_start_1|>
user = self.creat... | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
def create_user(self, email, password=None, is_active=False):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a superuser with the given e... | stack_v2_sparse_classes_36k_train_034378 | 5,775 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, password=None, is_active=False)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
... | 2 | stack_v2_sparse_classes_30k_train_009835 | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, is_active=False): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(... | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None, is_active=False): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(... | adf1f06027404cc3596b0d42668e7c081c50915c | <|skeleton|>
class CustomUserManager:
def create_user(self, email, password=None, is_active=False):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a superuser with the given e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
def create_user(self, email, password=None, is_active=False):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(... | the_stack_v2_python_sparse | apps/users/models.py | levon2111/test_h | train | 0 | |
ccd6f4f54e707fe8aa016c3c6b9407227f3fe0f0 | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=_build_enforcement_target)\nPROVIDERS.assignment_api.get_grant(role_id, domain_id=domain_id, user_id=user_id, inherited_to_projects=False)\nreturn (None, http_client.NO_CONTENT)",
"ENFORCER.enforce_call(action='identity:create_grant', build_target... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=_build_enforcement_target)
PROVIDERS.assignment_api.get_grant(role_id, domain_id=domain_id, user_id=user_id, inherited_to_projects=False)
return (None, http_client.NO_CONTENT)
<|end_body_0|>
<|body_start_1|>
... | DomainUserResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainUserResource:
def get(self, domain_id=None, user_id=None, role_id=None):
"""Check if a user has a specific role on the domain. GET/HEAD /v3/domains/{domain_id}/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, domain_id=None, user_id=None, role_id=None):
... | stack_v2_sparse_classes_36k_train_034379 | 19,761 | permissive | [
{
"docstring": "Check if a user has a specific role on the domain. GET/HEAD /v3/domains/{domain_id}/users/{user_id}/roles/{role_id}",
"name": "get",
"signature": "def get(self, domain_id=None, user_id=None, role_id=None)"
},
{
"docstring": "Create a role to a user on a domain. PUT /v3/domains/{d... | 3 | null | Implement the Python class `DomainUserResource` described below.
Class description:
Implement the DomainUserResource class.
Method signatures and docstrings:
- def get(self, domain_id=None, user_id=None, role_id=None): Check if a user has a specific role on the domain. GET/HEAD /v3/domains/{domain_id}/users/{user_id}... | Implement the Python class `DomainUserResource` described below.
Class description:
Implement the DomainUserResource class.
Method signatures and docstrings:
- def get(self, domain_id=None, user_id=None, role_id=None): Check if a user has a specific role on the domain. GET/HEAD /v3/domains/{domain_id}/users/{user_id}... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class DomainUserResource:
def get(self, domain_id=None, user_id=None, role_id=None):
"""Check if a user has a specific role on the domain. GET/HEAD /v3/domains/{domain_id}/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, domain_id=None, user_id=None, role_id=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DomainUserResource:
def get(self, domain_id=None, user_id=None, role_id=None):
"""Check if a user has a specific role on the domain. GET/HEAD /v3/domains/{domain_id}/users/{user_id}/roles/{role_id}"""
ENFORCER.enforce_call(action='identity:check_grant', build_target=_build_enforcement_target)
... | the_stack_v2_python_sparse | keystone/api/domains.py | sapcc/keystone | train | 0 | |
b69807a0d225de85c67cd4bd291d9f6454805238 | [
"uri = f'{self.bulk.endpoint}/job/{job_id}/batch'\nresponse = requests.get(uri, headers=self.bulk.headers())\nresponse.raise_for_status()\nreturn self._parse_job_state(response.content)",
"tree = lxml_parse_string(xml)\nstatuses = [el.text for el in tree.iterfind('.//{%s}state' % self.bulk.jobNS)]\nstate_messages... | <|body_start_0|>
uri = f'{self.bulk.endpoint}/job/{job_id}/batch'
response = requests.get(uri, headers=self.bulk.headers())
response.raise_for_status()
return self._parse_job_state(response.content)
<|end_body_0|>
<|body_start_1|>
tree = lxml_parse_string(xml)
statuses =... | Provides mixin utilities for classes that manage Bulk API jobs. | BulkJobMixin | [
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkJobMixin:
"""Provides mixin utilities for classes that manage Bulk API jobs."""
def _job_state_from_batches(self, job_id):
"""Query for batches under job_id and return overall status inferred from batch-level status values."""
<|body_0|>
def _parse_job_state(self, xm... | stack_v2_sparse_classes_36k_train_034380 | 22,114 | permissive | [
{
"docstring": "Query for batches under job_id and return overall status inferred from batch-level status values.",
"name": "_job_state_from_batches",
"signature": "def _job_state_from_batches(self, job_id)"
},
{
"docstring": "Parse the Bulk API return value and generate a summary status record ... | 3 | stack_v2_sparse_classes_30k_test_000959 | Implement the Python class `BulkJobMixin` described below.
Class description:
Provides mixin utilities for classes that manage Bulk API jobs.
Method signatures and docstrings:
- def _job_state_from_batches(self, job_id): Query for batches under job_id and return overall status inferred from batch-level status values.... | Implement the Python class `BulkJobMixin` described below.
Class description:
Provides mixin utilities for classes that manage Bulk API jobs.
Method signatures and docstrings:
- def _job_state_from_batches(self, job_id): Query for batches under job_id and return overall status inferred from batch-level status values.... | 9ccf3c9566f78c6e9102ac214db30470cef660c1 | <|skeleton|>
class BulkJobMixin:
"""Provides mixin utilities for classes that manage Bulk API jobs."""
def _job_state_from_batches(self, job_id):
"""Query for batches under job_id and return overall status inferred from batch-level status values."""
<|body_0|>
def _parse_job_state(self, xm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BulkJobMixin:
"""Provides mixin utilities for classes that manage Bulk API jobs."""
def _job_state_from_batches(self, job_id):
"""Query for batches under job_id and return overall status inferred from batch-level status values."""
uri = f'{self.bulk.endpoint}/job/{job_id}/batch'
r... | the_stack_v2_python_sparse | cumulusci/tasks/bulkdata/step.py | SFDO-Tooling/CumulusCI | train | 226 |
691baa7d7cce8f3a1d6fc504e8592fc404a9ec36 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('hek_kquirk', 'hek_kquirk')\nrepo.dropCollection('hek_kquirk.district_education')\nrepo.createCollection('hek_kquirk.district_education')\nrepo.dropCollection('hek_kquirk.tmp_collection')\nrepo.createColl... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('hek_kquirk', 'hek_kquirk')
repo.dropCollection('hek_kquirk.district_education')
repo.createCollection('hek_kquirk.district_education')
rep... | districts_education | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class districts_education:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_36k_train_034381 | 5,980 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `districts_education` described below.
Class description:
Implement the districts_education class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | Implement the Python class `districts_education` described below.
Class description:
Implement the districts_education class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class districts_education:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class districts_education:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('hek_kquirk', 'hek_kquirk')
... | the_stack_v2_python_sparse | hek_kquirk/districts_education.py | maximega/course-2019-spr-proj | train | 2 | |
4115cc4b29eae6f262d230434e474bdce80a47d2 | [
"result = Fragment()\nchild_frags = self.runtime.render_children(self, context=context)\nresult.add_resources(child_frags)\nresult.add_content('<div class=\"unit-xblock vertical\">')\nfor frag in child_frags:\n result.add_content(frag.content)\nresult.add_content('</div>')\nreturn result",
"xblock_body = super... | <|body_start_0|>
result = Fragment()
child_frags = self.runtime.render_children(self, context=context)
result.add_resources(child_frags)
result.add_content('<div class="unit-xblock vertical">')
for frag in child_frags:
result.add_content(frag.content)
result.a... | Unit XBlock: An XBlock which groups related XBlocks together. This is like the "vertical" block in principle, but this version is explicitly designed to not contain LMS-related logic, like vertical does. The application which renders XBlocks and/or the runtime should manage things like bookmarks, completion tracking, e... | UnitBlock | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitBlock:
"""Unit XBlock: An XBlock which groups related XBlocks together. This is like the "vertical" block in principle, but this version is explicitly designed to not contain LMS-related logic, like vertical does. The application which renders XBlocks and/or the runtime should manage things l... | stack_v2_sparse_classes_36k_train_034382 | 2,633 | permissive | [
{
"docstring": "Provide default student view.",
"name": "student_view",
"signature": "def student_view(self, context=None)"
},
{
"docstring": "Return dictionary prepared with module content and type for indexing, so that the contents of this block can be found in free-text searches.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_003013 | Implement the Python class `UnitBlock` described below.
Class description:
Unit XBlock: An XBlock which groups related XBlocks together. This is like the "vertical" block in principle, but this version is explicitly designed to not contain LMS-related logic, like vertical does. The application which renders XBlocks an... | Implement the Python class `UnitBlock` described below.
Class description:
Unit XBlock: An XBlock which groups related XBlocks together. This is like the "vertical" block in principle, but this version is explicitly designed to not contain LMS-related logic, like vertical does. The application which renders XBlocks an... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class UnitBlock:
"""Unit XBlock: An XBlock which groups related XBlocks together. This is like the "vertical" block in principle, but this version is explicitly designed to not contain LMS-related logic, like vertical does. The application which renders XBlocks and/or the runtime should manage things l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitBlock:
"""Unit XBlock: An XBlock which groups related XBlocks together. This is like the "vertical" block in principle, but this version is explicitly designed to not contain LMS-related logic, like vertical does. The application which renders XBlocks and/or the runtime should manage things like bookmarks... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/lib/xmodule/xmodule/unit_block.py | luque/better-ways-of-thinking-about-software | train | 3 |
4e1a10d3c871763d673fab186dd60ea91310ecd0 | [
"logic = RegistrationLogic(self.auth, sid, aid)\nparams = ParamsParser(request.GET)\ntemplate_id = params.int('template_id', desc='使用模板id')\nstart_time = params.float('start_time', desc='开始时间')\nend_time = params.float('end_time', desc='结束时间')\nconfig = AssociationConfigureEntity.parse(logic.association.config)\nin... | <|body_start_0|>
logic = RegistrationLogic(self.auth, sid, aid)
params = ParamsParser(request.GET)
template_id = params.int('template_id', desc='使用模板id')
start_time = params.float('start_time', desc='开始时间')
end_time = params.float('end_time', desc='结束时间')
config = Associa... | InterviewManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterviewManage:
def get(self, request, sid, aid):
"""发起招新 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, aid):
"""过滤报名表 or 导入协会 :param request: :param sid: :param aid: :return:"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_034383 | 3,415 | no_license | [
{
"docstring": "发起招新 :param request: :param sid: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, sid, aid)"
},
{
"docstring": "过滤报名表 or 导入协会 :param request: :param sid: :param aid: :return:",
"name": "post",
"signature": "def post(self, request, sid, aid)"
}
... | 2 | stack_v2_sparse_classes_30k_train_016026 | Implement the Python class `InterviewManage` described below.
Class description:
Implement the InterviewManage class.
Method signatures and docstrings:
- def get(self, request, sid, aid): 发起招新 :param request: :param sid: :param aid: :return:
- def post(self, request, sid, aid): 过滤报名表 or 导入协会 :param request: :param si... | Implement the Python class `InterviewManage` described below.
Class description:
Implement the InterviewManage class.
Method signatures and docstrings:
- def get(self, request, sid, aid): 发起招新 :param request: :param sid: :param aid: :return:
- def post(self, request, sid, aid): 过滤报名表 or 导入协会 :param request: :param si... | a0553be3c259712de1fe5517b06317ad5756f79d | <|skeleton|>
class InterviewManage:
def get(self, request, sid, aid):
"""发起招新 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, aid):
"""过滤报名表 or 导入协会 :param request: :param sid: :param aid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterviewManage:
def get(self, request, sid, aid):
"""发起招新 :param request: :param sid: :param aid: :return:"""
logic = RegistrationLogic(self.auth, sid, aid)
params = ParamsParser(request.GET)
template_id = params.int('template_id', desc='使用模板id')
start_time = params.fl... | the_stack_v2_python_sparse | LittlePigHoHo/server/interview/views/manage.py | shoogoome/hoho | train | 1 | |
55b1e02e9c4f37b52174cf1633a0778afd7d1f5e | [
"self.sums = [0 for i in range(len(nums))]\nif len(nums) > 0:\n self.sums[0] = nums[0]\nfor i in range(1, len(nums)):\n self.sums[i] = self.sums[i - 1] + nums[i]",
"if i == 0:\n return self.sums[j]\nelse:\n return self.sums[j] - self.sums[i - 1]"
] | <|body_start_0|>
self.sums = [0 for i in range(len(nums))]
if len(nums) > 0:
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.sums[j]
else:
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sums = [0 for i in range(len(nums))]
if len(nu... | stack_v2_sparse_classes_36k_train_034384 | 689 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000805 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | bf54a0c12f9bc2986e1fd6e62255830802fbcf43 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.sums = [0 for i in range(len(nums))]
if len(nums) > 0:
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
def sumRange(self, i, j):
... | the_stack_v2_python_sparse | ALG/303sumRange-2.py | scientiacoder/ALG | train | 0 | |
1b1f2a489667a63f905a47da921ad9674bd71d94 | [
"if num_seqs > 36:\n raise ValueError('Cannot handle more than 36 sequences')\nself.num_seqs = num_seqs\nself.table = dict()",
"h_state = hash_state(item, self.num_seqs)\nif h_state not in self.table:\n self.table[h_state] = np.zeros(self.num_seqs)\nreturn self.table[h_state]"
] | <|body_start_0|>
if num_seqs > 36:
raise ValueError('Cannot handle more than 36 sequences')
self.num_seqs = num_seqs
self.table = dict()
<|end_body_0|>
<|body_start_1|>
h_state = hash_state(item, self.num_seqs)
if h_state not in self.table:
self.table[h_s... | HashQTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashQTable:
def __init__(self, num_seqs):
"""Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1) But these many states are never visited in the small amount of games performed in training, so it is reduced to a dictionary with ... | stack_v2_sparse_classes_36k_train_034385 | 1,550 | no_license | [
{
"docstring": "Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1) But these many states are never visited in the small amount of games performed in training, so it is reduced to a dictionary with a perfect hash-function. So this class simulates a Q-... | 2 | stack_v2_sparse_classes_30k_train_002886 | Implement the Python class `HashQTable` described below.
Class description:
Implement the HashQTable class.
Method signatures and docstrings:
- def __init__(self, num_seqs): Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1) But these many states are never... | Implement the Python class `HashQTable` described below.
Class description:
Implement the HashQTable class.
Method signatures and docstrings:
- def __init__(self, num_seqs): Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1) But these many states are never... | 9d9f17162ff04f7b22060dab98624b67857abcd6 | <|skeleton|>
class HashQTable:
def __init__(self, num_seqs):
"""Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1) But these many states are never visited in the small amount of games performed in training, so it is reduced to a dictionary with ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HashQTable:
def __init__(self, num_seqs):
"""Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1) But these many states are never visited in the small amount of games performed in training, so it is reduced to a dictionary with a perfect hash... | the_stack_v2_python_sparse | utils/hash_q_table.py | Old-Shatterhand/MSADRL | train | 2 | |
4088eccc9276a89b7c6e4b7909423aa819791a93 | [
"self.repo = git.Repo(repodir)\n'Access to the local checked-out repo'\nif rev is None:\n commit = sorted(self.repo.tags, key=lambda x: x.commit.committed_date)[-1].commit\nelse:\n commit = self.repo.commit(rev=rev)\nself.last_release = datetime.datetime(*time.gmtime(commit.committed_date)[:6])\n'Time of the ... | <|body_start_0|>
self.repo = git.Repo(repodir)
'Access to the local checked-out repo'
if rev is None:
commit = sorted(self.repo.tags, key=lambda x: x.commit.committed_date)[-1].commit
else:
commit = self.repo.commit(rev=rev)
self.last_release = datetime.da... | Class to grab information for release notes from github | NoteCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteCreator:
"""Class to grab information for release notes from github"""
def __init__(self, repodir, rev=None, token=None):
"""Initialize variables Parameters ---------- repodir : str Path to the dbprocessing repository checkout rev : str, optional Revision (tag) of the last releas... | stack_v2_sparse_classes_36k_train_034386 | 6,492 | no_license | [
{
"docstring": "Initialize variables Parameters ---------- repodir : str Path to the dbprocessing repository checkout rev : str, optional Revision (tag) of the last release. Will only get information from this point on. Default: most recent tag. token : str, optional Github `access token <https://docs.github.co... | 6 | null | Implement the Python class `NoteCreator` described below.
Class description:
Class to grab information for release notes from github
Method signatures and docstrings:
- def __init__(self, repodir, rev=None, token=None): Initialize variables Parameters ---------- repodir : str Path to the dbprocessing repository check... | Implement the Python class `NoteCreator` described below.
Class description:
Class to grab information for release notes from github
Method signatures and docstrings:
- def __init__(self, repodir, rev=None, token=None): Initialize variables Parameters ---------- repodir : str Path to the dbprocessing repository check... | a0bf5e682fb917bb707b4f66787b0ecb860efce1 | <|skeleton|>
class NoteCreator:
"""Class to grab information for release notes from github"""
def __init__(self, repodir, rev=None, token=None):
"""Initialize variables Parameters ---------- repodir : str Path to the dbprocessing repository checkout rev : str, optional Revision (tag) of the last releas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoteCreator:
"""Class to grab information for release notes from github"""
def __init__(self, repodir, rev=None, token=None):
"""Initialize variables Parameters ---------- repodir : str Path to the dbprocessing repository checkout rev : str, optional Revision (tag) of the last release. Will only ... | the_stack_v2_python_sparse | developer/scripts/git_notes.py | spacepy/dbprocessing | train | 4 |
66d6103edd8c8709876c6325c8944af1e7790425 | [
"N = self._store.get_array('length')\nE = self._store.get_array('energy') / N\nC = self._store.get_array('cell')\nV = np.linalg.det(C) / N\ndf = pd.DataFrame({'V': V, 'E': E})\nif crystal_systems:\n spg = self._calc_spacegroups()\n df = df.join(spg)\n for cs, dd in df.groupby('crystal_system'):\n pl... | <|body_start_0|>
N = self._store.get_array('length')
E = self._store.get_array('energy') / N
C = self._store.get_array('cell')
V = np.linalg.det(C) / N
df = pd.DataFrame({'V': V, 'E': E})
if crystal_systems:
spg = self._calc_spacegroups()
df = df.j... | Simple interface to plot various properties of the structures inside the given :class:`.TrainingContainer`. | TrainingPlots | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingPlots:
"""Simple interface to plot various properties of the structures inside the given :class:`.TrainingContainer`."""
def energy_volume(self, crystal_systems=False):
"""Plot volume vs. energy. Volume and energy are normalized per atom before plotting. Args: crystal_systems... | stack_v2_sparse_classes_36k_train_034387 | 22,997 | permissive | [
{
"docstring": "Plot volume vs. energy. Volume and energy are normalized per atom before plotting. Args: crystal_systems (bool): if True, plot & label structures of different crystal systems separately. Returns: DataFrame: contains atomic energy and volumes in the columns 'E' and 'V'; if `crystal_systems` is gi... | 3 | null | Implement the Python class `TrainingPlots` described below.
Class description:
Simple interface to plot various properties of the structures inside the given :class:`.TrainingContainer`.
Method signatures and docstrings:
- def energy_volume(self, crystal_systems=False): Plot volume vs. energy. Volume and energy are n... | Implement the Python class `TrainingPlots` described below.
Class description:
Simple interface to plot various properties of the structures inside the given :class:`.TrainingContainer`.
Method signatures and docstrings:
- def energy_volume(self, crystal_systems=False): Plot volume vs. energy. Volume and energy are n... | 7e4085d60017be32624c2e47c10fa1a144c882a1 | <|skeleton|>
class TrainingPlots:
"""Simple interface to plot various properties of the structures inside the given :class:`.TrainingContainer`."""
def energy_volume(self, crystal_systems=False):
"""Plot volume vs. energy. Volume and energy are normalized per atom before plotting. Args: crystal_systems... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainingPlots:
"""Simple interface to plot various properties of the structures inside the given :class:`.TrainingContainer`."""
def energy_volume(self, crystal_systems=False):
"""Plot volume vs. energy. Volume and energy are normalized per atom before plotting. Args: crystal_systems (bool): if T... | the_stack_v2_python_sparse | pyiron_contrib/atomistics/atomistics/job/trainingcontainer.py | pyiron/pyiron_contrib | train | 8 |
9314a0dab97b74528dea35633438519b71226a51 | [
"def get_options():\n options = set()\n for sect, opts in self._sections.items():\n if sect == 'rcParams':\n continue\n options.update(('{}.{}'.format(sect, opt) for opt in opts.keys()))\n return options\nbefore = get_options()\nresult = super().read(filename, encoding)\nafter = ge... | <|body_start_0|>
def get_options():
options = set()
for sect, opts in self._sections.items():
if sect == 'rcParams':
continue
options.update(('{}.{}'.format(sect, opt) for opt in opts.keys()))
return options
before =... | Custom configuration parser with Matplotlib dimension and color support. | PgfutilsParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PgfutilsParser:
"""Custom configuration parser with Matplotlib dimension and color support."""
def read(self, filename, encoding=None):
"""Read configuration options from a file. This is an extension of the standard ConfigParser.read() method to reject unknown options. This provides ... | stack_v2_sparse_classes_36k_train_034388 | 36,118 | no_license | [
{
"docstring": "Read configuration options from a file. This is an extension of the standard ConfigParser.read() method to reject unknown options. This provides an early indication to the user that they have configured something incorrectly, rather than continuing and having their plot generated differently to ... | 5 | stack_v2_sparse_classes_30k_train_014968 | Implement the Python class `PgfutilsParser` described below.
Class description:
Custom configuration parser with Matplotlib dimension and color support.
Method signatures and docstrings:
- def read(self, filename, encoding=None): Read configuration options from a file. This is an extension of the standard ConfigParse... | Implement the Python class `PgfutilsParser` described below.
Class description:
Custom configuration parser with Matplotlib dimension and color support.
Method signatures and docstrings:
- def read(self, filename, encoding=None): Read configuration options from a file. This is an extension of the standard ConfigParse... | e43942bbd09f6675e7e2ff277f8930dc0518d08e | <|skeleton|>
class PgfutilsParser:
"""Custom configuration parser with Matplotlib dimension and color support."""
def read(self, filename, encoding=None):
"""Read configuration options from a file. This is an extension of the standard ConfigParser.read() method to reject unknown options. This provides ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PgfutilsParser:
"""Custom configuration parser with Matplotlib dimension and color support."""
def read(self, filename, encoding=None):
"""Read configuration options from a file. This is an extension of the standard ConfigParser.read() method to reject unknown options. This provides an early indi... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/pgfutils.py | jciech/HeisenbergSpinChains | train | 0 |
599ac5d70a03e18ea6841a4f40fd20fa0ac1ebe1 | [
"if len(data['changes']):\n if not isinstance(to, (list, set)):\n to = [to]\n if len(to) > 0:\n with transaction.atomic():\n message = Message()\n message.create_message_from_template(template_name=template_name, data=data)\n message.save()\n message.s... | <|body_start_0|>
if len(data['changes']):
if not isinstance(to, (list, set)):
to = [to]
if len(to) > 0:
with transaction.atomic():
message = Message()
message.create_message_from_template(template_name=template_name,... | Миксин для оповещения пользователя, что модератор исправил/изменил материал | MixinSaveModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixinSaveModel:
"""Миксин для оповещения пользователя, что модератор исправил/изменил материал"""
def _send_private_message(template_name, data, to):
"""Формирование автоматического уведомления с указанием измененных полей"""
<|body_0|>
def save_model(self, request, obj,... | stack_v2_sparse_classes_36k_train_034389 | 5,107 | no_license | [
{
"docstring": "Формирование автоматического уведомления с указанием измененных полей",
"name": "_send_private_message",
"signature": "def _send_private_message(template_name, data, to)"
},
{
"docstring": "Метод вызывается при сохранении материала из админки. При изменении полей формирует данные... | 2 | stack_v2_sparse_classes_30k_train_007558 | Implement the Python class `MixinSaveModel` described below.
Class description:
Миксин для оповещения пользователя, что модератор исправил/изменил материал
Method signatures and docstrings:
- def _send_private_message(template_name, data, to): Формирование автоматического уведомления с указанием измененных полей
- de... | Implement the Python class `MixinSaveModel` described below.
Class description:
Миксин для оповещения пользователя, что модератор исправил/изменил материал
Method signatures and docstrings:
- def _send_private_message(template_name, data, to): Формирование автоматического уведомления с указанием измененных полей
- de... | 9c46e756e285fba9853dad6c510b1f87968a7092 | <|skeleton|>
class MixinSaveModel:
"""Миксин для оповещения пользователя, что модератор исправил/изменил материал"""
def _send_private_message(template_name, data, to):
"""Формирование автоматического уведомления с указанием измененных полей"""
<|body_0|>
def save_model(self, request, obj,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixinSaveModel:
"""Миксин для оповещения пользователя, что модератор исправил/изменил материал"""
def _send_private_message(template_name, data, to):
"""Формирование автоматического уведомления с указанием измененных полей"""
if len(data['changes']):
if not isinstance(to, (lis... | the_stack_v2_python_sparse | main/admin.py | thewebcat/livecamsbay | train | 1 |
70d71fc894c7bf00217712c12bb367cf54620718 | [
"for c in set(s):\n if s.count(c) < k:\n return max((self.longestSubstring(x, k) for x in s.split(c)))\nreturn len(s)",
"res = 0\nfor exp_uni_count in range(1, 27):\n cur_uni_count, no_less_k, head, tail = (0, 0, 0, 0)\n alpha_map = {}\n while tail < len(s):\n if cur_uni_count <= exp_uni... | <|body_start_0|>
for c in set(s):
if s.count(c) < k:
return max((self.longestSubstring(x, k) for x in s.split(c)))
return len(s)
<|end_body_0|>
<|body_start_1|>
res = 0
for exp_uni_count in range(1, 27):
cur_uni_count, no_less_k, head, tail = (0, ... | LongestSubstringWithAtLeastKRepeatingCharacters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestSubstringWithAtLeastKRepeatingCharacters:
def longestSubstring(self, s: str, k: int) -> int:
"""https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ 统计出现的字母的数量,小于要求数量的字母用于字符串分片 利用小写字母总数26个降低复杂度"""
<|body_0|>
def longestSubstring_2(self... | stack_v2_sparse_classes_36k_train_034390 | 1,667 | no_license | [
{
"docstring": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ 统计出现的字母的数量,小于要求数量的字母用于字符串分片 利用小写字母总数26个降低复杂度",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s: str, k: int) -> int"
},
{
"docstring": "利用小写字母总数26个降低复杂度",
"name": "lon... | 2 | stack_v2_sparse_classes_30k_train_006743 | Implement the Python class `LongestSubstringWithAtLeastKRepeatingCharacters` described below.
Class description:
Implement the LongestSubstringWithAtLeastKRepeatingCharacters class.
Method signatures and docstrings:
- def longestSubstring(self, s: str, k: int) -> int: https://leetcode.com/problems/longest-substring-w... | Implement the Python class `LongestSubstringWithAtLeastKRepeatingCharacters` described below.
Class description:
Implement the LongestSubstringWithAtLeastKRepeatingCharacters class.
Method signatures and docstrings:
- def longestSubstring(self, s: str, k: int) -> int: https://leetcode.com/problems/longest-substring-w... | ba428d2183b916b39b50783c95f909993b04c1f0 | <|skeleton|>
class LongestSubstringWithAtLeastKRepeatingCharacters:
def longestSubstring(self, s: str, k: int) -> int:
"""https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ 统计出现的字母的数量,小于要求数量的字母用于字符串分片 利用小写字母总数26个降低复杂度"""
<|body_0|>
def longestSubstring_2(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LongestSubstringWithAtLeastKRepeatingCharacters:
def longestSubstring(self, s: str, k: int) -> int:
"""https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ 统计出现的字母的数量,小于要求数量的字母用于字符串分片 利用小写字母总数26个降低复杂度"""
for c in set(s):
if s.count(c) < k:
... | the_stack_v2_python_sparse | src/main/LeetCode/python/longest-substring-with-at-least-k-repeating-characters.py | chengqhuster/xishuashua | train | 0 | |
db2c5312beb5bbae00b5c9b4ad44ef4c3c80e458 | [
"user = User.objects.get(pk=pk)\nserializer = self.serializer(user)\nreturn serializer.data",
"queryset = User.objects.all().order_by('id')\nresults = self.paginate_queryset(queryset, request)\nserializer = self.serializer(results, many=True)\nreturn self.get_paginated_response(serializer.data)",
"response = Us... | <|body_start_0|>
user = User.objects.get(pk=pk)
serializer = self.serializer(user)
return serializer.data
<|end_body_0|>
<|body_start_1|>
queryset = User.objects.all().order_by('id')
results = self.paginate_queryset(queryset, request)
serializer = self.serializer(results... | ... | UserListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListView:
"""..."""
def serialize_user(self, pk):
"""..."""
<|body_0|>
def get(self, request, format=None):
"""..."""
<|body_1|>
def post(self, request, format=None):
"""..."""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_034391 | 4,540 | permissive | [
{
"docstring": "...",
"name": "serialize_user",
"signature": "def serialize_user(self, pk)"
},
{
"docstring": "...",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "...",
"name": "post",
"signature": "def post(self, request, format=Non... | 3 | stack_v2_sparse_classes_30k_train_016719 | Implement the Python class `UserListView` described below.
Class description:
...
Method signatures and docstrings:
- def serialize_user(self, pk): ...
- def get(self, request, format=None): ...
- def post(self, request, format=None): ... | Implement the Python class `UserListView` described below.
Class description:
...
Method signatures and docstrings:
- def serialize_user(self, pk): ...
- def get(self, request, format=None): ...
- def post(self, request, format=None): ...
<|skeleton|>
class UserListView:
"""..."""
def serialize_user(self, p... | 9c7f82a3fdaa7a8f2f34062d8803b4f33f8c07b7 | <|skeleton|>
class UserListView:
"""..."""
def serialize_user(self, pk):
"""..."""
<|body_0|>
def get(self, request, format=None):
"""..."""
<|body_1|>
def post(self, request, format=None):
"""..."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserListView:
"""..."""
def serialize_user(self, pk):
"""..."""
user = User.objects.get(pk=pk)
serializer = self.serializer(user)
return serializer.data
def get(self, request, format=None):
"""..."""
queryset = User.objects.all().order_by('id')
... | the_stack_v2_python_sparse | apps/user/views/vuser.py | magocod/dj_chat | train | 2 |
3027fb243398bba8e16f148d1c1b5d0fbf712d0f | [
"super(EmCgwshServiceManagementDelete, self).__init__()\nsuper(EmCgwshServiceFlavor, self).__init__()\nself.service = GlobalModule.SERVICE_CGWSH_SERVICE_MANAGEMENT\nself.order_type = GlobalModule.ORDER_DELETE\nself._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.service]\nself._scenario_name = 'CgwshServiceMana... | <|body_start_0|>
super(EmCgwshServiceManagementDelete, self).__init__()
super(EmCgwshServiceFlavor, self).__init__()
self.service = GlobalModule.SERVICE_CGWSH_SERVICE_MANAGEMENT
self.order_type = GlobalModule.ORDER_DELETE
self._xml_ns = '{%s}' % GlobalModule.EM_NAME_SPACES[self.s... | Class for deleting Cgwsh service | EmCgwshServiceManagementDelete | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmCgwshServiceManagementDelete:
"""Class for deleting Cgwsh service"""
def __init__(self):
"""Costructor"""
<|body_0|>
def _creating_json(self, device_message):
"""EC Message(XML) devided into each device is converted to JSON. Argument: device_message: message fo... | stack_v2_sparse_classes_36k_train_034392 | 2,052 | permissive | [
{
"docstring": "Costructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "EC Message(XML) devided into each device is converted to JSON. Argument: device_message: message for each device Return value: device_json_message: JSON message",
"name": "_creating_json",
... | 2 | stack_v2_sparse_classes_30k_train_010309 | Implement the Python class `EmCgwshServiceManagementDelete` described below.
Class description:
Class for deleting Cgwsh service
Method signatures and docstrings:
- def __init__(self): Costructor
- def _creating_json(self, device_message): EC Message(XML) devided into each device is converted to JSON. Argument: devic... | Implement the Python class `EmCgwshServiceManagementDelete` described below.
Class description:
Class for deleting Cgwsh service
Method signatures and docstrings:
- def __init__(self): Costructor
- def _creating_json(self, device_message): EC Message(XML) devided into each device is converted to JSON. Argument: devic... | e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f | <|skeleton|>
class EmCgwshServiceManagementDelete:
"""Class for deleting Cgwsh service"""
def __init__(self):
"""Costructor"""
<|body_0|>
def _creating_json(self, device_message):
"""EC Message(XML) devided into each device is converted to JSON. Argument: device_message: message fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmCgwshServiceManagementDelete:
"""Class for deleting Cgwsh service"""
def __init__(self):
"""Costructor"""
super(EmCgwshServiceManagementDelete, self).__init__()
super(EmCgwshServiceFlavor, self).__init__()
self.service = GlobalModule.SERVICE_CGWSH_SERVICE_MANAGEMENT
... | the_stack_v2_python_sparse | lib/Scenario/CGW-SH/EmCgwshServiceManagementDelete.py | lixiaochun/element-manager | train | 0 |
9689eeca03569387815b68344597f6e1c00654f0 | [
"super(AlphaBeta, self).__init__()\nself.portfolioReturn = portfolioReturn\nself.benchmarkReturn = benchmarkReturn\nself.riskfreeRate = riskfreeRate",
"alphas = []\nbetas = []\nfor i in range(len(self.portfolioReturn)):\n if i == 0:\n alpha = np.nan\n beta = np.nan\n else:\n n = i + 1\n... | <|body_start_0|>
super(AlphaBeta, self).__init__()
self.portfolioReturn = portfolioReturn
self.benchmarkReturn = benchmarkReturn
self.riskfreeRate = riskfreeRate
<|end_body_0|>
<|body_start_1|>
alphas = []
betas = []
for i in range(len(self.portfolioReturn)):
... | Alpha-beta of the given profit returns to the risk free rate. | AlphaBeta | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlphaBeta:
"""Alpha-beta of the given profit returns to the risk free rate."""
def __init__(self, portfolioReturn, benchmarkReturn, riskfreeRate):
"""Initialize the AlphaBeta calculator with the portfolio data and a benchmark one. Parameters ---------- portfolioReturn : pandas.Series... | stack_v2_sparse_classes_36k_train_034393 | 10,010 | permissive | [
{
"docstring": "Initialize the AlphaBeta calculator with the portfolio data and a benchmark one. Parameters ---------- portfolioReturn : pandas.Series annual returns indexed by trading date as strings in the format %Y%m%d; benchmarkReturn : pandas.Series benchmark return indexed by trading date as strings in th... | 2 | stack_v2_sparse_classes_30k_test_001202 | Implement the Python class `AlphaBeta` described below.
Class description:
Alpha-beta of the given profit returns to the risk free rate.
Method signatures and docstrings:
- def __init__(self, portfolioReturn, benchmarkReturn, riskfreeRate): Initialize the AlphaBeta calculator with the portfolio data and a benchmark o... | Implement the Python class `AlphaBeta` described below.
Class description:
Alpha-beta of the given profit returns to the risk free rate.
Method signatures and docstrings:
- def __init__(self, portfolioReturn, benchmarkReturn, riskfreeRate): Initialize the AlphaBeta calculator with the portfolio data and a benchmark o... | 139d604177da3855503643e0fcfa87711ba7e588 | <|skeleton|>
class AlphaBeta:
"""Alpha-beta of the given profit returns to the risk free rate."""
def __init__(self, portfolioReturn, benchmarkReturn, riskfreeRate):
"""Initialize the AlphaBeta calculator with the portfolio data and a benchmark one. Parameters ---------- portfolioReturn : pandas.Series... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlphaBeta:
"""Alpha-beta of the given profit returns to the risk free rate."""
def __init__(self, portfolioReturn, benchmarkReturn, riskfreeRate):
"""Initialize the AlphaBeta calculator with the portfolio data and a benchmark one. Parameters ---------- portfolioReturn : pandas.Series annual retur... | the_stack_v2_python_sparse | analytics/riskMeasurement/riskMetric.py | WinQuant/arsenal | train | 0 |
0e879438766d504a52b5f3ff1039a0dda3ff237a | [
"mapper = self.meta.get('mapper')\no = mapper.group.Group.get_by_uid(groupid)\nif o is None:\n raise falcon.HTTPInvalidParam('Organization not found', groupid)\nresp.body = {'group': o.to_dict()}\nreturn True",
"mapper = self.meta.get('mapper')\nbody = req.context['body']\no = EGroup(uid=body.get('id'), name=b... | <|body_start_0|>
mapper = self.meta.get('mapper')
o = mapper.group.Group.get_by_uid(groupid)
if o is None:
raise falcon.HTTPInvalidParam('Organization not found', groupid)
resp.body = {'group': o.to_dict()}
return True
<|end_body_0|>
<|body_start_1|>
mapper =... | Group A Group is a collection of User objects GET - Retrieve a Group POST - Create a new Group PUT - Update a Group DELETE - Remove a Group | Group | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group:
"""Group A Group is a collection of User objects GET - Retrieve a Group POST - Create a new Group PUT - Update a Group DELETE - Remove a Group"""
def on_get(self, req, resp, groupid):
"""Retrieve a Group specified by id :param req: :param resp: :param groupid: :return:"""
... | stack_v2_sparse_classes_36k_train_034394 | 4,399 | no_license | [
{
"docstring": "Retrieve a Group specified by id :param req: :param resp: :param groupid: :return:",
"name": "on_get",
"signature": "def on_get(self, req, resp, groupid)"
},
{
"docstring": "Create a new Group :param req: :param resp: :return:",
"name": "on_post",
"signature": "def on_pos... | 4 | stack_v2_sparse_classes_30k_train_010936 | Implement the Python class `Group` described below.
Class description:
Group A Group is a collection of User objects GET - Retrieve a Group POST - Create a new Group PUT - Update a Group DELETE - Remove a Group
Method signatures and docstrings:
- def on_get(self, req, resp, groupid): Retrieve a Group specified by id ... | Implement the Python class `Group` described below.
Class description:
Group A Group is a collection of User objects GET - Retrieve a Group POST - Create a new Group PUT - Update a Group DELETE - Remove a Group
Method signatures and docstrings:
- def on_get(self, req, resp, groupid): Retrieve a Group specified by id ... | a77366edeb73b257c23ab58bef6a23074948f007 | <|skeleton|>
class Group:
"""Group A Group is a collection of User objects GET - Retrieve a Group POST - Create a new Group PUT - Update a Group DELETE - Remove a Group"""
def on_get(self, req, resp, groupid):
"""Retrieve a Group specified by id :param req: :param resp: :param groupid: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Group:
"""Group A Group is a collection of User objects GET - Retrieve a Group POST - Create a new Group PUT - Update a Group DELETE - Remove a Group"""
def on_get(self, req, resp, groupid):
"""Retrieve a Group specified by id :param req: :param resp: :param groupid: :return:"""
mapper = ... | the_stack_v2_python_sparse | src/econtextauth/engine/routes/groups/group.py | info-com/econtext-auth | train | 0 |
8ec0ddc8b8d32afd52b2070f01a27d7faf7db5f3 | [
"self.degeneracy = kwargs.pop('degeneracy', 0.001)\n' Degeneracy parameter for oscillator strength. '\nsuper(Dipole, self).__init__(*args, **kwargs)",
"out = super(Dipole, self).run(indiv, outdir, comm, **kwargs)\ndegeneracy = getattr(self, 'degeneracy', 0.001)\nindiv.dipoles = out.dipole(degeneracy=degeneracy)\n... | <|body_start_0|>
self.degeneracy = kwargs.pop('degeneracy', 0.001)
' Degeneracy parameter for oscillator strength. '
super(Dipole, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
out = super(Dipole, self).run(indiv, outdir, comm, **kwargs)
degeneracy = getattr(se... | Evaluates the oscillator strength. On top of those quantities saved by base class BandgapEvaluator, this class stores the dipole elements in indiv.dipoles. | Dipole | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dipole:
"""Evaluates the oscillator strength. On top of those quantities saved by base class BandgapEvaluator, this class stores the dipole elements in indiv.dipoles."""
def __init__(self, *args, **kwargs):
"""Initializes the dipole element evaluator."""
<|body_0|>
def _... | stack_v2_sparse_classes_36k_train_034395 | 9,676 | no_license | [
{
"docstring": "Initializes the dipole element evaluator.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Computes the oscillator strength.",
"name": "__call__",
"signature": "def __call__(self, indiv, outdir=None, comm=None, **kwargs)"
}
] | 2 | null | Implement the Python class `Dipole` described below.
Class description:
Evaluates the oscillator strength. On top of those quantities saved by base class BandgapEvaluator, this class stores the dipole elements in indiv.dipoles.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the d... | Implement the Python class `Dipole` described below.
Class description:
Evaluates the oscillator strength. On top of those quantities saved by base class BandgapEvaluator, this class stores the dipole elements in indiv.dipoles.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initializes the d... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class Dipole:
"""Evaluates the oscillator strength. On top of those quantities saved by base class BandgapEvaluator, this class stores the dipole elements in indiv.dipoles."""
def __init__(self, *args, **kwargs):
"""Initializes the dipole element evaluator."""
<|body_0|>
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dipole:
"""Evaluates the oscillator strength. On top of those quantities saved by base class BandgapEvaluator, this class stores the dipole elements in indiv.dipoles."""
def __init__(self, *args, **kwargs):
"""Initializes the dipole element evaluator."""
self.degeneracy = kwargs.pop('dege... | the_stack_v2_python_sparse | ga/escan/evaluator.py | Shibu778/LaDa | train | 0 |
bcded976eed321ea693eb4817c9aee6473cf5afc | [
"formfield = super(TweetableAdminMixin, self).formfield_for_dbfield(db_field, request, **kwargs)\nif Api and db_field.name == 'status' and get_auth_settings():\n\n def wrapper(render):\n\n def wrapped(*args, **kwargs):\n rendered = render(*args, **kwargs)\n label = _('Send to Twitter... | <|body_start_0|>
formfield = super(TweetableAdminMixin, self).formfield_for_dbfield(db_field, request, **kwargs)
if Api and db_field.name == 'status' and get_auth_settings():
def wrapper(render):
def wrapped(*args, **kwargs):
rendered = render(*args, **k... | Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved. | TweetableAdminMixin | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TweetableAdminMixin:
"""Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved."""
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Adds the "Send to Twitter" ... | stack_v2_sparse_classes_36k_train_034396 | 2,268 | permissive | [
{
"docstring": "Adds the \"Send to Twitter\" checkbox after the \"status\" field, provided by any ``Displayable`` models. The approach here is quite a hack, however the sane approach of using a custom form with a boolean field defined, and then adding it to the formsets attribute of the admin class fell apart q... | 2 | stack_v2_sparse_classes_30k_train_003633 | Implement the Python class `TweetableAdminMixin` described below.
Class description:
Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved.
Method signatures and docstrings:
- def formfield_for_dbfield(self, ... | Implement the Python class `TweetableAdminMixin` described below.
Class description:
Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved.
Method signatures and docstrings:
- def formfield_for_dbfield(self, ... | 29203de1d111a6d94d576a89430b37edd24cef55 | <|skeleton|>
class TweetableAdminMixin:
"""Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved."""
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Adds the "Send to Twitter" ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TweetableAdminMixin:
"""Admin mixin that adds a "Send to Twitter" checkbox to the add/change views, which when checked, will send a tweet with the title and link to the object being saved."""
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Adds the "Send to Twitter" checkbox afte... | the_stack_v2_python_sparse | mezzanine/twitter/admin.py | fermorltd/mezzanine | train | 6 |
a4a4b424a9e28b1cd77c65e00c5ee41b20af15a0 | [
"cluster_attrs = objects.Cluster.get_editable_attributes(cluster)\nneutron_mellanox_data = cluster_attrs.get('neutron_mellanox', {})\nif neutron_mellanox_data:\n storage_data = cluster_attrs.get('storage', {})\n nm = objects.Cluster.get_network_manager(cluster)\n node_attrs['neutron_mellanox'] = {}\n if... | <|body_start_0|>
cluster_attrs = objects.Cluster.get_editable_attributes(cluster)
neutron_mellanox_data = cluster_attrs.get('neutron_mellanox', {})
if neutron_mellanox_data:
storage_data = cluster_attrs.get('storage', {})
nm = objects.Cluster.get_network_manager(cluster)
... | MellanoxMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MellanoxMixin:
def inject_mellanox_settings_for_deployment(cls, node_attrs, cluster, networks):
"""Mellanox settings for deployment Serialize mellanox node attrs then it will be merged with common attributes, if mellanox plugin or iSER storage enabled. :param node_attrs: attributes for s... | stack_v2_sparse_classes_36k_train_034397 | 6,772 | permissive | [
{
"docstring": "Mellanox settings for deployment Serialize mellanox node attrs then it will be merged with common attributes, if mellanox plugin or iSER storage enabled. :param node_attrs: attributes for specific node :type node_attrs: dict :param cluster: A cluster instance :type cluster: Cluster model :param ... | 2 | stack_v2_sparse_classes_30k_test_000707 | Implement the Python class `MellanoxMixin` described below.
Class description:
Implement the MellanoxMixin class.
Method signatures and docstrings:
- def inject_mellanox_settings_for_deployment(cls, node_attrs, cluster, networks): Mellanox settings for deployment Serialize mellanox node attrs then it will be merged w... | Implement the Python class `MellanoxMixin` described below.
Class description:
Implement the MellanoxMixin class.
Method signatures and docstrings:
- def inject_mellanox_settings_for_deployment(cls, node_attrs, cluster, networks): Mellanox settings for deployment Serialize mellanox node attrs then it will be merged w... | 768ac74a420f822261c4eb8da72f1d8af3c6bbff | <|skeleton|>
class MellanoxMixin:
def inject_mellanox_settings_for_deployment(cls, node_attrs, cluster, networks):
"""Mellanox settings for deployment Serialize mellanox node attrs then it will be merged with common attributes, if mellanox plugin or iSER storage enabled. :param node_attrs: attributes for s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MellanoxMixin:
def inject_mellanox_settings_for_deployment(cls, node_attrs, cluster, networks):
"""Mellanox settings for deployment Serialize mellanox node attrs then it will be merged with common attributes, if mellanox plugin or iSER storage enabled. :param node_attrs: attributes for specific node :... | the_stack_v2_python_sparse | nailgun/nailgun/orchestrator/base_serializers.py | dis-xcom/fuel-web | train | 0 | |
e66d8e24bf341965edfcaa2b53ed96840ee39fbc | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('yuxiao_yzhang11', 'yuxiao_yzhang11')\ncrime = repo['yuxiao_yzhang11.crime']\ngroup = {'_id': '$Location', 'count': {'$sum': 1}}\ncrimeCor = crime.aggregate([{'$group': group}])\nrepo.dropCollection('crim... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yuxiao_yzhang11', 'yuxiao_yzhang11')
crime = repo['yuxiao_yzhang11.crime']
group = {'_id': '$Location', 'count': {'$sum': 1}}
crimeCor = c... | getCrimeZip | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getCrimeZip:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything h... | stack_v2_sparse_classes_36k_train_034398 | 4,548 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `getCrimeZip` described below.
Class description:
Implement the getCrimeZip class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi... | Implement the Python class `getCrimeZip` described below.
Class description:
Implement the getCrimeZip class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class getCrimeZip:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getCrimeZip:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yuxiao_yzhang11', 'yuxiao_yzhang11')
... | the_stack_v2_python_sparse | yuxiao_yzhang11/getCrimeZip.py | dwang1995/course-2018-spr-proj | train | 1 | |
a4aeeae82450be013823ba2ca5a7cc8981fa6e64 | [
"n, m = (len(s), len(p))\ndp = [[0] * (n + 1) for _ in range(m + 1)]\ndp[0][0] = 1\nfor i in range(1, m + 1):\n for j in range(n + 1):\n if j > 0 and p[i - 1] == '?':\n dp[i][j] = dp[i - 1][j - 1]\n elif j > 0 and p[i - 1] == s[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n el... | <|body_start_0|>
n, m = (len(s), len(p))
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][0] = 1
for i in range(1, m + 1):
for j in range(n + 1):
if j > 0 and p[i - 1] == '?':
dp[i][j] = dp[i - 1][j - 1]
elif j > 0 and p[i -... | [44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/) | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""[44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/)"""
def isMatch(self, s: str, p: str) -> bool:
"""思路:和第十题类似,*的规则不同,动态规划,dp[i][j]表示p[:i+1]可以匹配s[:j+1]. 匹配成功的时候,按模式串p的种类可分三种情况: case1. p[i] == '?' case2. p[i] == '*' case3. p[i] == s[j]"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_034399 | 2,700 | no_license | [
{
"docstring": "思路:和第十题类似,*的规则不同,动态规划,dp[i][j]表示p[:i+1]可以匹配s[:j+1]. 匹配成功的时候,按模式串p的种类可分三种情况: case1. p[i] == '?' case2. p[i] == '*' case3. p[i] == s[j]",
"name": "isMatch",
"signature": "def isMatch(self, s: str, p: str) -> bool"
},
{
"docstring": "思路:回溯,上面O(n^2)的动态规划只超过了20%的用户,说明一定有比O(n^2)更低的复杂度解... | 2 | null | Implement the Python class `Solution` described below.
Class description:
[44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/)
Method signatures and docstrings:
- def isMatch(self, s: str, p: str) -> bool: 思路:和第十题类似,*的规则不同,动态规划,dp[i][j]表示p[:i+1]可以匹配s[:j+1]. 匹配成功的时候,按模式串p的种类可分三种情况: case1. p[i] == '?' case2... | Implement the Python class `Solution` described below.
Class description:
[44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/)
Method signatures and docstrings:
- def isMatch(self, s: str, p: str) -> bool: 思路:和第十题类似,*的规则不同,动态规划,dp[i][j]表示p[:i+1]可以匹配s[:j+1]. 匹配成功的时候,按模式串p的种类可分三种情况: case1. p[i] == '?' case2... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class Solution:
"""[44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/)"""
def isMatch(self, s: str, p: str) -> bool:
"""思路:和第十题类似,*的规则不同,动态规划,dp[i][j]表示p[:i+1]可以匹配s[:j+1]. 匹配成功的时候,按模式串p的种类可分三种情况: case1. p[i] == '?' case2. p[i] == '*' case3. p[i] == s[j]"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""[44. 通配符匹配](https://leetcode-cn.com/problems/wildcard-matching/)"""
def isMatch(self, s: str, p: str) -> bool:
"""思路:和第十题类似,*的规则不同,动态规划,dp[i][j]表示p[:i+1]可以匹配s[:j+1]. 匹配成功的时候,按模式串p的种类可分三种情况: case1. p[i] == '?' case2. p[i] == '*' case3. p[i] == s[j]"""
n, m = (len(s), len(p))
... | the_stack_v2_python_sparse | leetcode/1-300/44.py | Rivarrl/leetcode_python | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.