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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c179f6185a227367bb957a4354ba34e1a24951b8 | [
"val = {'pay_now': operation_type == 'treasury' and 'pay_later' or 'pay_now', 'payment_option': operation_type == 'treasury' and 'with_writeoff' or 'without_writeoff'}\nif operation_type == 'treasury':\n val.update({'line_dr_ids': False})\n account = self.pool.get('res.partner').browse(cr, uid, partner_id, co... | <|body_start_0|>
val = {'pay_now': operation_type == 'treasury' and 'pay_later' or 'pay_now', 'payment_option': operation_type == 'treasury' and 'with_writeoff' or 'without_writeoff'}
if operation_type == 'treasury':
val.update({'line_dr_ids': False})
account = self.pool.get('res... | account_voucher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_voucher:
def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None):
"""Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return:... | stack_v2_sparse_classes_36k_train_027400 | 3,763 | no_license | [
{
"docstring": "Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return: dictionary of fields values",
"name": "onchange_operation_type",
"signature": "def onchange_operation_type(sel... | 5 | stack_v2_sparse_classes_30k_train_006275 | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None): Method that call when changing operation_type value, when operation is tr... | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None): Method that call when changing operation_type value, when operation is tr... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_voucher:
def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None):
"""Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_voucher:
def onchange_operation_type(self, cr, uid, ids, operation_type, partner_id, context=None):
"""Method that call when changing operation_type value, when operation is treasury feeding: * Reset line_dr_ids field * Make voucher with writeoff * Make voucher pay later @return: dictionary of... | the_stack_v2_python_sparse | v_7/Dongola/wafi/account_indirect_treasury_feeding/account_custom.py | musabahmed/baba | train | 0 | |
f4d8b32220926433d2d1a23a2e1371ff284c648b | [
"super(ClassificationModelWrapper, self).__init__()\nself.model: SwinTransformerV2 = model\nself.pooling: nn.Module = nn.AdaptiveAvgPool2d(1)\nself.classification_head: nn.Module = nn.Linear(in_features=output_channels, out_features=number_of_classes)",
"features: List[torch.Tensor] = self.model(input)\nclassific... | <|body_start_0|>
super(ClassificationModelWrapper, self).__init__()
self.model: SwinTransformerV2 = model
self.pooling: nn.Module = nn.AdaptiveAvgPool2d(1)
self.classification_head: nn.Module = nn.Linear(in_features=output_channels, out_features=number_of_classes)
<|end_body_0|>
<|body_... | Wraps a Swin Transformer V2 model to perform image classification. | ClassificationModelWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationModelWrapper:
"""Wraps a Swin Transformer V2 model to perform image classification."""
def __init__(self, model: SwinTransformerV2, number_of_classes: int=10, output_channels: int=768) -> None:
"""Constructor method :param model: (SwinTransformerV2) Swin Transformer V2 ... | stack_v2_sparse_classes_36k_train_027401 | 41,159 | no_license | [
{
"docstring": "Constructor method :param model: (SwinTransformerV2) Swin Transformer V2 model :param number_of_classes: (int) Number of classes to predict :param output_channels: (int) Output channels of the last feature map of the Swin Transformer V2 model",
"name": "__init__",
"signature": "def __ini... | 2 | stack_v2_sparse_classes_30k_train_011725 | Implement the Python class `ClassificationModelWrapper` described below.
Class description:
Wraps a Swin Transformer V2 model to perform image classification.
Method signatures and docstrings:
- def __init__(self, model: SwinTransformerV2, number_of_classes: int=10, output_channels: int=768) -> None: Constructor meth... | Implement the Python class `ClassificationModelWrapper` described below.
Class description:
Wraps a Swin Transformer V2 model to perform image classification.
Method signatures and docstrings:
- def __init__(self, model: SwinTransformerV2, number_of_classes: int=10, output_channels: int=768) -> None: Constructor meth... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ClassificationModelWrapper:
"""Wraps a Swin Transformer V2 model to perform image classification."""
def __init__(self, model: SwinTransformerV2, number_of_classes: int=10, output_channels: int=768) -> None:
"""Constructor method :param model: (SwinTransformerV2) Swin Transformer V2 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationModelWrapper:
"""Wraps a Swin Transformer V2 model to perform image classification."""
def __init__(self, model: SwinTransformerV2, number_of_classes: int=10, output_channels: int=768) -> None:
"""Constructor method :param model: (SwinTransformerV2) Swin Transformer V2 model :param ... | the_stack_v2_python_sparse | generated/test_ChristophReich1996_Swin_Transformer_V2.py | jansel/pytorch-jit-paritybench | train | 35 |
ff007b3d0666a62f2f445470b43b24805a201fb1 | [
"super(Union, self).__init__(metadata_processor=metadata_processor)\nif stream is not None:\n self._pfp__offset = stream.tell()\nself._pfp__buff = six.BytesIO()",
"res = super(Union, self)._pfp__add_child(name, child)\nself._pfp__buff.seek(0, 0)\nchild._pfp__build(stream=self._pfp__buff)\nsize = len(self._pfp_... | <|body_start_0|>
super(Union, self).__init__(metadata_processor=metadata_processor)
if stream is not None:
self._pfp__offset = stream.tell()
self._pfp__buff = six.BytesIO()
<|end_body_0|>
<|body_start_1|>
res = super(Union, self)._pfp__add_child(name, child)
self._pf... | A union field, where each member is an alternate view of the data | Union | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Union:
"""A union field, where each member is an alternate view of the data"""
def __init__(self, stream=None, metadata_processor=None):
"""Init the union and its buff stream"""
<|body_0|>
def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the... | stack_v2_sparse_classes_36k_train_027402 | 47,990 | permissive | [
{
"docstring": "Init the union and its buff stream",
"name": "__init__",
"signature": "def __init__(self, stream=None, metadata_processor=None)"
},
{
"docstring": "Add a child to the Union field :name: The name of the child :child: A :class:`.Field` instance :returns: The resulting field",
"... | 6 | stack_v2_sparse_classes_30k_test_000344 | Implement the Python class `Union` described below.
Class description:
A union field, where each member is an alternate view of the data
Method signatures and docstrings:
- def __init__(self, stream=None, metadata_processor=None): Init the union and its buff stream
- def _pfp__add_child(self, name, child, stream=None... | Implement the Python class `Union` described below.
Class description:
A union field, where each member is an alternate view of the data
Method signatures and docstrings:
- def __init__(self, stream=None, metadata_processor=None): Init the union and its buff stream
- def _pfp__add_child(self, name, child, stream=None... | e4cba731aad43d8d217895d3d6ec7b41349794aa | <|skeleton|>
class Union:
"""A union field, where each member is an alternate view of the data"""
def __init__(self, stream=None, metadata_processor=None):
"""Init the union and its buff stream"""
<|body_0|>
def _pfp__add_child(self, name, child, stream=None):
"""Add a child to the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Union:
"""A union field, where each member is an alternate view of the data"""
def __init__(self, stream=None, metadata_processor=None):
"""Init the union and its buff stream"""
super(Union, self).__init__(metadata_processor=metadata_processor)
if stream is not None:
s... | the_stack_v2_python_sparse | pfp/fields.py | strazzere/pfp | train | 1 |
772983b8a117cd6885490e4147740dc1164f2f7b | [
"ParticleFilter.__init__(self, number_of_particles, limits, process_noise, measurement_noise)\nself.resolutions = resolutions\nself.epsilon = epsilon\nself.upper_quantile = upper_quantile\nself.minimum_number_of_particles = int(min_number_particles)\nself.maximum_number_of_particles = int(max_number_particles)",
... | <|body_start_0|>
ParticleFilter.__init__(self, number_of_particles, limits, process_noise, measurement_noise)
self.resolutions = resolutions
self.epsilon = epsilon
self.upper_quantile = upper_quantile
self.minimum_number_of_particles = int(min_number_particles)
self.maxim... | Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min) | AdaptiveParticleFilterKld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptiveParticleFilterKld:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, proces... | stack_v2_sparse_classes_36k_train_027403 | 6,194 | no_license | [
{
"docstring": "Initialize the adaptive particle filter using Kullback-Leibler divergence (KLD) sampling proposed in [1]. [1] Fox, Dieter. \"Adapting the sample size in particle filters through KLD-sampling.\" The international Journal of robotics research 22.12 (2003): 985-1003. :param number_of_particles: Num... | 2 | stack_v2_sparse_classes_30k_val_000611 | Implement the Python class `AdaptiveParticleFilterKld` described below.
Class description:
Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)
Method signatures and ... | Implement the Python class `AdaptiveParticleFilterKld` described below.
Class description:
Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)
Method signatures and ... | 4e5197c38a9d241d9ea06c06ab9fc893ffb8c70b | <|skeleton|>
class AdaptiveParticleFilterKld:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, proces... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdaptiveParticleFilterKld:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, process_noise, meas... | the_stack_v2_python_sparse | core/particle_filters/adaptive_particle_filter_kld.py | eternalamit5/Learning-Nuggets | train | 0 |
8fad2bf8da57820afd91f5f753e320cc912d39ae | [
"field = super(ProgramUsageAdmin, self).formfield_for_dbfield(db_field, **kwargs)\nif db_field.name == 'klass' and 'request' in kwargs:\n user = kwargs['request'].user\n field.queryset = models.Klass.objects.filter(contract__client__managers=user)\nreturn field",
"super(ProgramUsageAdmin, self).save_model(r... | <|body_start_0|>
field = super(ProgramUsageAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'klass' and 'request' in kwargs:
user = kwargs['request'].user
field.queryset = models.Klass.objects.filter(contract__client__managers=user)
return field
... | ProgramUsageAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramUsageAdmin:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Restrict choices of klasses to the related to current user. Get the user from request and filters klasses from clients where the user is manager. This way, it is not possible to start a program for a client throug... | stack_v2_sparse_classes_36k_train_027404 | 7,936 | no_license | [
{
"docstring": "Restrict choices of klasses to the related to current user. Get the user from request and filters klasses from clients where the user is manager. This way, it is not possible to start a program for a client through admin, it is only possible to start a program to himself for test purpouses.",
... | 2 | stack_v2_sparse_classes_30k_train_009212 | Implement the Python class `ProgramUsageAdmin` described below.
Class description:
Implement the ProgramUsageAdmin class.
Method signatures and docstrings:
- def formfield_for_dbfield(self, db_field, **kwargs): Restrict choices of klasses to the related to current user. Get the user from request and filters klasses f... | Implement the Python class `ProgramUsageAdmin` described below.
Class description:
Implement the ProgramUsageAdmin class.
Method signatures and docstrings:
- def formfield_for_dbfield(self, db_field, **kwargs): Restrict choices of klasses to the related to current user. Get the user from request and filters klasses f... | e2d24a82462a735fc722f0b228be04a4495185c1 | <|skeleton|>
class ProgramUsageAdmin:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Restrict choices of klasses to the related to current user. Get the user from request and filters klasses from clients where the user is manager. This way, it is not possible to start a program for a client throug... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgramUsageAdmin:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Restrict choices of klasses to the related to current user. Get the user from request and filters klasses from clients where the user is manager. This way, it is not possible to start a program for a client through admin, it is... | the_stack_v2_python_sparse | exercises/admin.py | fredericosachweh/amostra2 | train | 0 | |
fae33b1f82e046685bc49eabc32d474b99b91da2 | [
"self.input_list = [['HTML', 'C#'], ['C#', 'Python'], ['Python', 'HTML']]\nself.input_results = [0, 0, 1]\nself.output = 'Python'\nreturn (self.input_list, self.input_results, self.output)",
"input_list, input_results, output = self.setUp()\noutput_method = tournamentWinner(input_list, input_results)\nself.assert... | <|body_start_0|>
self.input_list = [['HTML', 'C#'], ['C#', 'Python'], ['Python', 'HTML']]
self.input_results = [0, 0, 1]
self.output = 'Python'
return (self.input_list, self.input_results, self.output)
<|end_body_0|>
<|body_start_1|>
input_list, input_results, output = self.setU... | Class with unittests for TournamentWinner.py | test_TournamentWinner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_TournamentWinner:
"""Class with unittests for TournamentWinner.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027405 | 1,093 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_TournamentWinner` described below.
Class description:
Class with unittests for TournamentWinner.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_TournamentWinner` described below.
Class description:
Class with unittests for TournamentWinner.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_TournamentWinner:
... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_TournamentWinner:
"""Class with unittests for TournamentWinner.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_TournamentWinner:
"""Class with unittests for TournamentWinner.py"""
def setUp(self):
"""Sets up input."""
self.input_list = [['HTML', 'C#'], ['C#', 'Python'], ['Python', 'HTML']]
self.input_results = [0, 0, 1]
self.output = 'Python'
return (self.input_list, s... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Easy/TournamentWinner/test_TournamentWinner.py | JakubKazimierski/PythonPortfolio | train | 9 |
f5a96a4aa95f78f534e578d094ca6e942af5505c | [
"super(Conformer, self).__init__()\nself.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nself.ff_module1 = Residual(module=FFModule(d_model=d_model, h_size=ff1_hsize, dropout=ff1_dropout), half=True)\nself.mha_module = Residual(module=MHAModule(d_model=d_model, n_head=n_head, dropout=mha_drop... | <|body_start_0|>
super(Conformer, self).__init__()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.ff_module1 = Residual(module=FFModule(d_model=d_model, h_size=ff1_hsize, dropout=ff1_dropout), half=True)
self.mha_module = Residual(module=MHAModule(d_model... | Conformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conformer:
def __init__(self, d_model, ff1_hsize=1024, ff1_dropout=0.2, n_head=4, mha_dropout=0.2, kernel_size=3, conv_dropout=0.2, ff2_hsize=1024, ff2_dropout=0.2):
"""RNN enhanced Transformer Block. Args: d_model (int): Embedded dimension of input. ff1_hsize (int): Hidden size of th fi... | stack_v2_sparse_classes_36k_train_027406 | 2,577 | permissive | [
{
"docstring": "RNN enhanced Transformer Block. Args: d_model (int): Embedded dimension of input. ff1_hsize (int): Hidden size of th first FFN ff1_drop (float): Dropout rate for the first FFN n_head (int): Number of heads for MHA mha_dropout (float): Dropout rate for the first MHA epsilon (float): Epsilon kerne... | 2 | stack_v2_sparse_classes_30k_train_000648 | Implement the Python class `Conformer` described below.
Class description:
Implement the Conformer class.
Method signatures and docstrings:
- def __init__(self, d_model, ff1_hsize=1024, ff1_dropout=0.2, n_head=4, mha_dropout=0.2, kernel_size=3, conv_dropout=0.2, ff2_hsize=1024, ff2_dropout=0.2): RNN enhanced Transfor... | Implement the Python class `Conformer` described below.
Class description:
Implement the Conformer class.
Method signatures and docstrings:
- def __init__(self, d_model, ff1_hsize=1024, ff1_dropout=0.2, n_head=4, mha_dropout=0.2, kernel_size=3, conv_dropout=0.2, ff2_hsize=1024, ff2_dropout=0.2): RNN enhanced Transfor... | bc599a352401a7e135ebaabead4d8e6d8835747e | <|skeleton|>
class Conformer:
def __init__(self, d_model, ff1_hsize=1024, ff1_dropout=0.2, n_head=4, mha_dropout=0.2, kernel_size=3, conv_dropout=0.2, ff2_hsize=1024, ff2_dropout=0.2):
"""RNN enhanced Transformer Block. Args: d_model (int): Embedded dimension of input. ff1_hsize (int): Hidden size of th fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conformer:
def __init__(self, d_model, ff1_hsize=1024, ff1_dropout=0.2, n_head=4, mha_dropout=0.2, kernel_size=3, conv_dropout=0.2, ff2_hsize=1024, ff2_dropout=0.2):
"""RNN enhanced Transformer Block. Args: d_model (int): Embedded dimension of input. ff1_hsize (int): Hidden size of th first FFN ff1_dr... | the_stack_v2_python_sparse | Sensation6/Conformer/CF.py | Geson-anko/JARVIS3 | train | 1 | |
f198abe47693fc23bb421d81567eb886a22ec6cc | [
"seen = kwargs.get('_commit_seen', set())\nif _checksetseen(id(self), seen):\n return\ndeep = kwargs.get('deep', True)\nstate = dict()\nfor key, val in self.__dict__.items():\n if isinstance(val, Transaction):\n state[key] = val\n if deep:\n val.commit(_commit_seen=seen)\n elif key... | <|body_start_0|>
seen = kwargs.get('_commit_seen', set())
if _checksetseen(id(self), seen):
return
deep = kwargs.get('deep', True)
state = dict()
for key, val in self.__dict__.items():
if isinstance(val, Transaction):
state[key] = val
... | This class allows sub-classes to commit changes to an instance to a history, and rollback to previous states. Because the class only stores attributes in self.__dict__ sub-classes need to use the methods __getstate__ and __setstate__ to provide additional state information. See the Transactionlist below for an example ... | Transaction | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transaction:
"""This class allows sub-classes to commit changes to an instance to a history, and rollback to previous states. Because the class only stores attributes in self.__dict__ sub-classes need to use the methods __getstate__ and __setstate__ to provide additional state information. See th... | stack_v2_sparse_classes_36k_train_027407 | 5,597 | permissive | [
{
"docstring": "Commit the object state. If the optional argument \"deep\" is set to False, objects of class Transaction stored in this object will not be committed.",
"name": "commit",
"signature": "def commit(self, **kwargs)"
},
{
"docstring": "Rollback the last committed object state. If the ... | 2 | null | Implement the Python class `Transaction` described below.
Class description:
This class allows sub-classes to commit changes to an instance to a history, and rollback to previous states. Because the class only stores attributes in self.__dict__ sub-classes need to use the methods __getstate__ and __setstate__ to provi... | Implement the Python class `Transaction` described below.
Class description:
This class allows sub-classes to commit changes to an instance to a history, and rollback to previous states. Because the class only stores attributes in self.__dict__ sub-classes need to use the methods __getstate__ and __setstate__ to provi... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class Transaction:
"""This class allows sub-classes to commit changes to an instance to a history, and rollback to previous states. Because the class only stores attributes in self.__dict__ sub-classes need to use the methods __getstate__ and __setstate__ to provide additional state information. See th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transaction:
"""This class allows sub-classes to commit changes to an instance to a history, and rollback to previous states. Because the class only stores attributes in self.__dict__ sub-classes need to use the methods __getstate__ and __setstate__ to provide additional state information. See the Transaction... | the_stack_v2_python_sparse | recipes/Python/551788_Transactionable_Objects_reloaded/recipe-551788.py | betty29/code-1 | train | 0 |
385e299765b8c3069eef30ee86c7eb7695710f56 | [
"net = super().get_net()\nnet.add(Dense(5))\nnet.add(Softmax())\nreturn net",
"data_loader = DataLoader()\nx, y = data_loader.load_data(data_file, has_labels, objects_per_row)\nif has_labels:\n self.predictions_to_labels = data_loader.predictions_to_labels\n self.split(x, y)\nreturn (x, y)",
"optimizer = ... | <|body_start_0|>
net = super().get_net()
net.add(Dense(5))
net.add(Softmax())
return net
<|end_body_0|>
<|body_start_1|>
data_loader = DataLoader()
x, y = data_loader.load_data(data_file, has_labels, objects_per_row)
if has_labels:
self.predictions_to... | Our classifier used for multi-class classification | MultiClassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiClassifier:
"""Our classifier used for multi-class classification"""
def get_net(self):
"""Get the network. Use the base network, append Dense(5) with softmax"""
<|body_0|>
def load_data(self, data_file: str=None, has_labels: bool=True, objects_per_row: int=None):
... | stack_v2_sparse_classes_36k_train_027408 | 2,474 | permissive | [
{
"docstring": "Get the network. Use the base network, append Dense(5) with softmax",
"name": "get_net",
"signature": "def get_net(self)"
},
{
"docstring": "Inherit doc",
"name": "load_data",
"signature": "def load_data(self, data_file: str=None, has_labels: bool=True, objects_per_row: i... | 4 | stack_v2_sparse_classes_30k_train_007258 | Implement the Python class `MultiClassifier` described below.
Class description:
Our classifier used for multi-class classification
Method signatures and docstrings:
- def get_net(self): Get the network. Use the base network, append Dense(5) with softmax
- def load_data(self, data_file: str=None, has_labels: bool=Tru... | Implement the Python class `MultiClassifier` described below.
Class description:
Our classifier used for multi-class classification
Method signatures and docstrings:
- def get_net(self): Get the network. Use the base network, append Dense(5) with softmax
- def load_data(self, data_file: str=None, has_labels: bool=Tru... | 4b6c563f93e1eb7fc90f66a9a6ada16c07664d71 | <|skeleton|>
class MultiClassifier:
"""Our classifier used for multi-class classification"""
def get_net(self):
"""Get the network. Use the base network, append Dense(5) with softmax"""
<|body_0|>
def load_data(self, data_file: str=None, has_labels: bool=True, objects_per_row: int=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiClassifier:
"""Our classifier used for multi-class classification"""
def get_net(self):
"""Get the network. Use the base network, append Dense(5) with softmax"""
net = super().get_net()
net.add(Dense(5))
net.add(Softmax())
return net
def load_data(self, d... | the_stack_v2_python_sparse | Element2/MultiClassification.py | AuckeBos/MLiPPaA | train | 1 |
8ff77552a38c02c2589e0c009711975985c866d4 | [
"try:\n if not current_user.is_admin() and current_user.account_id != jobs.find_job_by_label_id(label_id).account_id:\n return (get_message_json('用户无法访问其他用户的标注信息'), HTTPStatus.FORBIDDEN)\n result = labels.find_label_by_id(label_id)\n if result is None:\n return (get_message_json('标注不存在'), HTT... | <|body_start_0|>
try:
if not current_user.is_admin() and current_user.account_id != jobs.find_job_by_label_id(label_id).account_id:
return (get_message_json('用户无法访问其他用户的标注信息'), HTTPStatus.FORBIDDEN)
result = labels.find_label_by_id(label_id)
if result is None:... | Deal with single label. | LabelResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelResource:
"""Deal with single label."""
def get(self, label_id):
"""Retrieve a single label by id."""
<|body_0|>
def put(self, label_id):
"""Edit a single label by id."""
<|body_1|>
def delete(self, label_id):
"""Delete a single label by... | stack_v2_sparse_classes_36k_train_027409 | 5,560 | no_license | [
{
"docstring": "Retrieve a single label by id.",
"name": "get",
"signature": "def get(self, label_id)"
},
{
"docstring": "Edit a single label by id.",
"name": "put",
"signature": "def put(self, label_id)"
},
{
"docstring": "Delete a single label by id.",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_000306 | Implement the Python class `LabelResource` described below.
Class description:
Deal with single label.
Method signatures and docstrings:
- def get(self, label_id): Retrieve a single label by id.
- def put(self, label_id): Edit a single label by id.
- def delete(self, label_id): Delete a single label by id. | Implement the Python class `LabelResource` described below.
Class description:
Deal with single label.
Method signatures and docstrings:
- def get(self, label_id): Retrieve a single label by id.
- def put(self, label_id): Edit a single label by id.
- def delete(self, label_id): Delete a single label by id.
<|skeleto... | 747d1595a2918786f8cf953200c167601bf90977 | <|skeleton|>
class LabelResource:
"""Deal with single label."""
def get(self, label_id):
"""Retrieve a single label by id."""
<|body_0|>
def put(self, label_id):
"""Edit a single label by id."""
<|body_1|>
def delete(self, label_id):
"""Delete a single label by... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelResource:
"""Deal with single label."""
def get(self, label_id):
"""Retrieve a single label by id."""
try:
if not current_user.is_admin() and current_user.account_id != jobs.find_job_by_label_id(label_id).account_id:
return (get_message_json('用户无法访问其他用户的标注... | the_stack_v2_python_sparse | server/app/api/label.py | yoshua133/AppServer | train | 0 |
f8e5679c49ff1f700cc97bc9e6ca4d2d23d27725 | [
"n, m = (len(matrix), len(matrix[0]))\nfor i in range(n):\n for j in range(m):\n if i == j or i > j:\n continue\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nfor i in range(n):\n for j in range(m // 2):\n matrix[i][j], matrix[i][m - j - 1] = (matrix[i][m - j - 1]... | <|body_start_0|>
n, m = (len(matrix), len(matrix[0]))
for i in range(n):
for j in range(m):
if i == j or i > j:
continue
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
for i in range(n):
for j in range(m // 2)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate_traverse_flip(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate_intuition(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead.... | stack_v2_sparse_classes_36k_train_027410 | 1,068 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotate_traverse_flip",
"signature": "def rotate_traverse_flip(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotate_intuition",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def rotate_intuition(self, matrix: List[List[int]]) -> ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_traverse_flip(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def rotate_intuition(self, matrix: List[List[int]]) -> ... | 5ed070f22f4bc29777ee5cbb01bb9583726d8799 | <|skeleton|>
class Solution:
def rotate_traverse_flip(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate_intuition(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate_traverse_flip(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
n, m = (len(matrix), len(matrix[0]))
for i in range(n):
for j in range(m):
if i == j or i > j:
contin... | the_stack_v2_python_sparse | 48_rotate_image.py | zdadadaz/coding_practice | train | 0 | |
de62896e2c20de25c8a6502ce5ccb7cf989c0070 | [
"self.space = space if space else SparkSpace(context=self.engine.context)\nself.space.connect()\ntitle = u'{} - {}'.format(self.space.configured_title(), _(u'Audited content'))\nself.space.bond(title=title)\nself.context = Context()\nself.mouth = Queue()\nself.speaker = speaker if speaker else Speaker(engine=self.e... | <|body_start_0|>
self.space = space if space else SparkSpace(context=self.engine.context)
self.space.connect()
title = u'{} - {}'.format(self.space.configured_title(), _(u'Audited content'))
self.space.bond(title=title)
self.context = Context()
self.mouth = Queue()
... | Replicates messages to a secondary space | SpaceUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceUpdater:
"""Replicates messages to a secondary space"""
def on_init(self, space=None, speaker=None, **kwargs):
"""Replicates messages to a secondary space :param space: the target space to use (optional) :type space: Space :param speaker: the speaker instance to use (optional) :... | stack_v2_sparse_classes_36k_train_027411 | 3,870 | permissive | [
{
"docstring": "Replicates messages to a secondary space :param space: the target space to use (optional) :type space: Space :param speaker: the speaker instance to use (optional) :type speaker: Speaker Parameters are provided mainly for test injection.",
"name": "on_init",
"signature": "def on_init(sel... | 3 | null | Implement the Python class `SpaceUpdater` described below.
Class description:
Replicates messages to a secondary space
Method signatures and docstrings:
- def on_init(self, space=None, speaker=None, **kwargs): Replicates messages to a secondary space :param space: the target space to use (optional) :type space: Space... | Implement the Python class `SpaceUpdater` described below.
Class description:
Replicates messages to a secondary space
Method signatures and docstrings:
- def on_init(self, space=None, speaker=None, **kwargs): Replicates messages to a secondary space :param space: the target space to use (optional) :type space: Space... | daf64fbab4085d1591bf9a1aecd06b4fc615d132 | <|skeleton|>
class SpaceUpdater:
"""Replicates messages to a secondary space"""
def on_init(self, space=None, speaker=None, **kwargs):
"""Replicates messages to a secondary space :param space: the target space to use (optional) :type space: Space :param speaker: the speaker instance to use (optional) :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpaceUpdater:
"""Replicates messages to a secondary space"""
def on_init(self, space=None, speaker=None, **kwargs):
"""Replicates messages to a secondary space :param space: the target space to use (optional) :type space: Space :param speaker: the speaker instance to use (optional) :type speaker:... | the_stack_v2_python_sparse | shellbot/updaters/space.py | romainkotarba/shellbot | train | 0 |
9cb9763a33648590bea43184a84b938fa55347cf | [
"super(FrenchBonsaiTokenizer, self).__init__()\nself._sentence_tokenizer = data.load('tokenizers/punkt/french.pickle')\nself._encoding = encoding",
"if text != '':\n return self._sentence_tokenizer.tokenize(text)\nreturn []",
"tokenized_sentences = []\ninput_filepath = path.join(tempfile.gettempdir(), '.bons... | <|body_start_0|>
super(FrenchBonsaiTokenizer, self).__init__()
self._sentence_tokenizer = data.load('tokenizers/punkt/french.pickle')
self._encoding = encoding
<|end_body_0|>
<|body_start_1|>
if text != '':
return self._sentence_tokenizer.tokenize(text)
return []
<|e... | Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module for sentence tokenization and the bonsai word tokenizer for word tokenization. | FrenchBonsaiTokenizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrenchBonsaiTokenizer:
"""Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module for sentence tokenization and the bonsai word tokenizer for word tokenization."""
def __init__(self, encoding):
"""Constructor."""
<|body_0|>
def tokenizeS... | stack_v2_sparse_classes_36k_train_027412 | 2,773 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, encoding)"
},
{
"docstring": "Tokenizes a text into sentences. Args: text: The C{string} text to tokenize. Returns: The ordered C{list} of every C{string} sentence of the C{text}.",
"name": "tokenizeSentences... | 3 | stack_v2_sparse_classes_30k_train_012139 | Implement the Python class `FrenchBonsaiTokenizer` described below.
Class description:
Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module for sentence tokenization and the bonsai word tokenizer for word tokenization.
Method signatures and docstrings:
- def __init__(self, encodin... | Implement the Python class `FrenchBonsaiTokenizer` described below.
Class description:
Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module for sentence tokenization and the bonsai word tokenizer for word tokenization.
Method signatures and docstrings:
- def __init__(self, encodin... | a66cf98b11260d2b74cd990f36f5dcde192b0346 | <|skeleton|>
class FrenchBonsaiTokenizer:
"""Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module for sentence tokenization and the bonsai word tokenizer for word tokenization."""
def __init__(self, encoding):
"""Constructor."""
<|body_0|>
def tokenizeS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrenchBonsaiTokenizer:
"""Sentence and word tokenizer. Sentence and word tokenizer using the NLTK's C{punkt} module for sentence tokenization and the bonsai word tokenizer for word tokenization."""
def __init__(self, encoding):
"""Constructor."""
super(FrenchBonsaiTokenizer, self).__init_... | the_stack_v2_python_sparse | src/keybench/main/nlp_tool/implementation/tokenizer/french_bonsai_tokenizer.py | Archer-W/KeyBench | train | 0 |
68f9d96a05873787243d081f2baea52a71c59f78 | [
"self.logger = logging.getLogger(__name__)\nself.logger.addHandler(logging.NullHandler())\nself.logger.setLevel(logging_level)",
"filename = split(REGNSKABSDATA1000_URL)[-1]\nfull_filename = self.full_filename(filename)\nreturn full_filename",
"if sep in filename:\n return filename\nelse:\n return join(da... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.logger.addHandler(logging.NullHandler())
self.logger.setLevel(logging_level)
<|end_body_0|>
<|body_start_1|>
filename = split(REGNSKABSDATA1000_URL)[-1]
full_filename = self.full_filename(filename)
return fu... | Interface to Regnskabsdata sample. References ---------- http://datahub.virk.dk/dataset/regnskabsdata-fra-selskaber-sample | Regnskabsdata1000 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regnskabsdata1000:
"""Interface to Regnskabsdata sample. References ---------- http://datahub.virk.dk/dataset/regnskabsdata-fra-selskaber-sample"""
def __init__(self, logging_level=logging.WARN):
"""Setup logger."""
<|body_0|>
def zip_filename(self):
"""Return fu... | stack_v2_sparse_classes_36k_train_027413 | 15,506 | permissive | [
{
"docstring": "Setup logger.",
"name": "__init__",
"signature": "def __init__(self, logging_level=logging.WARN)"
},
{
"docstring": "Return full filename of zip file with XBRL.",
"name": "zip_filename",
"signature": "def zip_filename(self)"
},
{
"docstring": "Return filename with... | 6 | stack_v2_sparse_classes_30k_train_015161 | Implement the Python class `Regnskabsdata1000` described below.
Class description:
Interface to Regnskabsdata sample. References ---------- http://datahub.virk.dk/dataset/regnskabsdata-fra-selskaber-sample
Method signatures and docstrings:
- def __init__(self, logging_level=logging.WARN): Setup logger.
- def zip_file... | Implement the Python class `Regnskabsdata1000` described below.
Class description:
Interface to Regnskabsdata sample. References ---------- http://datahub.virk.dk/dataset/regnskabsdata-fra-selskaber-sample
Method signatures and docstrings:
- def __init__(self, logging_level=logging.WARN): Setup logger.
- def zip_file... | b5ace62550e37b20b1ec9e2e5a24ae2cefbb1e18 | <|skeleton|>
class Regnskabsdata1000:
"""Interface to Regnskabsdata sample. References ---------- http://datahub.virk.dk/dataset/regnskabsdata-fra-selskaber-sample"""
def __init__(self, logging_level=logging.WARN):
"""Setup logger."""
<|body_0|>
def zip_filename(self):
"""Return fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Regnskabsdata1000:
"""Interface to Regnskabsdata sample. References ---------- http://datahub.virk.dk/dataset/regnskabsdata-fra-selskaber-sample"""
def __init__(self, logging_level=logging.WARN):
"""Setup logger."""
self.logger = logging.getLogger(__name__)
self.logger.addHandler(... | the_stack_v2_python_sparse | cvrminer/xbrler.py | fnielsen/cvrminer | train | 3 |
db95b3aea68197823ccc068736545fbfa12ff048 | [
"self.weight_keep_drop = weight_keep_drop\nself.mode = mode\nsuper(WeightDropLSTMCell, self).__init__(num_units, forget_bias, state_is_tuple, activation, reuse)",
"sigmoid = tf.sigmoid\nif self._state_is_tuple:\n c, h = state\nelse:\n c, h = tf.split(value=state, num_or_size_splits=2, axis=1)\nif self._line... | <|body_start_0|>
self.weight_keep_drop = weight_keep_drop
self.mode = mode
super(WeightDropLSTMCell, self).__init__(num_units, forget_bias, state_is_tuple, activation, reuse)
<|end_body_0|>
<|body_start_1|>
sigmoid = tf.sigmoid
if self._state_is_tuple:
c, h = state
... | WeightDropLSTMCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightDropLSTMCell:
def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None):
"""Initialize the parameters for an LSTM cell."""
<|body_0|>
def call(self, inputs, state):
"... | stack_v2_sparse_classes_36k_train_027414 | 2,572 | permissive | [
{
"docstring": "Initialize the parameters for an LSTM cell.",
"name": "__init__",
"signature": "def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None)"
},
{
"docstring": "Long short-term memory cell... | 2 | stack_v2_sparse_classes_30k_train_004088 | Implement the Python class `WeightDropLSTMCell` described below.
Class description:
Implement the WeightDropLSTMCell class.
Method signatures and docstrings:
- def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None): Init... | Implement the Python class `WeightDropLSTMCell` described below.
Class description:
Implement the WeightDropLSTMCell class.
Method signatures and docstrings:
- def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None): Init... | de8095ecef9300e0f670062c2779459c19c2d49d | <|skeleton|>
class WeightDropLSTMCell:
def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None):
"""Initialize the parameters for an LSTM cell."""
<|body_0|>
def call(self, inputs, state):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightDropLSTMCell:
def __init__(self, num_units, weight_keep_drop=0.7, mode=tf.estimator.ModeKeys.TRAIN, forget_bias=1.0, state_is_tuple=True, activation=None, reuse=None):
"""Initialize the parameters for an LSTM cell."""
self.weight_keep_drop = weight_keep_drop
self.mode = mode
... | the_stack_v2_python_sparse | utils/weight_drop_lstm.py | Johnnytjn/RNN_classify | train | 0 | |
2d1b333d2e1403d1582431f1a6dc5348d084f571 | [
"m = abs(n)\nans = 1\nwhile m > 0:\n if m & 1 == 1:\n ans *= x\n x *= x\n m >>= 1\nreturn ans if n >= 0 else 1 / ans",
"if n == 0:\n return 1\nelif n == 1:\n return x\nelif n < 0:\n return self.myPow(1 / x, -n)\nelif n % 2 == 0:\n tmp = self.myPow(x, n // 2)\n return tmp * tmp\nelse... | <|body_start_0|>
m = abs(n)
ans = 1
while m > 0:
if m & 1 == 1:
ans *= x
x *= x
m >>= 1
return ans if n >= 0 else 1 / ans
<|end_body_0|>
<|body_start_1|>
if n == 0:
return 1
elif n == 1:
return x... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow_recursive(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
def myPow_dp(self, x, n):
""":type x: float :type n: int :rtyp... | stack_v2_sparse_classes_36k_train_027415 | 2,143 | no_license | [
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow",
"signature": "def myPow(self, x, n)"
},
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow_recursive",
"signature": "def myPow_recursive(self, x, n)"
},
{
"docstring": ":type x: f... | 3 | stack_v2_sparse_classes_30k_train_000276 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
- def myPow_recursive(self, x, n): :type x: float :type n: int :rtype: float
- def myPow_dp(self, x, n): :type x:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
- def myPow_recursive(self, x, n): :type x: float :type n: int :rtype: float
- def myPow_dp(self, x, n): :type x:... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow_recursive(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
def myPow_dp(self, x, n):
""":type x: float :type n: int :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
m = abs(n)
ans = 1
while m > 0:
if m & 1 == 1:
ans *= x
x *= x
m >>= 1
return ans if n >= 0 else 1 / ans
def myPow_recursive(self, x... | the_stack_v2_python_sparse | src/lt_50.py | oxhead/CodingYourWay | train | 0 | |
06526696370a81b601f219fb597e4e3a8edaa089 | [
"length = len(nums)\nsubsets = []\nnums.sort()\n\ndef dfs(index, subset):\n \"\"\"\n :type index: int\n :type subset: List[int]\n :rtype void\n \"\"\"\n subsets.append(subset)\n if index >= length:\n return\n for i in range(index, length):\n if i... | <|body_start_0|>
length = len(nums)
subsets = []
nums.sort()
def dfs(index, subset):
"""
:type index: int
:type subset: List[int]
:rtype void
"""
subsets.append(subset)
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
"""Implement with dfs :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
"""Implement with iteration. :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_027416 | 1,872 | no_license | [
{
"docstring": "Implement with dfs :type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
},
{
"docstring": "Implement with iteration. :type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): Implement with dfs :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): Implement with iteration. :type nums: List[int]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): Implement with dfs :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): Implement with iteration. :type nums: List[int]... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
"""Implement with dfs :type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
"""Implement with iteration. :type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subsetsWithDup(self, nums):
"""Implement with dfs :type nums: List[int] :rtype: List[List[int]]"""
length = len(nums)
subsets = []
nums.sort()
def dfs(index, subset):
"""
:type index: int
:type subset: L... | the_stack_v2_python_sparse | python_solution/Backtracking/90_SubsetsII.py | Dimen61/leetcode | train | 4 | |
e8f7f308fbdb781159ad5ed4ea769ea521670437 | [
"for object_query in self.query:\n query_type = object_query.get('type', 'values')\n if query_type not in {'values', 'ids', 'count'}:\n raise NotImplementedError(\"Only 'values', 'ids' and 'count' queries are supported now\")\n model = inflector.get_model(object_query['object_name'])\n if query_t... | <|body_start_0|>
for object_query in self.query:
query_type = object_query.get('type', 'values')
if query_type not in {'values', 'ids', 'count'}:
raise NotImplementedError("Only 'values', 'ids' and 'count' queries are supported now")
model = inflector.get_mode... | Helper class for handling request queries for query API. query object = [ { # the same parameters as in QueryHelper type: "values", "ids" or "count" - the type of results requested fields: [ a list of fields to include in JSON if type is "values" ] } ] After the query is done (by `get_results` method), the results are ... | DefaultHandler | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultHandler:
"""Helper class for handling request queries for query API. query object = [ { # the same parameters as in QueryHelper type: "values", "ids" or "count" - the type of results requested fields: [ a list of fields to include in JSON if type is "values" ] } ] After the query is done (... | stack_v2_sparse_classes_36k_train_027417 | 3,449 | permissive | [
{
"docstring": "Filter the objects and get their information. Updates self.query items with their results. The type of results required is read from \"type\" parameter of every object_query in self.query. Returns: list of dicts: same query as the input with requested results that match the filter.",
"name":... | 3 | null | Implement the Python class `DefaultHandler` described below.
Class description:
Helper class for handling request queries for query API. query object = [ { # the same parameters as in QueryHelper type: "values", "ids" or "count" - the type of results requested fields: [ a list of fields to include in JSON if type is "... | Implement the Python class `DefaultHandler` described below.
Class description:
Helper class for handling request queries for query API. query object = [ { # the same parameters as in QueryHelper type: "values", "ids" or "count" - the type of results requested fields: [ a list of fields to include in JSON if type is "... | 9bdc0fc6ca9e252f4919db682d80e360d5581eb4 | <|skeleton|>
class DefaultHandler:
"""Helper class for handling request queries for query API. query object = [ { # the same parameters as in QueryHelper type: "values", "ids" or "count" - the type of results requested fields: [ a list of fields to include in JSON if type is "values" ] } ] After the query is done (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultHandler:
"""Helper class for handling request queries for query API. query object = [ { # the same parameters as in QueryHelper type: "values", "ids" or "count" - the type of results requested fields: [ a list of fields to include in JSON if type is "values" ] } ] After the query is done (by `get_resul... | the_stack_v2_python_sparse | src/ggrc/query/default_handler.py | HLD/ggrc-core | train | 0 |
6c7d427a36f440e5a1aa19c82fce7f47b2a2432a | [
"self.minStepSize = min_alpha_step\nself.dampedError = damped_error\nself.stepSize = alpha_step",
"direction = state['direction']\nif 'initial_alpha_step' in state:\n stepSize = state['initial_alpha_step']\nelse:\n stepSize = self.stepSize\ncurrentValue = function(origin)\noptimalPoint = origin + stepSize *... | <|body_start_0|>
self.minStepSize = min_alpha_step
self.dampedError = damped_error
self.stepSize = alpha_step
<|end_body_0|>
<|body_start_1|>
direction = state['direction']
if 'initial_alpha_step' in state:
stepSize = state['initial_alpha_step']
else:
... | A damped line search, takes a point and a direction. Tests a new point for minimization, if it is greater that the current cost times (1 + error), the step is divided by two, until the step is too small | DampedLineSearch | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DampedLineSearch:
"""A damped line search, takes a point and a direction. Tests a new point for minimization, if it is greater that the current cost times (1 + error), the step is divided by two, until the step is too small"""
def __init__(self, min_alpha_step, damped_error, alpha_step=1.0, ... | stack_v2_sparse_classes_36k_train_027418 | 1,645 | permissive | [
{
"docstring": "Needs to have : - a minimum step size (min_alpha_step) - a factor to allow the cost to rise a little bit (damped_error) Can have : - a step modifier, a factor to modulate the step (alpha_step = 1.)",
"name": "__init__",
"signature": "def __init__(self, min_alpha_step, damped_error, alpha... | 2 | null | Implement the Python class `DampedLineSearch` described below.
Class description:
A damped line search, takes a point and a direction. Tests a new point for minimization, if it is greater that the current cost times (1 + error), the step is divided by two, until the step is too small
Method signatures and docstrings:... | Implement the Python class `DampedLineSearch` described below.
Class description:
A damped line search, takes a point and a direction. Tests a new point for minimization, if it is greater that the current cost times (1 + error), the step is divided by two, until the step is too small
Method signatures and docstrings:... | 3d298e908ff55340cd3612078508be0c791f63a8 | <|skeleton|>
class DampedLineSearch:
"""A damped line search, takes a point and a direction. Tests a new point for minimization, if it is greater that the current cost times (1 + error), the step is divided by two, until the step is too small"""
def __init__(self, min_alpha_step, damped_error, alpha_step=1.0, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DampedLineSearch:
"""A damped line search, takes a point and a direction. Tests a new point for minimization, if it is greater that the current cost times (1 + error), the step is divided by two, until the step is too small"""
def __init__(self, min_alpha_step, damped_error, alpha_step=1.0, **kwargs):
... | the_stack_v2_python_sparse | PyDSTool/Toolbox/optimizers/line_search/damped_line_search.py | mdlama/pydstool | train | 2 |
9e9f7f72b5d574afa57205991857ca42422d31c6 | [
"self.link = link\nself.lineproto = lineproto\nself.interface_name = interface_name",
"sb = ''\nsb += '\\nInterfaceStatus [ ' + self.interface_name + ' ]\\n'\nsb += '\\tLinkState : ' + str(self.InterfaceState.enumval(self.link)) + '\\n'\nsb += '\\tLineProtoState : ' + str(self.InterfaceState.enumval(self... | <|body_start_0|>
self.link = link
self.lineproto = lineproto
self.interface_name = interface_name
<|end_body_0|>
<|body_start_1|>
sb = ''
sb += '\nInterfaceStatus [ ' + self.interface_name + ' ]\n'
sb += '\tLinkState : ' + str(self.InterfaceState.enumval(self.link... | Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceState>} @ivar lineproto: The lineproto state ... | InterfaceStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceStatus:
"""Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceSt... | stack_v2_sparse_classes_36k_train_027419 | 1,914 | no_license | [
{
"docstring": "Constructor of InterfaceStatus class.",
"name": "__init__",
"signature": "def __init__(self, link, lineproto, interface_name)"
},
{
"docstring": "Obtain string representation of the Interface Status object.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005806 | Implement the Python class `InterfaceStatus` described below.
Class description:
Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.Inte... | Implement the Python class `InterfaceStatus` described below.
Class description:
Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.Inte... | 54bc49eaed14f7832aca45c4f52311a00282d862 | <|skeleton|>
class InterfaceStatus:
"""Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceSt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterfaceStatus:
"""Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceState>} @ivar l... | the_stack_v2_python_sparse | onepk_without_pyc/build/lib.linux-x86_64-2.7/onep/interfaces/InterfaceStatus.py | neoyogi/onepk | train | 0 |
f4e97a3530d6646bd1d2cffb5af78109dcc98901 | [
"super().__init__(input_format=Text)\nself.filebase = filebase\nself.flush = flush\nself.time_format = time_format\nself.date_format = date_format\nself.current_date = None\nself.current_filename = None\nself.writer = None",
"if record is None:\n return\ntry:\n time_str = record.split()[0]\n ts = timesta... | <|body_start_0|>
super().__init__(input_format=Text)
self.filebase = filebase
self.flush = flush
self.time_format = time_format
self.date_format = date_format
self.current_date = None
self.current_filename = None
self.writer = None
<|end_body_0|>
<|body_s... | Write to the specified file. If filename is empty, write to stdout. | LogfileWriter | [
"MIT",
"CC-BY-NC-4.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogfileWriter:
"""Write to the specified file. If filename is empty, write to stdout."""
def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT):
"""Write timestamped text records to file. Base filename will have date append... | stack_v2_sparse_classes_36k_train_027420 | 2,568 | permissive | [
{
"docstring": "Write timestamped text records to file. Base filename will have date appended, in keeping with R2R format recommendations (http://www.rvdata.us/operators/directory). When timestamped date on records rolls over to next day, create new file with new date suffix. ``` filebase Base name of file to w... | 2 | stack_v2_sparse_classes_30k_train_012673 | Implement the Python class `LogfileWriter` described below.
Class description:
Write to the specified file. If filename is empty, write to stdout.
Method signatures and docstrings:
- def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT): Write timestamped ... | Implement the Python class `LogfileWriter` described below.
Class description:
Write to the specified file. If filename is empty, write to stdout.
Method signatures and docstrings:
- def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT): Write timestamped ... | ba77d3958075abd21ff94a396e4a97879962ac0c | <|skeleton|>
class LogfileWriter:
"""Write to the specified file. If filename is empty, write to stdout."""
def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT):
"""Write timestamped text records to file. Base filename will have date append... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogfileWriter:
"""Write to the specified file. If filename is empty, write to stdout."""
def __init__(self, filebase=None, flush=True, time_format=timestamp.TIME_FORMAT, date_format=timestamp.DATE_FORMAT):
"""Write timestamped text records to file. Base filename will have date appended, in keepin... | the_stack_v2_python_sparse | logger/writers/logfile_writer.py | timburbank/openrvdas | train | 0 |
ac361e8b6ae4563b5b4c33a969fbea37be3bda3b | [
"curr_node = head\nself.length = 1\nwhile curr_node.next:\n curr_node = curr_node.next\n self.length += 1\nself.head = head",
"picked = random.choice(range(self.length))\ni = 0\ncurr_node = self.head\nwhile i < picked:\n curr_node = curr_node.next\n i += 1\nreturn curr_node.val"
] | <|body_start_0|>
curr_node = head
self.length = 1
while curr_node.next:
curr_node = curr_node.next
self.length += 1
self.head = head
<|end_body_0|>
<|body_start_1|>
picked = random.choice(range(self.length))
i = 0
curr_node = self.head
... | Solution_mine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_mine:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_... | stack_v2_sparse_classes_36k_train_027421 | 2,763 | permissive | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | null | Implement the Python class `Solution_mine` described below.
Class description:
Implement the Solution_mine class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRand... | Implement the Python class `Solution_mine` described below.
Class description:
Implement the Solution_mine class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRand... | 884422a7c9f531e7ccaae03ba1ccbd6966b23dd3 | <|skeleton|>
class Solution_mine:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_mine:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
curr_node = head
self.length = 1
while curr_node.next:
curr_node = curr_node.next
... | the_stack_v2_python_sparse | LinkedList/easy/getRandom.py | linminhtoo/algorithms | train | 0 | |
63486076b78466c6e2ae0a103a628f366a413ab2 | [
"time.sleep(2)\nMsgLoginPage(web_page).login(data['username'], data['code'])\nlogging.info('开始断言')\ntime.sleep(3)\ntry:\n assert MsgLoginPage(web_page).login_success() == data['check']\n logging.info('登录成功')\nexcept:\n print('登录失败')\n common.save_screenShot(web_page, model_name='登录页面')\n raise",
"M... | <|body_start_0|>
time.sleep(2)
MsgLoginPage(web_page).login(data['username'], data['code'])
logging.info('开始断言')
time.sleep(3)
try:
assert MsgLoginPage(web_page).login_success() == data['check']
logging.info('登录成功')
except:
print('登录失败'... | TestMsgLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMsgLogin:
def test_Msg_login_success(self, data, web_page):
"""成功登录"""
<|body_0|>
def test_Msg_usernotin(self, data, web_page):
"""验证码错误"""
<|body_1|>
def test_Msg_usernotin2(self, data, web_page):
"""手机号码错误"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k_train_027422 | 2,325 | no_license | [
{
"docstring": "成功登录",
"name": "test_Msg_login_success",
"signature": "def test_Msg_login_success(self, data, web_page)"
},
{
"docstring": "验证码错误",
"name": "test_Msg_usernotin",
"signature": "def test_Msg_usernotin(self, data, web_page)"
},
{
"docstring": "手机号码错误",
"name": "t... | 3 | stack_v2_sparse_classes_30k_train_019703 | Implement the Python class `TestMsgLogin` described below.
Class description:
Implement the TestMsgLogin class.
Method signatures and docstrings:
- def test_Msg_login_success(self, data, web_page): 成功登录
- def test_Msg_usernotin(self, data, web_page): 验证码错误
- def test_Msg_usernotin2(self, data, web_page): 手机号码错误 | Implement the Python class `TestMsgLogin` described below.
Class description:
Implement the TestMsgLogin class.
Method signatures and docstrings:
- def test_Msg_login_success(self, data, web_page): 成功登录
- def test_Msg_usernotin(self, data, web_page): 验证码错误
- def test_Msg_usernotin2(self, data, web_page): 手机号码错误
<|sk... | b262c13e55a6e9eae1d4fa11d50b71814028261c | <|skeleton|>
class TestMsgLogin:
def test_Msg_login_success(self, data, web_page):
"""成功登录"""
<|body_0|>
def test_Msg_usernotin(self, data, web_page):
"""验证码错误"""
<|body_1|>
def test_Msg_usernotin2(self, data, web_page):
"""手机号码错误"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMsgLogin:
def test_Msg_login_success(self, data, web_page):
"""成功登录"""
time.sleep(2)
MsgLoginPage(web_page).login(data['username'], data['code'])
logging.info('开始断言')
time.sleep(3)
try:
assert MsgLoginPage(web_page).login_success() == data['check... | the_stack_v2_python_sparse | TestCase/test_C_web/test_login_msg.py | xjx985426946/Test_UI | train | 0 | |
42d72c9db5451b3319437d5a855ea3b2932f65b0 | [
"self.metadata_factory = metadata_factory\nmetadata = metadata_factory.from_data(values)\nsuper(BitCountingGroup, self).__init__(metadata, values)",
"values = list(self.values)\nvalues.append(value)\nreturn BitCountingGroup(self.metadata_factory, values)"
] | <|body_start_0|>
self.metadata_factory = metadata_factory
metadata = metadata_factory.from_data(values)
super(BitCountingGroup, self).__init__(metadata, values)
<|end_body_0|>
<|body_start_1|>
values = list(self.values)
values.append(value)
return BitCountingGroup(self.m... | RunGroup with BitCountingMetadata. Support with_run_added() method to simplify extending the group. As bit content has to be re-counted, metadata factory is stored. | BitCountingGroup | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitCountingGroup:
"""RunGroup with BitCountingMetadata. Support with_run_added() method to simplify extending the group. As bit content has to be re-counted, metadata factory is stored."""
def __init__(self, metadata_factory, values=[]):
"""Create the group from metadata factory and ... | stack_v2_sparse_classes_36k_train_027423 | 1,998 | permissive | [
{
"docstring": "Create the group from metadata factory and values. :param metadata_factory: Factory object to create metadata with. :param values: The runs belonging to this group. :type metadata_factory: BitCountingMetadataFactory :type values: Iterable of float or of AvgStdevMetadata",
"name": "__init__",... | 2 | null | Implement the Python class `BitCountingGroup` described below.
Class description:
RunGroup with BitCountingMetadata. Support with_run_added() method to simplify extending the group. As bit content has to be re-counted, metadata factory is stored.
Method signatures and docstrings:
- def __init__(self, metadata_factory... | Implement the Python class `BitCountingGroup` described below.
Class description:
RunGroup with BitCountingMetadata. Support with_run_added() method to simplify extending the group. As bit content has to be re-counted, metadata factory is stored.
Method signatures and docstrings:
- def __init__(self, metadata_factory... | 3151c98618c78e3782e48bbe4d9c8f906c126f69 | <|skeleton|>
class BitCountingGroup:
"""RunGroup with BitCountingMetadata. Support with_run_added() method to simplify extending the group. As bit content has to be re-counted, metadata factory is stored."""
def __init__(self, metadata_factory, values=[]):
"""Create the group from metadata factory and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BitCountingGroup:
"""RunGroup with BitCountingMetadata. Support with_run_added() method to simplify extending the group. As bit content has to be re-counted, metadata factory is stored."""
def __init__(self, metadata_factory, values=[]):
"""Create the group from metadata factory and values. :para... | the_stack_v2_python_sparse | PyPI/jumpavg/jumpavg/BitCountingGroup.py | preym17/csit | train | 0 |
f7542da8340f0c6d3b57e7b58e81522c4f3a6587 | [
"node = Node()\nnode.id = '1234'\nself.assertEqual(node.getId(), node.id)",
"node = Node()\nnode.properties['datawire_nodeId'] = '4567'\nself.assertEqual(node.getId(), '4567')"
] | <|body_start_0|>
node = Node()
node.id = '1234'
self.assertEqual(node.getId(), node.id)
<|end_body_0|>
<|body_start_1|>
node = Node()
node.properties['datawire_nodeId'] = '4567'
self.assertEqual(node.getId(), '4567')
<|end_body_1|>
| Tests for Node. | NodeTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeTests:
"""Tests for Node."""
def test_id(self):
"""Node.getId() uses Node.id if present."""
<|body_0|>
def test_missingId(self):
"""Node.getId() uses the datawire_nodeId property if the id is not set."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027424 | 35,450 | permissive | [
{
"docstring": "Node.getId() uses Node.id if present.",
"name": "test_id",
"signature": "def test_id(self)"
},
{
"docstring": "Node.getId() uses the datawire_nodeId property if the id is not set.",
"name": "test_missingId",
"signature": "def test_missingId(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012333 | Implement the Python class `NodeTests` described below.
Class description:
Tests for Node.
Method signatures and docstrings:
- def test_id(self): Node.getId() uses Node.id if present.
- def test_missingId(self): Node.getId() uses the datawire_nodeId property if the id is not set. | Implement the Python class `NodeTests` described below.
Class description:
Tests for Node.
Method signatures and docstrings:
- def test_id(self): Node.getId() uses Node.id if present.
- def test_missingId(self): Node.getId() uses the datawire_nodeId property if the id is not set.
<|skeleton|>
class NodeTests:
""... | 8b4ad9aa1e3602f4ec7f3bdd5f2c22abcfe81463 | <|skeleton|>
class NodeTests:
"""Tests for Node."""
def test_id(self):
"""Node.getId() uses Node.id if present."""
<|body_0|>
def test_missingId(self):
"""Node.getId() uses the datawire_nodeId property if the id is not set."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeTests:
"""Tests for Node."""
def test_id(self):
"""Node.getId() uses Node.id if present."""
node = Node()
node.id = '1234'
self.assertEqual(node.getId(), node.id)
def test_missingId(self):
"""Node.getId() uses the datawire_nodeId property if the id is not ... | the_stack_v2_python_sparse | unittests/test_discovery.py | casualuser/mdk | train | 0 |
938395950df1218784819226f10431688a371e39 | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('DescribeDomainInfo', params, headers=headers)\n response = json.loads(body)\n model = models.DescribeDomainInfoResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n ... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('DescribeDomainInfo', params, headers=headers)
response = json.loads(body)
model = models.DescribeDomainInfoResponse()
model._deserialize(respons... | TicsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TicsClient:
def DescribeDomainInfo(self, request):
"""提供域名相关的基础信息以及与攻击事件(团伙、家族)、恶意文件等相关联信息。 :param request: Request instance for DescribeDomainInfo. :type request: :class:`tencentcloud.tics.v20181115.models.DescribeDomainInfoRequest` :rtype: :class:`tencentcloud.tics.v20181115.models.Des... | stack_v2_sparse_classes_36k_train_027425 | 4,917 | permissive | [
{
"docstring": "提供域名相关的基础信息以及与攻击事件(团伙、家族)、恶意文件等相关联信息。 :param request: Request instance for DescribeDomainInfo. :type request: :class:`tencentcloud.tics.v20181115.models.DescribeDomainInfoRequest` :rtype: :class:`tencentcloud.tics.v20181115.models.DescribeDomainInfoResponse`",
"name": "DescribeDomainInfo",
... | 4 | null | Implement the Python class `TicsClient` described below.
Class description:
Implement the TicsClient class.
Method signatures and docstrings:
- def DescribeDomainInfo(self, request): 提供域名相关的基础信息以及与攻击事件(团伙、家族)、恶意文件等相关联信息。 :param request: Request instance for DescribeDomainInfo. :type request: :class:`tencentcloud.tics... | Implement the Python class `TicsClient` described below.
Class description:
Implement the TicsClient class.
Method signatures and docstrings:
- def DescribeDomainInfo(self, request): 提供域名相关的基础信息以及与攻击事件(团伙、家族)、恶意文件等相关联信息。 :param request: Request instance for DescribeDomainInfo. :type request: :class:`tencentcloud.tics... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class TicsClient:
def DescribeDomainInfo(self, request):
"""提供域名相关的基础信息以及与攻击事件(团伙、家族)、恶意文件等相关联信息。 :param request: Request instance for DescribeDomainInfo. :type request: :class:`tencentcloud.tics.v20181115.models.DescribeDomainInfoRequest` :rtype: :class:`tencentcloud.tics.v20181115.models.Des... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TicsClient:
def DescribeDomainInfo(self, request):
"""提供域名相关的基础信息以及与攻击事件(团伙、家族)、恶意文件等相关联信息。 :param request: Request instance for DescribeDomainInfo. :type request: :class:`tencentcloud.tics.v20181115.models.DescribeDomainInfoRequest` :rtype: :class:`tencentcloud.tics.v20181115.models.DescribeDomainInf... | the_stack_v2_python_sparse | tencentcloud/tics/v20181115/tics_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
9b5d908f9b771f1fde66fa8d531704d0606ad104 | [
"if bool(data) is True:\n self._data = data\nelse:\n self._data = None",
"result = Translation(text=key, units='')\nif self._data is not None:\n for item in self._data:\n if item.idx_pair_xlate_group() == idx_pair_xlate_group:\n translations = item.translations()\n table = tr... | <|body_start_0|>
if bool(data) is True:
self._data = data
else:
self._data = None
<|end_body_0|>
<|body_start_1|>
result = Translation(text=key, units='')
if self._data is not None:
for item in self._data:
if item.idx_pair_xlate_group(... | Class to process the results of a PairXlates object. | KeyPair | [
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyPair:
"""Class to process the results of a PairXlates object."""
def __init__(self, data):
"""Initialize the class. Args: data: pattoo_web.web.query.datapoint PairXlates object Returns: None"""
<|body_0|>
def key(self, key, idx_pair_xlate_group):
"""Translate ... | stack_v2_sparse_classes_36k_train_027426 | 3,395 | permissive | [
{
"docstring": "Initialize the class. Args: data: pattoo_web.web.query.datapoint PairXlates object Returns: None",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Translate a key. Args: key: value to translate idx_pair_xlate_group: idx_pair_xlate_group value in pat... | 2 | stack_v2_sparse_classes_30k_train_011566 | Implement the Python class `KeyPair` described below.
Class description:
Class to process the results of a PairXlates object.
Method signatures and docstrings:
- def __init__(self, data): Initialize the class. Args: data: pattoo_web.web.query.datapoint PairXlates object Returns: None
- def key(self, key, idx_pair_xla... | Implement the Python class `KeyPair` described below.
Class description:
Class to process the results of a PairXlates object.
Method signatures and docstrings:
- def __init__(self, data): Initialize the class. Args: data: pattoo_web.web.query.datapoint PairXlates object Returns: None
- def key(self, key, idx_pair_xla... | 390c7cb687ba46aee1bbb5764cce01fec0d662fb | <|skeleton|>
class KeyPair:
"""Class to process the results of a PairXlates object."""
def __init__(self, data):
"""Initialize the class. Args: data: pattoo_web.web.query.datapoint PairXlates object Returns: None"""
<|body_0|>
def key(self, key, idx_pair_xlate_group):
"""Translate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyPair:
"""Class to process the results of a PairXlates object."""
def __init__(self, data):
"""Initialize the class. Args: data: pattoo_web.web.query.datapoint PairXlates object Returns: None"""
if bool(data) is True:
self._data = data
else:
self._data = ... | the_stack_v2_python_sparse | pattoo_web/translate.py | palisadoes/pattoo-web | train | 0 |
5c8c48b9a165fcae10294891be36963bf9797694 | [
"self.port = 19234\ntcp_server = socket.socket()\ntcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ntcp_server.bind(('', self.port))\ntcp_server.listen(128)\nprint('服务器已开启。。')\nself.tcp_server = tcp_server",
"while True:\n client_server, client_addr = self.tcp_server.accept()\n g1 = gevent.s... | <|body_start_0|>
self.port = 19234
tcp_server = socket.socket()
tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp_server.bind(('', self.port))
tcp_server.listen(128)
print('服务器已开启。。')
self.tcp_server = tcp_server
<|end_body_0|>
<|body_start_1|>... | HTTP 服务器类 | HTTPServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPServer:
"""HTTP 服务器类"""
def __init__(self):
"""建立套接字"""
<|body_0|>
def start(self):
"""开启服务器"""
<|body_1|>
def client_handler(self, client_server):
"""处理客户端请求"""
<|body_2|>
def dynamic_resource(client_server, resource):
... | stack_v2_sparse_classes_36k_train_027427 | 3,071 | permissive | [
{
"docstring": "建立套接字",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "开启服务器",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "处理客户端请求",
"name": "client_handler",
"signature": "def client_handler(self, client_server)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_004044 | Implement the Python class `HTTPServer` described below.
Class description:
HTTP 服务器类
Method signatures and docstrings:
- def __init__(self): 建立套接字
- def start(self): 开启服务器
- def client_handler(self, client_server): 处理客户端请求
- def dynamic_resource(client_server, resource): 处理动态资源请求
- def static_resource(resource, clie... | Implement the Python class `HTTPServer` described below.
Class description:
HTTP 服务器类
Method signatures and docstrings:
- def __init__(self): 建立套接字
- def start(self): 开启服务器
- def client_handler(self, client_server): 处理客户端请求
- def dynamic_resource(client_server, resource): 处理动态资源请求
- def static_resource(resource, clie... | dd88b9a5619d38fb8d236c932ffa8429d24b28ae | <|skeleton|>
class HTTPServer:
"""HTTP 服务器类"""
def __init__(self):
"""建立套接字"""
<|body_0|>
def start(self):
"""开启服务器"""
<|body_1|>
def client_handler(self, client_server):
"""处理客户端请求"""
<|body_2|>
def dynamic_resource(client_server, resource):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTTPServer:
"""HTTP 服务器类"""
def __init__(self):
"""建立套接字"""
self.port = 19234
tcp_server = socket.socket()
tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp_server.bind(('', self.port))
tcp_server.listen(128)
print('服务器已开启。。')
... | the_stack_v2_python_sparse | 07-Mini_Web/64-Web.py | ericson14/Small_project | train | 0 |
25247cd4a14129e3663bf1a210959c71e500f350 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | SpannerBenchWrapperServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpannerBenchWrapperServicer:
"""Missing associated documentation comment in .proto file."""
def Read(self, request, context):
"""Read represents operations like Go's ReadOnlyTransaction.Query, Java's ReadOnlyTransaction.executeQuery, Python's snapshot.read, and Node's Transaction.Rea... | stack_v2_sparse_classes_36k_train_027428 | 6,770 | permissive | [
{
"docstring": "Read represents operations like Go's ReadOnlyTransaction.Query, Java's ReadOnlyTransaction.executeQuery, Python's snapshot.read, and Node's Transaction.Read. It will typically be used to read many items.",
"name": "Read",
"signature": "def Read(self, request, context)"
},
{
"docs... | 3 | null | Implement the Python class `SpannerBenchWrapperServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Read(self, request, context): Read represents operations like Go's ReadOnlyTransaction.Query, Java's ReadOnlyTransaction.execute... | Implement the Python class `SpannerBenchWrapperServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Read(self, request, context): Read represents operations like Go's ReadOnlyTransaction.Query, Java's ReadOnlyTransaction.execute... | 43d7aec2f2a5b84cd23279ac32ae76a2be94b61f | <|skeleton|>
class SpannerBenchWrapperServicer:
"""Missing associated documentation comment in .proto file."""
def Read(self, request, context):
"""Read represents operations like Go's ReadOnlyTransaction.Query, Java's ReadOnlyTransaction.executeQuery, Python's snapshot.read, and Node's Transaction.Rea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpannerBenchWrapperServicer:
"""Missing associated documentation comment in .proto file."""
def Read(self, request, context):
"""Read represents operations like Go's ReadOnlyTransaction.Query, Java's ReadOnlyTransaction.executeQuery, Python's snapshot.read, and Node's Transaction.Read. It will ty... | the_stack_v2_python_sparse | benchmark/benchwrapper/proto/spanner_pb2_grpc.py | googleapis/python-spanner | train | 82 |
0f3c4d09b7dcc6b293fa1e0701c12a1a6c5fc585 | [
"super().__init__()\nself.d_model = d_model\nself.reverse = reverse\nself.xscale = math.sqrt(self.d_model)\nself.dropout = nn.Dropout(p=dropout_rate)\nself.pe = None\nself.dtype = dtype\nself.extend_pe(paddle.expand(paddle.zeros([1]), (1, max_len)))",
"x_shape = paddle.shape(x)\npe = paddle.zeros([x_shape[1], sel... | <|body_start_0|>
super().__init__()
self.d_model = d_model
self.reverse = reverse
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout_rate)
self.pe = None
self.dtype = dtype
self.extend_pe(paddle.expand(paddle.zeros([1]), (1, max_len)... | Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. type (str): dtype of param | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. type (str): dtype of param"""
def __init__(self, d_model, dropout_rate, max_le... | stack_v2_sparse_classes_36k_train_027429 | 9,302 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000, dtype='float32', reverse=False)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self,... | 3 | stack_v2_sparse_classes_30k_train_014587 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. type (str): dtype of param
Method signature... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. type (str): dtype of param
Method signature... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. type (str): dtype of param"""
def __init__(self, d_model, dropout_rate, max_le... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. type (str): dtype of param"""
def __init__(self, d_model, dropout_rate, max_len=5000, dtype... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/transformer/embedding.py | anniyanvr/DeepSpeech-1 | train | 0 |
e36c765bb308236a417478e84ace8a264fbb6d47 | [
"try:\n lobbies.update_lobby_member(current_user['player_id'], member_player_id, lobby_id, args.get('team_name'), args.get('ready'))\nexcept lobbies.NotFoundException as e:\n abort(http_client.NOT_FOUND, message=e.msg)\nexcept lobbies.InvalidRequestException as e:\n abort(http_client.BAD_REQUEST, message=e... | <|body_start_0|>
try:
lobbies.update_lobby_member(current_user['player_id'], member_player_id, lobby_id, args.get('team_name'), args.get('ready'))
except lobbies.NotFoundException as e:
abort(http_client.NOT_FOUND, message=e.msg)
except lobbies.InvalidRequestException as ... | LobbyMemberAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LobbyMemberAPI:
def put(self, args, lobby_id: str, member_player_id: int):
"""Update lobby member info, such as team status and ready check. Returns the updated lobby."""
<|body_0|>
def delete(self, lobby_id: str, member_player_id: int):
"""Leave the lobby or kick a ... | stack_v2_sparse_classes_36k_train_027430 | 13,314 | permissive | [
{
"docstring": "Update lobby member info, such as team status and ready check. Returns the updated lobby.",
"name": "put",
"signature": "def put(self, args, lobby_id: str, member_player_id: int)"
},
{
"docstring": "Leave the lobby or kick a player from the lobby",
"name": "delete",
"sign... | 2 | stack_v2_sparse_classes_30k_val_000318 | Implement the Python class `LobbyMemberAPI` described below.
Class description:
Implement the LobbyMemberAPI class.
Method signatures and docstrings:
- def put(self, args, lobby_id: str, member_player_id: int): Update lobby member info, such as team status and ready check. Returns the updated lobby.
- def delete(self... | Implement the Python class `LobbyMemberAPI` described below.
Class description:
Implement the LobbyMemberAPI class.
Method signatures and docstrings:
- def put(self, args, lobby_id: str, member_player_id: int): Update lobby member info, such as team status and ready check. Returns the updated lobby.
- def delete(self... | 2771bb46db7fd331448f9db3cfb257fab7f89bcc | <|skeleton|>
class LobbyMemberAPI:
def put(self, args, lobby_id: str, member_player_id: int):
"""Update lobby member info, such as team status and ready check. Returns the updated lobby."""
<|body_0|>
def delete(self, lobby_id: str, member_player_id: int):
"""Leave the lobby or kick a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LobbyMemberAPI:
def put(self, args, lobby_id: str, member_player_id: int):
"""Update lobby member info, such as team status and ready check. Returns the updated lobby."""
try:
lobbies.update_lobby_member(current_user['player_id'], member_player_id, lobby_id, args.get('team_name'), ... | the_stack_v2_python_sparse | driftbase/api/lobbies.py | directivegames/drift-base | train | 1 | |
632e8638b7aedc0d22daf0d7821a26f6a2ad33a5 | [
"ChungViscosityPure.build_common_parameters(cobj)\nif not hasattr(cobj, 'viscosity_collision_integral_callback'):\n cobj.viscosity_collision_integral_callback = collision_integral_neufeld_callback",
"units = b.params.get_metadata().derived_units\nT = pyunits.convert(T, to_units=pyunits.K)\nT_crit = pyunits.con... | <|body_start_0|>
ChungViscosityPure.build_common_parameters(cobj)
if not hasattr(cobj, 'viscosity_collision_integral_callback'):
cobj.viscosity_collision_integral_callback = collision_integral_neufeld_callback
<|end_body_0|>
<|body_start_1|>
units = b.params.get_metadata().derived_u... | Implementation of pure component gas dynamic viscosity via the method of Chung et al. as described in The Properties of Gases and Liquids, Section 9-4-2. | visc_d_phase_comp | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class visc_d_phase_comp:
"""Implementation of pure component gas dynamic viscosity via the method of Chung et al. as described in The Properties of Gases and Liquids, Section 9-4-2."""
def build_parameters(cobj, p):
"""Build common parameters and viscosity collision integral callback"""
... | stack_v2_sparse_classes_36k_train_027431 | 4,527 | permissive | [
{
"docstring": "Build common parameters and viscosity collision integral callback",
"name": "build_parameters",
"signature": "def build_parameters(cobj, p)"
},
{
"docstring": "Return expression for visc_d_phase_comp",
"name": "return_expression",
"signature": "def return_expression(b, co... | 2 | null | Implement the Python class `visc_d_phase_comp` described below.
Class description:
Implementation of pure component gas dynamic viscosity via the method of Chung et al. as described in The Properties of Gases and Liquids, Section 9-4-2.
Method signatures and docstrings:
- def build_parameters(cobj, p): Build common p... | Implement the Python class `visc_d_phase_comp` described below.
Class description:
Implementation of pure component gas dynamic viscosity via the method of Chung et al. as described in The Properties of Gases and Liquids, Section 9-4-2.
Method signatures and docstrings:
- def build_parameters(cobj, p): Build common p... | deacf4c422bc9e50cb347e11a8cbfa0195bd4274 | <|skeleton|>
class visc_d_phase_comp:
"""Implementation of pure component gas dynamic viscosity via the method of Chung et al. as described in The Properties of Gases and Liquids, Section 9-4-2."""
def build_parameters(cobj, p):
"""Build common parameters and viscosity collision integral callback"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class visc_d_phase_comp:
"""Implementation of pure component gas dynamic viscosity via the method of Chung et al. as described in The Properties of Gases and Liquids, Section 9-4-2."""
def build_parameters(cobj, p):
"""Build common parameters and viscosity collision integral callback"""
ChungVi... | the_stack_v2_python_sparse | idaes/models/properties/modular_properties/pure/ChungPure.py | IDAES/idaes-pse | train | 173 |
69c5768da344801d81417af7aa51d9c092b3087f | [
"if root.left != None:\n self.helper(res, root.left)\nres.append(root.val)\nif root.right != None:\n self.helper(res, root.right)",
"result = []\nif not root:\n return result\nself.helper(result, root)\nreturn result",
"result, stack = ([], [])\nwhile root or stack:\n while root:\n stack.appe... | <|body_start_0|>
if root.left != None:
self.helper(res, root.left)
res.append(root.val)
if root.right != None:
self.helper(res, root.right)
<|end_body_0|>
<|body_start_1|>
result = []
if not root:
return result
self.helper(result, root... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, res: List[int], root: TreeNode):
"""中序遍历二叉树 Args: res: 链表 root: 根节点"""
<|body_0|>
def inorder_traversal1(self, root: TreeNode) -> List[int]:
"""中序遍历二叉树 Args: root: 跟节点 Returns: 中序递归遍历二叉树"""
<|body_1|>
def inorder_traversal2(sel... | stack_v2_sparse_classes_36k_train_027432 | 2,388 | permissive | [
{
"docstring": "中序遍历二叉树 Args: res: 链表 root: 根节点",
"name": "helper",
"signature": "def helper(self, res: List[int], root: TreeNode)"
},
{
"docstring": "中序遍历二叉树 Args: root: 跟节点 Returns: 中序递归遍历二叉树",
"name": "inorder_traversal1",
"signature": "def inorder_traversal1(self, root: TreeNode) -> ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, res: List[int], root: TreeNode): 中序遍历二叉树 Args: res: 链表 root: 根节点
- def inorder_traversal1(self, root: TreeNode) -> List[int]: 中序遍历二叉树 Args: root: 跟节点 Returns: 中序... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, res: List[int], root: TreeNode): 中序遍历二叉树 Args: res: 链表 root: 根节点
- def inorder_traversal1(self, root: TreeNode) -> List[int]: 中序遍历二叉树 Args: root: 跟节点 Returns: 中序... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def helper(self, res: List[int], root: TreeNode):
"""中序遍历二叉树 Args: res: 链表 root: 根节点"""
<|body_0|>
def inorder_traversal1(self, root: TreeNode) -> List[int]:
"""中序遍历二叉树 Args: root: 跟节点 Returns: 中序递归遍历二叉树"""
<|body_1|>
def inorder_traversal2(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def helper(self, res: List[int], root: TreeNode):
"""中序遍历二叉树 Args: res: 链表 root: 根节点"""
if root.left != None:
self.helper(res, root.left)
res.append(root.val)
if root.right != None:
self.helper(res, root.right)
def inorder_traversal1(self,... | the_stack_v2_python_sparse | src/leetcodepython/tree/binary_tree_inorder_traversal_94.py | zhangyu345293721/leetcode | train | 101 | |
dc5d36b728d8615caf11cf93f85683b0d8182bdc | [
"user = YouYodaUser.objects.get(auth_token=request.headers['Authorization'].replace('Token ', ''))\nserializer = ProfileEditSerializer(user)\nreturn Response(serializer.data)",
"user = get_object_or_404(YouYodaUser, email=request.data.get('email'))\nserializer = ProfileEditSerializer(user, data=request.data, part... | <|body_start_0|>
user = YouYodaUser.objects.get(auth_token=request.headers['Authorization'].replace('Token ', ''))
serializer = ProfileEditSerializer(user)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
user = get_object_or_404(YouYodaUser, email=request.data.get('emai... | Takes data from ProfileEditSerializer for fill/edit user profile. | EditProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditProfile:
"""Takes data from ProfileEditSerializer for fill/edit user profile."""
def get(self, request):
"""Receives and transmits user profile data"""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""Receives and updates user profile data"""
... | stack_v2_sparse_classes_36k_train_027433 | 1,435 | no_license | [
{
"docstring": "Receives and transmits user profile data",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Receives and updates user profile data",
"name": "patch",
"signature": "def patch(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001014 | Implement the Python class `EditProfile` described below.
Class description:
Takes data from ProfileEditSerializer for fill/edit user profile.
Method signatures and docstrings:
- def get(self, request): Receives and transmits user profile data
- def patch(self, request, *args, **kwargs): Receives and updates user pro... | Implement the Python class `EditProfile` described below.
Class description:
Takes data from ProfileEditSerializer for fill/edit user profile.
Method signatures and docstrings:
- def get(self, request): Receives and transmits user profile data
- def patch(self, request, *args, **kwargs): Receives and updates user pro... | 62b4f1cc79b4c71cc44bb741fb20af066c7023a5 | <|skeleton|>
class EditProfile:
"""Takes data from ProfileEditSerializer for fill/edit user profile."""
def get(self, request):
"""Receives and transmits user profile data"""
<|body_0|>
def patch(self, request, *args, **kwargs):
"""Receives and updates user profile data"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditProfile:
"""Takes data from ProfileEditSerializer for fill/edit user profile."""
def get(self, request):
"""Receives and transmits user profile data"""
user = YouYodaUser.objects.get(auth_token=request.headers['Authorization'].replace('Token ', ''))
serializer = ProfileEditSer... | the_stack_v2_python_sparse | backend/appsrc/views/edit_profile.py | OleksandrHavrylchyk/YouYoda | train | 0 |
f4bf3d21085a2d482ac8116a3adc6e6d92a896f8 | [
"super(ConcatDB, self).__init__()\nself.imdbs = imdbs\nself.image_set = image_set\nself.image_index = self._load_image_index(shuffle)",
"self.num_images = 0\nfor db in self.imdbs:\n self.num_images += db.num_images\nindices = list(range(self.num_images))\nif shuffle:\n random.shuffle(indices)\nreturn indice... | <|body_start_0|>
super(ConcatDB, self).__init__()
self.imdbs = imdbs
self.image_set = image_set
self.image_index = self._load_image_index(shuffle)
<|end_body_0|>
<|body_start_1|>
self.num_images = 0
for db in self.imdbs:
self.num_images += db.num_images
... | ConcatDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcatDB:
def __init__(self, imdbs, image_set, shuffle):
"""连接多个imdb :param imdbs: imdb列表 :param image_set: 数据集属性 train,val,trianval,test :param shuffle: 是否打乱顺序"""
<|body_0|>
def _load_image_index(self, shuffle):
""":param shuffle: 是否打乱顺序 :return: 返回索引列表"""
<... | stack_v2_sparse_classes_36k_train_027434 | 2,333 | no_license | [
{
"docstring": "连接多个imdb :param imdbs: imdb列表 :param image_set: 数据集属性 train,val,trianval,test :param shuffle: 是否打乱顺序",
"name": "__init__",
"signature": "def __init__(self, imdbs, image_set, shuffle)"
},
{
"docstring": ":param shuffle: 是否打乱顺序 :return: 返回索引列表",
"name": "_load_image_index",
... | 6 | stack_v2_sparse_classes_30k_train_017650 | Implement the Python class `ConcatDB` described below.
Class description:
Implement the ConcatDB class.
Method signatures and docstrings:
- def __init__(self, imdbs, image_set, shuffle): 连接多个imdb :param imdbs: imdb列表 :param image_set: 数据集属性 train,val,trianval,test :param shuffle: 是否打乱顺序
- def _load_image_index(self, ... | Implement the Python class `ConcatDB` described below.
Class description:
Implement the ConcatDB class.
Method signatures and docstrings:
- def __init__(self, imdbs, image_set, shuffle): 连接多个imdb :param imdbs: imdb列表 :param image_set: 数据集属性 train,val,trianval,test :param shuffle: 是否打乱顺序
- def _load_image_index(self, ... | 33302a42b6002e1007e2e407bf5bfcde3527e780 | <|skeleton|>
class ConcatDB:
def __init__(self, imdbs, image_set, shuffle):
"""连接多个imdb :param imdbs: imdb列表 :param image_set: 数据集属性 train,val,trianval,test :param shuffle: 是否打乱顺序"""
<|body_0|>
def _load_image_index(self, shuffle):
""":param shuffle: 是否打乱顺序 :return: 返回索引列表"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConcatDB:
def __init__(self, imdbs, image_set, shuffle):
"""连接多个imdb :param imdbs: imdb列表 :param image_set: 数据集属性 train,val,trianval,test :param shuffle: 是否打乱顺序"""
super(ConcatDB, self).__init__()
self.imdbs = imdbs
self.image_set = image_set
self.image_index = self._lo... | the_stack_v2_python_sparse | tools/concat_db.py | Sparks-zs/mxnet-object-detection | train | 4 | |
fd12ebe84aab52fd70e3caeead3f1e45651f80c1 | [
"list_url = BASE_URL + '/upload/list'\npayload = {'token': test_token}\noutput = requests.post(list_url, json=payload)\ntest_upload_id = sorted(output.json()['uploads'], key=lambda upload: upload['id'], reverse=True)[0]['id']\npayload = {'id': test_upload_id, 'token': test_token}\noutput = requests.delete(url, json... | <|body_start_0|>
list_url = BASE_URL + '/upload/list'
payload = {'token': test_token}
output = requests.post(list_url, json=payload)
test_upload_id = sorted(output.json()['uploads'], key=lambda upload: upload['id'], reverse=True)[0]['id']
payload = {'id': test_upload_id, 'token':... | TestDeleteUploads | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDeleteUploads:
def test_delete_working(self):
"""this test will pass the uploads/remove method"""
<|body_0|>
def test_delete_missing_parameter(self):
"""this test will fail because the given parameters are wrong"""
<|body_1|>
def test_delete_user_uni... | stack_v2_sparse_classes_36k_train_027435 | 2,057 | permissive | [
{
"docstring": "this test will pass the uploads/remove method",
"name": "test_delete_working",
"signature": "def test_delete_working(self)"
},
{
"docstring": "this test will fail because the given parameters are wrong",
"name": "test_delete_missing_parameter",
"signature": "def test_dele... | 4 | stack_v2_sparse_classes_30k_train_002540 | Implement the Python class `TestDeleteUploads` described below.
Class description:
Implement the TestDeleteUploads class.
Method signatures and docstrings:
- def test_delete_working(self): this test will pass the uploads/remove method
- def test_delete_missing_parameter(self): this test will fail because the given pa... | Implement the Python class `TestDeleteUploads` described below.
Class description:
Implement the TestDeleteUploads class.
Method signatures and docstrings:
- def test_delete_working(self): this test will pass the uploads/remove method
- def test_delete_missing_parameter(self): this test will fail because the given pa... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestDeleteUploads:
def test_delete_working(self):
"""this test will pass the uploads/remove method"""
<|body_0|>
def test_delete_missing_parameter(self):
"""this test will fail because the given parameters are wrong"""
<|body_1|>
def test_delete_user_uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDeleteUploads:
def test_delete_working(self):
"""this test will pass the uploads/remove method"""
list_url = BASE_URL + '/upload/list'
payload = {'token': test_token}
output = requests.post(list_url, json=payload)
test_upload_id = sorted(output.json()['uploads'], ke... | the_stack_v2_python_sparse | pytest_suit/routes/uploads/test_zzdeleteUploads.py | HotMaps/Hotmaps-toolbox-service | train | 4 | |
7c1ca75a4f218e02e1c9b99c1c60a43e56d3f8f6 | [
"difficulty_ui = ui.get_by_name(self._get_difficulty_ui(difficulty))\nif wait_until(self.emulator.is_ui_element_on_screen, ui_element=self.stage_selector_ui):\n self.emulator.click_button(self.stage_selector_ui)\n if '_2_' in difficulty_ui.name:\n logger.debug('Difficulty is referring from the bottom o... | <|body_start_0|>
difficulty_ui = ui.get_by_name(self._get_difficulty_ui(difficulty))
if wait_until(self.emulator.is_ui_element_on_screen, ui_element=self.stage_selector_ui):
self.emulator.click_button(self.stage_selector_ui)
if '_2_' in difficulty_ui.name:
logger.... | TenStageWithDifficultyEpicQuest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenStageWithDifficultyEpicQuest:
def _select_stage(self, difficulty=6):
"""Selects stage in missions in Epic Quest."""
<|body_0|>
def _select_mission(self):
"""Selects missions in Epic Quest."""
<|body_1|>
def _get_difficulty_ui(self, difficulty):
... | stack_v2_sparse_classes_36k_train_027436 | 26,035 | permissive | [
{
"docstring": "Selects stage in missions in Epic Quest.",
"name": "_select_stage",
"signature": "def _select_stage(self, difficulty=6)"
},
{
"docstring": "Selects missions in Epic Quest.",
"name": "_select_mission",
"signature": "def _select_mission(self)"
},
{
"docstring": "Get... | 5 | stack_v2_sparse_classes_30k_train_021340 | Implement the Python class `TenStageWithDifficultyEpicQuest` described below.
Class description:
Implement the TenStageWithDifficultyEpicQuest class.
Method signatures and docstrings:
- def _select_stage(self, difficulty=6): Selects stage in missions in Epic Quest.
- def _select_mission(self): Selects missions in Epi... | Implement the Python class `TenStageWithDifficultyEpicQuest` described below.
Class description:
Implement the TenStageWithDifficultyEpicQuest class.
Method signatures and docstrings:
- def _select_stage(self, difficulty=6): Selects stage in missions in Epic Quest.
- def _select_mission(self): Selects missions in Epi... | fd3f0bd45aea45e2e8ad8e8fc73a8953c96d350a | <|skeleton|>
class TenStageWithDifficultyEpicQuest:
def _select_stage(self, difficulty=6):
"""Selects stage in missions in Epic Quest."""
<|body_0|>
def _select_mission(self):
"""Selects missions in Epic Quest."""
<|body_1|>
def _get_difficulty_ui(self, difficulty):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenStageWithDifficultyEpicQuest:
def _select_stage(self, difficulty=6):
"""Selects stage in missions in Epic Quest."""
difficulty_ui = ui.get_by_name(self._get_difficulty_ui(difficulty))
if wait_until(self.emulator.is_ui_element_on_screen, ui_element=self.stage_selector_ui):
... | the_stack_v2_python_sparse | lib/game/missions/epic_quest.py | th3f1v3/mff_auto | train | 0 | |
e936fa99361410dd4af805eacb81c0ed88056446 | [
"tf.compat.v1.logging.info('Initializing Subtokenizer from file %s.' % vocab_file)\nif reserved_tokens is None:\n reserved_tokens = RESERVED_TOKENS\nself.subtoken_list = _load_vocab_file(vocab_file, reserved_tokens)\nself.alphabet = _generate_alphabet_dict(self.subtoken_list)\nself.subtoken_to_id_dict = _list_to... | <|body_start_0|>
tf.compat.v1.logging.info('Initializing Subtokenizer from file %s.' % vocab_file)
if reserved_tokens is None:
reserved_tokens = RESERVED_TOKENS
self.subtoken_list = _load_vocab_file(vocab_file, reserved_tokens)
self.alphabet = _generate_alphabet_dict(self.sub... | Encodes and decodes strings to/from integer IDs. | Subtokenizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subtokenizer:
"""Encodes and decodes strings to/from integer IDs."""
def __init__(self, vocab_file, reserved_tokens=None):
"""Initializes class, creating a vocab file if data_files is provided."""
<|body_0|>
def init_from_files(vocab_file, files, target_vocab_size, thres... | stack_v2_sparse_classes_36k_train_027437 | 22,774 | permissive | [
{
"docstring": "Initializes class, creating a vocab file if data_files is provided.",
"name": "__init__",
"signature": "def __init__(self, vocab_file, reserved_tokens=None)"
},
{
"docstring": "Create subtoken vocabulary based on files, and save vocab to file. Args: vocab_file: String name of voc... | 6 | stack_v2_sparse_classes_30k_train_021269 | Implement the Python class `Subtokenizer` described below.
Class description:
Encodes and decodes strings to/from integer IDs.
Method signatures and docstrings:
- def __init__(self, vocab_file, reserved_tokens=None): Initializes class, creating a vocab file if data_files is provided.
- def init_from_files(vocab_file,... | Implement the Python class `Subtokenizer` described below.
Class description:
Encodes and decodes strings to/from integer IDs.
Method signatures and docstrings:
- def __init__(self, vocab_file, reserved_tokens=None): Initializes class, creating a vocab file if data_files is provided.
- def init_from_files(vocab_file,... | 9304c9f59fde013f158ac338fc80171c0e8cda5d | <|skeleton|>
class Subtokenizer:
"""Encodes and decodes strings to/from integer IDs."""
def __init__(self, vocab_file, reserved_tokens=None):
"""Initializes class, creating a vocab file if data_files is provided."""
<|body_0|>
def init_from_files(vocab_file, files, target_vocab_size, thres... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subtokenizer:
"""Encodes and decodes strings to/from integer IDs."""
def __init__(self, vocab_file, reserved_tokens=None):
"""Initializes class, creating a vocab file if data_files is provided."""
tf.compat.v1.logging.info('Initializing Subtokenizer from file %s.' % vocab_file)
if... | the_stack_v2_python_sparse | models/language_translation/tensorflow/transformer_mlperf/inference/int8/transformer/utils/tokenizer.py | IntelAI/models | train | 609 |
5b2bd5d12362a4f13201e4f3ada609714e554983 | [
"d = {}\nwhile headA:\n d[headA] = 1\n headA = headA.next\nwhile headB:\n if headB in d:\n return headB\n else:\n headB = headB.next",
"if not headA or not headB:\n return None\nl_1 = headA\nl_2 = headB\nwhile l_1 or l_2:\n if not l_1:\n l_1 = headB\n if not l_2:\n ... | <|body_start_0|>
d = {}
while headA:
d[headA] = 1
headA = headA.next
while headB:
if headB in d:
return headB
else:
headB = headB.next
<|end_body_0|>
<|body_start_1|>
if not headA or not headB:
r... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
"""Hashtable"""
<|body_0|>
def getIntersectionNode2(self, headA, headB):
"""Two Pointers: Let len(headA) -> m, len(headB) -> n. To ensure the compared lists have the same length, we concatenate them, l_1.e. compa... | stack_v2_sparse_classes_36k_train_027438 | 3,017 | permissive | [
{
"docstring": "Hashtable",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA, headB)"
},
{
"docstring": "Two Pointers: Let len(headA) -> m, len(headB) -> n. To ensure the compared lists have the same length, we concatenate them, l_1.e. comparing l_1 = headA + head... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): Hashtable
- def getIntersectionNode2(self, headA, headB): Two Pointers: Let len(headA) -> m, len(headB) -> n. To ensure the compared ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getIntersectionNode(self, headA, headB): Hashtable
- def getIntersectionNode2(self, headA, headB): Two Pointers: Let len(headA) -> m, len(headB) -> n. To ensure the compared ... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def getIntersectionNode(self, headA, headB):
"""Hashtable"""
<|body_0|>
def getIntersectionNode2(self, headA, headB):
"""Two Pointers: Let len(headA) -> m, len(headB) -> n. To ensure the compared lists have the same length, we concatenate them, l_1.e. compa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getIntersectionNode(self, headA, headB):
"""Hashtable"""
d = {}
while headA:
d[headA] = 1
headA = headA.next
while headB:
if headB in d:
return headB
else:
headB = headB.next
def ... | the_stack_v2_python_sparse | leetcode/0160_intersection_of_two_linked_lists.py | chaosWsF/Python-Practice | train | 1 | |
b29caa455d03142877ec7278b79aa4b91265889f | [
"target_real_sample = torch.ones_like(output_real_sample)\ntarget_fake_sample = torch.zeros_like(output_fake_sample)\noutput = torch.cat([output_real_sample, output_fake_sample])\ntarget = torch.cat([target_real_sample, target_fake_sample])\nfooling_rate = metrics.accuracy(output_fake_sample, target_real_sample)\np... | <|body_start_0|>
target_real_sample = torch.ones_like(output_real_sample)
target_fake_sample = torch.zeros_like(output_fake_sample)
output = torch.cat([output_real_sample, output_fake_sample])
target = torch.cat([target_real_sample, target_fake_sample])
fooling_rate = metrics.acc... | General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset split ratios in [0, 1] as [train, val] or [train, val,... | ImageTranslationExperiment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageTranslationExperiment:
"""General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset ... | stack_v2_sparse_classes_36k_train_027439 | 12,405 | no_license | [
{
"docstring": "Computes metrics on discriminator classification power : fooling rate of generator, precision and recall Args: output_real_sample (torch.Tensor): discriminator prediction on real samples output_fake_sample (torch.Tensor): discriminator prediction on fake samples Returns: type: tuple[float]",
... | 2 | stack_v2_sparse_classes_30k_train_002659 | Implement the Python class `ImageTranslationExperiment` described below.
Class description:
General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this e... | Implement the Python class `ImageTranslationExperiment` described below.
Class description:
General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this e... | 08f8c3351ec4f2f666e05b75b1130b78005489d1 | <|skeleton|>
class ImageTranslationExperiment:
"""General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageTranslationExperiment:
"""General class factorizing some common attributes and methods of image translation experiments Args: model (nn.Module): main model concerned by this experiment dataset (torch.utils.data.Dataset): main dataset concerned by this experiment split (list[float]): dataset split ratios ... | the_stack_v2_python_sparse | src/experiments/experiment.py | shahineb/ci-hackathon | train | 3 |
31d65fcd7da6bc1410e551274af92dd77be12504 | [
"if not v.exists():\n raise ValueError(f'Path object not found in filesystem : {v}')\nreturn v",
"configs = [c.config for c in values.get('configs')]\nfor test in values.get('tests'):\n if test.config not in configs:\n raise ValueError(f\"Test '{test.test}' gave the config '{test.config}', but this c... | <|body_start_0|>
if not v.exists():
raise ValueError(f'Path object not found in filesystem : {v}')
return v
<|end_body_0|>
<|body_start_1|>
configs = [c.config for c in values.get('configs')]
for test in values.get('tests'):
if test.config not in configs:
... | Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly-different to the validation schema defined h... | DirectedTestsYaml | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectedTestsYaml:
"""Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly... | stack_v2_sparse_classes_36k_train_027440 | 7,812 | permissive | [
{
"docstring": "Check that the yaml file exists on disk. This field needs its own validator, as other files are checked relative to the yaml file.",
"name": "yaml_file_must_exist",
"signature": "def yaml_file_must_exist(cls, v: pathlib.Path)"
},
{
"docstring": "Check that if a test specifies a c... | 3 | stack_v2_sparse_classes_30k_train_017633 | Implement the Python class `DirectedTestsYaml` described below.
Class description:
Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk ... | Implement the Python class `DirectedTestsYaml` described below.
Class description:
Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk ... | 51f6017b8425b14d5a4aa9abace8fe5a25ef08c8 | <|skeleton|>
class DirectedTestsYaml:
"""Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectedTestsYaml:
"""Represent the schema for the <directed-tests>.yaml file. The file on-disk should be of the form... - A flat list of both DConfig and DTest items - Each DTest must specify an existing DConfig item with the key 'config' Note that on-disk representation of this file is slightly-different to... | the_stack_v2_python_sparse | hw/vendor/lowrisc_ibex/dv/uvm/core_ibex/scripts/directed_test_schema.py | lowRISC/opentitan | train | 2,077 |
69b393cd5759dd2a7e1fb48e5e28999d4c630796 | [
"blog_ids = Blog.objects.filter(user=request.my_user).values_list('id', flat=True)\nblog_list = update.get_blog_info(list(blog_ids))\nreturn success(blog_list)",
"blog_id = json.loads(request.body).get('blog_id')\nif update.update_status(blog_id, '3'):\n return success()\nreturn error(404, '删除失败')"
] | <|body_start_0|>
blog_ids = Blog.objects.filter(user=request.my_user).values_list('id', flat=True)
blog_list = update.get_blog_info(list(blog_ids))
return success(blog_list)
<|end_body_0|>
<|body_start_1|>
blog_id = json.loads(request.body).get('blog_id')
if update.update_status... | BlogInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogInfo:
def get(self, request, user_id):
"""获取博客"""
<|body_0|>
def patch(self, request, user_id):
"""删除博客"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
blog_ids = Blog.objects.filter(user=request.my_user).values_list('id', flat=True)
blo... | stack_v2_sparse_classes_36k_train_027441 | 4,853 | no_license | [
{
"docstring": "获取博客",
"name": "get",
"signature": "def get(self, request, user_id)"
},
{
"docstring": "删除博客",
"name": "patch",
"signature": "def patch(self, request, user_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012870 | Implement the Python class `BlogInfo` described below.
Class description:
Implement the BlogInfo class.
Method signatures and docstrings:
- def get(self, request, user_id): 获取博客
- def patch(self, request, user_id): 删除博客 | Implement the Python class `BlogInfo` described below.
Class description:
Implement the BlogInfo class.
Method signatures and docstrings:
- def get(self, request, user_id): 获取博客
- def patch(self, request, user_id): 删除博客
<|skeleton|>
class BlogInfo:
def get(self, request, user_id):
"""获取博客"""
<|b... | 9870f9402c9416594409be974c640f890b46a41b | <|skeleton|>
class BlogInfo:
def get(self, request, user_id):
"""获取博客"""
<|body_0|>
def patch(self, request, user_id):
"""删除博客"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlogInfo:
def get(self, request, user_id):
"""获取博客"""
blog_ids = Blog.objects.filter(user=request.my_user).values_list('id', flat=True)
blog_list = update.get_blog_info(list(blog_ids))
return success(blog_list)
def patch(self, request, user_id):
"""删除博客"""
... | the_stack_v2_python_sparse | PYMARA 2/user/views.py | yuanzuliang/PyMara | train | 1 | |
0a7abcfdcea9e7a9d51bd700567e44d3f52d45fa | [
"path = path.decode('utf-8')\n\ndef run():\n tags = SecureTagAPI(session.auth.user)\n result = tags.get([path], withDescriptions=returnDescription)\n if not result:\n raise TNonexistentTag()\n else:\n tag = TTag()\n tag.objectId = str(result[path]['id'])\n tag.path = path\n ... | <|body_start_0|>
path = path.decode('utf-8')
def run():
tags = SecureTagAPI(session.auth.user)
result = tags.get([path], withDescriptions=returnDescription)
if not result:
raise TNonexistentTag()
else:
tag = TTag()
... | FacadeTagMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacadeTagMixin:
def getTag(self, session, path, returnDescription):
"""Get information about a L{Tag}. @param session: The L{AuthenticatedSession} for the request. @param path: The L{Tag.path} to get information about. @param returnDescription: A C{bool} indicating whether or not to incl... | stack_v2_sparse_classes_36k_train_027442 | 6,844 | permissive | [
{
"docstring": "Get information about a L{Tag}. @param session: The L{AuthenticatedSession} for the request. @param path: The L{Tag.path} to get information about. @param returnDescription: A C{bool} indicating whether or not to include the L{Tag}'s description in the result. @raise TNonexistentTag: Raised if a... | 4 | null | Implement the Python class `FacadeTagMixin` described below.
Class description:
Implement the FacadeTagMixin class.
Method signatures and docstrings:
- def getTag(self, session, path, returnDescription): Get information about a L{Tag}. @param session: The L{AuthenticatedSession} for the request. @param path: The L{Ta... | Implement the Python class `FacadeTagMixin` described below.
Class description:
Implement the FacadeTagMixin class.
Method signatures and docstrings:
- def getTag(self, session, path, returnDescription): Get information about a L{Tag}. @param session: The L{AuthenticatedSession} for the request. @param path: The L{Ta... | b5a8c8349f3eaf3364cc4efba4736c3e33b30d96 | <|skeleton|>
class FacadeTagMixin:
def getTag(self, session, path, returnDescription):
"""Get information about a L{Tag}. @param session: The L{AuthenticatedSession} for the request. @param path: The L{Tag.path} to get information about. @param returnDescription: A C{bool} indicating whether or not to incl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FacadeTagMixin:
def getTag(self, session, path, returnDescription):
"""Get information about a L{Tag}. @param session: The L{AuthenticatedSession} for the request. @param path: The L{Tag.path} to get information about. @param returnDescription: A C{bool} indicating whether or not to include the L{Tag}... | the_stack_v2_python_sparse | fluiddb/api/tag.py | fluidinfo/fluiddb | train | 3 | |
9fd626af541d89c0687f091151f430c86ffbf94c | [
"def isPalindrome(t, start, end):\n while end < len(t) and start >= 0 and (t[start] == t[end]):\n start -= 1\n end += 1\n return end - start - 1\nc = -1\nstart = 0\nend = 1\nfor i in range(len(s)):\n l1 = isPalindrome(s, i, i)\n l2 = isPalindrome(s, i, i + 1)\n l = max(l1, l2)\n if l... | <|body_start_0|>
def isPalindrome(t, start, end):
while end < len(t) and start >= 0 and (t[start] == t[end]):
start -= 1
end += 1
return end - start - 1
c = -1
start = 0
end = 1
for i in range(len(s)):
l1 = isPal... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def isPalindrome(t, start, end):
while end ... | stack_v2_sparse_classes_36k_train_027443 | 1,613 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome_1",
"signature": "def longestPalindrome_1(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome_1(s... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome_1(self, s):
""":type s: str :rtype: str"""
def isPalindrome(t, start, end):
while end < len(t) and start >= 0 and (t[start] == t[end]):
start -= 1
end += 1
return end - start - 1
c = -1
star... | the_stack_v2_python_sparse | PythonCode/src/0005_Longest_Palindromic_Substring.py | oneyuan/CodeforFun | train | 0 | |
2f059578a4f95f081c051be0395ae404875cac18 | [
"memo = [1, 2]\nfor i in range(2, n):\n memo[i % 2] = sum(memo)\nreturn memo[(n - 1) % 2]",
"two = 1\none = 1\nfor i in range(2, n + 1):\n new = one + two\n two = one\n one = new\nreturn one",
"if n <= 1:\n return 1\nreturn self.climbStairs(n - 1) + self.climbStairs(n - 2)"
] | <|body_start_0|>
memo = [1, 2]
for i in range(2, n):
memo[i % 2] = sum(memo)
return memo[(n - 1) % 2]
<|end_body_0|>
<|body_start_1|>
two = 1
one = 1
for i in range(2, n + 1):
new = one + two
two = one
one = new
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
"""12/31/2017 01:49"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""Oct 13, 2021 10:57"""
<|body_1|>
def climbStairs(self, n: int) -> int:
"""Feb 19, 2023 15:07"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_027444 | 1,538 | no_license | [
{
"docstring": "12/31/2017 01:49",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": "Oct 13, 2021 10:57",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
},
{
"docstring": "Feb 19, 2023 15:07",
"name": "climbStairs",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): 12/31/2017 01:49
- def climbStairs(self, n: int) -> int: Oct 13, 2021 10:57
- def climbStairs(self, n: int) -> int: Feb 19, 2023 15:07 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): 12/31/2017 01:49
- def climbStairs(self, n: int) -> int: Oct 13, 2021 10:57
- def climbStairs(self, n: int) -> int: Feb 19, 2023 15:07
<|skeleton|>
cla... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def climbStairs(self, n):
"""12/31/2017 01:49"""
<|body_0|>
def climbStairs(self, n: int) -> int:
"""Oct 13, 2021 10:57"""
<|body_1|>
def climbStairs(self, n: int) -> int:
"""Feb 19, 2023 15:07"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n):
"""12/31/2017 01:49"""
memo = [1, 2]
for i in range(2, n):
memo[i % 2] = sum(memo)
return memo[(n - 1) % 2]
def climbStairs(self, n: int) -> int:
"""Oct 13, 2021 10:57"""
two = 1
one = 1
for i ... | the_stack_v2_python_sparse | leetcode/solved/70_Climbing_Stairs/solution.py | sungminoh/algorithms | train | 0 | |
531cf53fd5626912a737ad87ac6f1c1f65b39711 | [
"torch_and_transformers_import.check()\nsuper().__init__()\nself.devices, _ = initialize_device_settings(devices=devices, use_cuda=use_gpu, multi_gpu=False)\nif len(self.devices) > 1:\n logger.warning('Multiple devices are not supported in %s inference, using the first device %s.', self.__class__.__name__, self.... | <|body_start_0|>
torch_and_transformers_import.check()
super().__init__()
self.devices, _ = initialize_device_settings(devices=devices, use_cuda=use_gpu, multi_gpu=False)
if len(self.devices) > 1:
logger.warning('Multiple devices are not supported in %s inference, using the f... | A transformer-based model to generate captions for images using the Hugging Face's transformers framework. **Example** ```python image_file_paths = ["/path/to/images/apple.jpg", "/path/to/images/cat.jpg", ] # Generate captions documents = image_to_text.generate_captions(image_file_paths=image_file_paths) # Show results... | TransformersImageToText | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformersImageToText:
"""A transformer-based model to generate captions for images using the Hugging Face's transformers framework. **Example** ```python image_file_paths = ["/path/to/images/apple.jpg", "/path/to/images/cat.jpg", ] # Generate captions documents = image_to_text.generate_caption... | stack_v2_sparse_classes_36k_train_027445 | 8,732 | permissive | [
{
"docstring": "Load an Image-to-Text model from transformers. :param model_name_or_path: Directory of a saved model or the name of a public model. To find these models: 1. Visit [Hugging Face image to text models](https://huggingface.co/models?pipeline_tag=image-to-text).` 2. Open the model you want to check. ... | 2 | stack_v2_sparse_classes_30k_val_001133 | Implement the Python class `TransformersImageToText` described below.
Class description:
A transformer-based model to generate captions for images using the Hugging Face's transformers framework. **Example** ```python image_file_paths = ["/path/to/images/apple.jpg", "/path/to/images/cat.jpg", ] # Generate captions doc... | Implement the Python class `TransformersImageToText` described below.
Class description:
A transformer-based model to generate captions for images using the Hugging Face's transformers framework. **Example** ```python image_file_paths = ["/path/to/images/apple.jpg", "/path/to/images/cat.jpg", ] # Generate captions doc... | 5f1256ac7e5734c2ea481e72cb7e02c34baf8c43 | <|skeleton|>
class TransformersImageToText:
"""A transformer-based model to generate captions for images using the Hugging Face's transformers framework. **Example** ```python image_file_paths = ["/path/to/images/apple.jpg", "/path/to/images/cat.jpg", ] # Generate captions documents = image_to_text.generate_caption... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformersImageToText:
"""A transformer-based model to generate captions for images using the Hugging Face's transformers framework. **Example** ```python image_file_paths = ["/path/to/images/apple.jpg", "/path/to/images/cat.jpg", ] # Generate captions documents = image_to_text.generate_captions(image_file_... | the_stack_v2_python_sparse | haystack/nodes/image_to_text/transformers.py | deepset-ai/haystack | train | 10,599 |
c8c2e911fdbdf5a2565d21e58be0231a37200d78 | [
"self.history = []\nself.history.append(homepage)\nself.cur = 0",
"while len(self.history) > self.cur + 1:\n self.history.pop()\nself.history.append(url)\nself.cur += 1",
"if self.cur - steps >= 0:\n self.cur -= steps\nelse:\n self.cur = 0\nreturn self.history[self.cur]",
"length = len(self.history)\... | <|body_start_0|>
self.history = []
self.history.append(homepage)
self.cur = 0
<|end_body_0|>
<|body_start_1|>
while len(self.history) > self.cur + 1:
self.history.pop()
self.history.append(url)
self.cur += 1
<|end_body_1|>
<|body_start_2|>
if self.cu... | BrowserHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str"""
<|body_2|>
def forward(se... | stack_v2_sparse_classes_36k_train_027446 | 1,169 | no_license | [
{
"docstring": ":type homepage: str",
"name": "__init__",
"signature": "def __init__(self, homepage)"
},
{
"docstring": ":type url: str :rtype: None",
"name": "visit",
"signature": "def visit(self, url)"
},
{
"docstring": ":type steps: int :rtype: str",
"name": "back",
"s... | 4 | null | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str
- def forw... | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str
- def forw... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str"""
<|body_2|>
def forward(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
self.history = []
self.history.append(homepage)
self.cur = 0
def visit(self, url):
""":type url: str :rtype: None"""
while len(self.history) > self.cur + 1:
self.history.pop... | the_stack_v2_python_sparse | problems/N1472_Design_Browser_History.py | wan-catherine/Leetcode | train | 5 | |
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([mbart_layer.self_attn.q_proj.weight, mbart_layer.self_attn.k_proj.weight, mbart_layer.self_attn.v_proj.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([mbart_layer.self_attn.q_proj.bias, mbart_layer.self_attn.k_proj.bias, mbart_layer.sel... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([mbart_layer.self_attn.q_proj.weight, mbart_layer.self_attn.k_proj.weight, mbart_layer.self_attn.v_proj.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([mbart_layer.self_attn.q_proj.bias, mbart_layer.self... | MBartEncoderLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBartEncoderLayerBetterTransformer:
def __init__(self, mbart_layer, config):
"""A simple conversion of the `MBartEncoderLayer` to its `BetterTransformer` implementation. Args: mbart_layer (`torch.nn.Module`): The original `MBartEncoderLayer` where the weights needs to be retrieved."""
... | stack_v2_sparse_classes_36k_train_027447 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the `MBartEncoderLayer` to its `BetterTransformer` implementation. Args: mbart_layer (`torch.nn.Module`): The original `MBartEncoderLayer` where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, mbart_layer, config)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_013538 | Implement the Python class `MBartEncoderLayerBetterTransformer` described below.
Class description:
Implement the MBartEncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, mbart_layer, config): A simple conversion of the `MBartEncoderLayer` to its `BetterTransformer` implementat... | Implement the Python class `MBartEncoderLayerBetterTransformer` described below.
Class description:
Implement the MBartEncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, mbart_layer, config): A simple conversion of the `MBartEncoderLayer` to its `BetterTransformer` implementat... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MBartEncoderLayerBetterTransformer:
def __init__(self, mbart_layer, config):
"""A simple conversion of the `MBartEncoderLayer` to its `BetterTransformer` implementation. Args: mbart_layer (`torch.nn.Module`): The original `MBartEncoderLayer` where the weights needs to be retrieved."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MBartEncoderLayerBetterTransformer:
def __init__(self, mbart_layer, config):
"""A simple conversion of the `MBartEncoderLayer` to its `BetterTransformer` implementation. Args: mbart_layer (`torch.nn.Module`): The original `MBartEncoderLayer` where the weights needs to be retrieved."""
super().... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
25260a855834f56702f6484e1b7905fc500a3a2b | [
"try:\n return cls._get_conn_from_k8s(conn_id)\nexcept Exception as e:\n LoggingMixin().log.warning('Failed to retrieve connection {} from k8s secret. The error message is {} retrieving from env/db'.format(conn_id, e), exc_info=True, stack_info=True)\nreturn super().get_connection(conn_id)",
"config_map = K... | <|body_start_0|>
try:
return cls._get_conn_from_k8s(conn_id)
except Exception as e:
LoggingMixin().log.warning('Failed to retrieve connection {} from k8s secret. The error message is {} retrieving from env/db'.format(conn_id, e), exc_info=True, stack_info=True)
return sup... | A hook to work with k8s secret storage as a first default source of connections. Retrieves connection via BaseHook parent method upon failure to retrieve from k8s. | K8SBaseHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class K8SBaseHook:
"""A hook to work with k8s secret storage as a first default source of connections. Retrieves connection via BaseHook parent method upon failure to retrieve from k8s."""
def get_connection(cls, conn_id):
"""Try to get connection from k8 and if failed - invoke parent meth... | stack_v2_sparse_classes_36k_train_027448 | 2,349 | permissive | [
{
"docstring": "Try to get connection from k8 and if failed - invoke parent method. :param conn_id: connection id :type conn_id: str",
"name": "get_connection",
"signature": "def get_connection(cls, conn_id)"
},
{
"docstring": "Retrieve connection config from k8s secrets and initialize connectio... | 2 | stack_v2_sparse_classes_30k_train_005686 | Implement the Python class `K8SBaseHook` described below.
Class description:
A hook to work with k8s secret storage as a first default source of connections. Retrieves connection via BaseHook parent method upon failure to retrieve from k8s.
Method signatures and docstrings:
- def get_connection(cls, conn_id): Try to ... | Implement the Python class `K8SBaseHook` described below.
Class description:
A hook to work with k8s secret storage as a first default source of connections. Retrieves connection via BaseHook parent method upon failure to retrieve from k8s.
Method signatures and docstrings:
- def get_connection(cls, conn_id): Try to ... | 8d0599105284987fdc2ff3d130607f65ff4ce898 | <|skeleton|>
class K8SBaseHook:
"""A hook to work with k8s secret storage as a first default source of connections. Retrieves connection via BaseHook parent method upon failure to retrieve from k8s."""
def get_connection(cls, conn_id):
"""Try to get connection from k8 and if failed - invoke parent meth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class K8SBaseHook:
"""A hook to work with k8s secret storage as a first default source of connections. Retrieves connection via BaseHook parent method upon failure to retrieve from k8s."""
def get_connection(cls, conn_id):
"""Try to get connection from k8 and if failed - invoke parent method. :param co... | the_stack_v2_python_sparse | legion_airflow/legion_airflow/hooks/k8s_base_hook.py | akharlamov/legion | train | 1 |
8b44b3e1f7a451cf4076ccc875df59795ae48bc3 | [
"time = self.flowsheet().config.time\nt = self.flowsheet().config.time.first()\nself.lift_height = Var(time, initialize=400, domain=NonNegativeReals, units=pyunits.ft, doc='Lift height for pump [ft]')\nself.flow_in = pyunits.convert(self.flow_vol_in[t], to_units=pyunits.m ** 3 / pyunits.hr)\ntry:\n self.lift_hei... | <|body_start_0|>
time = self.flowsheet().config.time
t = self.flowsheet().config.time.first()
self.lift_height = Var(time, initialize=400, domain=NonNegativeReals, units=pyunits.ft, doc='Lift height for pump [ft]')
self.flow_in = pyunits.convert(self.flow_vol_in[t], to_units=pyunits.m **... | UnitProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping dista... | stack_v2_sparse_classes_36k_train_027449 | 3,523 | permissive | [
{
"docstring": "Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping distance to deep well injection site :type pipe_distance: float... | 3 | stack_v2_sparse_classes_30k_val_000354 | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :para... | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :para... | 0e9713a195b50824c4d38ff6ea5db244a6f1ad57 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping dista... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital cost for deep well injection. :param unit_params: Input parameter dictionary from input sheet. :type unit_params: dict :param lift_height: Lift height for pump [ft] :type lift_height: float :param pipe_distance: Piping distance to deep we... | the_stack_v2_python_sparse | watertap3/watertap3/wt_units/deep_well_injection.py | JamariMurke/WaterTAP3 | train | 0 | |
3dae9e209e3cc86fc3482ccfe8dae4f9597ae13d | [
"iteration = n / 4\nindex = 0\nfor i in range(iteration + 1):\n buf4 = [''] * 4\n cur = read4(buf4)\n if not cur:\n return index\n for i in range(min(n, cur)):\n buf[index] = buf4[i]\n index += 1\n n -= 1\nreturn index",
"readByte = 0\nwhile readByte < n:\n buf4 = [''] *... | <|body_start_0|>
iteration = n / 4
index = 0
for i in range(iteration + 1):
buf4 = [''] * 4
cur = read4(buf4)
if not cur:
return index
for i in range(min(n, cur)):
buf[index] = buf4[i]
index += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def read(self, buf, n):
""":type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)"""
<|body_0|>
def read(self, buf, n):
""":type buf: Destination buffer (List[str]) :type n: ... | stack_v2_sparse_classes_36k_train_027450 | 1,488 | no_license | [
{
"docstring": ":type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)",
"name": "read",
"signature": "def read(self, buf, n)"
},
{
"docstring": ":type buf: Destination buffer (List[str]) :type n: Maximum number o... | 2 | stack_v2_sparse_classes_30k_train_000313 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def read(self, buf, n): :type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)
- def read(self,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def read(self, buf, n): :type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)
- def read(self,... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def read(self, buf, n):
""":type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)"""
<|body_0|>
def read(self, buf, n):
""":type buf: Destination buffer (List[str]) :type n: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def read(self, buf, n):
""":type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int)"""
iteration = n / 4
index = 0
for i in range(iteration + 1):
buf4 = [''] * 4
c... | the_stack_v2_python_sparse | Python_leetcode/157_read_n_character_given_read4.py | xiangcao/Leetcode | train | 0 | |
517f2d828d87b510187bb24b319ac2969b302d72 | [
"super(AbstractMapSolver, self).__init__(dim, **kwds)\ntrialPop = [[0.0 for i in range(dim)] for j in range(self.nPop)]\nself.trialSolution = trialPop\nself._map_solver = True\nfrom python_map import serial_launcher\nfrom python_map import python_map\nfrom python_map import worker_pool\nfrom python_map import defau... | <|body_start_0|>
super(AbstractMapSolver, self).__init__(dim, **kwds)
trialPop = [[0.0 for i in range(dim)] for j in range(self.nPop)]
self.trialSolution = trialPop
self._map_solver = True
from python_map import serial_launcher
from python_map import python_map
fr... | AbstractMapSolver base class for mystic optimizers that utilize parallel map. | AbstractMapSolver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractMapSolver:
"""AbstractMapSolver base class for mystic optimizers that utilize parallel map."""
def __init__(self, dim, **kwds):
"""Takes one initial input: dim -- dimensionality of the problem. Additional inputs: npop -- size of the trial solution population. [default = 1] Im... | stack_v2_sparse_classes_36k_train_027451 | 8,738 | permissive | [
{
"docstring": "Takes one initial input: dim -- dimensionality of the problem. Additional inputs: npop -- size of the trial solution population. [default = 1] Important class members: nDim, nPop = dim, npop generations - an iteration counter. evaluations - an evaluation counter. bestEnergy - current best energy... | 5 | null | Implement the Python class `AbstractMapSolver` described below.
Class description:
AbstractMapSolver base class for mystic optimizers that utilize parallel map.
Method signatures and docstrings:
- def __init__(self, dim, **kwds): Takes one initial input: dim -- dimensionality of the problem. Additional inputs: npop -... | Implement the Python class `AbstractMapSolver` described below.
Class description:
AbstractMapSolver base class for mystic optimizers that utilize parallel map.
Method signatures and docstrings:
- def __init__(self, dim, **kwds): Takes one initial input: dim -- dimensionality of the problem. Additional inputs: npop -... | 3dcdd4627eb759672091859e8334be075bfd25a5 | <|skeleton|>
class AbstractMapSolver:
"""AbstractMapSolver base class for mystic optimizers that utilize parallel map."""
def __init__(self, dim, **kwds):
"""Takes one initial input: dim -- dimensionality of the problem. Additional inputs: npop -- size of the trial solution population. [default = 1] Im... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractMapSolver:
"""AbstractMapSolver base class for mystic optimizers that utilize parallel map."""
def __init__(self, dim, **kwds):
"""Takes one initial input: dim -- dimensionality of the problem. Additional inputs: npop -- size of the trial solution population. [default = 1] Important class... | the_stack_v2_python_sparse | mystic/abstract_map_solver.py | arita37/mystic | train | 1 |
54f3751dbbd8e273ab00db09996ba4fd0de8dedd | [
"self.layer_id = layer_id\nself.receive_buffer = Queue()\nself.send_buffer = Queue()\nself.above_layer = None\nself.below_layer = None\nself.args = args\nself.node_data = node_data\nself.simulation_mng = simulation_mng\nself.metric_mng = metric_mng\nreceive_thread = Thread(target=self.receive)\nreceive_thread.daemo... | <|body_start_0|>
self.layer_id = layer_id
self.receive_buffer = Queue()
self.send_buffer = Queue()
self.above_layer = None
self.below_layer = None
self.args = args
self.node_data = node_data
self.simulation_mng = simulation_mng
self.metric_mng = me... | Interface for each layer Processes each packet the layer sends and receives See test_layer.py for an example on how to create a layer | LayerBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerBase:
"""Interface for each layer Processes each packet the layer sends and receives See test_layer.py for an example on how to create a layer"""
def __init__(self, simulation_mng, metric_mng, node_data, layer_id, args):
"""Spawns the threads to retreive and process message from... | stack_v2_sparse_classes_36k_train_027452 | 2,746 | permissive | [
{
"docstring": "Spawns the threads to retreive and process message from the send and receive buffers Arguments simulation_mng - used to stop the simulation when a node goes offline metric_mng - used to keep track of loss and delay note_data - initialized node data including ID and battery life layer_id - unique... | 5 | stack_v2_sparse_classes_30k_train_015614 | Implement the Python class `LayerBase` described below.
Class description:
Interface for each layer Processes each packet the layer sends and receives See test_layer.py for an example on how to create a layer
Method signatures and docstrings:
- def __init__(self, simulation_mng, metric_mng, node_data, layer_id, args)... | Implement the Python class `LayerBase` described below.
Class description:
Interface for each layer Processes each packet the layer sends and receives See test_layer.py for an example on how to create a layer
Method signatures and docstrings:
- def __init__(self, simulation_mng, metric_mng, node_data, layer_id, args)... | f8ddef779a574306af861dcc5bc3602674e699cd | <|skeleton|>
class LayerBase:
"""Interface for each layer Processes each packet the layer sends and receives See test_layer.py for an example on how to create a layer"""
def __init__(self, simulation_mng, metric_mng, node_data, layer_id, args):
"""Spawns the threads to retreive and process message from... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayerBase:
"""Interface for each layer Processes each packet the layer sends and receives See test_layer.py for an example on how to create a layer"""
def __init__(self, simulation_mng, metric_mng, node_data, layer_id, args):
"""Spawns the threads to retreive and process message from the send and... | the_stack_v2_python_sparse | load_distributed/layers/layer_base.py | kylebrain/networking-final-project | train | 2 |
78a6bbb9e28feea5e61784d0e391b1b11a96d5de | [
"pe.set_default_val(config, 'layer_norm', True)\npe.set_default_val(config, 'activation_fn', tfe.leakyrelu(0.1))\npe.set_default_val(config, 'mask_type', None)\nself.shared_structure = shared_structure\nself.head_structure = head_structure\nsuper().__init__(K, D, K, config)",
"with tf.variable_scope(scope, reuse=... | <|body_start_0|>
pe.set_default_val(config, 'layer_norm', True)
pe.set_default_val(config, 'activation_fn', tfe.leakyrelu(0.1))
pe.set_default_val(config, 'mask_type', None)
self.shared_structure = shared_structure
self.head_structure = head_structure
super().__init__(K, ... | This represents a general DuplicatedEnsembleNetwork. It can be used in different types of contexts. | DuplicatedEnsembleNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DuplicatedEnsembleNetwork:
"""This represents a general DuplicatedEnsembleNetwork. It can be used in different types of contexts."""
def __init__(self, K, D, shared_structure, head_structure, config):
"""This constructs a new DuplicatedEnsembleNetwork. It takes the structure of the n... | stack_v2_sparse_classes_36k_train_027453 | 3,371 | permissive | [
{
"docstring": "This constructs a new DuplicatedEnsembleNetwork. It takes the structure of the network and also the configuration. Args: shared_structure: The structure for the shared network head_structure: The structure for the head network config: layer_norm: Activate Layer Normalization activation_fn: Defin... | 2 | stack_v2_sparse_classes_30k_train_019948 | Implement the Python class `DuplicatedEnsembleNetwork` described below.
Class description:
This represents a general DuplicatedEnsembleNetwork. It can be used in different types of contexts.
Method signatures and docstrings:
- def __init__(self, K, D, shared_structure, head_structure, config): This constructs a new D... | Implement the Python class `DuplicatedEnsembleNetwork` described below.
Class description:
This represents a general DuplicatedEnsembleNetwork. It can be used in different types of contexts.
Method signatures and docstrings:
- def __init__(self, K, D, shared_structure, head_structure, config): This constructs a new D... | 0d72e0a3e6f39c9a4e797a17911e2beec352b14a | <|skeleton|>
class DuplicatedEnsembleNetwork:
"""This represents a general DuplicatedEnsembleNetwork. It can be used in different types of contexts."""
def __init__(self, K, D, shared_structure, head_structure, config):
"""This constructs a new DuplicatedEnsembleNetwork. It takes the structure of the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DuplicatedEnsembleNetwork:
"""This represents a general DuplicatedEnsembleNetwork. It can be used in different types of contexts."""
def __init__(self, K, D, shared_structure, head_structure, config):
"""This constructs a new DuplicatedEnsembleNetwork. It takes the structure of the network and al... | the_stack_v2_python_sparse | nn/DuplicatedEnsembleNetwork.py | kosmitive/bootstrapped-dqn | train | 2 |
05a152f09390369a6d9d02a0febe6cec74d508b7 | [
"response = {'success': False, 'message': 'Something bad happened', 'data': []}\nuser = request.user\ntry:\n requestBody = json.loads(request.body)\n label_name = requestBody['name']\n label_updated = Label.objects.get(id=label_id, user_id=user.id)\n label_updated.name = label_name\n label_updated.sa... | <|body_start_0|>
response = {'success': False, 'message': 'Something bad happened', 'data': []}
user = request.user
try:
requestBody = json.loads(request.body)
label_name = requestBody['name']
label_updated = Label.objects.get(id=label_id, user_id=user.id)
... | Summary: -------- Label update class will let authorized user to update or delete label. Methods: -------- put: User will be able to update label. delete: User will able to delete one or more labels. | LabelsUpdate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelsUpdate:
"""Summary: -------- Label update class will let authorized user to update or delete label. Methods: -------- put: User will be able to update label. delete: User will able to delete one or more labels."""
def put(self, request, label_id):
"""Summary: -------- label wil... | stack_v2_sparse_classes_36k_train_027454 | 30,711 | no_license | [
{
"docstring": "Summary: -------- label will be updated by the User. Exception: ---------- Exception: if anything goes wrong. Returns: -------- response: User will able to updated label or error msg if something goes wrong",
"name": "put",
"signature": "def put(self, request, label_id)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_000067 | Implement the Python class `LabelsUpdate` described below.
Class description:
Summary: -------- Label update class will let authorized user to update or delete label. Methods: -------- put: User will be able to update label. delete: User will able to delete one or more labels.
Method signatures and docstrings:
- def ... | Implement the Python class `LabelsUpdate` described below.
Class description:
Summary: -------- Label update class will let authorized user to update or delete label. Methods: -------- put: User will be able to update label. delete: User will able to delete one or more labels.
Method signatures and docstrings:
- def ... | f4035742d959f493f93a593f49e2fcacb721f85d | <|skeleton|>
class LabelsUpdate:
"""Summary: -------- Label update class will let authorized user to update or delete label. Methods: -------- put: User will be able to update label. delete: User will able to delete one or more labels."""
def put(self, request, label_id):
"""Summary: -------- label wil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelsUpdate:
"""Summary: -------- Label update class will let authorized user to update or delete label. Methods: -------- put: User will be able to update label. delete: User will able to delete one or more labels."""
def put(self, request, label_id):
"""Summary: -------- label will be updated ... | the_stack_v2_python_sparse | note/views.py | nk900600/fundooapp | train | 3 |
45e6674031a8b222dfc223c2c011e027760a90d0 | [
"super().__init__()\nself.output_size = output_size\nself.use_sigmoid = use_sigmoid\nself.dense_bn_dropout = DenseBnDropout(lin_layer_sizes=lin_layer_sizes, lin_layer_dropouts=lin_layer_dropouts, input_size=input_size)\nself.output_layer = nn.Linear(lin_layer_sizes[-1], output_size)\nnn.init.kaiming_normal_(self.ou... | <|body_start_0|>
super().__init__()
self.output_size = output_size
self.use_sigmoid = use_sigmoid
self.dense_bn_dropout = DenseBnDropout(lin_layer_sizes=lin_layer_sizes, lin_layer_dropouts=lin_layer_dropouts, input_size=input_size)
self.output_layer = nn.Linear(lin_layer_sizes[-1... | MLP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
def __init__(self, input_size, lin_layer_sizes, lin_layer_dropouts, output_size, use_sigmoid=False):
"""Initialize model with params."""
<|body_0|>
def forward(self, inp):
"""Run a forward pass of model over the data."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_027455 | 1,148 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, input_size, lin_layer_sizes, lin_layer_dropouts, output_size, use_sigmoid=False)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forw... | 2 | stack_v2_sparse_classes_30k_train_021182 | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, input_size, lin_layer_sizes, lin_layer_dropouts, output_size, use_sigmoid=False): Initialize model with params.
- def forward(self, inp): Run a forward pass of model ove... | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, input_size, lin_layer_sizes, lin_layer_dropouts, output_size, use_sigmoid=False): Initialize model with params.
- def forward(self, inp): Run a forward pass of model ove... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class MLP:
def __init__(self, input_size, lin_layer_sizes, lin_layer_dropouts, output_size, use_sigmoid=False):
"""Initialize model with params."""
<|body_0|>
def forward(self, inp):
"""Run a forward pass of model over the data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLP:
def __init__(self, input_size, lin_layer_sizes, lin_layer_dropouts, output_size, use_sigmoid=False):
"""Initialize model with params."""
super().__init__()
self.output_size = output_size
self.use_sigmoid = use_sigmoid
self.dense_bn_dropout = DenseBnDropout(lin_laye... | the_stack_v2_python_sparse | caspr/models/mlp.py | microsoft/CASPR | train | 29 | |
b67860fa5829925ba8b94f029d289e7b7713da6f | [
"super(afsc_bot_detector, self).__init__()\nself.search_min = search_min\nself.window_len = window_len\nself.backstep = backstep",
"if not isinstance(p_data, processed_data.processed_data):\n raise TypeError('You must pass a processed_data object to this method.')\nv_axis, v_axis_type = p_data.get_v_axis()\nbo... | <|body_start_0|>
super(afsc_bot_detector, self).__init__()
self.search_min = search_min
self.window_len = window_len
self.backstep = backstep
<|end_body_0|>
<|body_start_1|>
if not isinstance(p_data, processed_data.processed_data):
raise TypeError('You must pass a pr... | The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom deteciton parameters, then call the detect me... | afsc_bot_detector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class afsc_bot_detector:
"""The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom ... | stack_v2_sparse_classes_36k_train_027456 | 7,840 | permissive | [
{
"docstring": "Initializes afsc_bot_detector object and sets several internal properties.",
"name": "__init__",
"signature": "def __init__(self, search_min=10, window_len=11, backstep=35)"
},
{
"docstring": "p_data - an instance of a processed data object that contains the data to perform the b... | 3 | stack_v2_sparse_classes_30k_train_004381 | Implement the Python class `afsc_bot_detector` described below.
Class description:
The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you insta... | Implement the Python class `afsc_bot_detector` described below.
Class description:
The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you insta... | 6e165ad1a947e62fc233467631c445fe9ebcdad2 | <|skeleton|>
class afsc_bot_detector:
"""The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class afsc_bot_detector:
"""The afsc_bot_detector class implements a simple amplitude based bottom detection algorithm. It was written mainly as an example and will need to be developed further if you're looking for a robust bottom pick solution. To use, you instantiate an instance setting your bottom deteciton par... | the_stack_v2_python_sparse | echolab2/processing/afsc_bot_detector.py | iambaim/pyEcholab | train | 2 |
dfef8cd9592db326be2be7bddf7cea57302ec83a | [
"self.sums = [0] * (len(nums) + 1)\nprev = 0\ni = 0\nfor x in nums:\n prev = prev + x\n self.sums[i] = prev\n i += 1\nself.sums = self.sums",
"if i == 0:\n return self.sums[j]\nelse:\n return self.sums[j] - self.sums[i - 1]"
] | <|body_start_0|>
self.sums = [0] * (len(nums) + 1)
prev = 0
i = 0
for x in nums:
prev = prev + x
self.sums[i] = prev
i += 1
self.sums = self.sums
<|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] * (len(nums) + 1)
prev = 0
... | stack_v2_sparse_classes_36k_train_027457 | 657 | 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_val_000981 | 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):
... | 5be9fab24c0c1fd9d5dc7a7bdaca105f1ca873ee | <|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] * (len(nums) + 1)
prev = 0
i = 0
for x in nums:
prev = prev + x
self.sums[i] = prev
i += 1
self.sums = self.sums
def sumRange(self, i, j):
... | the_stack_v2_python_sparse | Easy/dp/NumArray.py | unsortedtosorted/elgoog | train | 0 | |
5e544f198d41eb0e5675a14b3c2775fa53fcacf4 | [
"regex = '^(\\\\d+).*'\npattern = re.compile(regex)\nmatcher = pattern.search(limit_text_of_per_page)\nif matcher:\n return matcher.group(1)\nelse:\n return None",
"regex = '\\\\d+-\\\\d+\\\\s共(\\\\d+)条$'\npattern = re.compile(regex)\nmatcher = pattern.search(total_data_text)\nif matcher:\n return matche... | <|body_start_0|>
regex = '^(\\d+).*'
pattern = re.compile(regex)
matcher = pattern.search(limit_text_of_per_page)
if matcher:
return matcher.group(1)
else:
return None
<|end_body_0|>
<|body_start_1|>
regex = '\\d+-\\d+\\s共(\\d+)条$'
pattern... | 广告位管理页面 | ADPlaceManagePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADPlaceManagePage:
"""广告位管理页面"""
def get_limit_number(self, limit_text_of_per_page):
"""获取每页显示条数"""
<|body_0|>
def get_total_datas(self, total_data_text):
"""获取数据总数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
regex = '^(\\d+).*'
patt... | stack_v2_sparse_classes_36k_train_027458 | 12,259 | no_license | [
{
"docstring": "获取每页显示条数",
"name": "get_limit_number",
"signature": "def get_limit_number(self, limit_text_of_per_page)"
},
{
"docstring": "获取数据总数",
"name": "get_total_datas",
"signature": "def get_total_datas(self, total_data_text)"
}
] | 2 | null | Implement the Python class `ADPlaceManagePage` described below.
Class description:
广告位管理页面
Method signatures and docstrings:
- def get_limit_number(self, limit_text_of_per_page): 获取每页显示条数
- def get_total_datas(self, total_data_text): 获取数据总数 | Implement the Python class `ADPlaceManagePage` described below.
Class description:
广告位管理页面
Method signatures and docstrings:
- def get_limit_number(self, limit_text_of_per_page): 获取每页显示条数
- def get_total_datas(self, total_data_text): 获取数据总数
<|skeleton|>
class ADPlaceManagePage:
"""广告位管理页面"""
def get_limit_n... | 3011071556a3fa097d951a1823a4870cc4cc81e1 | <|skeleton|>
class ADPlaceManagePage:
"""广告位管理页面"""
def get_limit_number(self, limit_text_of_per_page):
"""获取每页显示条数"""
<|body_0|>
def get_total_datas(self, total_data_text):
"""获取数据总数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ADPlaceManagePage:
"""广告位管理页面"""
def get_limit_number(self, limit_text_of_per_page):
"""获取每页显示条数"""
regex = '^(\\d+).*'
pattern = re.compile(regex)
matcher = pattern.search(limit_text_of_per_page)
if matcher:
return matcher.group(1)
else:
... | the_stack_v2_python_sparse | sevenautotest/testobjects/pages/webpages/yy/ad_place_manage_page.py | hotswwkyo/SevenPytest | train | 3 |
e3f696c7779863c6bee0963f1ca34d494b11beb7 | [
"invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(account_id=account_id)\nif self.sale_layout_cat_id:\n invoice_vals['sale_layout_cat_id'] = self.sale_layout_cat_id.id\nif self.categ_sequence:\n invoice_vals['categ_sequence'] = self.categ_sequence\nreturn invoice_vals",
"res = supe... | <|body_start_0|>
invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(account_id=account_id)
if self.sale_layout_cat_id:
invoice_vals['sale_layout_cat_id'] = self.sale_layout_cat_id.id
if self.categ_sequence:
invoice_vals['categ_sequence'] = self.cat... | SaleOrderLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleOrderLine:
def _prepare_order_line_invoice_line(self, account_id=False):
"""Save the layout when converting to an invoice line."""
<|body_0|>
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line... | stack_v2_sparse_classes_36k_train_027459 | 3,772 | no_license | [
{
"docstring": "Save the layout when converting to an invoice line.",
"name": "_prepare_order_line_invoice_line",
"signature": "def _prepare_order_line_invoice_line(self, account_id=False)"
},
{
"docstring": "Prepare the dict of values to create the new invoice line for a sales order line. :para... | 2 | stack_v2_sparse_classes_30k_train_010762 | Implement the Python class `SaleOrderLine` described below.
Class description:
Implement the SaleOrderLine class.
Method signatures and docstrings:
- def _prepare_order_line_invoice_line(self, account_id=False): Save the layout when converting to an invoice line.
- def _prepare_invoice_line(self, qty): Prepare the di... | Implement the Python class `SaleOrderLine` described below.
Class description:
Implement the SaleOrderLine class.
Method signatures and docstrings:
- def _prepare_order_line_invoice_line(self, account_id=False): Save the layout when converting to an invoice line.
- def _prepare_invoice_line(self, qty): Prepare the di... | a12caeabf64662fb134c2b10c4ede8006173edfd | <|skeleton|>
class SaleOrderLine:
def _prepare_order_line_invoice_line(self, account_id=False):
"""Save the layout when converting to an invoice line."""
<|body_0|>
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaleOrderLine:
def _prepare_order_line_invoice_line(self, account_id=False):
"""Save the layout when converting to an invoice line."""
invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(account_id=account_id)
if self.sale_layout_cat_id:
invoice_vals[... | the_stack_v2_python_sparse | talentys_custom/models/sale_layout.py | lekaizen210/addons_talentys | train | 0 | |
4566edfc665af9d418fc8f243902a4308f34769f | [
"self.data_bounds = data_bounds\nself._tr = Range(from_bounds=NDC, to_bounds=self.data_bounds)\nself._tri = self._tr.inverse()\nself.set_nbins(nbinsx, nbinsy)",
"nbinsx = self._bins_margin * nbinsx if _is_integer(nbinsx) else self._default_nbinsx\nnbinsy = self._bins_margin * nbinsy if _is_integer(nbinsy) else se... | <|body_start_0|>
self.data_bounds = data_bounds
self._tr = Range(from_bounds=NDC, to_bounds=self.data_bounds)
self._tri = self._tr.inverse()
self.set_nbins(nbinsx, nbinsy)
<|end_body_0|>
<|body_start_1|>
nbinsx = self._bins_margin * nbinsx if _is_integer(nbinsx) else self._defau... | Determine the location of ticks in a view. Constructor ----------- nbinsx : int Number of ticks on the x axis. nbinsy : int Number of ticks on the y axis. data_bounds : 4-tuple Initial coordinates of the viewport, as (xmin, ymin, xmax, ymax), in data coordinates. These are the data coordinates of the lower left and upp... | AxisLocator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisLocator:
"""Determine the location of ticks in a view. Constructor ----------- nbinsx : int Number of ticks on the x axis. nbinsy : int Number of ticks on the y axis. data_bounds : 4-tuple Initial coordinates of the viewport, as (xmin, ymin, xmax, ymax), in data coordinates. These are the dat... | stack_v2_sparse_classes_36k_train_027460 | 9,151 | permissive | [
{
"docstring": "data_bounds is the initial bounds of the view in data coordinates.",
"name": "__init__",
"signature": "def __init__(self, nbinsx=None, nbinsy=None, data_bounds=None)"
},
{
"docstring": "Change the number of bins on the x and y axes.",
"name": "set_nbins",
"signature": "de... | 4 | null | Implement the Python class `AxisLocator` described below.
Class description:
Determine the location of ticks in a view. Constructor ----------- nbinsx : int Number of ticks on the x axis. nbinsy : int Number of ticks on the y axis. data_bounds : 4-tuple Initial coordinates of the viewport, as (xmin, ymin, xmax, ymax),... | Implement the Python class `AxisLocator` described below.
Class description:
Determine the location of ticks in a view. Constructor ----------- nbinsx : int Number of ticks on the x axis. nbinsy : int Number of ticks on the y axis. data_bounds : 4-tuple Initial coordinates of the viewport, as (xmin, ymin, xmax, ymax),... | 642c875994b44618c3b3157d6e6f4425450813f8 | <|skeleton|>
class AxisLocator:
"""Determine the location of ticks in a view. Constructor ----------- nbinsx : int Number of ticks on the x axis. nbinsy : int Number of ticks on the y axis. data_bounds : 4-tuple Initial coordinates of the viewport, as (xmin, ymin, xmax, ymax), in data coordinates. These are the dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisLocator:
"""Determine the location of ticks in a view. Constructor ----------- nbinsx : int Number of ticks on the x axis. nbinsy : int Number of ticks on the y axis. data_bounds : 4-tuple Initial coordinates of the viewport, as (xmin, ymin, xmax, ymax), in data coordinates. These are the data coordinates... | the_stack_v2_python_sparse | phy/plot/axes.py | cortex-lab/phy | train | 192 |
e62a825fc930d50875e5756d9a82cab964d6a5f2 | [
"self.data = data\nself.plot_title = plot_title\nself.label_names = label_names",
"try:\n assert isinstance(title, str)\n self.plot_title = title\nexcept AssertionError:\n print('the add_title method requires a sting input')\n print(\"therefore not changing plot's title\")",
"try:\n if not isinst... | <|body_start_0|>
self.data = data
self.plot_title = plot_title
self.label_names = label_names
<|end_body_0|>
<|body_start_1|>
try:
assert isinstance(title, str)
self.plot_title = title
except AssertionError:
print('the add_title method require... | Generic plotting class used in the grapher module | Plotter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plotter:
"""Generic plotting class used in the grapher module"""
def __init__(self, data, plot_title=None, label_names=None):
"""Initializes plotting class with an optional plot title and label Parameters ---------- data : pandas.DataFrame the Pandas Dataframe to be plotted plot_titl... | stack_v2_sparse_classes_36k_train_027461 | 4,793 | permissive | [
{
"docstring": "Initializes plotting class with an optional plot title and label Parameters ---------- data : pandas.DataFrame the Pandas Dataframe to be plotted plot_title : str, optional (default = None) the plot title label_names : str tuple, optional (default = None) the x-axis and y-axis titles (x-axis is ... | 5 | stack_v2_sparse_classes_30k_train_015066 | Implement the Python class `Plotter` described below.
Class description:
Generic plotting class used in the grapher module
Method signatures and docstrings:
- def __init__(self, data, plot_title=None, label_names=None): Initializes plotting class with an optional plot title and label Parameters ---------- data : pand... | Implement the Python class `Plotter` described below.
Class description:
Generic plotting class used in the grapher module
Method signatures and docstrings:
- def __init__(self, data, plot_title=None, label_names=None): Initializes plotting class with an optional plot title and label Parameters ---------- data : pand... | 8fbcf41d579be76eadf0ac980f4c9cbe30d60d93 | <|skeleton|>
class Plotter:
"""Generic plotting class used in the grapher module"""
def __init__(self, data, plot_title=None, label_names=None):
"""Initializes plotting class with an optional plot title and label Parameters ---------- data : pandas.DataFrame the Pandas Dataframe to be plotted plot_titl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Plotter:
"""Generic plotting class used in the grapher module"""
def __init__(self, data, plot_title=None, label_names=None):
"""Initializes plotting class with an optional plot title and label Parameters ---------- data : pandas.DataFrame the Pandas Dataframe to be plotted plot_title : str, opti... | the_stack_v2_python_sparse | quickscreen/plot/plotter.py | mqharris/533_lab2 | train | 0 |
af6e25c503633ec286a5f35da590d8e5dd9cb57f | [
"self.directory = directory\nself.session = session\nself.project_id = project_id\nself.configuration = config",
"logging.info('export_to_csv')\nexcluded_versions = self.configuration.exclude_versions\nincluded_and_current_versions = get_included_and_current_versions_filter(self.session, self.configuration)\nmetr... | <|body_start_0|>
self.directory = directory
self.session = session
self.project_id = project_id
self.configuration = config
<|end_body_0|>
<|body_start_1|>
logging.info('export_to_csv')
excluded_versions = self.configuration.exclude_versions
included_and_current_... | Export the database to a flat file | FlatFileExporter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlatFileExporter:
"""Export the database to a flat file"""
def __init__(self, project_id, directory, session, config):
"""Constructor Parameters: ----------- session : Session SQLAlchemy session project_id : int Project Identifier directory : str Output path"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_027462 | 2,752 | permissive | [
{
"docstring": "Constructor Parameters: ----------- session : Session SQLAlchemy session project_id : int Project Identifier directory : str Output path",
"name": "__init__",
"signature": "def __init__(self, project_id, directory, session, config)"
},
{
"docstring": "Export the database to CSV P... | 3 | stack_v2_sparse_classes_30k_train_006901 | Implement the Python class `FlatFileExporter` described below.
Class description:
Export the database to a flat file
Method signatures and docstrings:
- def __init__(self, project_id, directory, session, config): Constructor Parameters: ----------- session : Session SQLAlchemy session project_id : int Project Identif... | Implement the Python class `FlatFileExporter` described below.
Class description:
Export the database to a flat file
Method signatures and docstrings:
- def __init__(self, project_id, directory, session, config): Constructor Parameters: ----------- session : Session SQLAlchemy session project_id : int Project Identif... | 161628d504627d0623b584e7e92bb3130a24b8ef | <|skeleton|>
class FlatFileExporter:
"""Export the database to a flat file"""
def __init__(self, project_id, directory, session, config):
"""Constructor Parameters: ----------- session : Session SQLAlchemy session project_id : int Project Identifier directory : str Output path"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlatFileExporter:
"""Export the database to a flat file"""
def __init__(self, project_id, directory, session, config):
"""Constructor Parameters: ----------- session : Session SQLAlchemy session project_id : int Project Identifier directory : str Output path"""
self.directory = directory
... | the_stack_v2_python_sparse | exporters/flatfile.py | optittm/bugprediction | train | 2 |
3b6dd19f6d0ad43bf8fe62e84f348525992328b5 | [
"sum = 0\nres = []\nfor i in nums:\n if i == 1:\n sum += 1\n else:\n res.append(sum)\n sum = 0\n res.append(sum)\nreturn max(res)",
"sum = 0\nres = 0\nfor i in nums:\n if i == 1:\n sum += 1\n else:\n res = max(res, sum)\n sum = 0\n res = max(res, sum)\nr... | <|body_start_0|>
sum = 0
res = []
for i in nums:
if i == 1:
sum += 1
else:
res.append(sum)
sum = 0
res.append(sum)
return max(res)
<|end_body_0|>
<|body_start_1|>
sum = 0
res = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxConsecutiveOnes(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sum = 0
res = []
for i... | stack_v2_sparse_classes_36k_train_027463 | 1,088 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMaxConsecutiveOnes",
"signature": "def findMaxConsecutiveOnes(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMax",
"signature": "def findMax(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011194 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): :type nums: List[int] :rtype: int
- def findMax(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): :type nums: List[int] :rtype: int
- def findMax(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def find... | 1040b5dbbe509abe42df848bc34dd1626d7a05fb | <|skeleton|>
class Solution:
def findMaxConsecutiveOnes(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMax(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaxConsecutiveOnes(self, nums):
""":type nums: List[int] :rtype: int"""
sum = 0
res = []
for i in nums:
if i == 1:
sum += 1
else:
res.append(sum)
sum = 0
res.append(sum)
... | the_stack_v2_python_sparse | list/findMaxConsecutiveOnes.py | NJ-zero/LeetCode_Answer | train | 1 | |
61c14109b4ea67de36be535b4f96e9dfb61f50df | [
"if not email:\n raise ValueError('Введите e-mail')\nuser = self.model(email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, confirm_email=False, is_active=True)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email=sel... | <|body_start_0|>
if not email:
raise ValueError('Введите e-mail')
user = self.model(email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, confirm_email=False, is_active=True)
user.set_password(password)
user.save(using=self._db)
... | Account manager. | MyAccountManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyAccountManager:
"""Account manager."""
def create_user(self, first_name, last_name, email, username, password=None):
"""Creates and saves a new user."""
<|body_0|>
def create_superuser(self, first_name, last_name, email, username, password):
"""Creates and save... | stack_v2_sparse_classes_36k_train_027464 | 3,931 | permissive | [
{
"docstring": "Creates and saves a new user.",
"name": "create_user",
"signature": "def create_user(self, first_name, last_name, email, username, password=None)"
},
{
"docstring": "Creates and saves a new super user.",
"name": "create_superuser",
"signature": "def create_superuser(self,... | 2 | null | Implement the Python class `MyAccountManager` described below.
Class description:
Account manager.
Method signatures and docstrings:
- def create_user(self, first_name, last_name, email, username, password=None): Creates and saves a new user.
- def create_superuser(self, first_name, last_name, email, username, passwo... | Implement the Python class `MyAccountManager` described below.
Class description:
Account manager.
Method signatures and docstrings:
- def create_user(self, first_name, last_name, email, username, password=None): Creates and saves a new user.
- def create_superuser(self, first_name, last_name, email, username, passwo... | cbb16fc9ab2b85232e4c05446697fc82b78bc8e4 | <|skeleton|>
class MyAccountManager:
"""Account manager."""
def create_user(self, first_name, last_name, email, username, password=None):
"""Creates and saves a new user."""
<|body_0|>
def create_superuser(self, first_name, last_name, email, username, password):
"""Creates and save... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyAccountManager:
"""Account manager."""
def create_user(self, first_name, last_name, email, username, password=None):
"""Creates and saves a new user."""
if not email:
raise ValueError('Введите e-mail')
user = self.model(email=self.normalize_email(email), username=use... | the_stack_v2_python_sparse | shop/accounts/models.py | Anych/mila-iris | train | 0 |
da94067534fe0d909b4cddfb4a5d47467b9dd595 | [
"global COMPANY_CONN\ncursor = None\ntry:\n cursor = COMPANY_CONN.cursor(buffered=True, dictionary=True)\n sql = 'insert into lie_category_items(items_name,cat_id, brand_id,url) values(%(items_name)s,%(cat_id)s,%(brand_id)s,%(url)s)'\n cursor.execute(sql, lieCategoryItems)\n COMPANY_CONN.commit()\nexcep... | <|body_start_0|>
global COMPANY_CONN
cursor = None
try:
cursor = COMPANY_CONN.cursor(buffered=True, dictionary=True)
sql = 'insert into lie_category_items(items_name,cat_id, brand_id,url) values(%(items_name)s,%(cat_id)s,%(brand_id)s,%(url)s)'
cursor.execute(s... | LieCategoryItems | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LieCategoryItems:
def addLieCategoryItems(cls, lieCategoryItems):
"""method: addLieCategoryItems params: lieCategoryItems-type: LieCategoryItems"""
<|body_0|>
def get_items_id_by_items_name(cls, items_name):
"""method: get_items_id_by_items_name params: items_name-ty... | stack_v2_sparse_classes_36k_train_027465 | 13,174 | no_license | [
{
"docstring": "method: addLieCategoryItems params: lieCategoryItems-type: LieCategoryItems",
"name": "addLieCategoryItems",
"signature": "def addLieCategoryItems(cls, lieCategoryItems)"
},
{
"docstring": "method: get_items_id_by_items_name params: items_name-type: str return: items_id return-ty... | 5 | stack_v2_sparse_classes_30k_val_000012 | Implement the Python class `LieCategoryItems` described below.
Class description:
Implement the LieCategoryItems class.
Method signatures and docstrings:
- def addLieCategoryItems(cls, lieCategoryItems): method: addLieCategoryItems params: lieCategoryItems-type: LieCategoryItems
- def get_items_id_by_items_name(cls, ... | Implement the Python class `LieCategoryItems` described below.
Class description:
Implement the LieCategoryItems class.
Method signatures and docstrings:
- def addLieCategoryItems(cls, lieCategoryItems): method: addLieCategoryItems params: lieCategoryItems-type: LieCategoryItems
- def get_items_id_by_items_name(cls, ... | 1e49a6e13ea4b11427f47999c13a609be9ae3ecf | <|skeleton|>
class LieCategoryItems:
def addLieCategoryItems(cls, lieCategoryItems):
"""method: addLieCategoryItems params: lieCategoryItems-type: LieCategoryItems"""
<|body_0|>
def get_items_id_by_items_name(cls, items_name):
"""method: get_items_id_by_items_name params: items_name-ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LieCategoryItems:
def addLieCategoryItems(cls, lieCategoryItems):
"""method: addLieCategoryItems params: lieCategoryItems-type: LieCategoryItems"""
global COMPANY_CONN
cursor = None
try:
cursor = COMPANY_CONN.cursor(buffered=True, dictionary=True)
sql = ... | the_stack_v2_python_sparse | rsonline/server/db/company/mysql_client.py | yunhao-qing/PythonScrapy | train | 0 | |
07282fa0406820e353a4f534af7da84ba2f74a86 | [
"self.up_read = up_read\nself.down_write = down_write\nself.socks = socks\nself.idx = idx",
"logger.debug('Starting child %s', self.idx)\nself._started = True\nself.loop = asyncio.new_event_loop()\nasyncio.set_event_loop(self.loop)\nsignal.signal(signal.SIGTERM, self.stop)\nself.heartbeat_task = asyncio.Task(self... | <|body_start_0|>
self.up_read = up_read
self.down_write = down_write
self.socks = socks
self.idx = idx
<|end_body_0|>
<|body_start_1|>
logger.debug('Starting child %s', self.idx)
self._started = True
self.loop = asyncio.new_event_loop()
asyncio.set_event_... | A child process. Each child process maintains a list of the internal :py:class:`asyncio.Server` instances it utilises. Each child also maintains a list of all connections being managed by the child. | Child | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Child:
"""A child process. Each child process maintains a list of the internal :py:class:`asyncio.Server` instances it utilises. Each child also maintains a list of all connections being managed by the child."""
def __init__(self, up_read, down_write, socks, idx):
"""Initialise a chi... | stack_v2_sparse_classes_36k_train_027466 | 5,375 | permissive | [
{
"docstring": "Initialise a child process. :param int up_read: A file descriptor for reading. :param int down_write: A file descriptor for writing. :param list socks: A list of sockets.",
"name": "__init__",
"signature": "def __init__(self, up_read, down_write, socks, idx)"
},
{
"docstring": "S... | 5 | stack_v2_sparse_classes_30k_train_008058 | Implement the Python class `Child` described below.
Class description:
A child process. Each child process maintains a list of the internal :py:class:`asyncio.Server` instances it utilises. Each child also maintains a list of all connections being managed by the child.
Method signatures and docstrings:
- def __init__... | Implement the Python class `Child` described below.
Class description:
A child process. Each child process maintains a list of the internal :py:class:`asyncio.Server` instances it utilises. Each child also maintains a list of all connections being managed by the child.
Method signatures and docstrings:
- def __init__... | 34e6b2c70fd519191daa53b7691fa7a6aa105428 | <|skeleton|>
class Child:
"""A child process. Each child process maintains a list of the internal :py:class:`asyncio.Server` instances it utilises. Each child also maintains a list of all connections being managed by the child."""
def __init__(self, up_read, down_write, socks, idx):
"""Initialise a chi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Child:
"""A child process. Each child process maintains a list of the internal :py:class:`asyncio.Server` instances it utilises. Each child also maintains a list of all connections being managed by the child."""
def __init__(self, up_read, down_write, socks, idx):
"""Initialise a child process. :... | the_stack_v2_python_sparse | blackhole/child.py | wildernesstechie/blackhole | train | 0 |
096b99a19923ac32eb08a9ce3ab32b8c964c62f4 | [
"self.path = os.path.normpath(path)\nself.name = string.replace(os.path.basename(os.path.normpath(path)), '.cfg', '')\nconfigdir = os.path.dirname(self.path)\nif not os.path.exists(configdir):\n os.makedirs(configdir)\nif not os.path.exists(self.path):\n f = open(self.path, 'w')\n f.close()\nself.update()"... | <|body_start_0|>
self.path = os.path.normpath(path)
self.name = string.replace(os.path.basename(os.path.normpath(path)), '.cfg', '')
configdir = os.path.dirname(self.path)
if not os.path.exists(configdir):
os.makedirs(configdir)
if not os.path.exists(self.path):
... | ConfigWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigWrapper:
def __init__(self, path):
"""Creates a object which parsed the file 'path' and created Config.parser"""
<|body_0|>
def update(self):
"""Reparses the file to have the latest information. Will replace current parser so save changes beforehand"""
... | stack_v2_sparse_classes_36k_train_027467 | 945 | no_license | [
{
"docstring": "Creates a object which parsed the file 'path' and created Config.parser",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Reparses the file to have the latest information. Will replace current parser so save changes beforehand",
"name": "update"... | 2 | null | Implement the Python class `ConfigWrapper` described below.
Class description:
Implement the ConfigWrapper class.
Method signatures and docstrings:
- def __init__(self, path): Creates a object which parsed the file 'path' and created Config.parser
- def update(self): Reparses the file to have the latest information. ... | Implement the Python class `ConfigWrapper` described below.
Class description:
Implement the ConfigWrapper class.
Method signatures and docstrings:
- def __init__(self, path): Creates a object which parsed the file 'path' and created Config.parser
- def update(self): Reparses the file to have the latest information. ... | 0cf22df3b59809e6fe24435f0faa9f091635c392 | <|skeleton|>
class ConfigWrapper:
def __init__(self, path):
"""Creates a object which parsed the file 'path' and created Config.parser"""
<|body_0|>
def update(self):
"""Reparses the file to have the latest information. Will replace current parser so save changes beforehand"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigWrapper:
def __init__(self, path):
"""Creates a object which parsed the file 'path' and created Config.parser"""
self.path = os.path.normpath(path)
self.name = string.replace(os.path.basename(os.path.normpath(path)), '.cfg', '')
configdir = os.path.dirname(self.path)
... | the_stack_v2_python_sparse | ManageStudy/Config/ConfigWrapper.py | steffejr/CogRes_import | train | 0 | |
cb923c7e56935ff9210d5a1a82cb5141cc5e1e26 | [
"super(focal_loss, self).__init__()\nself.size_average = size_average\nif isinstance(alpha, list):\n assert len(alpha) == num_classes\n self.alpha = torch.Tensor(alpha)\nelse:\n assert alpha < 1\n self.alpha = torch.zeros(num_classes)\n self.alpha[0] += alpha\n self.alpha[1:] += 1 - alpha\nself.ga... | <|body_start_0|>
super(focal_loss, self).__init__()
self.size_average = size_average
if isinstance(alpha, list):
assert len(alpha) == num_classes
self.alpha = torch.Tensor(alpha)
else:
assert alpha < 1
self.alpha = torch.zeros(num_classes)
... | focal_loss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class focal_loss:
def __init__(self, alpha=0.25, gamma=2, num_classes=2, size_average=False):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易... | stack_v2_sparse_classes_36k_train_027468 | 5,854 | no_license | [
{
"docstring": "focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainnet中设置为2 :param num_classes: 类别数量 :param size_average: 损失计算方式,默认取均值",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_014834 | Implement the Python class `focal_loss` described below.
Class description:
Implement the focal_loss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=2, size_average=False): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列... | Implement the Python class `focal_loss` described below.
Class description:
Implement the focal_loss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=2, size_average=False): focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列... | 1272fed2dc8fef78a9ded0f1ae1644d613a3b57b | <|skeleton|>
class focal_loss:
def __init__(self, alpha=0.25, gamma=2, num_classes=2, size_average=False):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class focal_loss:
def __init__(self, alpha=0.25, gamma=2, num_classes=2, size_average=False):
"""focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retain... | the_stack_v2_python_sparse | Text_Similarity/ERNIE_Coattention/utils.py | shawroad/NLP_pytorch_project | train | 530 | |
1ca937f5041f074785ced5911ad90d0dae4daf47 | [
"TASK_LOG.debug('Task %s: success returned with progress: %s', task_id, task_progress)\nentry_id = args[0]\nentry = InstructorTask.objects.get(pk=entry_id)\nif len(entry.subtasks) == 0:\n entry.task_output = InstructorTask.create_output_for_success(task_progress)\n entry.task_state = SUCCESS\n entry.save_n... | <|body_start_0|>
TASK_LOG.debug('Task %s: success returned with progress: %s', task_id, task_progress)
entry_id = args[0]
entry = InstructorTask.objects.get(pk=entry_id)
if len(entry.subtasks) == 0:
entry.task_output = InstructorTask.create_output_for_success(task_progress)
... | Base task class for use with InstructorTask models. Permits updating information about task in corresponding InstructorTask for monitoring purposes. Assumes that the entry_id of the InstructorTask model is the first argument to the task. The `entry_id` is the primary key for the InstructorTask entry representing the ta... | BaseInstructorTask | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseInstructorTask:
"""Base task class for use with InstructorTask models. Permits updating information about task in corresponding InstructorTask for monitoring purposes. Assumes that the entry_id of the InstructorTask model is the first argument to the task. The `entry_id` is the primary key fo... | stack_v2_sparse_classes_36k_train_027469 | 4,688 | permissive | [
{
"docstring": "Update InstructorTask object corresponding to this task with info about success. Updates task_output and task_state. But it shouldn't actually do anything if the task is only creating subtasks to actually do the work. Assumes `task_progress` is a dict containing the task's result, with the follo... | 2 | null | Implement the Python class `BaseInstructorTask` described below.
Class description:
Base task class for use with InstructorTask models. Permits updating information about task in corresponding InstructorTask for monitoring purposes. Assumes that the entry_id of the InstructorTask model is the first argument to the tas... | Implement the Python class `BaseInstructorTask` described below.
Class description:
Base task class for use with InstructorTask models. Permits updating information about task in corresponding InstructorTask for monitoring purposes. Assumes that the entry_id of the InstructorTask model is the first argument to the tas... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class BaseInstructorTask:
"""Base task class for use with InstructorTask models. Permits updating information about task in corresponding InstructorTask for monitoring purposes. Assumes that the entry_id of the InstructorTask model is the first argument to the task. The `entry_id` is the primary key fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseInstructorTask:
"""Base task class for use with InstructorTask models. Permits updating information about task in corresponding InstructorTask for monitoring purposes. Assumes that the entry_id of the InstructorTask model is the first argument to the task. The `entry_id` is the primary key for the Instruc... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/instructor_task/tasks_base.py | luque/better-ways-of-thinking-about-software | train | 3 |
e618cb325b0e55c1582a4ea84233f16ed3fd24f5 | [
"super(GANLoss, self).__init__()\nself.register_buffer('real_label', torch.tensor(target_real_label))\nself.register_buffer('fake_label', torch.tensor(target_fake_label))\nself.gan_mode = gan_mode\nif gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\nelif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLo... | <|body_start_0|>
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.gan_mode = gan_mode
if gan_mode == 'lsgan':
self.loss = nn.MSELoss()
e... | Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. | GANLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""Initialize the GANLoss class. Parameters: ga... | stack_v2_sparse_classes_36k_train_027470 | 29,830 | no_license | [
{
"docstring": "Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discrimin... | 3 | null | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=1.0, target_fake... | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=1.0, target_fake... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""Initialize the GANLoss class. Parameters: ga... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
"""Initialize the GANLoss class. Parameters: gan_mode (str) ... | the_stack_v2_python_sparse | generated/test_junleen_RainNet.py | jansel/pytorch-jit-paritybench | train | 35 |
ac6bd7d74c96158fb125a67695b9ef3d2d73ac33 | [
"dp = [0, 1, 2, 3]\nres = [0, 1, 1, 2]\nif n < 4:\n return res[n]\nres = 0\nfor i in range(4, n + 1):\n temp = 0\n for j in range(1, i // 2 + 1):\n temp = max(temp, dp[j] * dp[i - j])\n dp.append(temp)\nreturn dp[-1]",
"res = [0, 1, 1, 2]\nif n < 4:\n return res[n]\nif n % 3 == 1:\n num3 ... | <|body_start_0|>
dp = [0, 1, 2, 3]
res = [0, 1, 1, 2]
if n < 4:
return res[n]
res = 0
for i in range(4, n + 1):
temp = 0
for j in range(1, i // 2 + 1):
temp = max(temp, dp[j] * dp[i - j])
dp.append(temp)
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def cuttingRope(self, n):
"""动态规划: dp[j] 长度为j的最大积; dp[j] = max(dp[i]*dp[j-i]) i = 0, 1_最短回文串.py, ... ,j//2. 边界 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py dp[2] = 2 dp[3] = 3 res = dp[-1_最短回文串.py] 时间 O(n^2) 空间 O(n)"""
<|body_0|>
def cuttingRope(self, n):
"""贪心算法:... | stack_v2_sparse_classes_36k_train_027471 | 1,430 | no_license | [
{
"docstring": "动态规划: dp[j] 长度为j的最大积; dp[j] = max(dp[i]*dp[j-i]) i = 0, 1_最短回文串.py, ... ,j//2. 边界 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py dp[2] = 2 dp[3] = 3 res = dp[-1_最短回文串.py] 时间 O(n^2) 空间 O(n)",
"name": "cuttingRope",
"signature": "def cuttingRope(self, n)"
},
{
"docstring": "贪心算法: i = 1_最短回文... | 2 | stack_v2_sparse_classes_30k_train_008564 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def cuttingRope(self, n): 动态规划: dp[j] 长度为j的最大积; dp[j] = max(dp[i]*dp[j-i]) i = 0, 1_最短回文串.py, ... ,j//2. 边界 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py dp[2] = 2 dp[3] = 3 res = dp[-1_... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def cuttingRope(self, n): 动态规划: dp[j] 长度为j的最大积; dp[j] = max(dp[i]*dp[j-i]) i = 0, 1_最短回文串.py, ... ,j//2. 边界 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py dp[2] = 2 dp[3] = 3 res = dp[-1_... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def cuttingRope(self, n):
"""动态规划: dp[j] 长度为j的最大积; dp[j] = max(dp[i]*dp[j-i]) i = 0, 1_最短回文串.py, ... ,j//2. 边界 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py dp[2] = 2 dp[3] = 3 res = dp[-1_最短回文串.py] 时间 O(n^2) 空间 O(n)"""
<|body_0|>
def cuttingRope(self, n):
"""贪心算法:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def cuttingRope(self, n):
"""动态规划: dp[j] 长度为j的最大积; dp[j] = max(dp[i]*dp[j-i]) i = 0, 1_最短回文串.py, ... ,j//2. 边界 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py dp[2] = 2 dp[3] = 3 res = dp[-1_最短回文串.py] 时间 O(n^2) 空间 O(n)"""
dp = [0, 1, 2, 3]
res = [0, 1, 1, 2]
if n < 4:
... | the_stack_v2_python_sparse | 4_LEETCODE/7_MATH/剪绳子.py | fzingithub/SwordRefers2Offer | train | 1 | |
c38961be6a51046ba1b3467ade6742179ee25dc2 | [
"content_parser = self.get(content_type)\nif not content_parser:\n raise UnsupportedContentType(f'No parser for `{content_type}`')\nreturn content_parser(fp)",
"if isinstance(content_types, str):\n content_types = (content_types,)\nfor content_type in content_types:\n self[content_type] = parser"
] | <|body_start_0|>
content_parser = self.get(content_type)
if not content_parser:
raise UnsupportedContentType(f'No parser for `{content_type}`')
return content_parser(fp)
<|end_body_0|>
<|body_start_1|>
if isinstance(content_types, str):
content_types = (content_t... | Registry of content type parsers. | ContentTypeParserRegistry | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentTypeParserRegistry:
"""Registry of content type parsers."""
def parse_file(self, fp, content_type: str) -> Dict[str, Any]:
"""Parse a file using the specified content type. :raises: UnsupportedContentType"""
<|body_0|>
def register(self, content_types: Union[str, ... | stack_v2_sparse_classes_36k_train_027472 | 2,441 | permissive | [
{
"docstring": "Parse a file using the specified content type. :raises: UnsupportedContentType",
"name": "parse_file",
"signature": "def parse_file(self, fp, content_type: str) -> Dict[str, Any]"
},
{
"docstring": "Register a content type parser.",
"name": "register",
"signature": "def r... | 2 | stack_v2_sparse_classes_30k_train_020813 | Implement the Python class `ContentTypeParserRegistry` described below.
Class description:
Registry of content type parsers.
Method signatures and docstrings:
- def parse_file(self, fp, content_type: str) -> Dict[str, Any]: Parse a file using the specified content type. :raises: UnsupportedContentType
- def register(... | Implement the Python class `ContentTypeParserRegistry` described below.
Class description:
Registry of content type parsers.
Method signatures and docstrings:
- def parse_file(self, fp, content_type: str) -> Dict[str, Any]: Parse a file using the specified content type. :raises: UnsupportedContentType
- def register(... | 1fa2651d8b42f6e28b0c33b2b4fd287affd3a88f | <|skeleton|>
class ContentTypeParserRegistry:
"""Registry of content type parsers."""
def parse_file(self, fp, content_type: str) -> Dict[str, Any]:
"""Parse a file using the specified content type. :raises: UnsupportedContentType"""
<|body_0|>
def register(self, content_types: Union[str, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContentTypeParserRegistry:
"""Registry of content type parsers."""
def parse_file(self, fp, content_type: str) -> Dict[str, Any]:
"""Parse a file using the specified content type. :raises: UnsupportedContentType"""
content_parser = self.get(content_type)
if not content_parser:
... | the_stack_v2_python_sparse | pyapp/conf/loaders/content_types.py | gc-ss/pyapp | train | 0 |
5edf793862bb5091737a8be1284e2d91c0dde783 | [
"super(QDockRubberBand, self).__init__(parent)\nself.setWindowFlags(Qt.ToolTip | Qt.FramelessWindowHint)\nself.setAttribute(Qt.WA_TranslucentBackground)",
"painter = QPainter(self)\nopt = QStyleOption()\nopt.initFrom(self)\nself.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)"
] | <|body_start_0|>
super(QDockRubberBand, self).__init__(parent)
self.setWindowFlags(Qt.ToolTip | Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
<|end_body_0|>
<|body_start_1|>
painter = QPainter(self)
opt = QStyleOption()
opt.initFrom(self)
... | A custom rubber band widget for use with the dock overlay. This class is stylable from Qt style sheets. | QDockRubberBand | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QDockRubberBand:
"""A custom rubber band widget for use with the dock overlay. This class is stylable from Qt style sheets."""
def __init__(self, parent=None):
"""Initialize a QDockRubberBand. Parameters ---------- parent : QWidget, optional The parent of the dock rubber band."""
... | stack_v2_sparse_classes_36k_train_027473 | 18,455 | permissive | [
{
"docstring": "Initialize a QDockRubberBand. Parameters ---------- parent : QWidget, optional The parent of the dock rubber band.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Handle the paint event for the dock rubber band.",
"name": "paintEvent",
... | 2 | stack_v2_sparse_classes_30k_train_011227 | Implement the Python class `QDockRubberBand` described below.
Class description:
A custom rubber band widget for use with the dock overlay. This class is stylable from Qt style sheets.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize a QDockRubberBand. Parameters ---------- parent : QWi... | Implement the Python class `QDockRubberBand` described below.
Class description:
A custom rubber band widget for use with the dock overlay. This class is stylable from Qt style sheets.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize a QDockRubberBand. Parameters ---------- parent : QWi... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QDockRubberBand:
"""A custom rubber band widget for use with the dock overlay. This class is stylable from Qt style sheets."""
def __init__(self, parent=None):
"""Initialize a QDockRubberBand. Parameters ---------- parent : QWidget, optional The parent of the dock rubber band."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QDockRubberBand:
"""A custom rubber band widget for use with the dock overlay. This class is stylable from Qt style sheets."""
def __init__(self, parent=None):
"""Initialize a QDockRubberBand. Parameters ---------- parent : QWidget, optional The parent of the dock rubber band."""
super(QD... | the_stack_v2_python_sparse | enaml/qt/docking/dock_overlay.py | MatthieuDartiailh/enaml | train | 26 |
95f84fd12c584fdd90fb54d9f5b193c0c61bb680 | [
"try:\n custom_world = CustomWorld.objects.get(access_code=access_code)\n if custom_world_type == 'assignment' and (not Assignment.objects.filter(custom_world=custom_world).exists()):\n raise ParseError(detail='Custom World exists but not as part of an Assignment')\n elif custom_world_type == 'chall... | <|body_start_0|>
try:
custom_world = CustomWorld.objects.get(access_code=access_code)
if custom_world_type == 'assignment' and (not Assignment.objects.filter(custom_world=custom_world).exists()):
raise ParseError(detail='Custom World exists but not as part of an Assignmen... | API endpoint for handling user-specified Custom World. Requests handled: GET, PUT, DELETE | CustomWorldDetails | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomWorldDetails:
"""API endpoint for handling user-specified Custom World. Requests handled: GET, PUT, DELETE"""
def get_custom_world(self, access_code, custom_world_type=None):
"""Method to retrieve a Custom World :param access_code: access code of Custom World to retrieve :param... | stack_v2_sparse_classes_36k_train_027474 | 30,034 | no_license | [
{
"docstring": "Method to retrieve a Custom World :param access_code: access code of Custom World to retrieve :param custom_world_type: optional. Accepts the exact strings 'assignment' and 'challenge' :return: Custom World object :raise: ParseError if custom_world_type is 'assignment' but access_code points to ... | 4 | stack_v2_sparse_classes_30k_val_000662 | Implement the Python class `CustomWorldDetails` described below.
Class description:
API endpoint for handling user-specified Custom World. Requests handled: GET, PUT, DELETE
Method signatures and docstrings:
- def get_custom_world(self, access_code, custom_world_type=None): Method to retrieve a Custom World :param ac... | Implement the Python class `CustomWorldDetails` described below.
Class description:
API endpoint for handling user-specified Custom World. Requests handled: GET, PUT, DELETE
Method signatures and docstrings:
- def get_custom_world(self, access_code, custom_world_type=None): Method to retrieve a Custom World :param ac... | ea0e59de38505beba3b490a3b107f884b35986fd | <|skeleton|>
class CustomWorldDetails:
"""API endpoint for handling user-specified Custom World. Requests handled: GET, PUT, DELETE"""
def get_custom_world(self, access_code, custom_world_type=None):
"""Method to retrieve a Custom World :param access_code: access code of Custom World to retrieve :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomWorldDetails:
"""API endpoint for handling user-specified Custom World. Requests handled: GET, PUT, DELETE"""
def get_custom_world(self, access_code, custom_world_type=None):
"""Method to retrieve a Custom World :param access_code: access code of Custom World to retrieve :param custom_world... | the_stack_v2_python_sparse | main/views.py | weixingp/slay-the-software-backend | train | 0 |
f15ec4b1bd8e85c26f8bb5b0c0de15839210cfb4 | [
"cost_total = 0\nif 'specified' in redemption.keys():\n for key1, value1 in redemption['specified'].items():\n purchase[key1][0] = (purchase[key1][0] * purchase[key1][1] - value1) / purchase[key1][1]\n cost_total += value1 * purchase[key1][1]\nif 'first_in_first_out' in redemption.keys():\n for ... | <|body_start_0|>
cost_total = 0
if 'specified' in redemption.keys():
for key1, value1 in redemption['specified'].items():
purchase[key1][0] = (purchase[key1][0] * purchase[key1][1] - value1) / purchase[key1][1]
cost_total += value1 * purchase[key1][1]
... | TestBankFinancing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBankFinancing:
def test_redemption_costs(purchase, redemption):
"""计算银行理财赎回的份额对应的成本,传入参数见下面方法注释 计算银行理财日收益需要先计算成本,考虑两种赎回方式:先进先出,指定赎回 申购是对应的金额,赎回是份额,所以需要传入申购的时间和金额和对应的单位净值(数据格式为dict,key为时间,value为list,对应的金额和净值) 需要传入对应的赎回方式,优先指定赎回,然后再先进先出。指定赎回需要传入赎回的时间和赎回的份数,先进先出要传入赎回的份数"""
<|bod... | stack_v2_sparse_classes_36k_train_027475 | 5,564 | no_license | [
{
"docstring": "计算银行理财赎回的份额对应的成本,传入参数见下面方法注释 计算银行理财日收益需要先计算成本,考虑两种赎回方式:先进先出,指定赎回 申购是对应的金额,赎回是份额,所以需要传入申购的时间和金额和对应的单位净值(数据格式为dict,key为时间,value为list,对应的金额和净值) 需要传入对应的赎回方式,优先指定赎回,然后再先进先出。指定赎回需要传入赎回的时间和赎回的份数,先进先出要传入赎回的份数",
"name": "test_redemption_costs",
"signature": "def test_redemption_costs(purchase, re... | 3 | null | Implement the Python class `TestBankFinancing` described below.
Class description:
Implement the TestBankFinancing class.
Method signatures and docstrings:
- def test_redemption_costs(purchase, redemption): 计算银行理财赎回的份额对应的成本,传入参数见下面方法注释 计算银行理财日收益需要先计算成本,考虑两种赎回方式:先进先出,指定赎回 申购是对应的金额,赎回是份额,所以需要传入申购的时间和金额和对应的单位净值(数据格式为dic... | Implement the Python class `TestBankFinancing` described below.
Class description:
Implement the TestBankFinancing class.
Method signatures and docstrings:
- def test_redemption_costs(purchase, redemption): 计算银行理财赎回的份额对应的成本,传入参数见下面方法注释 计算银行理财日收益需要先计算成本,考虑两种赎回方式:先进先出,指定赎回 申购是对应的金额,赎回是份额,所以需要传入申购的时间和金额和对应的单位净值(数据格式为dic... | eae782a78ffde1276a0812a43d7deefb0bdedeb4 | <|skeleton|>
class TestBankFinancing:
def test_redemption_costs(purchase, redemption):
"""计算银行理财赎回的份额对应的成本,传入参数见下面方法注释 计算银行理财日收益需要先计算成本,考虑两种赎回方式:先进先出,指定赎回 申购是对应的金额,赎回是份额,所以需要传入申购的时间和金额和对应的单位净值(数据格式为dict,key为时间,value为list,对应的金额和净值) 需要传入对应的赎回方式,优先指定赎回,然后再先进先出。指定赎回需要传入赎回的时间和赎回的份数,先进先出要传入赎回的份数"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBankFinancing:
def test_redemption_costs(purchase, redemption):
"""计算银行理财赎回的份额对应的成本,传入参数见下面方法注释 计算银行理财日收益需要先计算成本,考虑两种赎回方式:先进先出,指定赎回 申购是对应的金额,赎回是份额,所以需要传入申购的时间和金额和对应的单位净值(数据格式为dict,key为时间,value为list,对应的金额和净值) 需要传入对应的赎回方式,优先指定赎回,然后再先进先出。指定赎回需要传入赎回的时间和赎回的份数,先进先出要传入赎回的份数"""
cost_total = 0
... | the_stack_v2_python_sparse | test_case/custom_system/monarch_futures/test_bank_financing.py | liufubin-git/python | train | 0 | |
95cf464069ed778b512f13bd687183449b7b1609 | [
"with Environment.manage():\n proc_obj = self.pool.get('procurement.order')\n new_cr = self.pool.cursor()\n user_obj = self.pool.get('res.users')\n company_id = user_obj.browse(new_cr, uid, uid, context=context).company_id.id\n proc_obj._procure_orderpoint_confirm(new_cr, uid, use_new_cursor=new_cr.d... | <|body_start_0|>
with Environment.manage():
proc_obj = self.pool.get('procurement.order')
new_cr = self.pool.cursor()
user_obj = self.pool.get('res.users')
company_id = user_obj.browse(new_cr, uid, uid, context=context).company_id.id
proc_obj._procure_... | procurement_compute | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class procurement_compute:
def _procure_calculation_orderpoint(self, cr, uid, ids, context=None):
"""@param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary"""
<|... | stack_v2_sparse_classes_36k_train_027476 | 1,906 | no_license | [
{
"docstring": "@param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary",
"name": "_procure_calculation_orderpoint",
"signature": "def _procure_calculation_orderpoint(self, cr, uid... | 2 | null | Implement the Python class `procurement_compute` described below.
Class description:
Implement the procurement_compute class.
Method signatures and docstrings:
- def _procure_calculation_orderpoint(self, cr, uid, ids, context=None): @param self: The object pointer. @param cr: A database cursor @param uid: ID of the u... | Implement the Python class `procurement_compute` described below.
Class description:
Implement the procurement_compute class.
Method signatures and docstrings:
- def _procure_calculation_orderpoint(self, cr, uid, ids, context=None): @param self: The object pointer. @param cr: A database cursor @param uid: ID of the u... | 5a4fd72991c846d5cb7c5082f6bdfef5b2bca572 | <|skeleton|>
class procurement_compute:
def _procure_calculation_orderpoint(self, cr, uid, ids, context=None):
"""@param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class procurement_compute:
def _procure_calculation_orderpoint(self, cr, uid, ids, context=None):
"""@param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary"""
with Environment... | the_stack_v2_python_sparse | yuancloud/addons/stock/wizard/orderpoint_procurement.py | cash2one/yuancloud | train | 0 | |
e785ead71f85338077f7f5b738d54dcb89fb86a1 | [
"model = AttentiveFP(n_tasks=n_tasks, num_layers=num_layers, num_timesteps=num_timesteps, graph_feat_size=graph_feat_size, dropout=dropout, mode=mode, number_atom_features=number_atom_features, number_bond_features=number_bond_features, n_classes=n_classes)\nif mode == 'regression':\n loss: Loss = L2Loss()\n ... | <|body_start_0|>
model = AttentiveFP(n_tasks=n_tasks, num_layers=num_layers, num_timesteps=num_timesteps, graph_feat_size=graph_feat_size, dropout=dropout, mode=mode, number_atom_features=number_atom_features, number_bond_features=number_bond_features, n_classes=n_classes)
if mode == 'regression':
... | Model for Graph Property Prediction. This model proceeds as follows: * Combine node features and edge features for initializing node representations, which involves a round of message passing * Update node representations with multiple rounds of message passing * For each graph, compute its representation by combining ... | AttentiveFPModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentiveFPModel:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine node features and edge features for initializing node representations, which involves a round of message passing * Update node representations with multiple rounds of message passing * For each gra... | stack_v2_sparse_classes_36k_train_027477 | 12,226 | permissive | [
{
"docstring": "Parameters ---------- n_tasks: int Number of tasks. num_layers: int Number of graph neural network layers, i.e. number of rounds of message passing. Default to 2. num_timesteps: int Number of time steps for updating graph representations with a GRU. Default to 2. graph_feat_size: int Size for gr... | 2 | null | Implement the Python class `AttentiveFPModel` described below.
Class description:
Model for Graph Property Prediction. This model proceeds as follows: * Combine node features and edge features for initializing node representations, which involves a round of message passing * Update node representations with multiple r... | Implement the Python class `AttentiveFPModel` described below.
Class description:
Model for Graph Property Prediction. This model proceeds as follows: * Combine node features and edge features for initializing node representations, which involves a round of message passing * Update node representations with multiple r... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class AttentiveFPModel:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine node features and edge features for initializing node representations, which involves a round of message passing * Update node representations with multiple rounds of message passing * For each gra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentiveFPModel:
"""Model for Graph Property Prediction. This model proceeds as follows: * Combine node features and edge features for initializing node representations, which involves a round of message passing * Update node representations with multiple rounds of message passing * For each graph, compute i... | the_stack_v2_python_sparse | deepchem/models/torch_models/attentivefp.py | deepchem/deepchem | train | 4,876 |
35eb14f18f7d14b130427e4c9492aa8f7a77a4b4 | [
"if lmax < abs(m):\n raise ValueError('lmax must be >= |m|')\nl = np.arange(abs(m), lmax + 1)\nsuper().__init__(self._ftheta, nf=len(l), nx=1, maxderiv=None, zlevel=None)\nself.l = l\nself.m = m\nreturn",
"nd, nvar = dfun.ndnvar(deriv, var, self.nx)\nif out is None:\n base_shape = X.shape[1:]\n out = np.... | <|body_start_0|>
if lmax < abs(m):
raise ValueError('lmax must be >= |m|')
l = np.arange(abs(m), lmax + 1)
super().__init__(self._ftheta, nf=len(l), nx=1, maxderiv=None, zlevel=None)
self.l = l
self.m = m
return
<|end_body_0|>
<|body_start_1|>
nd, nva... | Associated Legendre polynomials of a given order, :math:`m`, with :math:`\\cos \\theta` argument for :math:`\\theta \\in [0,\\pi]`. .. math:: F_\\ell^m(\\theta) = N^m_l P_l^{|m|}(\\cos \\theta), with :math:`m = 0, 1, 2, \\ldots` and :math:`\\ell = |m|, |m|+1, \\ldots, \\ell_\\text{max}`. (Negative :math:`m` is defined,... | LegendreLMCos | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegendreLMCos:
"""Associated Legendre polynomials of a given order, :math:`m`, with :math:`\\cos \\theta` argument for :math:`\\theta \\in [0,\\pi]`. .. math:: F_\\ell^m(\\theta) = N^m_l P_l^{|m|}(\\cos \\theta), with :math:`m = 0, 1, 2, \\ldots` and :math:`\\ell = |m|, |m|+1, \\ldots, \\ell_\\te... | stack_v2_sparse_classes_36k_train_027478 | 39,055 | permissive | [
{
"docstring": "Create associated Legendre basis DFuns Parameters ---------- m : int The Legendre order. lmax : int The maximum value of :math:`\\\\ell`. This must be greater than or equal to :math:`|m|`.",
"name": "__init__",
"signature": "def __init__(self, m, lmax)"
},
{
"docstring": "basis e... | 2 | stack_v2_sparse_classes_30k_train_020003 | Implement the Python class `LegendreLMCos` described below.
Class description:
Associated Legendre polynomials of a given order, :math:`m`, with :math:`\\cos \\theta` argument for :math:`\\theta \\in [0,\\pi]`. .. math:: F_\\ell^m(\\theta) = N^m_l P_l^{|m|}(\\cos \\theta), with :math:`m = 0, 1, 2, \\ldots` and :math:`... | Implement the Python class `LegendreLMCos` described below.
Class description:
Associated Legendre polynomials of a given order, :math:`m`, with :math:`\\cos \\theta` argument for :math:`\\theta \\in [0,\\pi]`. .. math:: F_\\ell^m(\\theta) = N^m_l P_l^{|m|}(\\cos \\theta), with :math:`m = 0, 1, 2, \\ldots` and :math:`... | c6341a58331deef3728cc43c627c556139deb673 | <|skeleton|>
class LegendreLMCos:
"""Associated Legendre polynomials of a given order, :math:`m`, with :math:`\\cos \\theta` argument for :math:`\\theta \\in [0,\\pi]`. .. math:: F_\\ell^m(\\theta) = N^m_l P_l^{|m|}(\\cos \\theta), with :math:`m = 0, 1, 2, \\ldots` and :math:`\\ell = |m|, |m|+1, \\ldots, \\ell_\\te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LegendreLMCos:
"""Associated Legendre polynomials of a given order, :math:`m`, with :math:`\\cos \\theta` argument for :math:`\\theta \\in [0,\\pi]`. .. math:: F_\\ell^m(\\theta) = N^m_l P_l^{|m|}(\\cos \\theta), with :math:`m = 0, 1, 2, \\ldots` and :math:`\\ell = |m|, |m|+1, \\ldots, \\ell_\\text{max}`. (Ne... | the_stack_v2_python_sparse | nitrogen/special.py | bchangala/nitrogen | train | 11 |
99b091d65dfbf5f1bd5d7e25602896ee5ce9b6fe | [
"self._output_size = output_size\nself._aug_rand_hflip = aug_rand_hflip\nself._num_classes = num_classes\nif dtype == 'float32':\n self._dtype = tf.float32\nelif dtype == 'float16':\n self._dtype = tf.float16\nelif dtype == 'bfloat16':\n self._dtype = tf.bfloat16\nelse:\n raise ValueError('dtype {!r} is... | <|body_start_0|>
self._output_size = output_size
self._aug_rand_hflip = aug_rand_hflip
self._num_classes = num_classes
if dtype == 'float32':
self._dtype = tf.float32
elif dtype == 'float16':
self._dtype = tf.float16
elif dtype == 'bfloat16':
... | Parser to parse an image and its annotations into a dictionary of tensors. | Parser | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser to parse an image and its annotations into a dictionary of tensors."""
def __init__(self, output_size: List[int], num_classes: float, aug_rand_hflip: bool=True, aug_policy: Optional[str]=None, dtype: str='float32'):
"""Initializes parameters for parsing annotations ... | stack_v2_sparse_classes_36k_train_027479 | 5,452 | permissive | [
{
"docstring": "Initializes parameters for parsing annotations in the dataset. Args: output_size: `Tensor` or `list` for [height, width] of output image. The output_size should be divided by the largest feature stride 2^max_level. num_classes: `float`, number of classes. aug_rand_hflip: `bool`, if True, augment... | 3 | null | Implement the Python class `Parser` described below.
Class description:
Parser to parse an image and its annotations into a dictionary of tensors.
Method signatures and docstrings:
- def __init__(self, output_size: List[int], num_classes: float, aug_rand_hflip: bool=True, aug_policy: Optional[str]=None, dtype: str='f... | Implement the Python class `Parser` described below.
Class description:
Parser to parse an image and its annotations into a dictionary of tensors.
Method signatures and docstrings:
- def __init__(self, output_size: List[int], num_classes: float, aug_rand_hflip: bool=True, aug_policy: Optional[str]=None, dtype: str='f... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class Parser:
"""Parser to parse an image and its annotations into a dictionary of tensors."""
def __init__(self, output_size: List[int], num_classes: float, aug_rand_hflip: bool=True, aug_policy: Optional[str]=None, dtype: str='float32'):
"""Initializes parameters for parsing annotations ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser to parse an image and its annotations into a dictionary of tensors."""
def __init__(self, output_size: List[int], num_classes: float, aug_rand_hflip: bool=True, aug_policy: Optional[str]=None, dtype: str='float32'):
"""Initializes parameters for parsing annotations in the datase... | the_stack_v2_python_sparse | models/official/vision/beta/dataloaders/classification_input.py | aboerzel/German_License_Plate_Recognition | train | 34 |
b2e0fe2f6f67ebeabd8733a92d188cd605929882 | [
"parser = ParlaiParser(True, True, 'Generate Dense Embs')\nparser.add_argument('--passages-file', type=str, help='file containing passages to encode. file should be a tsv file.')\nparser.add_argument('--outfile', type=str, help='where to save the passage embeddings')\nparser.add_argument('--num-shards', type=int, d... | <|body_start_0|>
parser = ParlaiParser(True, True, 'Generate Dense Embs')
parser.add_argument('--passages-file', type=str, help='file containing passages to encode. file should be a tsv file.')
parser.add_argument('--outfile', type=str, help='where to save the passage embeddings')
parser... | Generate Dense Embeddings. | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Generate Dense Embeddings."""
def setup_args(cls):
"""File in/out args, and sharding args."""
<|body_0|>
def run(self):
"""1) load model 2) generate embeddings 3) save embeddings."""
<|body_1|>
def encode_passages(self, agent: TorchRank... | stack_v2_sparse_classes_36k_train_027480 | 7,678 | permissive | [
{
"docstring": "File in/out args, and sharding args.",
"name": "setup_args",
"signature": "def setup_args(cls)"
},
{
"docstring": "1) load model 2) generate embeddings 3) save embeddings.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Encode passages with model,... | 5 | stack_v2_sparse_classes_30k_train_014154 | Implement the Python class `Generator` described below.
Class description:
Generate Dense Embeddings.
Method signatures and docstrings:
- def setup_args(cls): File in/out args, and sharding args.
- def run(self): 1) load model 2) generate embeddings 3) save embeddings.
- def encode_passages(self, agent: TorchRankerAg... | Implement the Python class `Generator` described below.
Class description:
Generate Dense Embeddings.
Method signatures and docstrings:
- def setup_args(cls): File in/out args, and sharding args.
- def run(self): 1) load model 2) generate embeddings 3) save embeddings.
- def encode_passages(self, agent: TorchRankerAg... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class Generator:
"""Generate Dense Embeddings."""
def setup_args(cls):
"""File in/out args, and sharding args."""
<|body_0|>
def run(self):
"""1) load model 2) generate embeddings 3) save embeddings."""
<|body_1|>
def encode_passages(self, agent: TorchRank... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Generate Dense Embeddings."""
def setup_args(cls):
"""File in/out args, and sharding args."""
parser = ParlaiParser(True, True, 'Generate Dense Embs')
parser.add_argument('--passages-file', type=str, help='file containing passages to encode. file should be a tsv file... | the_stack_v2_python_sparse | parlai/agents/rag/scripts/generate_dense_embeddings.py | facebookresearch/ParlAI | train | 10,943 |
1d386009bb49de6400c3db7928f2956695c770d6 | [
"self._tiles = getTilingCatalogue(tilingCatalogue=tilingCatalogue)\nmockFields = []\nfor tile in self._tiles:\n mockField = Field.createMockPlate(ra=tile['RA'], dec=tile['DEC'], silent=True, **kwargs)\n mockField.manga_tileid = int(tile['ID'])\n mockFields.append(mockField)\nlist.__init__(self, mockFields)... | <|body_start_0|>
self._tiles = getTilingCatalogue(tilingCatalogue=tilingCatalogue)
mockFields = []
for tile in self._tiles:
mockField = Field.createMockPlate(ra=tile['RA'], dec=tile['DEC'], silent=True, **kwargs)
mockField.manga_tileid = int(tile['ID'])
mockFi... | Fields | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fields:
def __init__(self, tilingCatalogue=None, rejectDrilled=True, silent=False, **kwargs):
"""Returns a list of `Totoro.Field` instances. Reads a tiling catalogue and returns a list of `Totoro.Field` objects, one for each tile. If `rejectDrilled=True`, tiles that have already been dri... | stack_v2_sparse_classes_36k_train_027481 | 5,700 | permissive | [
{
"docstring": "Returns a list of `Totoro.Field` instances. Reads a tiling catalogue and returns a list of `Totoro.Field` objects, one for each tile. If `rejectDrilled=True`, tiles that have already been drilled are skipped. Parameters ---------- tilingCatalogue : str or None The path to the tiling catalogue to... | 3 | stack_v2_sparse_classes_30k_train_009157 | Implement the Python class `Fields` described below.
Class description:
Implement the Fields class.
Method signatures and docstrings:
- def __init__(self, tilingCatalogue=None, rejectDrilled=True, silent=False, **kwargs): Returns a list of `Totoro.Field` instances. Reads a tiling catalogue and returns a list of `Toto... | Implement the Python class `Fields` described below.
Class description:
Implement the Fields class.
Method signatures and docstrings:
- def __init__(self, tilingCatalogue=None, rejectDrilled=True, silent=False, **kwargs): Returns a list of `Totoro.Field` instances. Reads a tiling catalogue and returns a list of `Toto... | 74befd99bda47ebb8c03a276b57371b5788e154a | <|skeleton|>
class Fields:
def __init__(self, tilingCatalogue=None, rejectDrilled=True, silent=False, **kwargs):
"""Returns a list of `Totoro.Field` instances. Reads a tiling catalogue and returns a list of `Totoro.Field` objects, one for each tile. If `rejectDrilled=True`, tiles that have already been dri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fields:
def __init__(self, tilingCatalogue=None, rejectDrilled=True, silent=False, **kwargs):
"""Returns a list of `Totoro.Field` instances. Reads a tiling catalogue and returns a list of `Totoro.Field` objects, one for each tile. If `rejectDrilled=True`, tiles that have already been drilled are skipp... | the_stack_v2_python_sparse | Totoro/dbclasses/field.py | sdss/Totoro | train | 2 | |
c33b461c736e3fef11a1144b442e366c2d373fca | [
"for line in self:\n model_from_field_id = False\n field = line.field_id\n if field and field.ttype in ['many2one', 'one2many', 'many2many']:\n model_from_field_id = self.env['ir.model'].search([('model', '=', field.relation)], limit=1)\n line.model_from_field_id = model_from_field_id",
"for li... | <|body_start_0|>
for line in self:
model_from_field_id = False
field = line.field_id
if field and field.ttype in ['many2one', 'one2many', 'many2many']:
model_from_field_id = self.env['ir.model'].search([('model', '=', field.relation)], limit=1)
lin... | field_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class field_line:
def _compute_model_from_field_id(self):
"""Compute method for model_from_field_id Attrs update: * model_from_field_id - as model of linked field if exist"""
<|body_0|>
def onchange_field_id(self):
"""Onchange method for field_id and related_field The goal... | stack_v2_sparse_classes_36k_train_027482 | 2,343 | no_license | [
{
"docstring": "Compute method for model_from_field_id Attrs update: * model_from_field_id - as model of linked field if exist",
"name": "_compute_model_from_field_id",
"signature": "def _compute_model_from_field_id(self)"
},
{
"docstring": "Onchange method for field_id and related_field The goa... | 2 | stack_v2_sparse_classes_30k_train_018234 | Implement the Python class `field_line` described below.
Class description:
Implement the field_line class.
Method signatures and docstrings:
- def _compute_model_from_field_id(self): Compute method for model_from_field_id Attrs update: * model_from_field_id - as model of linked field if exist
- def onchange_field_id... | Implement the Python class `field_line` described below.
Class description:
Implement the field_line class.
Method signatures and docstrings:
- def _compute_model_from_field_id(self): Compute method for model_from_field_id Attrs update: * model_from_field_id - as model of linked field if exist
- def onchange_field_id... | 5ebad7ede4690e1bb9e2c1063abf677e675631b4 | <|skeleton|>
class field_line:
def _compute_model_from_field_id(self):
"""Compute method for model_from_field_id Attrs update: * model_from_field_id - as model of linked field if exist"""
<|body_0|>
def onchange_field_id(self):
"""Onchange method for field_id and related_field The goal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class field_line:
def _compute_model_from_field_id(self):
"""Compute method for model_from_field_id Attrs update: * model_from_field_id - as model of linked field if exist"""
for line in self:
model_from_field_id = False
field = line.field_id
if field and field.tt... | the_stack_v2_python_sparse | sea_reminder_schedule/models/field_line.py | viethoang66666/seatek_viet | train | 0 | |
1dc25f3e8bd1e2a153e5e3147c1941088acffc95 | [
"info = OrderedDict({})\ntry:\n info_editors = OrderedDict({})\n for instance in obj.editors.all():\n info_editors[instance.pk] = instance.pen_name\n info['editors'] = info_editors\nexcept Editor.DoesNotExist as e:\n info['editors'] = str(e)\ntry:\n info['domain'] = domain.DOMAIN_DICT[obj.doma... | <|body_start_0|>
info = OrderedDict({})
try:
info_editors = OrderedDict({})
for instance in obj.editors.all():
info_editors[instance.pk] = instance.pen_name
info['editors'] = info_editors
except Editor.DoesNotExist as e:
info['edito... | Problem Base Serializer | ProblemBaseSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProblemBaseSerializer:
"""Problem Base Serializer"""
def get_info_data(self, obj, *args, **kwargs):
"""Get Information Data :param obj: :param args: :param kwargs: :return:"""
<|body_0|>
def get_links_url(self, obj, *args, **kwargs):
"""Get links url :param obj: ... | stack_v2_sparse_classes_36k_train_027483 | 6,316 | no_license | [
{
"docstring": "Get Information Data :param obj: :param args: :param kwargs: :return:",
"name": "get_info_data",
"signature": "def get_info_data(self, obj, *args, **kwargs)"
},
{
"docstring": "Get links url :param obj: :param args: :param kwargs: :return:",
"name": "get_links_url",
"sign... | 2 | stack_v2_sparse_classes_30k_test_000865 | Implement the Python class `ProblemBaseSerializer` described below.
Class description:
Problem Base Serializer
Method signatures and docstrings:
- def get_info_data(self, obj, *args, **kwargs): Get Information Data :param obj: :param args: :param kwargs: :return:
- def get_links_url(self, obj, *args, **kwargs): Get l... | Implement the Python class `ProblemBaseSerializer` described below.
Class description:
Problem Base Serializer
Method signatures and docstrings:
- def get_info_data(self, obj, *args, **kwargs): Get Information Data :param obj: :param args: :param kwargs: :return:
- def get_links_url(self, obj, *args, **kwargs): Get l... | acd31a2f43d7ea83fc9bb34627f5dca94763eade | <|skeleton|>
class ProblemBaseSerializer:
"""Problem Base Serializer"""
def get_info_data(self, obj, *args, **kwargs):
"""Get Information Data :param obj: :param args: :param kwargs: :return:"""
<|body_0|>
def get_links_url(self, obj, *args, **kwargs):
"""Get links url :param obj: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProblemBaseSerializer:
"""Problem Base Serializer"""
def get_info_data(self, obj, *args, **kwargs):
"""Get Information Data :param obj: :param args: :param kwargs: :return:"""
info = OrderedDict({})
try:
info_editors = OrderedDict({})
for instance in obj.ed... | the_stack_v2_python_sparse | problem/serializers.py | JoenyBui/mywaterbuffalo | train | 0 |
52cb1acf84d978477972c8683b4fb112d77c9568 | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'], carType=send_data['carType'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMsg'])",
"re = Information(userLogin).getPresentCar(send_data['parkName'], send_data['carNum'])\nresult = re[0]\nAssertions().... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'], carType=send_data['carType'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMsg'])
<|end_body_0|>
<|body_start_1|>
re = Information(userLogin).getPresentCar(send... | 黄牌车宽进,需缴费宽出(岗亭收费处收费放行) | TestYellowCarWideInOut | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestYellowCarWideInOut:
"""黄牌车宽进,需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCarType(self, userLogin, send_data, expect):
"""查看在场车辆"""
<|body_1|>
def test_mockCarOut(self, send_d... | stack_v2_sparse_classes_36k_train_027484 | 2,376 | no_license | [
{
"docstring": "模拟进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, sentryLogin, send_data, expect)"
},
{
"docstring": "查看在场车辆",
"name": "test_presentCarType",
"signature": "def test_presentCarType(self, userLogin, send_data, expect)"
},
{
"docstring": "模拟离场",... | 5 | stack_v2_sparse_classes_30k_train_004576 | Implement the Python class `TestYellowCarWideInOut` described below.
Class description:
黄牌车宽进,需缴费宽出(岗亭收费处收费放行)
Method signatures and docstrings:
- def test_mockCarIn(self, sentryLogin, send_data, expect): 模拟进场
- def test_presentCarType(self, userLogin, send_data, expect): 查看在场车辆
- def test_mockCarOut(self, send_data,... | Implement the Python class `TestYellowCarWideInOut` described below.
Class description:
黄牌车宽进,需缴费宽出(岗亭收费处收费放行)
Method signatures and docstrings:
- def test_mockCarIn(self, sentryLogin, send_data, expect): 模拟进场
- def test_presentCarType(self, userLogin, send_data, expect): 查看在场车辆
- def test_mockCarOut(self, send_data,... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestYellowCarWideInOut:
"""黄牌车宽进,需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCarType(self, userLogin, send_data, expect):
"""查看在场车辆"""
<|body_1|>
def test_mockCarOut(self, send_d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestYellowCarWideInOut:
"""黄牌车宽进,需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'], carType=send_data['carType'])
result = re
Assertions().assert... | the_stack_v2_python_sparse | test_suite/sentryDutyRoom/carInOutHandle/test_yellowCarWideInOut.py | oyebino/pomp_api | train | 1 |
96960f49e08b49b8281452e5fe72128ae4bf2a7f | [
"self.count = count\nself.strict = strict\nsuper(MultiFileField, self).__init__(*args, **kwargs)",
"if isinstance(widget, MultiFileInput):\n return {'count': self.count}\nreturn {}",
"super(MultiFileField, self).clean(data)\nif not self.required and data in EMPTY_VALUES:\n return None\ntry:\n f = data\... | <|body_start_0|>
self.count = count
self.strict = strict
super(MultiFileField, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if isinstance(widget, MultiFileInput):
return {'count': self.count}
return {}
<|end_body_1|>
<|body_start_2|>
super... | A field allowing users to upload multiple files at once. | MultiFileField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiFileField:
"""A field allowing users to upload multiple files at once."""
def __init__(self, count=1, strict=False, *args, **kwargs):
"""strict is whether the number of files uploaded must equal count"""
<|body_0|>
def widget_attrs(self, widget):
"""Adds the... | stack_v2_sparse_classes_36k_train_027485 | 6,914 | no_license | [
{
"docstring": "strict is whether the number of files uploaded must equal count",
"name": "__init__",
"signature": "def __init__(self, count=1, strict=False, *args, **kwargs)"
},
{
"docstring": "Adds the count to the MultiFileInput widget.",
"name": "widget_attrs",
"signature": "def widg... | 3 | null | Implement the Python class `MultiFileField` described below.
Class description:
A field allowing users to upload multiple files at once.
Method signatures and docstrings:
- def __init__(self, count=1, strict=False, *args, **kwargs): strict is whether the number of files uploaded must equal count
- def widget_attrs(se... | Implement the Python class `MultiFileField` described below.
Class description:
A field allowing users to upload multiple files at once.
Method signatures and docstrings:
- def __init__(self, count=1, strict=False, *args, **kwargs): strict is whether the number of files uploaded must equal count
- def widget_attrs(se... | 612f215ac032e14669b3e8f75bc13ac0d4eda9dc | <|skeleton|>
class MultiFileField:
"""A field allowing users to upload multiple files at once."""
def __init__(self, count=1, strict=False, *args, **kwargs):
"""strict is whether the number of files uploaded must equal count"""
<|body_0|>
def widget_attrs(self, widget):
"""Adds the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiFileField:
"""A field allowing users to upload multiple files at once."""
def __init__(self, count=1, strict=False, *args, **kwargs):
"""strict is whether the number of files uploaded must equal count"""
self.count = count
self.strict = strict
super(MultiFileField, se... | the_stack_v2_python_sparse | tags/epic/sprint3_2010-04-08/core/util/multifile.py | project-renard-survey/nwb | train | 0 |
ee6685a11c7ef3cbc8d92107bed289b3c836c42a | [
"i = inspection.inspect(user.__class__)\nGroup = i.relationships['groups'].mapper.entity\nif dbsession.query(Group).count() > 0:\n return\ng = Group(name=Group.DEFAULT_ADMIN_GROUP_NAME)\ndbsession.add(g)\ng.users.append(user)",
"assert user.id, 'Please flush your db'\ni = inspection.inspect(user.__class__)\nGr... | <|body_start_0|>
i = inspection.inspect(user.__class__)
Group = i.relationships['groups'].mapper.entity
if dbsession.query(Group).count() > 0:
return
g = Group(name=Group.DEFAULT_ADMIN_GROUP_NAME)
dbsession.add(g)
g.users.append(user)
<|end_body_0|>
<|body_st... | Component responsible for setting up an empty site on first login. The site creator is run by the activation of the first user. This either happens¨ * When the activation email is sent to the first user * When the first user logs through social media account | SiteCreator | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteCreator:
"""Component responsible for setting up an empty site on first login. The site creator is run by the activation of the first user. This either happens¨ * When the activation email is sent to the first user * When the first user logs through social media account"""
def init_empty... | stack_v2_sparse_classes_36k_train_027486 | 10,474 | permissive | [
{
"docstring": "When the first user signs up build the admin groups and make the user member of it. Make the first member of the site to be admin and superuser.",
"name": "init_empty_site",
"signature": "def init_empty_site(self, dbsession: Session, user: UserMixin)"
},
{
"docstring": "Call afte... | 2 | null | Implement the Python class `SiteCreator` described below.
Class description:
Component responsible for setting up an empty site on first login. The site creator is run by the activation of the first user. This either happens¨ * When the activation email is sent to the first user * When the first user logs through soci... | Implement the Python class `SiteCreator` described below.
Class description:
Component responsible for setting up an empty site on first login. The site creator is run by the activation of the first user. This either happens¨ * When the activation email is sent to the first user * When the first user logs through soci... | a57de54fb8a3fae859f24f373f0292e1e4b3c344 | <|skeleton|>
class SiteCreator:
"""Component responsible for setting up an empty site on first login. The site creator is run by the activation of the first user. This either happens¨ * When the activation email is sent to the first user * When the first user logs through social media account"""
def init_empty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SiteCreator:
"""Component responsible for setting up an empty site on first login. The site creator is run by the activation of the first user. This either happens¨ * When the activation email is sent to the first user * When the first user logs through social media account"""
def init_empty_site(self, d... | the_stack_v2_python_sparse | websauna/system/user/usermixin.py | websauna/websauna | train | 294 |
d31168d655411ee11106f3a933d1d7db153c4904 | [
"self.__db_path = db_path\nif os.path.isfile(self.__db_path):\n self.__read_db()\nelse:\n self.__fibonacci = [0, 1]\nself.__initial_fibonaccis_number = len(self.__fibonacci)",
"db_file = open(self.__db_path, 'r')\nself.__fibonacci = [int(line) for line in db_file.readlines()]\ndb_file.close()",
"db_file =... | <|body_start_0|>
self.__db_path = db_path
if os.path.isfile(self.__db_path):
self.__read_db()
else:
self.__fibonacci = [0, 1]
self.__initial_fibonaccis_number = len(self.__fibonacci)
<|end_body_0|>
<|body_start_1|>
db_file = open(self.__db_path, 'r')
... | Has single method generate(nth) that returns nth fibonacci num | FibonacciNumber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FibonacciNumber:
"""Has single method generate(nth) that returns nth fibonacci num"""
def __init__(self, db_path='fibonaccis.txt'):
"""Initializing array of pre-defined Fibonacci numbers and predefined path where file with those numbers is stored"""
<|body_0|>
def __read... | stack_v2_sparse_classes_36k_train_027487 | 16,748 | no_license | [
{
"docstring": "Initializing array of pre-defined Fibonacci numbers and predefined path where file with those numbers is stored",
"name": "__init__",
"signature": "def __init__(self, db_path='fibonaccis.txt')"
},
{
"docstring": "Reads Fibonaccis from DB file",
"name": "__read_db",
"signa... | 5 | stack_v2_sparse_classes_30k_val_001197 | Implement the Python class `FibonacciNumber` described below.
Class description:
Has single method generate(nth) that returns nth fibonacci num
Method signatures and docstrings:
- def __init__(self, db_path='fibonaccis.txt'): Initializing array of pre-defined Fibonacci numbers and predefined path where file with thos... | Implement the Python class `FibonacciNumber` described below.
Class description:
Has single method generate(nth) that returns nth fibonacci num
Method signatures and docstrings:
- def __init__(self, db_path='fibonaccis.txt'): Initializing array of pre-defined Fibonacci numbers and predefined path where file with thos... | 5a94ff283e6340dfd7f6ded4b7f45ba9f513e14c | <|skeleton|>
class FibonacciNumber:
"""Has single method generate(nth) that returns nth fibonacci num"""
def __init__(self, db_path='fibonaccis.txt'):
"""Initializing array of pre-defined Fibonacci numbers and predefined path where file with those numbers is stored"""
<|body_0|>
def __read... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FibonacciNumber:
"""Has single method generate(nth) that returns nth fibonacci num"""
def __init__(self, db_path='fibonaccis.txt'):
"""Initializing array of pre-defined Fibonacci numbers and predefined path where file with those numbers is stored"""
self.__db_path = db_path
if os.... | the_stack_v2_python_sparse | basics/fibonacci_oop.py | Baitala/Python | train | 1 |
1b90bf16b9ec49b8766d9150db91b8706610a94f | [
"if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.ValidationError(_('The email address provided is already registered. Please use a different email address/login now.'))\nreturn self.cleaned_data['email']",
"if User.objects.filter(email__iexact=self.cleaned_data['username']):\n ... | <|body_start_0|>
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_('The email address provided is already registered. Please use a different email address/login now.'))
return self.cleaned_data['email']
<|end_body_0|>
<|body_start_1|>
if... | Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user... | RegistrationForm | [
"BSD-2-Clause-Views",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m... | stack_v2_sparse_classes_36k_train_027488 | 11,099 | permissive | [
{
"docstring": "Validate that the supplied email address is unique for the site.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Validate that the supplied username is unique for the site.",
"name": "clean_username",
"signature": "def clean_username(self)... | 3 | null | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b... | 75a09bc5d0a2ec0ae994ac900a93dc027b527860 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the ... | the_stack_v2_python_sparse | Web_Server/webapps/accounts/forms.py | bemoss/BEMOSS3.5 | train | 81 |
dee69ac75f23bc07b74bc85aa6a3723f14b04ded | [
"map = {}\nfor i in range(26):\n map[order[i]] = chr(97 + i)\nprint(map)\nfor i in range(len(words)):\n newW = ''\n for c in words[i]:\n newW += map[c]\n words[i] = newW\nif words == sorted(words):\n return True\nreturn False",
"A.sort()\nneg = []\npos = []\nfor i in range(len(A)):\n if A... | <|body_start_0|>
map = {}
for i in range(26):
map[order[i]] = chr(97 + i)
print(map)
for i in range(len(words)):
newW = ''
for c in words[i]:
newW += map[c]
words[i] = newW
if words == sorted(words):
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool"""
<|body_0|>
def canReorderDoubled(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def minDeletionSize(self, A):
""":type A: List... | stack_v2_sparse_classes_36k_train_027489 | 3,442 | no_license | [
{
"docstring": ":type words: List[str] :type order: str :rtype: bool",
"name": "isAlienSorted",
"signature": "def isAlienSorted(self, words, order)"
},
{
"docstring": ":type A: List[int] :rtype: bool",
"name": "canReorderDoubled",
"signature": "def canReorderDoubled(self, A)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_002939 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAlienSorted(self, words, order): :type words: List[str] :type order: str :rtype: bool
- def canReorderDoubled(self, A): :type A: List[int] :rtype: bool
- def minDeletionSiz... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAlienSorted(self, words, order): :type words: List[str] :type order: str :rtype: bool
- def canReorderDoubled(self, A): :type A: List[int] :rtype: bool
- def minDeletionSiz... | e43776978a1d0f00e79ba965ca6b77263d907b4d | <|skeleton|>
class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool"""
<|body_0|>
def canReorderDoubled(self, A):
""":type A: List[int] :rtype: bool"""
<|body_1|>
def minDeletionSize(self, A):
""":type A: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool"""
map = {}
for i in range(26):
map[order[i]] = chr(97 + i)
print(map)
for i in range(len(words)):
newW = ''
for c in words[i]:
... | the_stack_v2_python_sparse | Contest114.py | unlimitediw/LCContest | train | 0 | |
2352f1cbefac384a41208cf7efbce5751aaf459a | [
"args = self.args\nif args and (not args[0] in [\"'\", ',', ':']):\n args = ' %s' % args.strip()\nself.args = args",
"if not self.args:\n msg = 'What do you want to do?'\n self.caller.msg(msg)\nelse:\n msg = '%s%s' % (getNameAnsi(self.caller), self.args)\n self.caller.location.msg_contents(text=(ms... | <|body_start_0|>
args = self.args
if args and (not args[0] in ["'", ',', ':']):
args = ' %s' % args.strip()
self.args = args
<|end_body_0|>
<|body_start_1|>
if not self.args:
msg = 'What do you want to do?'
self.caller.msg(msg)
else:
... | strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name. | CmdPose | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdPose:
"""strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
""... | stack_v2_sparse_classes_36k_train_027490 | 11,105 | no_license | [
{
"docstring": "Custom parse the cases where the emote starts with some special letter, such as 's, at which we don't want to separate the caller's name and the emote with a space.",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "Hook function",
"name": "func",
"signa... | 2 | stack_v2_sparse_classes_30k_train_009851 | Implement the Python class `CmdPose` described below.
Class description:
strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your na... | Implement the Python class `CmdPose` described below.
Class description:
strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your na... | 1a315ddab39d8cf093185acaaf68590288bbf3c1 | <|skeleton|>
class CmdPose:
"""strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CmdPose:
"""strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name."""
def parse(self):
"""Custom parse... | the_stack_v2_python_sparse | tekmunkey/evennia_overrides/command_overrides.py | DamnedScholar/evennia-testbox | train | 0 |
94bee6a377ebd61106d4c5da29f84a1645f56fda | [
"args = parser.parse_args()\nrequest_id = args.get('request_id')\nstatus_num = args.get('status_num')\npage = args.get('pgnum')\nif not page:\n page = 1\noptions = {'page': page, 'request_id': request_id, 'status_num': status_num}\nif log_list_c(options=options):\n request_logs, pg = log_list_c(options=option... | <|body_start_0|>
args = parser.parse_args()
request_id = args.get('request_id')
status_num = args.get('status_num')
page = args.get('pgnum')
if not page:
page = 1
options = {'page': page, 'request_id': request_id, 'status_num': status_num}
if log_list_... | LogRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogRequest:
def get(self):
"""获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: descrip... | stack_v2_sparse_classes_36k_train_027491 | 3,392 | no_license | [
{
"docstring": "获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: description: A single logs item schema: id: R... | 2 | stack_v2_sparse_classes_30k_train_002291 | Implement the Python class `LogRequest` described below.
Class description:
Implement the LogRequest class.
Method signatures and docstrings:
- def get(self): 获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page ty... | Implement the Python class `LogRequest` described below.
Class description:
Implement the LogRequest class.
Method signatures and docstrings:
- def get(self): 获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page ty... | 73246bbd492fd991e0329b9a011b5380b11a1618 | <|skeleton|>
class LogRequest:
def get(self):
"""获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogRequest:
def get(self):
"""获取请求日志信息 --- tags: - logs summary: Add a new pet to the store parameters: - in: query name: request_id type: string description: 请求id - in: query name: page type: int description: 页码 - name: status type: int in: query description: 状态码 responses: 200: description: A single... | the_stack_v2_python_sparse | app/main/base/apis/request_logs.py | zhouliang0v0/naguan-kpy | train | 0 | |
36c384feb6b3d0cb71d4b77668306da6da1ecfcd | [
"if context is None:\n context = {}\nproduct_import_info_obj = self.pool.get('product.import.info')\nproduct_uom_obj = self.pool.get('product.uom')\nfor move in self.browse(cr, uid, ids, context=context):\n import_id = move.tracking_id and move.tracking_id.import_id and move.tracking_id.import_id.id or False\... | <|body_start_0|>
if context is None:
context = {}
product_import_info_obj = self.pool.get('product.import.info')
product_uom_obj = self.pool.get('product.uom')
for move in self.browse(cr, uid, ids, context=context):
import_id = move.tracking_id and move.tracking_i... | stock_move for validations in the move of inventory | stock_move_constraint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_move_constraint:
"""stock_move for validations in the move of inventory"""
def _check_product_qty(self, cr, uid, ids, context=None):
"""Check if quantity of product planified on import info document is bigger than this qty more qty already received with this tracking lot"""
... | stack_v2_sparse_classes_36k_train_027492 | 9,266 | no_license | [
{
"docstring": "Check if quantity of product planified on import info document is bigger than this qty more qty already received with this tracking lot",
"name": "_check_product_qty",
"signature": "def _check_product_qty(self, cr, uid, ids, context=None)"
},
{
"docstring": "check if product at l... | 4 | stack_v2_sparse_classes_30k_train_018451 | Implement the Python class `stock_move_constraint` described below.
Class description:
stock_move for validations in the move of inventory
Method signatures and docstrings:
- def _check_product_qty(self, cr, uid, ids, context=None): Check if quantity of product planified on import info document is bigger than this qt... | Implement the Python class `stock_move_constraint` described below.
Class description:
stock_move for validations in the move of inventory
Method signatures and docstrings:
- def _check_product_qty(self, cr, uid, ids, context=None): Check if quantity of product planified on import info document is bigger than this qt... | 1931e4b702d5c75b75fad8a3a6c5b387da6888d2 | <|skeleton|>
class stock_move_constraint:
"""stock_move for validations in the move of inventory"""
def _check_product_qty(self, cr, uid, ids, context=None):
"""Check if quantity of product planified on import info document is bigger than this qty more qty already received with this tracking lot"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_move_constraint:
"""stock_move for validations in the move of inventory"""
def _check_product_qty(self, cr, uid, ids, context=None):
"""Check if quantity of product planified on import info document is bigger than this qty more qty already received with this tracking lot"""
if conte... | the_stack_v2_python_sparse | l10n_mx_import_info/stock.py | razieledev/custom | train | 0 |
3554249ca6c1b9fcdfe14372cfed88d293e1424e | [
"if len(matrix) == 0 or len(matrix[0]) == 0:\n return False\nm, n = (len(matrix), len(matrix[0]))\nrow, col = (m - 1, 0)\ncount = 0\nwhile row >= 0 and col < n:\n if matrix[row][col] > target:\n row -= 1\n elif matrix[row][col] < target:\n col += 1\n else:\n return True\n print(r... | <|body_start_0|>
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
m, n = (len(matrix), len(matrix[0]))
row, col = (m - 1, 0)
count = 0
while row >= 0 and col < n:
if matrix[row][col] > target:
row -= 1
elif matrix[row][c... | 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 searchMatrixCount(self, matrix, target):
"""return the occurrence number of 'target' in 'matrix' :type matrix: List[List[int]] :type ta... | stack_v2_sparse_classes_36k_train_027493 | 1,909 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "return the occurrence number of 'target' in 'matrix' :type matrix: List[List[int]] :type target: int :rtype: bool",
... | 2 | null | 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 searchMatrixCount(self, matrix, target): return the occurrence number o... | 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 searchMatrixCount(self, matrix, target): return the occurrence number o... | e1a4c1bc5d01b4e2ba51a5255deed6426557dcb0 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrixCount(self, matrix, target):
"""return the occurrence number of 'target' in 'matrix' :type matrix: List[List[int]] :type ta... | 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 len(matrix) == 0 or len(matrix[0]) == 0:
return False
m, n = (len(matrix), len(matrix[0]))
row, col = (m - 1, 0)
count = 0
while r... | the_stack_v2_python_sparse | src/search2DMatrix2.py | xuetingandyang/leetcode | train | 3 | |
9b4bf0253c7fd3d332029fc82721f97597464b19 | [
"registry = er.async_get(hass)\ndevice_registry = dr.async_get(hass)\nwrapped_switch = registry.async_get(switch_entity_id)\ndevice_id = wrapped_switch.device_id if wrapped_switch else None\nentity_category = wrapped_switch.entity_category if wrapped_switch else None\nhas_entity_name = wrapped_switch.has_entity_nam... | <|body_start_0|>
registry = er.async_get(hass)
device_registry = dr.async_get(hass)
wrapped_switch = registry.async_get(switch_entity_id)
device_id = wrapped_switch.device_id if wrapped_switch else None
entity_category = wrapped_switch.entity_category if wrapped_switch else None
... | Represents a Switch as an X. | BaseEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseEntity:
"""Represents a Switch as an X."""
def __init__(self, hass: HomeAssistant, config_entry_title: str, domain: str, switch_entity_id: str, unique_id: str) -> None:
"""Initialize Switch as an X."""
<|body_0|>
def async_state_changed_listener(self, event: EventTyp... | stack_v2_sparse_classes_36k_train_027494 | 6,290 | permissive | [
{
"docstring": "Initialize Switch as an X.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, config_entry_title: str, domain: str, switch_entity_id: str, unique_id: str) -> None"
},
{
"docstring": "Handle child updates.",
"name": "async_state_changed_listener",
... | 3 | null | Implement the Python class `BaseEntity` described below.
Class description:
Represents a Switch as an X.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry_title: str, domain: str, switch_entity_id: str, unique_id: str) -> None: Initialize Switch as an X.
- def async_state_change... | Implement the Python class `BaseEntity` described below.
Class description:
Represents a Switch as an X.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, config_entry_title: str, domain: str, switch_entity_id: str, unique_id: str) -> None: Initialize Switch as an X.
- def async_state_change... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BaseEntity:
"""Represents a Switch as an X."""
def __init__(self, hass: HomeAssistant, config_entry_title: str, domain: str, switch_entity_id: str, unique_id: str) -> None:
"""Initialize Switch as an X."""
<|body_0|>
def async_state_changed_listener(self, event: EventTyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseEntity:
"""Represents a Switch as an X."""
def __init__(self, hass: HomeAssistant, config_entry_title: str, domain: str, switch_entity_id: str, unique_id: str) -> None:
"""Initialize Switch as an X."""
registry = er.async_get(hass)
device_registry = dr.async_get(hass)
... | the_stack_v2_python_sparse | homeassistant/components/switch_as_x/entity.py | home-assistant/core | train | 35,501 |
e2242486d3cffbeaa72969c014b426277c821ef4 | [
"Action.__init__(self, 'trace', 'out')\nself.enabled = True\nself.terminal = True\nself.branching = False\nself.start_ttl = start_ttl\nself.end_ttl = end_ttl\nself.ran = False\nself.socket = conf.L3socket(iface=actions.utils.get_interface())",
"logger.debug(' - Starting Trace action')\nif not packet.haslayer('IP... | <|body_start_0|>
Action.__init__(self, 'trace', 'out')
self.enabled = True
self.terminal = True
self.branching = False
self.start_ttl = start_ttl
self.end_ttl = end_ttl
self.ran = False
self.socket = conf.L3socket(iface=actions.utils.get_interface())
<|end... | The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution | TraceAction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraceAction:
"""The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution"""
def __init__(self, start_ttl=1, end_ttl=6... | stack_v2_sparse_classes_36k_train_027495 | 3,105 | permissive | [
{
"docstring": "Initializes the trace action. Args: start_ttl (int): Starting TTL to use end_ttl (int): TTL to end with environment_id (str, optional): Environment ID associated with the strategy we are a part of",
"name": "__init__",
"signature": "def __init__(self, start_ttl=1, end_ttl=64, environment... | 4 | stack_v2_sparse_classes_30k_train_005289 | Implement the Python class `TraceAction` described below.
Class description:
The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution
Method si... | Implement the Python class `TraceAction` described below.
Class description:
The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution
Method si... | 6b091060ed0946b98a2ff9196dfbf93d85cbb28a | <|skeleton|>
class TraceAction:
"""The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution"""
def __init__(self, start_ttl=1, end_ttl=6... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TraceAction:
"""The Trace Action is used to TTL probe/traceroute a censor. When the action fires, it sends the captured packet with increasing ttls within a certain range TraceAction is an experimental action that is never used in actual evolution"""
def __init__(self, start_ttl=1, end_ttl=64, environmen... | the_stack_v2_python_sparse | actions/trace.py | Kkevsterrr/geneva | train | 1,771 |
4695784a3f157e9a6d3e17212f1f079d42b282fc | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['Shore Fishing Missed NESA']\nURLS = ['https://www.nesa.co.uk/forums/shore-fishing/']\nLAST_SCRAPED = 501\nPAGES = [994 - LAST_SCRAPED]\nassert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match'\nfor i, root_url i... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Shore Fishing Missed NESA']
URLS = ['https://www.nesa.co.uk/forums/shore-fishing/']
LAST_SCRAPED = 501
PAGES = [994 - LAST_SCRAPED]
assert len(BOARDS) == len(URLS) == len(PAGES... | scrape reports from angling addicts forum | NESASpiderShoreMissed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NESASpiderShoreMissed:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
... | stack_v2_sparse_classes_36k_train_027496 | 13,051 | no_license | [
{
"docstring": "generate links to pages in a board",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "crawl",
"name": "crawl_board_threads",
"signature": "def crawl_board_threads(self, response)"
},
{
"docstring": "open a report thread and parse first ... | 3 | null | Implement the Python class `NESASpiderShoreMissed` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a... | Implement the Python class `NESASpiderShoreMissed` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class NESASpiderShoreMissed:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NESASpiderShoreMissed:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Shore Fishing Missed NESA']
URLS = ['https://www.nesa.c... | the_stack_v2_python_sparse | imgscrape/spiders/nesa.py | gmonkman/python | train | 0 |
b11191c0d69b66ef7cd72c030f8e4619bc90c4ba | [
"super().__init__()\nself.num_queries = num_queries\nself.transformer = transformer\nhidden_dim = transformer.d_model\nself.class_embed = nn.Linear(hidden_dim, num_classes + 1)\nself.bsegment_embed = MLP(hidden_dim, hidden_dim, 2, 3)\nself.input_proj = nn.Conv1d(backbone.num_channels, hidden_dim, kernel_size=1)\nse... | <|body_start_0|>
super().__init__()
self.num_queries = num_queries
self.transformer = transformer
hidden_dim = transformer.d_model
self.class_embed = nn.Linear(hidden_dim, num_classes + 1)
self.bsegment_embed = MLP(hidden_dim, hidden_dim, 2, 3)
self.input_proj = n... | This is the DETR module that performs translocation detection | DETR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DETR:
"""This is the DETR module that performs translocation detection"""
def __init__(self, backbone, transformer, num_classes, num_queries):
"""Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the tra... | stack_v2_sparse_classes_36k_train_027497 | 11,449 | permissive | [
{
"docstring": "Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of translocation classes num_queries: number of translocation queries, ie detection slot. This i... | 2 | stack_v2_sparse_classes_30k_train_009218 | Implement the Python class `DETR` described below.
Class description:
This is the DETR module that performs translocation detection
Method signatures and docstrings:
- def __init__(self, backbone, transformer, num_classes, num_queries): Initializes the model. Parameters: backbone: torch module of the backbone to be u... | Implement the Python class `DETR` described below.
Class description:
This is the DETR module that performs translocation detection
Method signatures and docstrings:
- def __init__(self, backbone, transformer, num_classes, num_queries): Initializes the model. Parameters: backbone: torch module of the backbone to be u... | 24c559869cee32487539fa3febc9f96919035278 | <|skeleton|>
class DETR:
"""This is the DETR module that performs translocation detection"""
def __init__(self, backbone, transformer, num_classes, num_queries):
"""Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DETR:
"""This is the DETR module that performs translocation detection"""
def __init__(self, backbone, transformer, num_classes, num_queries):
"""Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer arch... | the_stack_v2_python_sparse | Translocations_Detector/models/detr.py | dariodematties/NANOPORE_TRANSLOCATIONS | train | 0 |
4782f5becbace547088b04f348a2229a268ced5f | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ajr10_williami', 'ajr10_williami')\nrepo.dropCollection('ajr10_williami.cleaned_energy_cambridge')\nrepo.createCollection('ajr10_williami.cleaned_energy_cambridge')\nrepo.dropCollection('ajr10_williami.c... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_williami', 'ajr10_williami')
repo.dropCollection('ajr10_williami.cleaned_energy_cambridge')
repo.createCollection('ajr10_williami.cleaned_en... | clean_energy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class clean_energy:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this s... | stack_v2_sparse_classes_36k_train_027498 | 5,514 | no_license | [
{
"docstring": "Retrieve some data sets and store in mongodb collections.",
"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 document describing ... | 2 | stack_v2_sparse_classes_30k_train_016722 | Implement the Python class `clean_energy` described below.
Class description:
Implement the clean_energy class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets and store in mongodb collections.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create ... | Implement the Python class `clean_energy` described below.
Class description:
Implement the clean_energy class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets and store in mongodb collections.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create ... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class clean_energy:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class clean_energy:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_williami', 'ajr10_williami')
repo.dropColle... | the_stack_v2_python_sparse | ajr10_williami/clean_energy.py | lingyigu/course-2017-spr-proj | train | 0 | |
c32c6693fa3fc44e808b5e59c91f5c59ff963547 | [
"candidates.sort()\nres = []\nself._dfs(candidates, [], target, res)\nreturn res",
"value = sum(path)\nif value > target:\n return\nif value == target:\n res.append(path.copy())\n return\nfor i in range(len(nums)):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n path.append(nums[i])\n ... | <|body_start_0|>
candidates.sort()
res = []
self._dfs(candidates, [], target, res)
return res
<|end_body_0|>
<|body_start_1|>
value = sum(path)
if value > target:
return
if value == target:
res.append(path.copy())
return
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
""":param candidates: :param target: :return:"""
<|body_0|>
def _dfs(self, nums, path, target, res):
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027499 | 1,128 | no_license | [
{
"docstring": ":param candidates: :param target: :return:",
"name": "combinationSum2",
"signature": "def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]"
},
{
"docstring": ":return:",
"name": "_dfs",
"signature": "def _dfs(self, nums, path, target, res)"
}... | 2 | stack_v2_sparse_classes_30k_train_019174 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: :param candidates: :param target: :return:
- def _dfs(self, nums, path, target, res): :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: :param candidates: :param target: :return:
- def _dfs(self, nums, path, target, res): :return:
... | 6708479302cca3ea3d930e6e80264f213ea29c5f | <|skeleton|>
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
""":param candidates: :param target: :return:"""
<|body_0|>
def _dfs(self, nums, path, target, res):
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
""":param candidates: :param target: :return:"""
candidates.sort()
res = []
self._dfs(candidates, [], target, res)
return res
def _dfs(self, nums, path, target, res):
... | the_stack_v2_python_sparse | DFS回溯/leetcode_40.py | Gyczero/Leetcode_practice | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.