blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
271f1b18ec797c25f684df51ed466dbfd051ab2e | [
"self.connector_group_id = connector_group_id\nself.entity_id = entity_id\nself.network_realm_id = network_realm_id",
"if dictionary is None:\n return None\nconnector_group_id = dictionary.get('connectorGroupId')\nentity_id = dictionary.get('entityId')\nnetwork_realm_id = dictionary.get('networkRealmId')\nretu... | <|body_start_0|>
self.connector_group_id = connector_group_id
self.entity_id = entity_id
self.network_realm_id = network_realm_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
connector_group_id = dictionary.get('connectorGroupId')
entity... | Implementation of the 'NetworkRealmInfo' model. Contains mapping of network realms with adapter specific entities. This will be populated by IRIS for create/update source requests so that we can persist the mapping in the corresponding entity hierarchy. Attributes: connector_group_id (long|int): 'network_realm_id' main... | NetworkRealmInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkRealmInfo:
"""Implementation of the 'NetworkRealmInfo' model. Contains mapping of network realms with adapter specific entities. This will be populated by IRIS for create/update source requests so that we can persist the mapping in the corresponding entity hierarchy. Attributes: connector_... | stack_v2_sparse_classes_75kplus_train_072900 | 2,452 | permissive | [
{
"docstring": "Constructor for the NetworkRealmInfo class",
"name": "__init__",
"signature": "def __init__(self, connector_group_id=None, entity_id=None, network_realm_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary re... | 2 | stack_v2_sparse_classes_30k_train_046030 | Implement the Python class `NetworkRealmInfo` described below.
Class description:
Implementation of the 'NetworkRealmInfo' model. Contains mapping of network realms with adapter specific entities. This will be populated by IRIS for create/update source requests so that we can persist the mapping in the corresponding e... | Implement the Python class `NetworkRealmInfo` described below.
Class description:
Implementation of the 'NetworkRealmInfo' model. Contains mapping of network realms with adapter specific entities. This will be populated by IRIS for create/update source requests so that we can persist the mapping in the corresponding e... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NetworkRealmInfo:
"""Implementation of the 'NetworkRealmInfo' model. Contains mapping of network realms with adapter specific entities. This will be populated by IRIS for create/update source requests so that we can persist the mapping in the corresponding entity hierarchy. Attributes: connector_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkRealmInfo:
"""Implementation of the 'NetworkRealmInfo' model. Contains mapping of network realms with adapter specific entities. This will be populated by IRIS for create/update source requests so that we can persist the mapping in the corresponding entity hierarchy. Attributes: connector_group_id (lon... | the_stack_v2_python_sparse | cohesity_management_sdk/models/network_realm_info.py | cohesity/management-sdk-python | train | 24 |
7d9d4a4407380532ffb02e401c0759c92f37220a | [
"self.wrapping_algorithm = wrapping_algorithm\nself.wrapping_key_type = wrapping_key_type\nif wrapping_key_type is EncryptionKeyType.PRIVATE:\n self._wrapping_key = serialization.load_pem_private_key(data=wrapping_key, password=password, backend=default_backend())\nelif wrapping_key_type is EncryptionKeyType.PUB... | <|body_start_0|>
self.wrapping_algorithm = wrapping_algorithm
self.wrapping_key_type = wrapping_key_type
if wrapping_key_type is EncryptionKeyType.PRIVATE:
self._wrapping_key = serialization.load_pem_private_key(data=wrapping_key, password=password, backend=default_backend())
... | Creates a wrapping encryption key object to encrypt and decrypt data keys. For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects. :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key :type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgor... | WrappingKey | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WrappingKey:
"""Creates a wrapping encryption key object to encrypt and decrypt data keys. For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects. :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key :type wrapping_algorithm: aws_e... | stack_v2_sparse_classes_75kplus_train_072901 | 5,499 | permissive | [
{
"docstring": "Prepares initial values.",
"name": "__init__",
"signature": "def __init__(self, wrapping_algorithm, wrapping_key, wrapping_key_type, password=None)"
},
{
"docstring": "Encrypts a data key using a direct wrapping key. :param bytes plaintext_data_key: Data key to encrypt :param dic... | 3 | stack_v2_sparse_classes_30k_val_002920 | Implement the Python class `WrappingKey` described below.
Class description:
Creates a wrapping encryption key object to encrypt and decrypt data keys. For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects. :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_d... | Implement the Python class `WrappingKey` described below.
Class description:
Creates a wrapping encryption key object to encrypt and decrypt data keys. For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects. :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_d... | 3ba8019681ed95c41bb9448f0c3897d1aecc7559 | <|skeleton|>
class WrappingKey:
"""Creates a wrapping encryption key object to encrypt and decrypt data keys. For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects. :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key :type wrapping_algorithm: aws_e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WrappingKey:
"""Creates a wrapping encryption key object to encrypt and decrypt data keys. For use inside :class:`aws_encryption_sdk.key_providers.raw.RawMasterKeyProvider` objects. :param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key :type wrapping_algorithm: aws_encryption_sdk... | the_stack_v2_python_sparse | src/aws_encryption_sdk/internal/crypto/wrapping_keys.py | aws/aws-encryption-sdk-python | train | 137 |
0508711350f81b2fa70226122ce407e491024899 | [
"if not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nres = []\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_072902 | 2,088 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_021511 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | dbd04a17cf61bac37531e3337ba197c4af19489e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
i... | the_stack_v2_python_sparse | leetcodeDay/June/prac297.py | zhengjiani/pyAlgorithm | train | 0 | |
8eb79998d207f97000902786ea60215a1f5151bd | [
"super().__init__()\nself.tanh = nn.Tanh()\nself.W = nn.Linear(enc_dim, att_dim, bias=False)\nself.V = nn.Linear(dec_dim, att_dim, bias=False)\nself.b = nn.Parameter(torch.Tensor(att_dim).normal_())\nself.v = nn.utils.weight_norm(nn.Linear(att_dim, 1))\nself.v.weight_g = nn.Parameter(torch.Tensor([1 / att_dim]).sqr... | <|body_start_0|>
super().__init__()
self.tanh = nn.Tanh()
self.W = nn.Linear(enc_dim, att_dim, bias=False)
self.V = nn.Linear(dec_dim, att_dim, bias=False)
self.b = nn.Parameter(torch.Tensor(att_dim).normal_())
self.v = nn.utils.weight_norm(nn.Linear(att_dim, 1))
... | Energy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Energy:
def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None:
"""[Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic Alignment" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk At... | stack_v2_sparse_classes_75kplus_train_072903 | 23,577 | no_license | [
{
"docstring": "[Modified Bahdahnau attention] from \"Online and Linear-Time Attention by Enforcing Monotonic Alignment\" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk Attention",
"name": "__init__",
"signature": "def __init__(self, enc_dim: int, dec_dim: int, att_di... | 2 | stack_v2_sparse_classes_30k_train_001110 | Implement the Python class `Energy` described below.
Class description:
Implement the Energy class.
Method signatures and docstrings:
- def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None: [Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic A... | Implement the Python class `Energy` described below.
Class description:
Implement the Energy class.
Method signatures and docstrings:
- def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None: [Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic A... | 9f9a55f8020ac05b7bb84746a62a83950fe833a2 | <|skeleton|>
class Energy:
def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None:
"""[Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic Alignment" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk At... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Energy:
def __init__(self, enc_dim: int, dec_dim: int, att_dim: int, init_r: float=-4) -> None:
"""[Modified Bahdahnau attention] from "Online and Linear-Time Attention by Enforcing Monotonic Alignment" (ICML 2017) http://arxiv.org/abs/1704.00784 Used for Monotonic Attention and Chunk Attention"""
... | the_stack_v2_python_sparse | stt/modules/attention.py | Chung-I/tsm-rnnt | train | 4 | |
c2bf6d0972da5d5c95a22318020fe1ea535d2b2d | [
"context = super().get_context_data(**kwargs)\nid_user = self.request.user\nuser = CustomUser.objects.get(user=id_user)\ndocument_user = DocumentUser.objects.filter(user=id_user)\nuser_doc_done = user.complete_flag\ncontext['user_doc_done'] = user_doc_done\ncontext['document_user'] = document_user\ncontext['custom_... | <|body_start_0|>
context = super().get_context_data(**kwargs)
id_user = self.request.user
user = CustomUser.objects.get(user=id_user)
document_user = DocumentUser.objects.filter(user=id_user)
user_doc_done = user.complete_flag
context['user_doc_done'] = user_doc_done
... | DocumentsAddView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentsAddView:
def get_context_data(self, **kwargs):
"""Переопределяем базовый метод, чтобы передать свой контекст"""
<|body_0|>
def form_valid(self, form):
"""Метод сохранения записи за конкретным пользователем"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_072904 | 33,253 | no_license | [
{
"docstring": "Переопределяем базовый метод, чтобы передать свой контекст",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Метод сохранения записи за конкретным пользователем",
"name": "form_valid",
"signature": "def form_valid(self, f... | 2 | null | Implement the Python class `DocumentsAddView` described below.
Class description:
Implement the DocumentsAddView class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Переопределяем базовый метод, чтобы передать свой контекст
- def form_valid(self, form): Метод сохранения записи за конкретн... | Implement the Python class `DocumentsAddView` described below.
Class description:
Implement the DocumentsAddView class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Переопределяем базовый метод, чтобы передать свой контекст
- def form_valid(self, form): Метод сохранения записи за конкретн... | 2242d925b08b450bca927e2b5a59a13725e37d33 | <|skeleton|>
class DocumentsAddView:
def get_context_data(self, **kwargs):
"""Переопределяем базовый метод, чтобы передать свой контекст"""
<|body_0|>
def form_valid(self, form):
"""Метод сохранения записи за конкретным пользователем"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DocumentsAddView:
def get_context_data(self, **kwargs):
"""Переопределяем базовый метод, чтобы передать свой контекст"""
context = super().get_context_data(**kwargs)
id_user = self.request.user
user = CustomUser.objects.get(user=id_user)
document_user = DocumentUser.obj... | the_stack_v2_python_sparse | myproject/regabitur/views.py | Pauuukin/abiturient | train | 0 | |
32a21addfbb1d488d95643e6e418a4ce4cac8cfe | [
"self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(10, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=11.3)\nself.pump.get_state = MagicMock(return_value='PUMP_IN')\nself.pump.set_state = ... | <|body_start_0|>
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=11.3)
... | Module tests for the water-regulation module | ModuleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sensor = ... | stack_v2_sparse_classes_75kplus_train_072905 | 956 | no_license | [
{
"docstring": "Set up controller for test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test controller tick method",
"name": "test_controller",
"signature": "def test_controller(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008966 | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method
<|skeleton|>
class ModuleTests:
"""Module tests for th... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Set up controller for test"""
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, ... | the_stack_v2_python_sparse | students/smitco/lesson06/waterregulation/integrationtest.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
3be4dca51f0ca1b859bd59a41d5a4ce242c87fca | [
"if tf.executing_eagerly():\n return _EagerPlaceholder()\nreturn tf.compat.v1.placeholder(dtype, shape=shape, name=name)",
"if tf.executing_eagerly():\n return _EagerWrappedSession()\nreturn _GraphWrappedSession(self.session())"
] | <|body_start_0|>
if tf.executing_eagerly():
return _EagerPlaceholder()
return tf.compat.v1.placeholder(dtype, shape=shape, name=name)
<|end_body_0|>
<|body_start_1|>
if tf.executing_eagerly():
return _EagerWrappedSession()
return _GraphWrappedSession(self.session... | A `TestCase` including the `wrapped_session()` method. | GraphAndEagerTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphAndEagerTestCase:
"""A `TestCase` including the `wrapped_session()` method."""
def wrapped_placeholder(self, dtype, shape=None, name=None):
"""Returns a placeholder in graph mode, or a fake in eager mode."""
<|body_0|>
def wrapped_session(self):
"""Returns a... | stack_v2_sparse_classes_75kplus_train_072906 | 9,283 | permissive | [
{
"docstring": "Returns a placeholder in graph mode, or a fake in eager mode.",
"name": "wrapped_placeholder",
"signature": "def wrapped_placeholder(self, dtype, shape=None, name=None)"
},
{
"docstring": "Returns a wrapper object around a session. In graph mode, this wrapper does nothing but sli... | 2 | stack_v2_sparse_classes_30k_train_018724 | Implement the Python class `GraphAndEagerTestCase` described below.
Class description:
A `TestCase` including the `wrapped_session()` method.
Method signatures and docstrings:
- def wrapped_placeholder(self, dtype, shape=None, name=None): Returns a placeholder in graph mode, or a fake in eager mode.
- def wrapped_ses... | Implement the Python class `GraphAndEagerTestCase` described below.
Class description:
A `TestCase` including the `wrapped_session()` method.
Method signatures and docstrings:
- def wrapped_placeholder(self, dtype, shape=None, name=None): Returns a placeholder in graph mode, or a fake in eager mode.
- def wrapped_ses... | 2cc7d204b206674d4ca648965c6a3deb4ef6783a | <|skeleton|>
class GraphAndEagerTestCase:
"""A `TestCase` including the `wrapped_session()` method."""
def wrapped_placeholder(self, dtype, shape=None, name=None):
"""Returns a placeholder in graph mode, or a fake in eager mode."""
<|body_0|>
def wrapped_session(self):
"""Returns a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphAndEagerTestCase:
"""A `TestCase` including the `wrapped_session()` method."""
def wrapped_placeholder(self, dtype, shape=None, name=None):
"""Returns a placeholder in graph mode, or a fake in eager mode."""
if tf.executing_eagerly():
return _EagerPlaceholder()
re... | the_stack_v2_python_sparse | tensorflow_constrained_optimization/python/graph_and_eager_test_case.py | autoih/tensorflow_constrained_optimization | train | 1 |
1a556f92f4cbf571bca3ac9e5cbc4976555802ad | [
"from aiida.common import exceptions\nsuper().__init__(sub_classes=sub_classes)\nself._process_classes = []\nif process_classes is not None:\n if not isinstance(process_classes, tuple):\n raise TypeError('process_classes should be a tuple of entry point strings')\n for entry_point_string in process_cla... | <|body_start_0|>
from aiida.common import exceptions
super().__init__(sub_classes=sub_classes)
self._process_classes = []
if process_classes is not None:
if not isinstance(process_classes, tuple):
raise TypeError('process_classes should be a tuple of entry poi... | The ParamType for identifying WorkflowNode entities or its subclasses. Filter the ``process_class`` by the ``self._prcess_classes``. | FilteredWorkflowParamType | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteredWorkflowParamType:
"""The ParamType for identifying WorkflowNode entities or its subclasses. Filter the ``process_class`` by the ``self._prcess_classes``."""
def __init__(self, sub_classes=None, process_classes: ty.Sequence[str]=None):
"""Initialize. :param process_classes: v... | stack_v2_sparse_classes_75kplus_train_072907 | 2,787 | permissive | [
{
"docstring": "Initialize. :param process_classes: valid entry points for ``aiida.workflows``, defaults to None :type process_classes: ty.Sequence[str], optional",
"name": "__init__",
"signature": "def __init__(self, sub_classes=None, process_classes: ty.Sequence[str]=None)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_017451 | Implement the Python class `FilteredWorkflowParamType` described below.
Class description:
The ParamType for identifying WorkflowNode entities or its subclasses. Filter the ``process_class`` by the ``self._prcess_classes``.
Method signatures and docstrings:
- def __init__(self, sub_classes=None, process_classes: ty.S... | Implement the Python class `FilteredWorkflowParamType` described below.
Class description:
The ParamType for identifying WorkflowNode entities or its subclasses. Filter the ``process_class`` by the ``self._prcess_classes``.
Method signatures and docstrings:
- def __init__(self, sub_classes=None, process_classes: ty.S... | aeceb3519ffd1cd071d5b98f81888052fff58163 | <|skeleton|>
class FilteredWorkflowParamType:
"""The ParamType for identifying WorkflowNode entities or its subclasses. Filter the ``process_class`` by the ``self._prcess_classes``."""
def __init__(self, sub_classes=None, process_classes: ty.Sequence[str]=None):
"""Initialize. :param process_classes: v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilteredWorkflowParamType:
"""The ParamType for identifying WorkflowNode entities or its subclasses. Filter the ``process_class`` by the ``self._prcess_classes``."""
def __init__(self, sub_classes=None, process_classes: ty.Sequence[str]=None):
"""Initialize. :param process_classes: valid entry po... | the_stack_v2_python_sparse | src/aiida_wannier90_workflows/cli/params.py | aiidateam/aiida-wannier90-workflows | train | 5 |
f4efbece647e5b9a29e18533458bb62b47c830bd | [
"if self.creator is not None:\n kwargs.pop('creator', None)\nsuper().save(*args, **kwargs)",
"result = self.updater.get_full_name()\nif not result:\n result = self.updater.username\nreturn result",
"result = self.creator.get_full_name()\nif not result:\n result = self.creator.username\nreturn result"
] | <|body_start_0|>
if self.creator is not None:
kwargs.pop('creator', None)
super().save(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
result = self.updater.get_full_name()
if not result:
result = self.updater.username
return result
<|end_body_1|>
<|bod... | Abstract model mixin used in the model classes to provide user and creator fields. | UserModelMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserModelMixin:
"""Abstract model mixin used in the model classes to provide user and creator fields."""
def save(self, *args, **kwargs):
"""Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments."""
... | stack_v2_sparse_classes_75kplus_train_072908 | 5,231 | permissive | [
{
"docstring": "Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments.",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "Primary use is in an admin class to supply the updater's full ... | 3 | stack_v2_sparse_classes_30k_train_050164 | Implement the Python class `UserModelMixin` described below.
Class description:
Abstract model mixin used in the model classes to provide user and creator fields.
Method signatures and docstrings:
- def save(self, *args, **kwargs): Save is here to assure that save is executed throughout the MRO. :param args: Position... | Implement the Python class `UserModelMixin` described below.
Class description:
Abstract model mixin used in the model classes to provide user and creator fields.
Method signatures and docstrings:
- def save(self, *args, **kwargs): Save is here to assure that save is executed throughout the MRO. :param args: Position... | 44a8f151652640306bd6112c9838db99f5fc5c38 | <|skeleton|>
class UserModelMixin:
"""Abstract model mixin used in the model classes to provide user and creator fields."""
def save(self, *args, **kwargs):
"""Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserModelMixin:
"""Abstract model mixin used in the model classes to provide user and creator fields."""
def save(self, *args, **kwargs):
"""Save is here to assure that save is executed throughout the MRO. :param args: Positional arguments. :param kwargs: Keyword arguments."""
if self.cre... | the_stack_v2_python_sparse | inventory/common/model_mixins.py | cnobile2012/inventory | train | 14 |
efaf94f3c6b79f9294ae7f7e7a070a7902cf9c12 | [
"@wraps(self)\ndef decorated(*args, **kwargs):\n token = None\n if 'token' in request.headers:\n token = request.headers['token']\n if not token:\n return (jsonify({'message': 'Token is missing!'}), 401)\n try:\n data = jwt.decode(token, app.config['SECRET_KEY'])\n User.query... | <|body_start_0|>
@wraps(self)
def decorated(*args, **kwargs):
token = None
if 'token' in request.headers:
token = request.headers['token']
if not token:
return (jsonify({'message': 'Token is missing!'}), 401)
try:
... | Search_note | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Search_note:
def token_required(self):
"""Decorator meant to check if the token exists or not If the token exists check if it is valid"""
<|body_0|>
def get_user_by_token(self):
""":param token: has to be a jwt token :return: the user based on the public_id supplied ... | stack_v2_sparse_classes_75kplus_train_072909 | 8,581 | permissive | [
{
"docstring": "Decorator meant to check if the token exists or not If the token exists check if it is valid",
"name": "token_required",
"signature": "def token_required(self)"
},
{
"docstring": ":param token: has to be a jwt token :return: the user based on the public_id supplied by the token",... | 3 | stack_v2_sparse_classes_30k_train_017973 | Implement the Python class `Search_note` described below.
Class description:
Implement the Search_note class.
Method signatures and docstrings:
- def token_required(self): Decorator meant to check if the token exists or not If the token exists check if it is valid
- def get_user_by_token(self): :param token: has to b... | Implement the Python class `Search_note` described below.
Class description:
Implement the Search_note class.
Method signatures and docstrings:
- def token_required(self): Decorator meant to check if the token exists or not If the token exists check if it is valid
- def get_user_by_token(self): :param token: has to b... | db351b2053be5e9568d731006fd2af7002a40ca0 | <|skeleton|>
class Search_note:
def token_required(self):
"""Decorator meant to check if the token exists or not If the token exists check if it is valid"""
<|body_0|>
def get_user_by_token(self):
""":param token: has to be a jwt token :return: the user based on the public_id supplied ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Search_note:
def token_required(self):
"""Decorator meant to check if the token exists or not If the token exists check if it is valid"""
@wraps(self)
def decorated(*args, **kwargs):
token = None
if 'token' in request.headers:
token = request.hea... | the_stack_v2_python_sparse | server2/api/endpoints/stand_alone_views.py | Terkea/beds-uni-hackathon-4-notes | train | 0 | |
3c54d4d5a6dbb932dbd355a2eed5e7d066a8e03b | [
"self.parsing_error = None\nself.tree = None\ntry:\n self.tree = lxml.etree.fromstring(data)\nexcept lxml.etree.XMLSyntaxError as ex:\n self.parsing_error = 'Parsing error: ' + str(ex)",
"if self.parsing_error:\n return self.parsing_error\nfor node in self.tree.iter():\n if isinstance(node, lxml.etree... | <|body_start_0|>
self.parsing_error = None
self.tree = None
try:
self.tree = lxml.etree.fromstring(data)
except lxml.etree.XMLSyntaxError as ex:
self.parsing_error = 'Parsing error: ' + str(ex)
<|end_body_0|>
<|body_start_1|>
if self.parsing_error:
... | XMLTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLTree:
def __init__(self, data):
"""The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str"""
<|body_0|>
def is_data_unclean(self):
"""Ensure that the tree parses as XML and... | stack_v2_sparse_classes_75kplus_train_072910 | 4,781 | no_license | [
{
"docstring": "The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Ensure that the tree parses as XML and that it conta... | 4 | stack_v2_sparse_classes_30k_train_039223 | Implement the Python class `XMLTree` described below.
Class description:
Implement the XMLTree class.
Method signatures and docstrings:
- def __init__(self, data): The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str
- def i... | Implement the Python class `XMLTree` described below.
Class description:
Implement the XMLTree class.
Method signatures and docstrings:
- def __init__(self, data): The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str
- def i... | ea54b58ef15a738500547e73e02935d95775c798 | <|skeleton|>
class XMLTree:
def __init__(self, data):
"""The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str"""
<|body_0|>
def is_data_unclean(self):
"""Ensure that the tree parses as XML and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XMLTree:
def __init__(self, data):
"""The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str"""
self.parsing_error = None
self.tree = None
try:
self.tree = lxml.etree.fromstr... | the_stack_v2_python_sparse | lexicography/xml.py | keisetsu/btw | train | 0 | |
c85cf8903c0fea89158f771f1fad49626b078a21 | [
"self.num = 0\nself.num_list = []\nself.sort_num_list = None\nself.k = k\nself.m = m",
"if len(self.num_list) < self.m:\n self.num_list.append(num)\nelse:\n self.num_list.pop(0)\n self.num_list.append(num)\nif len(self.num_list) == self.m:\n self.sort_num_list = copy.deepcopy(self.num_list)\n self.... | <|body_start_0|>
self.num = 0
self.num_list = []
self.sort_num_list = None
self.k = k
self.m = m
<|end_body_0|>
<|body_start_1|>
if len(self.num_list) < self.m:
self.num_list.append(num)
else:
self.num_list.pop(0)
self.num_list... | MKAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MKAverage:
def __init__(self, m, k):
""":type m: int :type k: int"""
<|body_0|>
def addElement(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def calculateMKAverage(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_072911 | 881 | no_license | [
{
"docstring": ":type m: int :type k: int",
"name": "__init__",
"signature": "def __init__(self, m, k)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addElement",
"signature": "def addElement(self, num)"
},
{
"docstring": ":rtype: int",
"name": "calculateMKAverage... | 3 | stack_v2_sparse_classes_30k_train_048177 | Implement the Python class `MKAverage` described below.
Class description:
Implement the MKAverage class.
Method signatures and docstrings:
- def __init__(self, m, k): :type m: int :type k: int
- def addElement(self, num): :type num: int :rtype: None
- def calculateMKAverage(self): :rtype: int | Implement the Python class `MKAverage` described below.
Class description:
Implement the MKAverage class.
Method signatures and docstrings:
- def __init__(self, m, k): :type m: int :type k: int
- def addElement(self, num): :type num: int :rtype: None
- def calculateMKAverage(self): :rtype: int
<|skeleton|>
class MKA... | d34d4b592d05e9e0e724d8834eaf9587a64c5034 | <|skeleton|>
class MKAverage:
def __init__(self, m, k):
""":type m: int :type k: int"""
<|body_0|>
def addElement(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def calculateMKAverage(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MKAverage:
def __init__(self, m, k):
""":type m: int :type k: int"""
self.num = 0
self.num_list = []
self.sort_num_list = None
self.k = k
self.m = m
def addElement(self, num):
""":type num: int :rtype: None"""
if len(self.num_list) < self.m:... | the_stack_v2_python_sparse | LeetCode算法题/1825_求出MK平均值/求出MK平均值.py | exueyuanAlgorithm/AlgorithmDemo | train | 0 | |
c1818059ead7e4901afe5594f9675b82000c4fb2 | [
"self.db_key = db_key\nself.list_of_ids = list_of_ids\nself.default_metric = default_metric",
"import spotdb\nif isinstance(self.db_key, str):\n db = spotdb.connect(self.db_key)\nelse:\n db = self.db_key\nruns = self.list_of_ids or db.get_all_run_ids()\nregionprofiles = db.get_regionprofiles(runs)\nmetadata... | <|body_start_0|>
self.db_key = db_key
self.list_of_ids = list_of_ids
self.default_metric = default_metric
<|end_body_0|>
<|body_start_1|>
import spotdb
if isinstance(self.db_key, str):
db = spotdb.connect(self.db_key)
else:
db = self.db_key
... | Import multiple runs as graph frames from a SpotDB instance | SpotDBReader | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpotDBReader:
"""Import multiple runs as graph frames from a SpotDB instance"""
def __init__(self, db_key, list_of_ids=None, default_metric='Total time (inc)'):
"""Initialize SpotDBReader Args: db_key (str or SpotDB object): locator for SpotDB instance This can be a SpotDB object dir... | stack_v2_sparse_classes_75kplus_train_072912 | 5,976 | permissive | [
{
"docstring": "Initialize SpotDBReader Args: db_key (str or SpotDB object): locator for SpotDB instance This can be a SpotDB object directly, or a locator for a spot database, which is a string with either * A directory for .cali files, * A .sqlite file name * A SQL database URL (e.g., \"mysql://hostname/db\")... | 2 | stack_v2_sparse_classes_30k_train_041071 | Implement the Python class `SpotDBReader` described below.
Class description:
Import multiple runs as graph frames from a SpotDB instance
Method signatures and docstrings:
- def __init__(self, db_key, list_of_ids=None, default_metric='Total time (inc)'): Initialize SpotDBReader Args: db_key (str or SpotDB object): lo... | Implement the Python class `SpotDBReader` described below.
Class description:
Import multiple runs as graph frames from a SpotDB instance
Method signatures and docstrings:
- def __init__(self, db_key, list_of_ids=None, default_metric='Total time (inc)'): Initialize SpotDBReader Args: db_key (str or SpotDB object): lo... | 5d0efca4ea9cca03497d0b89b6ffada37242d579 | <|skeleton|>
class SpotDBReader:
"""Import multiple runs as graph frames from a SpotDB instance"""
def __init__(self, db_key, list_of_ids=None, default_metric='Total time (inc)'):
"""Initialize SpotDBReader Args: db_key (str or SpotDB object): locator for SpotDB instance This can be a SpotDB object dir... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpotDBReader:
"""Import multiple runs as graph frames from a SpotDB instance"""
def __init__(self, db_key, list_of_ids=None, default_metric='Total time (inc)'):
"""Initialize SpotDBReader Args: db_key (str or SpotDB object): locator for SpotDB instance This can be a SpotDB object directly, or a l... | the_stack_v2_python_sparse | hatchet/readers/spotdb_reader.py | LLNL/hatchet | train | 19 |
1d241961d4ad5143937af7a637711ee23c1f7a96 | [
"super(CustomResNet152, self).__init__()\nself.dim = dim\nresnet = torchvision.models.resnet152(pretrained=True)\nmodules = list(resnet.children())[:-1]\nself.resnet = nn.Sequential(*modules)\nself.linear = nn.Linear(2048, self.dim)\nif train_resnet:\n for i, child in enumerate(self.resnet.children()):\n ... | <|body_start_0|>
super(CustomResNet152, self).__init__()
self.dim = dim
resnet = torchvision.models.resnet152(pretrained=True)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.linear = nn.Linear(2048, self.dim)
if train_resnet:
... | Image encoder that computes both its image embedding and its convolutional feature map | CustomResNet152 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomResNet152:
"""Image encoder that computes both its image embedding and its convolutional feature map"""
def __init__(self, dim=1024, train_resnet=False):
"""Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets bac... | stack_v2_sparse_classes_75kplus_train_072913 | 12,660 | no_license | [
{
"docstring": "Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets backbone's weights as trainable if true",
"name": "__init__",
"signature": "def __init__(self, dim=1024, train_resnet=False)"
},
{
"docstring": "Initialize weight... | 3 | stack_v2_sparse_classes_30k_train_013526 | Implement the Python class `CustomResNet152` described below.
Class description:
Image encoder that computes both its image embedding and its convolutional feature map
Method signatures and docstrings:
- def __init__(self, dim=1024, train_resnet=False): Initializes image encoder based on ResNet :param dim: length of ... | Implement the Python class `CustomResNet152` described below.
Class description:
Image encoder that computes both its image embedding and its convolutional feature map
Method signatures and docstrings:
- def __init__(self, dim=1024, train_resnet=False): Initializes image encoder based on ResNet :param dim: length of ... | bc4fe571775e982975d6ecac82253e94de9dcd2b | <|skeleton|>
class CustomResNet152:
"""Image encoder that computes both its image embedding and its convolutional feature map"""
def __init__(self, dim=1024, train_resnet=False):
"""Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets bac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomResNet152:
"""Image encoder that computes both its image embedding and its convolutional feature map"""
def __init__(self, dim=1024, train_resnet=False):
"""Initializes image encoder based on ResNet :param dim: length of the UniVSE space embeddings :param train_resnet: sets backbone's weigh... | the_stack_v2_python_sparse | models/simplified_univse/model.py | strategist922/UniVSE | train | 0 |
2ba968b2d16f711cb4bd1b9898e1e1928fd1017b | [
"rv = []\nfor filename in os.listdir(cmd_folder):\n if filename.endswith('.py') and filename.startswith('cmd_'):\n rv.append(filename[4:-3])\nrv.sort()\nreturn rv",
"try:\n if sys.version_info[0] == 2:\n name = name.encode('ascii', 'replace')\n mod = __import__('fluctmatch.commands.cmd_' + ... | <|body_start_0|>
rv = []
for filename in os.listdir(cmd_folder):
if filename.endswith('.py') and filename.startswith('cmd_'):
rv.append(filename[4:-3])
rv.sort()
return rv
<|end_body_0|>
<|body_start_1|>
try:
if sys.version_info[0] == 2:
... | Complex command-line options with subcommands for fluctmatch. | ComplexCLI | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexCLI:
"""Complex command-line options with subcommands for fluctmatch."""
def list_commands(self, ctx):
"""List available commands. Parameters ---------- ctx : :object:`Context` click context Returns ------- List of available commands"""
<|body_0|>
def get_command(... | stack_v2_sparse_classes_75kplus_train_072914 | 3,431 | permissive | [
{
"docstring": "List available commands. Parameters ---------- ctx : :object:`Context` click context Returns ------- List of available commands",
"name": "list_commands",
"signature": "def list_commands(self, ctx)"
},
{
"docstring": "Run the selected command Parameters ---------- ctx : :class:`C... | 2 | stack_v2_sparse_classes_30k_train_013425 | Implement the Python class `ComplexCLI` described below.
Class description:
Complex command-line options with subcommands for fluctmatch.
Method signatures and docstrings:
- def list_commands(self, ctx): List available commands. Parameters ---------- ctx : :object:`Context` click context Returns ------- List of avail... | Implement the Python class `ComplexCLI` described below.
Class description:
Complex command-line options with subcommands for fluctmatch.
Method signatures and docstrings:
- def list_commands(self, ctx): List available commands. Parameters ---------- ctx : :object:`Context` click context Returns ------- List of avail... | a3682a5597cc775d2c79959e125672cd8742e659 | <|skeleton|>
class ComplexCLI:
"""Complex command-line options with subcommands for fluctmatch."""
def list_commands(self, ctx):
"""List available commands. Parameters ---------- ctx : :object:`Context` click context Returns ------- List of available commands"""
<|body_0|>
def get_command(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComplexCLI:
"""Complex command-line options with subcommands for fluctmatch."""
def list_commands(self, ctx):
"""List available commands. Parameters ---------- ctx : :object:`Context` click context Returns ------- List of available commands"""
rv = []
for filename in os.listdir(cm... | the_stack_v2_python_sparse | src/fluctmatch/cli.py | nixnmtm/python-fluctmatch | train | 0 |
89ccd82de8599c07112014d1c6fa851bacecc33d | [
"url = 'http://third.payment.pay/'\ndata = {'card_num': card_num, 'amount': amount}\nresponse = requests.post(url=url, data=data)\nreturn requests.status_codes",
"try:\n resp = self.requestOutofSystem(card_num, amount)\n print('调用第三方支付接口返回结果:%s' % resp)\nexcept TimeoutError:\n print('支付超时,重新支付')\n res... | <|body_start_0|>
url = 'http://third.payment.pay/'
data = {'card_num': card_num, 'amount': amount}
response = requests.post(url=url, data=data)
return requests.status_codes
<|end_body_0|>
<|body_start_1|>
try:
resp = self.requestOutofSystem(card_num, amount)
... | Payment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Payment:
def requestOutofSystem(self, card_num, amount):
"""请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败"""
<|body_0|>
def doPay(self, user_id, card_num, amount):
"""支付 :param user_id:用户id :param card_num:卡号 :param a... | stack_v2_sparse_classes_75kplus_train_072915 | 3,097 | no_license | [
{
"docstring": "请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败",
"name": "requestOutofSystem",
"signature": "def requestOutofSystem(self, card_num, amount)"
},
{
"docstring": "支付 :param user_id:用户id :param card_num:卡号 :param amount: 支付金额 :return:"... | 2 | stack_v2_sparse_classes_30k_train_011708 | Implement the Python class `Payment` described below.
Class description:
Implement the Payment class.
Method signatures and docstrings:
- def requestOutofSystem(self, card_num, amount): 请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败
- def doPay(self, user_id, card_num,... | Implement the Python class `Payment` described below.
Class description:
Implement the Payment class.
Method signatures and docstrings:
- def requestOutofSystem(self, card_num, amount): 请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败
- def doPay(self, user_id, card_num,... | 8f10d3c70ab785d4120d24673b0945a169f2355c | <|skeleton|>
class Payment:
def requestOutofSystem(self, card_num, amount):
"""请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败"""
<|body_0|>
def doPay(self, user_id, card_num, amount):
"""支付 :param user_id:用户id :param card_num:卡号 :param a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Payment:
def requestOutofSystem(self, card_num, amount):
"""请求第三方外部支付接口,并返回响应码 :param card_num: 卡号 :param amount: 支付金额 :return: 返回状态码,200代表支付成功,500代表支付异常失败"""
url = 'http://third.payment.pay/'
data = {'card_num': card_num, 'amount': amount}
response = requests.post(url=url, dat... | the_stack_v2_python_sparse | mystudy/mockdemo/mock_03.py | zhenfang95/Hello-World | train | 0 | |
703232a621d6c94a7c084dfac8099e2a409e4695 | [
"osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)\nself.deploy._CheckDeployType()\nself.assertTrue(self.getCopyPath('envoy_shell'))\nself.assertFalse(self.getCopyPath('app_shell'))\nself.assertFalse(self.getCopyPath('chrome'))",
"osutils.Touch(os.path.join(self.deploy.optio... | <|body_start_0|>
osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)
self.deploy._CheckDeployType()
self.assertTrue(self.getCopyPath('envoy_shell'))
self.assertFalse(self.getCopyPath('app_shell'))
self.assertFalse(self.getCopyPath('chrome'))
<... | Test detection of deployment type using build dir. | TestDeploymentType | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDeploymentType:
"""Test detection of deployment type using build dir."""
def testEnvoyDetection(self):
"""Check for an envoy deployment"""
<|body_0|>
def testAppShellDetection(self):
"""Check for an app_shell deployment"""
<|body_1|>
def testChro... | stack_v2_sparse_classes_75kplus_train_072916 | 13,041 | permissive | [
{
"docstring": "Check for an envoy deployment",
"name": "testEnvoyDetection",
"signature": "def testEnvoyDetection(self)"
},
{
"docstring": "Check for an app_shell deployment",
"name": "testAppShellDetection",
"signature": "def testAppShellDetection(self)"
},
{
"docstring": "Chec... | 4 | stack_v2_sparse_classes_30k_train_050209 | Implement the Python class `TestDeploymentType` described below.
Class description:
Test detection of deployment type using build dir.
Method signatures and docstrings:
- def testEnvoyDetection(self): Check for an envoy deployment
- def testAppShellDetection(self): Check for an app_shell deployment
- def testChromeAn... | Implement the Python class `TestDeploymentType` described below.
Class description:
Test detection of deployment type using build dir.
Method signatures and docstrings:
- def testEnvoyDetection(self): Check for an envoy deployment
- def testAppShellDetection(self): Check for an app_shell deployment
- def testChromeAn... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TestDeploymentType:
"""Test detection of deployment type using build dir."""
def testEnvoyDetection(self):
"""Check for an envoy deployment"""
<|body_0|>
def testAppShellDetection(self):
"""Check for an app_shell deployment"""
<|body_1|>
def testChro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDeploymentType:
"""Test detection of deployment type using build dir."""
def testEnvoyDetection(self):
"""Check for an envoy deployment"""
osutils.Touch(os.path.join(self.deploy.options.build_dir, 'envoy_shell'), makedirs=True)
self.deploy._CheckDeployType()
self.asser... | the_stack_v2_python_sparse | third_party/chromite/scripts/deploy_chrome_unittest.py | metux/chromium-suckless | train | 5 |
f81468dd4ab0c156e5b11c3c8f20f2dfae846e8f | [
"image = np.asfarray(image)\nself.image = color.rgb2gray(image)\nself.image = dwi.util.flip_minmax(self.image)\nself.voxel_size = voxel_size\nself.set_kwargs(**kwargs)",
"mm = 1 / self.voxel_size\nself.blob_ka = dict(min_sigma=5 * mm, max_sigma=12 * mm, overlap=0.5)\nself.log_ka = dict(num_sigma=5, threshold=0.1,... | <|body_start_0|>
image = np.asfarray(image)
self.image = color.rgb2gray(image)
self.image = dwi.util.flip_minmax(self.image)
self.voxel_size = voxel_size
self.set_kwargs(**kwargs)
<|end_body_0|>
<|body_start_1|>
mm = 1 / self.voxel_size
self.blob_ka = dict(min_si... | ... | BlobDetector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlobDetector:
"""..."""
def __init__(self, image, voxel_size, **kwargs):
"""..."""
<|body_0|>
def set_kwargs(self, blob_ka={}, log_ka={}, dog_ka={}, doh_ka={}):
"""Set keyword arguments for blob detection functions."""
<|body_1|>
def log(self):
... | stack_v2_sparse_classes_75kplus_train_072917 | 13,518 | permissive | [
{
"docstring": "...",
"name": "__init__",
"signature": "def __init__(self, image, voxel_size, **kwargs)"
},
{
"docstring": "Set keyword arguments for blob detection functions.",
"name": "set_kwargs",
"signature": "def set_kwargs(self, blob_ka={}, log_ka={}, dog_ka={}, doh_ka={})"
},
... | 6 | stack_v2_sparse_classes_30k_train_030008 | Implement the Python class `BlobDetector` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self, image, voxel_size, **kwargs): ...
- def set_kwargs(self, blob_ka={}, log_ka={}, dog_ka={}, doh_ka={}): Set keyword arguments for blob detection functions.
- def log(self): Laplacian... | Implement the Python class `BlobDetector` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self, image, voxel_size, **kwargs): ...
- def set_kwargs(self, blob_ka={}, log_ka={}, dog_ka={}, doh_ka={}): Set keyword arguments for blob detection functions.
- def log(self): Laplacian... | 6655eea21037977ed528b992b3a8471393127b77 | <|skeleton|>
class BlobDetector:
"""..."""
def __init__(self, image, voxel_size, **kwargs):
"""..."""
<|body_0|>
def set_kwargs(self, blob_ka={}, log_ka={}, dog_ka={}, doh_ka={}):
"""Set keyword arguments for blob detection functions."""
<|body_1|>
def log(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlobDetector:
"""..."""
def __init__(self, image, voxel_size, **kwargs):
"""..."""
image = np.asfarray(image)
self.image = color.rgb2gray(image)
self.image = dwi.util.flip_minmax(self.image)
self.voxel_size = voxel_size
self.set_kwargs(**kwargs)
def se... | the_stack_v2_python_sparse | dwi/detectlesion.py | AdamWu1979/dwilib | train | 0 |
094f280dc466524908b45ac12649a475e517111e | [
"super(AttentionMask, self).__init__()\nself.causal = causal\nself.mask_value = mask_value\nif not isinstance(mask_value, float):\n raise ValueError('Mask value must be a float.')",
"batch_size = tf.shape(inp)[0]\nmax_seq_len = tf.shape(inp)[1]\nflat_seq_mask = Masking(mask_value=0.0).compute_mask(inp)\nseq_ma... | <|body_start_0|>
super(AttentionMask, self).__init__()
self.causal = causal
self.mask_value = mask_value
if not isinstance(mask_value, float):
raise ValueError('Mask value must be a float.')
<|end_body_0|>
<|body_start_1|>
batch_size = tf.shape(inp)[0]
max_se... | Computes attention mask. | AttentionMask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionMask:
"""Computes attention mask."""
def __init__(self, causal, mask_value=-1000000000.0):
"""Argument/s: causal - causal attention mask flag. mask_value - value used to mask components that aren't to be attended to (typically -1e9)."""
<|body_0|>
def call(self,... | stack_v2_sparse_classes_75kplus_train_072918 | 12,314 | no_license | [
{
"docstring": "Argument/s: causal - causal attention mask flag. mask_value - value used to mask components that aren't to be attended to (typically -1e9).",
"name": "__init__",
"signature": "def __init__(self, causal, mask_value=-1000000000.0)"
},
{
"docstring": "Compute attention mask. Argumen... | 4 | stack_v2_sparse_classes_30k_train_009283 | Implement the Python class `AttentionMask` described below.
Class description:
Computes attention mask.
Method signatures and docstrings:
- def __init__(self, causal, mask_value=-1000000000.0): Argument/s: causal - causal attention mask flag. mask_value - value used to mask components that aren't to be attended to (t... | Implement the Python class `AttentionMask` described below.
Class description:
Computes attention mask.
Method signatures and docstrings:
- def __init__(self, causal, mask_value=-1000000000.0): Argument/s: causal - causal attention mask flag. mask_value - value used to mask components that aren't to be attended to (t... | e455ea79ae1522397c1f46a9fc1ac65a7fabe295 | <|skeleton|>
class AttentionMask:
"""Computes attention mask."""
def __init__(self, causal, mask_value=-1000000000.0):
"""Argument/s: causal - causal attention mask flag. mask_value - value used to mask components that aren't to be attended to (typically -1e9)."""
<|body_0|>
def call(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttentionMask:
"""Computes attention mask."""
def __init__(self, causal, mask_value=-1000000000.0):
"""Argument/s: causal - causal attention mask flag. mask_value - value used to mask components that aren't to be attended to (typically -1e9)."""
super(AttentionMask, self).__init__()
... | the_stack_v2_python_sparse | models/snr_estimation/network/attention.py | celpas/SpeakerIdentificationSystem | train | 2 |
97bc0017f7fd2828023604518e36d0bfaf3fe51a | [
"super().__init__()\nself.dropout = nn.Dropout(p=dropout)\nself.layers = numlayers\nself.dirs = 2 if bidirectional else 1\nself.hsz = hiddensize\nif input_dropout > 0 and unknown_idx is None:\n raise RuntimeError('input_dropout > 0 but unknown_idx not set')\nself.input_dropout = UnknownDropout(unknown_idx, input... | <|body_start_0|>
super().__init__()
self.dropout = nn.Dropout(p=dropout)
self.layers = numlayers
self.dirs = 2 if bidirectional else 1
self.hsz = hiddensize
if input_dropout > 0 and unknown_idx is None:
raise RuntimeError('input_dropout > 0 but unknown_idx not... | RNN Encoder. | RNNEncoder | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""RNN Encoder."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False):
"""Initialize recurrent encode... | stack_v2_sparse_classes_75kplus_train_072919 | 29,402 | permissive | [
{
"docstring": "Initialize recurrent encoder.",
"name": "__init__",
"signature": "def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False)"... | 2 | null | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder.
Method signatures and docstrings:
- def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unk... | Implement the Python class `RNNEncoder` described below.
Class description:
RNN Encoder.
Method signatures and docstrings:
- def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unk... | ccf60824b28f0ce8ceda44a7ce52a0d117669115 | <|skeleton|>
class RNNEncoder:
"""RNN Encoder."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False):
"""Initialize recurrent encode... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNEncoder:
"""RNN Encoder."""
def __init__(self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=False):
"""Initialize recurrent encoder."""
... | the_stack_v2_python_sparse | ParlAI/parlai/agents/legacy_agents/seq2seq/modules_v1.py | ethanjperez/convince | train | 27 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nassert len(fft_sizes) == len(hop_sizes) == len(win_lengths)\nself.stft_losses = nn.LayerList()\nfor fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):\n self.stft_losses.append(STFTLoss(fs, ss, wl, window))",
"if len(x.shape) == 3:\n x = x.reshape([-1, x.shape[2]])\n y = y.reshape... | <|body_start_0|>
super().__init__()
assert len(fft_sizes) == len(hop_sizes) == len(win_lengths)
self.stft_losses = nn.LayerList()
for fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):
self.stft_losses.append(STFTLoss(fs, ss, wl, window))
<|end_body_0|>
<|body_start_1|>
... | Multi resolution STFT loss module. | MultiResolutionSTFTLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_si... | stack_v2_sparse_classes_75kplus_train_072920 | 46,210 | permissive | [
{
"docstring": "Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_sizes (list): List of hop sizes. win_lengths (list): List of window lengths. window (str): Window function type.",
"name": "__init__",
"signature": "def __init__(self, fft_sizes=[1024, 2048, 512]... | 2 | stack_v2_sparse_classes_30k_train_017324 | Implement the Python class `MultiResolutionSTFTLoss` described below.
Class description:
Multi resolution STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'): Initialize Multi resolution STFT loss ... | Implement the Python class `MultiResolutionSTFTLoss` described below.
Class description:
Multi resolution STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'): Initialize Multi resolution STFT loss ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_sizes (list): L... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
9ed31c2f4c0dae8f3995fec816b80c90453d2389 | [
"self.writers = writerList\nself.allowedProblemNumbers = allowedProblems\nself.allowedLanguages = allowedLanguages\nself.allocation_queue = queue.PriorityQueue()\nself.writer_queue = queue.PriorityQueue()\nself.populate_allocation_queue(allZeroes=fromScratch)",
"try:\n nextProblem = self.allocation_queue.get_n... | <|body_start_0|>
self.writers = writerList
self.allowedProblemNumbers = allowedProblems
self.allowedLanguages = allowedLanguages
self.allocation_queue = queue.PriorityQueue()
self.writer_queue = queue.PriorityQueue()
self.populate_allocation_queue(allZeroes=fromScratch)
<... | An object used to assign problems and languages to various solution writers | AssignmentAllocator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignmentAllocator:
"""An object used to assign problems and languages to various solution writers"""
def __init__(self, allowedProblems: list, allowedLanguages: list, writerList: list, fromScratch=False):
"""Create a new assignment allocator by providing a list of allowed problem n... | stack_v2_sparse_classes_75kplus_train_072921 | 11,436 | no_license | [
{
"docstring": "Create a new assignment allocator by providing a list of allowed problem numbers (where each element is an int) and a list of allowed languages (where each element is a Language object)",
"name": "__init__",
"signature": "def __init__(self, allowedProblems: list, allowedLanguages: list, ... | 4 | stack_v2_sparse_classes_30k_val_000589 | Implement the Python class `AssignmentAllocator` described below.
Class description:
An object used to assign problems and languages to various solution writers
Method signatures and docstrings:
- def __init__(self, allowedProblems: list, allowedLanguages: list, writerList: list, fromScratch=False): Create a new assi... | Implement the Python class `AssignmentAllocator` described below.
Class description:
An object used to assign problems and languages to various solution writers
Method signatures and docstrings:
- def __init__(self, allowedProblems: list, allowedLanguages: list, writerList: list, fromScratch=False): Create a new assi... | b640bda2aaee31e1aeaf887b4a9e329d5304d791 | <|skeleton|>
class AssignmentAllocator:
"""An object used to assign problems and languages to various solution writers"""
def __init__(self, allowedProblems: list, allowedLanguages: list, writerList: list, fromScratch=False):
"""Create a new assignment allocator by providing a list of allowed problem n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssignmentAllocator:
"""An object used to assign problems and languages to various solution writers"""
def __init__(self, allowedProblems: list, allowedLanguages: list, writerList: list, fromScratch=False):
"""Create a new assignment allocator by providing a list of allowed problem numbers (where... | the_stack_v2_python_sparse | Solutions/dev/util/subparsers/subparsers/writersassign.py | brandonio21/PyCFramework | train | 0 |
25f270f640e3e584c90da6cdc143480c60e589af | [
"asyncore.dispatcher.__init__(self)\nself.create_socket(socket.AF_INET, socket.SOCK_STREAM)\nself.set_reuse_addr()\nself.bind((host, port))\nself.listen(1)",
"pair = self.accept()\nif pair is not None:\n sock, addr = pair\n RPCHandle(sock, addr)",
"for i in range(n):\n pid = os.fork()\n if pid < 0:\... | <|body_start_0|>
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(1)
<|end_body_0|>
<|body_start_1|>
pair = self.accept()
if pair is not None:
sock, add... | RPCServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPCServer:
def __init__(self, host, port):
"""初始化server"""
<|body_0|>
def handle_accept(self):
"""处理连接"""
<|body_1|>
def prefork(self, n=10):
"""开启多进程"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
asyncore.dispatcher.__init__(... | stack_v2_sparse_classes_75kplus_train_072922 | 11,496 | no_license | [
{
"docstring": "初始化server",
"name": "__init__",
"signature": "def __init__(self, host, port)"
},
{
"docstring": "处理连接",
"name": "handle_accept",
"signature": "def handle_accept(self)"
},
{
"docstring": "开启多进程",
"name": "prefork",
"signature": "def prefork(self, n=10)"
}... | 3 | stack_v2_sparse_classes_30k_train_015806 | Implement the Python class `RPCServer` described below.
Class description:
Implement the RPCServer class.
Method signatures and docstrings:
- def __init__(self, host, port): 初始化server
- def handle_accept(self): 处理连接
- def prefork(self, n=10): 开启多进程 | Implement the Python class `RPCServer` described below.
Class description:
Implement the RPCServer class.
Method signatures and docstrings:
- def __init__(self, host, port): 初始化server
- def handle_accept(self): 处理连接
- def prefork(self, n=10): 开启多进程
<|skeleton|>
class RPCServer:
def __init__(self, host, port):
... | 3b16cf261b153ef9525fff592a34e8c5bd842f80 | <|skeleton|>
class RPCServer:
def __init__(self, host, port):
"""初始化server"""
<|body_0|>
def handle_accept(self):
"""处理连接"""
<|body_1|>
def prefork(self, n=10):
"""开启多进程"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RPCServer:
def __init__(self, host, port):
"""初始化server"""
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(1)
def handle_accept(self):
"""处理连接"""
... | the_stack_v2_python_sparse | rpc_server.py | Jevade/python_script | train | 0 | |
472ddc989d8451afb6fedb4bb5c8347c77d03ee6 | [
"self.input_dir_back = input_dir\nself.input_type = input_type\nif self.input_type == 1:\n input_dir_split = input_dir.split('/')\n input_dir = '/'.join(input_dir_split[:-1])\n input_file = input_dir\nself.algorithms = algorithms\n' List of segmentation algorithms '\nself.metrics = metrics\n' List of metri... | <|body_start_0|>
self.input_dir_back = input_dir
self.input_type = input_type
if self.input_type == 1:
input_dir_split = input_dir.split('/')
input_dir = '/'.join(input_dir_split[:-1])
input_file = input_dir
self.algorithms = algorithms
' List ... | A class to create a table with general metrics for different algorithms :param algorithms: List of segmentation algorithms :type algorithms: list :param metrics: List of metrics :type metrics: list :param input_dir: Name of input directory :type input_dir: str :param vis_settings: Dictionary with visualization settings... | MetricsWriter | [
"BSD-3-Clause-LBNL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricsWriter:
"""A class to create a table with general metrics for different algorithms :param algorithms: List of segmentation algorithms :type algorithms: list :param metrics: List of metrics :type metrics: list :param input_dir: Name of input directory :type input_dir: str :param vis_setting... | stack_v2_sparse_classes_75kplus_train_072923 | 2,984 | permissive | [
{
"docstring": "Initialize MetricsWriter",
"name": "__init__",
"signature": "def __init__(self, algorithms, metrics, input_dir, input_type, vis_settings, in_memory, run_number)"
},
{
"docstring": "Function to create table with general metrics and visualize graphics",
"name": "createTable",
... | 2 | stack_v2_sparse_classes_30k_train_045032 | Implement the Python class `MetricsWriter` described below.
Class description:
A class to create a table with general metrics for different algorithms :param algorithms: List of segmentation algorithms :type algorithms: list :param metrics: List of metrics :type metrics: list :param input_dir: Name of input directory ... | Implement the Python class `MetricsWriter` described below.
Class description:
A class to create a table with general metrics for different algorithms :param algorithms: List of segmentation algorithms :type algorithms: list :param metrics: List of metrics :type metrics: list :param input_dir: Name of input directory ... | 6942a44d7acde1e1480bee0409b377c8ee4c246d | <|skeleton|>
class MetricsWriter:
"""A class to create a table with general metrics for different algorithms :param algorithms: List of segmentation algorithms :type algorithms: list :param metrics: List of metrics :type metrics: list :param input_dir: Name of input directory :type input_dir: str :param vis_setting... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetricsWriter:
"""A class to create a table with general metrics for different algorithms :param algorithms: List of segmentation algorithms :type algorithms: list :param metrics: List of metrics :type metrics: list :param input_dir: Name of input directory :type input_dir: str :param vis_settings: Dictionary... | the_stack_v2_python_sparse | src/metrics/general/MetricsWriter.py | CameraIA/MSM | train | 1 |
762c479b0e1ec339deb147fd4ba85be8d3431efc | [
"super(MyRNN, self).__init__()\nself.hidden_size = hidden_size\nself.w_h = nn.Parameter(torch.rand(input_size, hidden_size))\nself.u_h = nn.Parameter(torch.rand(hidden_size, hidden_size))\nself.b_h = nn.Parameter(torch.zeros(hidden_size))\nself.w_y = nn.Parameter(torch.rand(hidden_size, output_size))\nself.b_y = nn... | <|body_start_0|>
super(MyRNN, self).__init__()
self.hidden_size = hidden_size
self.w_h = nn.Parameter(torch.rand(input_size, hidden_size))
self.u_h = nn.Parameter(torch.rand(hidden_size, hidden_size))
self.b_h = nn.Parameter(torch.zeros(hidden_size))
self.w_y = nn.Paramet... | MyRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyRNN:
def __init__(self, input_size, hidden_size, output_size):
""":param input_size: 指定输入数据的维度。例如,对于简单的时间序列预测问题,每一步的输入均为一个采样值,因此input_size=1. :param hidden_size: 指定隐藏状态的维度。这个值并不受输入和输出控制,但会影响模型的容量. :param output_size: 指定输出数据的维度,此值取决于具体的预测要求。例如,对简单的时间序列预测问题, output_size=1."""
<|b... | stack_v2_sparse_classes_75kplus_train_072924 | 4,891 | no_license | [
{
"docstring": ":param input_size: 指定输入数据的维度。例如,对于简单的时间序列预测问题,每一步的输入均为一个采样值,因此input_size=1. :param hidden_size: 指定隐藏状态的维度。这个值并不受输入和输出控制,但会影响模型的容量. :param output_size: 指定输出数据的维度,此值取决于具体的预测要求。例如,对简单的时间序列预测问题, output_size=1.",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size, ou... | 2 | stack_v2_sparse_classes_30k_train_001056 | Implement the Python class `MyRNN` described below.
Class description:
Implement the MyRNN class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, output_size): :param input_size: 指定输入数据的维度。例如,对于简单的时间序列预测问题,每一步的输入均为一个采样值,因此input_size=1. :param hidden_size: 指定隐藏状态的维度。这个值并不受输入和输出控制,但会影响模型... | Implement the Python class `MyRNN` described below.
Class description:
Implement the MyRNN class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, output_size): :param input_size: 指定输入数据的维度。例如,对于简单的时间序列预测问题,每一步的输入均为一个采样值,因此input_size=1. :param hidden_size: 指定隐藏状态的维度。这个值并不受输入和输出控制,但会影响模型... | e66be80a44537ae034925df0fe322598d360f38c | <|skeleton|>
class MyRNN:
def __init__(self, input_size, hidden_size, output_size):
""":param input_size: 指定输入数据的维度。例如,对于简单的时间序列预测问题,每一步的输入均为一个采样值,因此input_size=1. :param hidden_size: 指定隐藏状态的维度。这个值并不受输入和输出控制,但会影响模型的容量. :param output_size: 指定输出数据的维度,此值取决于具体的预测要求。例如,对简单的时间序列预测问题, output_size=1."""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyRNN:
def __init__(self, input_size, hidden_size, output_size):
""":param input_size: 指定输入数据的维度。例如,对于简单的时间序列预测问题,每一步的输入均为一个采样值,因此input_size=1. :param hidden_size: 指定隐藏状态的维度。这个值并不受输入和输出控制,但会影响模型的容量. :param output_size: 指定输出数据的维度,此值取决于具体的预测要求。例如,对简单的时间序列预测问题, output_size=1."""
super(MyRNN, self... | the_stack_v2_python_sparse | 实验四/core/model.py | 346644054/deep-learning-course-code | train | 0 | |
46bc95112f8930cfc3a979df2a5ad43a6ae9cd43 | [
"if n == 0:\n return 1\nelif n == 1:\n return 1\nelse:\n return self.climbStairs(n - 1) + self.climbStairs(n - 2)",
"if n <= 2:\n return n\npoint1 = 1\npoint2 = 2\nfor i in range(3, n + 1):\n temp = point1 + point2\n point1 = point2\n point2 = temp\nreturn point2"
] | <|body_start_0|>
if n == 0:
return 1
elif n == 1:
return 1
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
<|end_body_0|>
<|body_start_1|>
if n <= 2:
return n
point1 = 1
point2 = 2
for i in range(3, n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int 超出时间限制2333,从后往前看"""
<|body_0|>
def climbStairs1(self, n):
"""从前往后看"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return 1
elif n == 1:
retur... | stack_v2_sparse_classes_75kplus_train_072925 | 1,031 | no_license | [
{
"docstring": ":type n: int :rtype: int 超出时间限制2333,从后往前看",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": "从前往后看",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001217 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int 超出时间限制2333,从后往前看
- def climbStairs1(self, n): 从前往后看 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int 超出时间限制2333,从后往前看
- def climbStairs1(self, n): 从前往后看
<|skeleton|>
class Solution:
def climbStairs(self, n):
""":ty... | 2dc982e690b153c33bc7e27a63604f754a0df90c | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int 超出时间限制2333,从后往前看"""
<|body_0|>
def climbStairs1(self, n):
"""从前往后看"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int 超出时间限制2333,从后往前看"""
if n == 0:
return 1
elif n == 1:
return 1
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
def climbStairs1(self, n):
"""从前往后看"""
... | the_stack_v2_python_sparse | 70_climbing-stairs.py | 95275059/Algorithm | train | 0 | |
f03440f4918b1cf3bddc4044ae371b24da2e5d5b | [
"username = attrs['username']\npassword = attrs['password']\ntry:\n user = User.objects.get(username=username, is_staff=True)\nexcept User.DoesNotExit:\n raise serializers.ValidationError('手机号或密码错误')\nif not user.check_password(password):\n raise serializers.ValidationError('手机号或密码错误')\nattrs['user'] = use... | <|body_start_0|>
username = attrs['username']
password = attrs['password']
try:
user = User.objects.get(username=username, is_staff=True)
except User.DoesNotExit:
raise serializers.ValidationError('手机号或密码错误')
if not user.check_password(password):
... | 验证序列化器类 | AuthorizationSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorizationSerializer:
"""验证序列化器类"""
def validate(self, attrs):
"""自定义验证用户名和密码"""
<|body_0|>
def create(self, validated_data):
"""重新增加一个jwt"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
username = attrs['username']
password = attrs['... | stack_v2_sparse_classes_75kplus_train_072926 | 3,173 | permissive | [
{
"docstring": "自定义验证用户名和密码",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "重新增加一个jwt",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000529 | Implement the Python class `AuthorizationSerializer` described below.
Class description:
验证序列化器类
Method signatures and docstrings:
- def validate(self, attrs): 自定义验证用户名和密码
- def create(self, validated_data): 重新增加一个jwt | Implement the Python class `AuthorizationSerializer` described below.
Class description:
验证序列化器类
Method signatures and docstrings:
- def validate(self, attrs): 自定义验证用户名和密码
- def create(self, validated_data): 重新增加一个jwt
<|skeleton|>
class AuthorizationSerializer:
"""验证序列化器类"""
def validate(self, attrs):
... | d3ce2185ec3c68325e8becddce07d0a9da144325 | <|skeleton|>
class AuthorizationSerializer:
"""验证序列化器类"""
def validate(self, attrs):
"""自定义验证用户名和密码"""
<|body_0|>
def create(self, validated_data):
"""重新增加一个jwt"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthorizationSerializer:
"""验证序列化器类"""
def validate(self, attrs):
"""自定义验证用户名和密码"""
username = attrs['username']
password = attrs['password']
try:
user = User.objects.get(username=username, is_staff=True)
except User.DoesNotExit:
raise seria... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/serializers/users.py | qls7/dianshanghoutai | train | 0 |
f32e5b16a0b8fc2faf1eb529e72dc883284ca008 | [
"args = parser.parse_args()\nqnodes = [node]\nif args.cnode is not None:\n qnodes += args.cnode\nont = get_ontology(ontology)\nrelations = args.relation\nlog.info('Traversing: {} using {}'.format(qnodes, relations))\nnodes = ont.traverse_nodes(qnodes, up=args.include_ancestors, down=args.include_descendants, rel... | <|body_start_0|>
args = parser.parse_args()
qnodes = [node]
if args.cnode is not None:
qnodes += args.cnode
ont = get_ontology(ontology)
relations = args.relation
log.info('Traversing: {} using {}'.format(qnodes, relations))
nodes = ont.traverse_nodes(... | ExtractOntologySubgraphResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractOntologySubgraphResource:
def get(self, ontology, node):
"""Extract a subgraph from an ontology"""
<|body_0|>
def post(self, ontology, node):
"""Extract a subgraph from an ontology"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = parser... | stack_v2_sparse_classes_75kplus_train_072927 | 2,678 | permissive | [
{
"docstring": "Extract a subgraph from an ontology",
"name": "get",
"signature": "def get(self, ontology, node)"
},
{
"docstring": "Extract a subgraph from an ontology",
"name": "post",
"signature": "def post(self, ontology, node)"
}
] | 2 | null | Implement the Python class `ExtractOntologySubgraphResource` described below.
Class description:
Implement the ExtractOntologySubgraphResource class.
Method signatures and docstrings:
- def get(self, ontology, node): Extract a subgraph from an ontology
- def post(self, ontology, node): Extract a subgraph from an onto... | Implement the Python class `ExtractOntologySubgraphResource` described below.
Class description:
Implement the ExtractOntologySubgraphResource class.
Method signatures and docstrings:
- def get(self, ontology, node): Extract a subgraph from an ontology
- def post(self, ontology, node): Extract a subgraph from an onto... | 881e108912174f33f9d69f5e36ee779733d6618f | <|skeleton|>
class ExtractOntologySubgraphResource:
def get(self, ontology, node):
"""Extract a subgraph from an ontology"""
<|body_0|>
def post(self, ontology, node):
"""Extract a subgraph from an ontology"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtractOntologySubgraphResource:
def get(self, ontology, node):
"""Extract a subgraph from an ontology"""
args = parser.parse_args()
qnodes = [node]
if args.cnode is not None:
qnodes += args.cnode
ont = get_ontology(ontology)
relations = args.relatio... | the_stack_v2_python_sparse | biolink/api/ontol/endpoints/subgraph.py | monarch-initiative/biolink-api | train | 8 | |
01e8bea3c5104e64f7901f6e7a0a6688bb959d12 | [
"super().__init__()\nimport sklearn\nimport sklearn.svm\nself.model = sklearn.svm.NuSVC",
"specs = super(NuSVC, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{NuSVC} \\\\textit{Nu-Support Vector Classification} is an Nu-Support Vector Classification.\\n It is very si... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.NuSVC
<|end_body_0|>
<|body_start_1|>
specs = super(NuSVC, cls).getInputSpecification()
specs.description = 'The \\xmlNode{NuSVC} \\textit{Nu-Support Vector Classification} is ... | Support Vector Classifier | NuSVC | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NuSVC:
"""Support Vector Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies t... | stack_v2_sparse_classes_75kplus_train_072928 | 9,261 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | stack_v2_sparse_classes_30k_train_029647 | Implement the Python class `NuSVC` described below.
Class description:
Support Vector Classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a reference to a c... | Implement the Python class `NuSVC` described below.
Class description:
Support Vector Classifier
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Method to get a reference to a c... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class NuSVC:
"""Support Vector Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NuSVC:
"""Support Vector Classifier"""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.svm
self.model = sklearn.svm.NuSVC
def getInput... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/SVM/NuSVC.py | idaholab/raven | train | 201 |
39b17239a3a3658044307180c9ddcefa60dca73d | [
"self.__phone_number = phone_number\nself.__password_hash = password_hash\nself.__connection = connection\nself.__first_name = first_name\nself.__middle_name = middle_name\nself.__last_name = last_name\nself.__dob = dob",
"try:\n cursor = self.__connection.cursor()\n cursor.execute('insert into neutron_buye... | <|body_start_0|>
self.__phone_number = phone_number
self.__password_hash = password_hash
self.__connection = connection
self.__first_name = first_name
self.__middle_name = middle_name
self.__last_name = last_name
self.__dob = dob
<|end_body_0|>
<|body_start_1|>
... | This class is used to create a new buyer account | BuyerSignUp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuyerSignUp:
"""This class is used to create a new buyer account"""
def __init__(self, phone_number, password_hash, first_name, middle_name, last_name, dob, connection):
"""Constructor to initialize the instance variables. :param phone_number: The phone number of the buyer :param pas... | stack_v2_sparse_classes_75kplus_train_072929 | 2,462 | no_license | [
{
"docstring": "Constructor to initialize the instance variables. :param phone_number: The phone number of the buyer :param password_hash: The sha512 hash of the password of the buyer :param first_name: First Name of the buyer :param last_name: Last Name of the buyer :param middle_name: Middle Name of the buyer... | 2 | stack_v2_sparse_classes_30k_train_017393 | Implement the Python class `BuyerSignUp` described below.
Class description:
This class is used to create a new buyer account
Method signatures and docstrings:
- def __init__(self, phone_number, password_hash, first_name, middle_name, last_name, dob, connection): Constructor to initialize the instance variables. :par... | Implement the Python class `BuyerSignUp` described below.
Class description:
This class is used to create a new buyer account
Method signatures and docstrings:
- def __init__(self, phone_number, password_hash, first_name, middle_name, last_name, dob, connection): Constructor to initialize the instance variables. :par... | c3b067492b9ffa885323f457a6e101ced8dcef06 | <|skeleton|>
class BuyerSignUp:
"""This class is used to create a new buyer account"""
def __init__(self, phone_number, password_hash, first_name, middle_name, last_name, dob, connection):
"""Constructor to initialize the instance variables. :param phone_number: The phone number of the buyer :param pas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuyerSignUp:
"""This class is used to create a new buyer account"""
def __init__(self, phone_number, password_hash, first_name, middle_name, last_name, dob, connection):
"""Constructor to initialize the instance variables. :param phone_number: The phone number of the buyer :param password_hash: T... | the_stack_v2_python_sparse | Neutron/buyer/sign_up.py | VISWESWARAN1998/Neutron | train | 6 |
a8158003a712984d92ac5510fe6a4656fea84fab | [
"self.enabled = enabled\nself._contract = None\nif not enabled:\n return\nif error is None:\n pass\nelif isinstance(error, type):\n if not issubclass(error, BaseException):\n raise ValueError('The error of the contract is given as a type, but the type does not inherit from BaseException: {}'.format(... | <|body_start_0|>
self.enabled = enabled
self._contract = None
if not enabled:
return
if error is None:
pass
elif isinstance(error, type):
if not issubclass(error, BaseException):
raise ValueError('The error of the contract is gi... | Decorate a function with a postcondition. The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument "result" is reserved for the result of the wrapped function. The wrapped function must not have "result" among its arguments. | ensure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ensure:
"""Decorate a function with a postcondition. The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument "result" is reserved for the result of the wrapped function. The wrapped function must not have "result" among i... | stack_v2_sparse_classes_75kplus_train_072930 | 16,996 | permissive | [
{
"docstring": "Initialize. :param condition: postcondition predicate. If the condition returns a coroutine, you must specify the `error` as coroutines have side effects and can not be recomputed. :param description: textual description of the postcondition :param a_repr: representation instance that defines ho... | 2 | stack_v2_sparse_classes_30k_train_010215 | Implement the Python class `ensure` described below.
Class description:
Decorate a function with a postcondition. The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument "result" is reserved for the result of the wrapped function. The wrapped ... | Implement the Python class `ensure` described below.
Class description:
Decorate a function with a postcondition. The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument "result" is reserved for the result of the wrapped function. The wrapped ... | 1883ed04f0684705727c2a03eaa50446de29d733 | <|skeleton|>
class ensure:
"""Decorate a function with a postcondition. The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument "result" is reserved for the result of the wrapped function. The wrapped function must not have "result" among i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ensure:
"""Decorate a function with a postcondition. The arguments of the postcondition are expected to be a subset of the arguments of the wrapped function. Additionally, the argument "result" is reserved for the result of the wrapped function. The wrapped function must not have "result" among its arguments.... | the_stack_v2_python_sparse | icontract/_decorators.py | Parquery/icontract | train | 324 |
84d9b8901cc3d22d250bc8973dce1eb989f87800 | [
"if not create:\n return\nif extracted:\n for channel in extracted:\n self.channels.add(channel)",
"if not create:\n return\nif extracted:\n for user in extracted:\n self.users.add(user)"
] | <|body_start_0|>
if not create:
return
if extracted:
for channel in extracted:
self.channels.add(channel)
<|end_body_0|>
<|body_start_1|>
if not create:
return
if extracted:
for user in extracted:
self.users... | Factory for Moira Lists | MoiraListFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoiraListFactory:
"""Factory for Moira Lists"""
def channels(self, create, extracted, **kwargs):
"""Create associated channels"""
<|body_0|>
def users(self, create, extracted, **kwargs):
"""Create associated users"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_072931 | 1,035 | permissive | [
{
"docstring": "Create associated channels",
"name": "channels",
"signature": "def channels(self, create, extracted, **kwargs)"
},
{
"docstring": "Create associated users",
"name": "users",
"signature": "def users(self, create, extracted, **kwargs)"
}
] | 2 | null | Implement the Python class `MoiraListFactory` described below.
Class description:
Factory for Moira Lists
Method signatures and docstrings:
- def channels(self, create, extracted, **kwargs): Create associated channels
- def users(self, create, extracted, **kwargs): Create associated users | Implement the Python class `MoiraListFactory` described below.
Class description:
Factory for Moira Lists
Method signatures and docstrings:
- def channels(self, create, extracted, **kwargs): Create associated channels
- def users(self, create, extracted, **kwargs): Create associated users
<|skeleton|>
class MoiraLis... | ba7442482da97d463302658c0aac989567ee1241 | <|skeleton|>
class MoiraListFactory:
"""Factory for Moira Lists"""
def channels(self, create, extracted, **kwargs):
"""Create associated channels"""
<|body_0|>
def users(self, create, extracted, **kwargs):
"""Create associated users"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MoiraListFactory:
"""Factory for Moira Lists"""
def channels(self, create, extracted, **kwargs):
"""Create associated channels"""
if not create:
return
if extracted:
for channel in extracted:
self.channels.add(channel)
def users(self, c... | the_stack_v2_python_sparse | moira_lists/factories.py | mitodl/open-discussions | train | 13 |
8213564301aa39c8f4182908fa25f7539981a669 | [
"toggle = NanpyGPIOToggle(self.mudpi, config)\nif toggle:\n node = self.extension.nodes[config['node']]\n if node:\n toggle.node = node\n self.add_component(toggle)\n else:\n raise MudPiError(f\"Nanpy node {config['node']} not found trying to connect {config['key']}.\")\nreturn True",
... | <|body_start_0|>
toggle = NanpyGPIOToggle(self.mudpi, config)
if toggle:
node = self.extension.nodes[config['node']]
if node:
toggle.node = node
self.add_component(toggle)
else:
raise MudPiError(f"Nanpy node {config['nod... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load Nanpy Toggle components from configs"""
<|body_0|>
def validate(self, config):
"""Validate the Nanpy control config"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
toggle = NanpyGPIOToggle(self.mudpi, confi... | stack_v2_sparse_classes_75kplus_train_072932 | 5,292 | permissive | [
{
"docstring": "Load Nanpy Toggle components from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Validate the Nanpy control config",
"name": "validate",
"signature": "def validate(self, config)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027973 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load Nanpy Toggle components from configs
- def validate(self, config): Validate the Nanpy control config | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load Nanpy Toggle components from configs
- def validate(self, config): Validate the Nanpy control config
<|skeleton|>
class Interface:
def load(s... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load Nanpy Toggle components from configs"""
<|body_0|>
def validate(self, config):
"""Validate the Nanpy control config"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interface:
def load(self, config):
"""Load Nanpy Toggle components from configs"""
toggle = NanpyGPIOToggle(self.mudpi, config)
if toggle:
node = self.extension.nodes[config['node']]
if node:
toggle.node = node
self.add_component(... | the_stack_v2_python_sparse | mudpi/extensions/nanpy/toggle.py | mistasp0ck/mudpi-core | train | 0 | |
f461c7d0144dcee17906fbafed05a10af8fb7723 | [
"self.interpreter = interpreter\nassert os.path.isfile(interpreter) and os.path.exists(interpreter), \"'%s' is not a valid interpreter path\" % interpreter\nself.paths = paths\nself.flags = flags\nself.environ = environ",
"rt_env = self._runtime_environment(self.paths)\narg_string = ''\nif len(args):\n arg_str... | <|body_start_0|>
self.interpreter = interpreter
assert os.path.isfile(interpreter) and os.path.exists(interpreter), "'%s' is not a valid interpreter path" % interpreter
self.paths = paths
self.flags = flags
self.environ = environ
<|end_body_0|>
<|body_start_1|>
rt_env = ... | For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard libraries if these are installed in non-st... | MayaPyManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MayaPyManager:
"""For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard l... | stack_v2_sparse_classes_75kplus_train_072933 | 9,665 | permissive | [
{
"docstring": "Create a MayaPyManager for ths supplied interpreter and paths Arguments: - intepreter is a disk path to a maya python interpreter - environ is a dictionary of environment variables. If no dictionary is provided, intepreter will use os.environ. - paths is an array of strings. It will completely r... | 6 | stack_v2_sparse_classes_30k_train_000142 | Implement the Python class `MayaPyManager` described below.
Class description:
For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions m... | Implement the Python class `MayaPyManager` described below.
Class description:
For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions m... | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | <|skeleton|>
class MayaPyManager:
"""For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MayaPyManager:
"""For running a maya python interpreter* under controlled conditions: - Override default paths - Overrides environment variables - Disable userSetup.py * Technically this _should_ work for any Python installation, although non-maya versions may not be able to find their standard libraries if t... | the_stack_v2_python_sparse | dockerized-gists/2c712a91155c7e1c4c15/snippet.py | gistable/gistable | train | 76 |
4b83163dd1d632ad4e4d61fef5d6cd547ed515f9 | [
"self.transform_types: Dict[str, List[str]] = {'str': ['interpolation', 'dtype', 'label_file', 'vocab_file'], 'int': ['x', 'y', 'height', 'width', 'offset_height', 'offset_width', 'target_height', 'target_width', 'dim', 'resize_side', 'label_shift'], 'float': ['scale', 'central_fraction'], 'list<float>': ['mean', '... | <|body_start_0|>
self.transform_types: Dict[str, List[str]] = {'str': ['interpolation', 'dtype', 'label_file', 'vocab_file'], 'int': ['x', 'y', 'height', 'width', 'offset_height', 'offset_width', 'target_height', 'target_width', 'dim', 'resize_side', 'label_shift'], 'float': ['scale', 'central_fraction'], 'list... | Configuration type parser class. | ConfigurationParser | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationParser:
"""Configuration type parser class."""
def __init__(self) -> None:
"""Initialize configuration type parser."""
<|body_0|>
def parse(self, data: dict) -> dict:
"""Parse configuration."""
<|body_1|>
def parse_transforms(self, trans... | stack_v2_sparse_classes_75kplus_train_072934 | 9,825 | permissive | [
{
"docstring": "Initialize configuration type parser.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Parse configuration.",
"name": "parse",
"signature": "def parse(self, data: dict) -> dict"
},
{
"docstring": "Parse transforms list.",
"nam... | 6 | stack_v2_sparse_classes_30k_train_012475 | Implement the Python class `ConfigurationParser` described below.
Class description:
Configuration type parser class.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize configuration type parser.
- def parse(self, data: dict) -> dict: Parse configuration.
- def parse_transforms(self, transform... | Implement the Python class `ConfigurationParser` described below.
Class description:
Configuration type parser class.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize configuration type parser.
- def parse(self, data: dict) -> dict: Parse configuration.
- def parse_transforms(self, transform... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class ConfigurationParser:
"""Configuration type parser class."""
def __init__(self) -> None:
"""Initialize configuration type parser."""
<|body_0|>
def parse(self, data: dict) -> dict:
"""Parse configuration."""
<|body_1|>
def parse_transforms(self, trans... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigurationParser:
"""Configuration type parser class."""
def __init__(self) -> None:
"""Initialize configuration type parser."""
self.transform_types: Dict[str, List[str]] = {'str': ['interpolation', 'dtype', 'label_file', 'vocab_file'], 'int': ['x', 'y', 'height', 'width', 'offset_hei... | the_stack_v2_python_sparse | neural_compressor/ux/components/configuration_wizard/configuration_parser.py | Skp80/neural-compressor | train | 0 |
894f6d3dd1a1c59083c029285f86fca532c54472 | [
"def load_words(txt_file):\n words = set()\n file = open(txt_file, 'r')\n for line in file:\n if str.startswith(line, ';' or ' ' or '\\n'):\n continue\n else:\n word = line.rstrip('\\n')\n words.add(word)\n file.close()\n return words\nself.positives = l... | <|body_start_0|>
def load_words(txt_file):
words = set()
file = open(txt_file, 'r')
for line in file:
if str.startswith(line, ';' or ' ' or '\n'):
continue
else:
word = line.rstrip('\n')
... | Implements sentiment analysis. | Analyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Analyzer:
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
<|body_0|>
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072935 | 2,032 | no_license | [
{
"docstring": "Initialize Analyzer.",
"name": "__init__",
"signature": "def __init__(self, positives, negatives)"
},
{
"docstring": "Analyze text for sentiment, returning its score.",
"name": "analyze",
"signature": "def analyze(self, text)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011953 | Implement the Python class `Analyzer` described below.
Class description:
Implements sentiment analysis.
Method signatures and docstrings:
- def __init__(self, positives, negatives): Initialize Analyzer.
- def analyze(self, text): Analyze text for sentiment, returning its score. | Implement the Python class `Analyzer` described below.
Class description:
Implements sentiment analysis.
Method signatures and docstrings:
- def __init__(self, positives, negatives): Initialize Analyzer.
- def analyze(self, text): Analyze text for sentiment, returning its score.
<|skeleton|>
class Analyzer:
"""I... | 953b7b547cfdfe8ac631476a5a7724bd8af81d56 | <|skeleton|>
class Analyzer:
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
<|body_0|>
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Analyzer:
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
def load_words(txt_file):
words = set()
file = open(txt_file, 'r')
for line in file:
if str.startswith(line, ';' or ' ' o... | the_stack_v2_python_sparse | pset6/sentiments/analyzer.py | jwq1/CS50x_jwq1 | train | 2 |
f9459571eb87e957df89eb1796c9a42d77506896 | [
"base.Layer.__init__(self, **kwargs)\nself._num_output = self.spec.get('num_output', 0)\nif self._num_output <= 0:\n raise base.InvalidLayerError('Incorrect or unspecified num_output for %s' % self.name)\nself._reg = self.spec.get('reg', None)\nself._filler = self.spec.get('filler', None)\nself._weight = base.Bl... | <|body_start_0|>
base.Layer.__init__(self, **kwargs)
self._num_output = self.spec.get('num_output', 0)
if self._num_output <= 0:
raise base.InvalidLayerError('Incorrect or unspecified num_output for %s' % self.name)
self._reg = self.spec.get('reg', None)
self._filler ... | A layer that implements the inner product. | InnerProductLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InnerProductLayer:
"""A layer that implements the inner product."""
def __init__(self, **kwargs):
"""Initializes an inner product layer. kwargs: num_output: the number of outputs. reg: the regularizer to be used to add regularization terms. should be a decaf.base.Regularizer instance... | stack_v2_sparse_classes_75kplus_train_072936 | 3,377 | no_license | [
{
"docstring": "Initializes an inner product layer. kwargs: num_output: the number of outputs. reg: the regularizer to be used to add regularization terms. should be a decaf.base.Regularizer instance. Default None. filler: a filler to initialize the weights. Should be a decaf.base.Filler instance. Default None.... | 4 | stack_v2_sparse_classes_30k_val_001496 | Implement the Python class `InnerProductLayer` described below.
Class description:
A layer that implements the inner product.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializes an inner product layer. kwargs: num_output: the number of outputs. reg: the regularizer to be used to add regulari... | Implement the Python class `InnerProductLayer` described below.
Class description:
A layer that implements the inner product.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializes an inner product layer. kwargs: num_output: the number of outputs. reg: the regularizer to be used to add regulari... | 6fa4cdfbd0d0b8d486d7146bf1e32edd3662fec4 | <|skeleton|>
class InnerProductLayer:
"""A layer that implements the inner product."""
def __init__(self, **kwargs):
"""Initializes an inner product layer. kwargs: num_output: the number of outputs. reg: the regularizer to be used to add regularization terms. should be a decaf.base.Regularizer instance... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InnerProductLayer:
"""A layer that implements the inner product."""
def __init__(self, **kwargs):
"""Initializes an inner product layer. kwargs: num_output: the number of outputs. reg: the regularizer to be used to add regularization terms. should be a decaf.base.Regularizer instance. Default Non... | the_stack_v2_python_sparse | decaf/layers/innerproduct.py | UCBAIR/decaf-release | train | 62 |
2d4abe0f05bd4838b1e6b4b2796ebb2a9dad22ee | [
"if len(nums) == 0:\n return 0\nD = [0 for _ in nums]\nfor index, num in enumerate(nums):\n if index == 0:\n D[index] = num\n elif index == 1:\n D[index] = max(D[index - 1], num)\n else:\n D[index] = max(D[index - 2] + num, D[index - 1])\nreturn D[-1]",
"if not nums:\n return 0... | <|body_start_0|>
if len(nums) == 0:
return 0
D = [0 for _ in nums]
for index, num in enumerate(nums):
if index == 0:
D[index] = num
elif index == 1:
D[index] = max(D[index - 1], num)
else:
D[index] = ... | 同 HouseRobber,不过这里的数组是环状的,不允许0和n-1同时出现, 分解成0~n-2 和 1~n-1的问题, 如果不偷0, 那么1~n-1可以随便,退化成HouseRobber问题, 如果偷0,那么n-1肯定不能,退化成 0~n-2问题 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""同 HouseRobber,不过这里的数组是环状的,不允许0和n-1同时出现, 分解成0~n-2 和 1~n-1的问题, 如果不偷0, 那么1~n-1可以随便,退化成HouseRobber问题, 如果偷0,那么n-1肯定不能,退化成 0~n-2问题"""
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rt... | stack_v2_sparse_classes_75kplus_train_072937 | 1,047 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob2",
"signature": "def rob2(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030689 | Implement the Python class `Solution` described below.
Class description:
同 HouseRobber,不过这里的数组是环状的,不允许0和n-1同时出现, 分解成0~n-2 和 1~n-1的问题, 如果不偷0, 那么1~n-1可以随便,退化成HouseRobber问题, 如果偷0,那么n-1肯定不能,退化成 0~n-2问题
Method signatures and docstrings:
- def rob2(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :typ... | Implement the Python class `Solution` described below.
Class description:
同 HouseRobber,不过这里的数组是环状的,不允许0和n-1同时出现, 分解成0~n-2 和 1~n-1的问题, 如果不偷0, 那么1~n-1可以随便,退化成HouseRobber问题, 如果偷0,那么n-1肯定不能,退化成 0~n-2问题
Method signatures and docstrings:
- def rob2(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :typ... | f563dbf35878808491f03281889c9a0800be7d90 | <|skeleton|>
class Solution:
"""同 HouseRobber,不过这里的数组是环状的,不允许0和n-1同时出现, 分解成0~n-2 和 1~n-1的问题, 如果不偷0, 那么1~n-1可以随便,退化成HouseRobber问题, 如果偷0,那么n-1肯定不能,退化成 0~n-2问题"""
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""同 HouseRobber,不过这里的数组是环状的,不允许0和n-1同时出现, 分解成0~n-2 和 1~n-1的问题, 如果不偷0, 那么1~n-1可以随便,退化成HouseRobber问题, 如果偷0,那么n-1肯定不能,退化成 0~n-2问题"""
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
D = [0 for _ in nums]
for inde... | the_stack_v2_python_sparse | leetcode/213.HouseRobber2/main.py | lee3164/newcoder | train | 1 |
0b839aed9f6d5a504876879e753df63c85d3b9b9 | [
"version = ''\nif config_file == '':\n version = 'params'\nelse:\n version = config_file\nwandb = False\ncfg = cfg_parser(osp.join('config', version + '.json'))\ncfg['experiment'].wandb = wandb\ncfg['experiment'].version = version\ncfg['experiment'].wandb_id = 'id'\ncfg['experiment'].wandb_name = 'MicroNet-Ts... | <|body_start_0|>
version = ''
if config_file == '':
version = 'params'
else:
version = config_file
wandb = False
cfg = cfg_parser(osp.join('config', version + '.json'))
cfg['experiment'].wandb = wandb
cfg['experiment'].version = version
... | Training options for commandline | TrainOptions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainOptions:
"""Training options for commandline"""
def initialize(self, config_file):
"""Parameter definitions Returns: ArgumentParser.parse_args: Params values for training Command line arguments: --version [str]: name of the config file to use --wandb [bool]: Log to wandb or not"... | stack_v2_sparse_classes_75kplus_train_072938 | 1,974 | no_license | [
{
"docstring": "Parameter definitions Returns: ArgumentParser.parse_args: Params values for training Command line arguments: --version [str]: name of the config file to use --wandb [bool]: Log to wandb or not",
"name": "initialize",
"signature": "def initialize(self, config_file)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_040043 | Implement the Python class `TrainOptions` described below.
Class description:
Training options for commandline
Method signatures and docstrings:
- def initialize(self, config_file): Parameter definitions Returns: ArgumentParser.parse_args: Params values for training Command line arguments: --version [str]: name of th... | Implement the Python class `TrainOptions` described below.
Class description:
Training options for commandline
Method signatures and docstrings:
- def initialize(self, config_file): Parameter definitions Returns: ArgumentParser.parse_args: Params values for training Command line arguments: --version [str]: name of th... | dc35bc0d2896f7d76074c83fc633d2bf86cf2c0e | <|skeleton|>
class TrainOptions:
"""Training options for commandline"""
def initialize(self, config_file):
"""Parameter definitions Returns: ArgumentParser.parse_args: Params values for training Command line arguments: --version [str]: name of the config file to use --wandb [bool]: Log to wandb or not"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainOptions:
"""Training options for commandline"""
def initialize(self, config_file):
"""Parameter definitions Returns: ArgumentParser.parse_args: Params values for training Command line arguments: --version [str]: name of the config file to use --wandb [bool]: Log to wandb or not"""
ve... | the_stack_v2_python_sparse | data/traffic_sign_interiit/options/train_options.py | yash12khandelwal/traffic_sign_interiit | train | 4 |
efcf711f6fb5421eccd60f160795aca6a70f53ea | [
"length = 6\nsymbols = string.digits\nlogin = 'test_login'\npassword = '{random:7:L}'\nparams = Params()\nparams['login'] = login\nparams['password'] = password\nparams2 = Params().loads(params.dumps())\nself.assertEquals(unicode(params2['login']), login)\nself.assertEquals(unicode(params2['password']), password)",... | <|body_start_0|>
length = 6
symbols = string.digits
login = 'test_login'
password = '{random:7:L}'
params = Params()
params['login'] = login
params['password'] = password
params2 = Params().loads(params.dumps())
self.assertEquals(unicode(params2['l... | ParamsTestCase | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamsTestCase:
def test_serialize(self):
"""Tests params serialization."""
<|body_0|>
def test_resolve(self):
"""Should return new Params() with all variables resolved"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = 6
symbols = str... | stack_v2_sparse_classes_75kplus_train_072939 | 2,615 | permissive | [
{
"docstring": "Tests params serialization.",
"name": "test_serialize",
"signature": "def test_serialize(self)"
},
{
"docstring": "Should return new Params() with all variables resolved",
"name": "test_resolve",
"signature": "def test_resolve(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051949 | Implement the Python class `ParamsTestCase` described below.
Class description:
Implement the ParamsTestCase class.
Method signatures and docstrings:
- def test_serialize(self): Tests params serialization.
- def test_resolve(self): Should return new Params() with all variables resolved | Implement the Python class `ParamsTestCase` described below.
Class description:
Implement the ParamsTestCase class.
Method signatures and docstrings:
- def test_serialize(self): Tests params serialization.
- def test_resolve(self): Should return new Params() with all variables resolved
<|skeleton|>
class ParamsTestC... | 57f5e7d16185d91a06fc3ad9ecd26fbef1c0a84d | <|skeleton|>
class ParamsTestCase:
def test_serialize(self):
"""Tests params serialization."""
<|body_0|>
def test_resolve(self):
"""Should return new Params() with all variables resolved"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParamsTestCase:
def test_serialize(self):
"""Tests params serialization."""
length = 6
symbols = string.digits
login = 'test_login'
password = '{random:7:L}'
params = Params()
params['login'] = login
params['password'] = password
params2 ... | the_stack_v2_python_sparse | fortuitus/feditor/tests.py | elegion/djangodash2012 | train | 0 | |
4e4369a646698128a210a6d2d696b7fdf9769459 | [
"params = dict(output='extend', history=self.value_type.val, itemids=self.id, limit=limit, sortfield='clock', sortorder='DESC')\nif ts_from:\n params['time_from'] = ts_from.strftime('%s')\nif ts_to:\n params['time_till'] = ts_to.strftime('%s')\nreturn [(i['clock'], self._typed_value(i['value'])) for i in self... | <|body_start_0|>
params = dict(output='extend', history=self.value_type.val, itemids=self.id, limit=limit, sortfield='clock', sortorder='DESC')
if ts_from:
params['time_from'] = ts_from.strftime('%s')
if ts_to:
params['time_till'] = ts_to.strftime('%s')
return [(i... | https://www.xibbaz.com/documentation/3.4/manual/api/reference/item/object | Item | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Item:
"""https://www.xibbaz.com/documentation/3.4/manual/api/reference/item/object"""
def history(self, ts_from=None, ts_to=None, limit=10):
"""`(ts, val)` for latest `limit` from `ts_from` until `ts_to`."""
<|body_0|>
def _typed_value(self, val):
"""Return `val`... | stack_v2_sparse_classes_75kplus_train_072940 | 9,815 | permissive | [
{
"docstring": "`(ts, val)` for latest `limit` from `ts_from` until `ts_to`.",
"name": "history",
"signature": "def history(self, ts_from=None, ts_to=None, limit=10)"
},
{
"docstring": "Return `val` with proper type based on this Item's `value_type`.",
"name": "_typed_value",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_006787 | Implement the Python class `Item` described below.
Class description:
https://www.xibbaz.com/documentation/3.4/manual/api/reference/item/object
Method signatures and docstrings:
- def history(self, ts_from=None, ts_to=None, limit=10): `(ts, val)` for latest `limit` from `ts_from` until `ts_to`.
- def _typed_value(sel... | Implement the Python class `Item` described below.
Class description:
https://www.xibbaz.com/documentation/3.4/manual/api/reference/item/object
Method signatures and docstrings:
- def history(self, ts_from=None, ts_to=None, limit=10): `(ts, val)` for latest `limit` from `ts_from` until `ts_to`.
- def _typed_value(sel... | 5c245ee516dcd7e6dbffac364c6a434bd13a69a4 | <|skeleton|>
class Item:
"""https://www.xibbaz.com/documentation/3.4/manual/api/reference/item/object"""
def history(self, ts_from=None, ts_to=None, limit=10):
"""`(ts, val)` for latest `limit` from `ts_from` until `ts_to`."""
<|body_0|>
def _typed_value(self, val):
"""Return `val`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Item:
"""https://www.xibbaz.com/documentation/3.4/manual/api/reference/item/object"""
def history(self, ts_from=None, ts_to=None, limit=10):
"""`(ts, val)` for latest `limit` from `ts_from` until `ts_to`."""
params = dict(output='extend', history=self.value_type.val, itemids=self.id, limi... | the_stack_v2_python_sparse | xibbaz/objects/item.py | erik-stephens/xibbaz | train | 1 |
d867235ee5b73666a4eff11710dcbeca37736eaf | [
"if not env_schema:\n env_schema = ENVIRONMENT\nurl = u'http://{0}:{1}/mysql/find'.format(MYSQL_CONFIG[u'SERVICE'][env_schema][u'host'], MYSQL_CONFIG[u'SERVICE'][env_schema][u'port'])\ndata = {u'schema': schema, u'sql_str': db_query, u'params_str': params}\nmessage = http_client.do_http_post(url, data=data)[0]\n... | <|body_start_0|>
if not env_schema:
env_schema = ENVIRONMENT
url = u'http://{0}:{1}/mysql/find'.format(MYSQL_CONFIG[u'SERVICE'][env_schema][u'host'], MYSQL_CONFIG[u'SERVICE'][env_schema][u'port'])
data = {u'schema': schema, u'sql_str': db_query, u'params_str': params}
message... | 二次封装的MySQL相关方法类 | MySQLInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLInterface:
"""二次封装的MySQL相关方法类"""
def find(cls, schema, db_query, params=u'{}', env_schema=None):
"""查询满足条件的所有数据 :param schema: schema :param db_query: 查询语句 :param params: 参数 :param env_schema: 环境模式 :return: 查询结果"""
<|body_0|>
def insert(cls, schema, db_query, params... | stack_v2_sparse_classes_75kplus_train_072941 | 7,612 | no_license | [
{
"docstring": "查询满足条件的所有数据 :param schema: schema :param db_query: 查询语句 :param params: 参数 :param env_schema: 环境模式 :return: 查询结果",
"name": "find",
"signature": "def find(cls, schema, db_query, params=u'{}', env_schema=None)"
},
{
"docstring": "insert一条数据 :param schema: schema :param db_query: ins... | 4 | stack_v2_sparse_classes_30k_train_021695 | Implement the Python class `MySQLInterface` described below.
Class description:
二次封装的MySQL相关方法类
Method signatures and docstrings:
- def find(cls, schema, db_query, params=u'{}', env_schema=None): 查询满足条件的所有数据 :param schema: schema :param db_query: 查询语句 :param params: 参数 :param env_schema: 环境模式 :return: 查询结果
- def inse... | Implement the Python class `MySQLInterface` described below.
Class description:
二次封装的MySQL相关方法类
Method signatures and docstrings:
- def find(cls, schema, db_query, params=u'{}', env_schema=None): 查询满足条件的所有数据 :param schema: schema :param db_query: 查询语句 :param params: 参数 :param env_schema: 环境模式 :return: 查询结果
- def inse... | 518a74e734046d0f45510456bf55a71e2666bd49 | <|skeleton|>
class MySQLInterface:
"""二次封装的MySQL相关方法类"""
def find(cls, schema, db_query, params=u'{}', env_schema=None):
"""查询满足条件的所有数据 :param schema: schema :param db_query: 查询语句 :param params: 参数 :param env_schema: 环境模式 :return: 查询结果"""
<|body_0|>
def insert(cls, schema, db_query, params... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MySQLInterface:
"""二次封装的MySQL相关方法类"""
def find(cls, schema, db_query, params=u'{}', env_schema=None):
"""查询满足条件的所有数据 :param schema: schema :param db_query: 查询语句 :param params: 参数 :param env_schema: 环境模式 :return: 查询结果"""
if not env_schema:
env_schema = ENVIRONMENT
url =... | the_stack_v2_python_sparse | src/cores/services/mysql_client.py | gentlemantong/iCrawler | train | 1 |
782ffaf89dd84f73cde443f8423eb85b5898a55c | [
"n = len(s)\nif n == 0:\n return 0\ncount = 0\nfor i in range(n - 1, -1, -1):\n if s[i] != ' ':\n count += 1\n elif count != 0:\n return count\n else:\n continue\nreturn count",
"splt = s.split()\nif splt:\n return len(splt[-1])\nreturn 0"
] | <|body_start_0|>
n = len(s)
if n == 0:
return 0
count = 0
for i in range(n - 1, -1, -1):
if s[i] != ' ':
count += 1
elif count != 0:
return count
else:
continue
return count
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLastWord(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLastWord0(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(s)
if n == 0:
return 0
... | stack_v2_sparse_classes_75kplus_train_072942 | 664 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLastWord",
"signature": "def lengthOfLastWord(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLastWord0",
"signature": "def lengthOfLastWord0(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048738 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLastWord(self, s): :type s: str :rtype: int
- def lengthOfLastWord0(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLastWord(self, s): :type s: str :rtype: int
- def lengthOfLastWord0(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOfLastWord(self, s... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def lengthOfLastWord(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLastWord0(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLastWord(self, s):
""":type s: str :rtype: int"""
n = len(s)
if n == 0:
return 0
count = 0
for i in range(n - 1, -1, -1):
if s[i] != ' ':
count += 1
elif count != 0:
return count
... | the_stack_v2_python_sparse | PythonCode/src/0058_Length_of_Last_Word.py | oneyuan/CodeforFun | train | 0 | |
63fb1d29047f51296c9d4894ab451f16bebce383 | [
"if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:\n return 0\ndp = []\nfor row in matrix:\n dp.append([int(n) for n in row])\nmax_n = 0\nmax_n = max(dp[0] + [dp[i][0] for i in range(len(dp))])\nfor i in range(1, len(matrix)):\n for j in range(1, len(matrix[i])):\n if dp[i][j]:\n ... | <|body_start_0|>
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
dp = []
for row in matrix:
dp.append([int(n) for n in row])
max_n = 0
max_n = max(dp[0] + [dp[i][0] for i in range(len(dp))])
for i in range(1, len(matrix)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare_failed(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix ... | stack_v2_sparse_classes_75kplus_train_072943 | 3,397 | no_license | [
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare",
"signature": "def maximalSquare(self, matrix)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalSquare_failed",
"signature": "def maximalSquare_failed(self, matrix)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010803 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare_failed(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximalSquare(self, matrix): :type matrix: List[List[str]] :rtype: int
- def maximalSquare_failed(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_0|>
def maximalSquare_failed(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximalSquare(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
dp = []
for row in matrix:
dp.append([int(n) for n in row])
max_n = 0
max_n = ma... | the_stack_v2_python_sparse | src/lt_221.py | oxhead/CodingYourWay | train | 0 | |
324c7f573275e04fc35996a0f471bd9d5233c4f8 | [
"config = configparser.ConfigParser()\nconfig = configparser.ConfigParser()\nconfig.read('settings.ini', encoding='UTF-8')\nself.TIMEOUT = connect = config.getint('COUNTRIES_ADVANCED', 'TIMEOUT')\nself.MAXTRIES = config.getint('COUNTRIES_ADVANCED', 'MAXTRIES')\nself.TASKS = config.getint('COUNTRIES_ADVANCED', 'TASK... | <|body_start_0|>
config = configparser.ConfigParser()
config = configparser.ConfigParser()
config.read('settings.ini', encoding='UTF-8')
self.TIMEOUT = connect = config.getint('COUNTRIES_ADVANCED', 'TIMEOUT')
self.MAXTRIES = config.getint('COUNTRIES_ADVANCED', 'MAXTRIES')
... | запрос | Check | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Check:
"""запрос"""
def __init__(self):
"""init"""
<|body_0|>
def request(self, proxy, protocol):
"""Отправка запроса"""
<|body_1|>
def answerStatus(self, answer):
"""Анализ ответа"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072944 | 5,372 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Отправка запроса",
"name": "request",
"signature": "def request(self, proxy, protocol)"
},
{
"docstring": "Анализ ответа",
"name": "answerStatus",
"signature": "def answerStatu... | 3 | stack_v2_sparse_classes_30k_train_032819 | Implement the Python class `Check` described below.
Class description:
запрос
Method signatures and docstrings:
- def __init__(self): init
- def request(self, proxy, protocol): Отправка запроса
- def answerStatus(self, answer): Анализ ответа | Implement the Python class `Check` described below.
Class description:
запрос
Method signatures and docstrings:
- def __init__(self): init
- def request(self, proxy, protocol): Отправка запроса
- def answerStatus(self, answer): Анализ ответа
<|skeleton|>
class Check:
"""запрос"""
def __init__(self):
... | 133e56528e05fcc71205ea7ab6b34b12ad5ffa51 | <|skeleton|>
class Check:
"""запрос"""
def __init__(self):
"""init"""
<|body_0|>
def request(self, proxy, protocol):
"""Отправка запроса"""
<|body_1|>
def answerStatus(self, answer):
"""Анализ ответа"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Check:
"""запрос"""
def __init__(self):
"""init"""
config = configparser.ConfigParser()
config = configparser.ConfigParser()
config.read('settings.ini', encoding='UTF-8')
self.TIMEOUT = connect = config.getint('COUNTRIES_ADVANCED', 'TIMEOUT')
self.MAXTRIES ... | the_stack_v2_python_sparse | modules/threading_countries_ipinfo.py | tranquilo108/proxy-master | train | 0 |
61493591dfeb6d5f7e7c504ff453ab487f2d1308 | [
"query = select_data.ORGANIZATIONS.format(timestamp)\nrows = self.execute_sql_with_fetch(resource_name, query, ())\norgs = []\nfor row in rows:\n org = organization.Organization(organization_id=row['org_id'], display_name=row['display_name'], lifecycle_state=row['lifecycle_state'])\n orgs.append(org)\nreturn ... | <|body_start_0|>
query = select_data.ORGANIZATIONS.format(timestamp)
rows = self.execute_sql_with_fetch(resource_name, query, ())
orgs = []
for row in rows:
org = organization.Organization(organization_id=row['org_id'], display_name=row['display_name'], lifecycle_state=row['l... | Data access object (DAO) for Organizations. | OrganizationDao | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationDao:
"""Data access object (DAO) for Organizations."""
def get_organizations(self, resource_name, timestamp):
"""Get organizations from snapshot table. Args: resource_name (str): The resource name. timestamp (str): The timestamp of the snapshot. Returns: list: A list of O... | stack_v2_sparse_classes_75kplus_train_072945 | 3,768 | permissive | [
{
"docstring": "Get organizations from snapshot table. Args: resource_name (str): The resource name. timestamp (str): The timestamp of the snapshot. Returns: list: A list of Organizations.",
"name": "get_organizations",
"signature": "def get_organizations(self, resource_name, timestamp)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_047242 | Implement the Python class `OrganizationDao` described below.
Class description:
Data access object (DAO) for Organizations.
Method signatures and docstrings:
- def get_organizations(self, resource_name, timestamp): Get organizations from snapshot table. Args: resource_name (str): The resource name. timestamp (str): ... | Implement the Python class `OrganizationDao` described below.
Class description:
Data access object (DAO) for Organizations.
Method signatures and docstrings:
- def get_organizations(self, resource_name, timestamp): Get organizations from snapshot table. Args: resource_name (str): The resource name. timestamp (str): ... | a6a1aa7464cda2ad5948e3e8876eb8dded5e2514 | <|skeleton|>
class OrganizationDao:
"""Data access object (DAO) for Organizations."""
def get_organizations(self, resource_name, timestamp):
"""Get organizations from snapshot table. Args: resource_name (str): The resource name. timestamp (str): The timestamp of the snapshot. Returns: list: A list of O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganizationDao:
"""Data access object (DAO) for Organizations."""
def get_organizations(self, resource_name, timestamp):
"""Get organizations from snapshot table. Args: resource_name (str): The resource name. timestamp (str): The timestamp of the snapshot. Returns: list: A list of Organizations.... | the_stack_v2_python_sparse | google/cloud/security/common/data_access/organization_dao.py | shimizu19691210/forseti-security | train | 1 |
75865bf85a74c9cab76934b4b73596c13092c7a4 | [
"try:\n self.f = lambda x: eval(function)\nexcept:\n print('Function was not understood.')\n self.f = lambda x: 0\nwhile True:\n colour = (random.randint(0, 5) * 51, random.randint(0, 5) * 51, random.randint(0, 5) * 51)\n if self.colour_check(colour):\n self.plotter = PygameTools.Sprite(Pygame... | <|body_start_0|>
try:
self.f = lambda x: eval(function)
except:
print('Function was not understood.')
self.f = lambda x: 0
while True:
colour = (random.randint(0, 5) * 51, random.randint(0, 5) * 51, random.randint(0, 5) * 51)
if self.co... | Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variable (a list) that will update as colours... | FunctionOfX | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionOfX:
"""Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variab... | stack_v2_sparse_classes_75kplus_train_072946 | 5,748 | no_license | [
{
"docstring": "Create the function object with an original plotter.",
"name": "__init__",
"signature": "def __init__(self, function)"
},
{
"docstring": "Plots the function to the surface.",
"name": "plot",
"signature": "def plot(self, surface)"
},
{
"docstring": "Return True and... | 3 | stack_v2_sparse_classes_30k_train_012234 | Implement the Python class `FunctionOfX` described below.
Class description:
Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours ... | Implement the Python class `FunctionOfX` described below.
Class description:
Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours ... | e7bbc0f7cfab13a2e16baa4c931d3a412c86277c | <|skeleton|>
class FunctionOfX:
"""Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variab... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionOfX:
"""Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variable (a list) t... | the_stack_v2_python_sparse | Plot2.py | Chig00/Python | train | 1 |
6a4c25bf48f1a14fbb3f4a09b3851c7da4544a67 | [
"self.iterations = 20\nself.ofc_box_size = 10\ndummy_cube = set_up_variable_cube(np.zeros((30, 30), dtype=np.float32), name='lwe_precipitation_rate', units='mm h-1', spatial_grid='equalarea', time=datetime(2018, 2, 20, 4, 0), frt=datetime(2018, 2, 20, 4, 0))\ncoord_points = 2000 * np.arange(30, dtype=np.float32)\nd... | <|body_start_0|>
self.iterations = 20
self.ofc_box_size = 10
dummy_cube = set_up_variable_cube(np.zeros((30, 30), dtype=np.float32), name='lwe_precipitation_rate', units='mm h-1', spatial_grid='equalarea', time=datetime(2018, 2, 20, 4, 0), frt=datetime(2018, 2, 20, 4, 0))
coord_points = ... | Tests for the generate_optical_flow_components function. Optical flow velocity values are tested within the Test_optical_flow module; this class tests timestamps only. | Test_generate_optical_flow_components | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_generate_optical_flow_components:
"""Tests for the generate_optical_flow_components function. Optical flow velocity values are tested within the Test_optical_flow module; this class tests timestamps only."""
def setUp(self):
"""Set up test input cubes"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_072947 | 4,618 | permissive | [
{
"docstring": "Set up test input cubes",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test output is a tuple of cubes",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test output timestamps are insensitive to input cube order",... | 4 | stack_v2_sparse_classes_30k_train_035916 | Implement the Python class `Test_generate_optical_flow_components` described below.
Class description:
Tests for the generate_optical_flow_components function. Optical flow velocity values are tested within the Test_optical_flow module; this class tests timestamps only.
Method signatures and docstrings:
- def setUp(s... | Implement the Python class `Test_generate_optical_flow_components` described below.
Class description:
Tests for the generate_optical_flow_components function. Optical flow velocity values are tested within the Test_optical_flow module; this class tests timestamps only.
Method signatures and docstrings:
- def setUp(s... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_generate_optical_flow_components:
"""Tests for the generate_optical_flow_components function. Optical flow velocity values are tested within the Test_optical_flow module; this class tests timestamps only."""
def setUp(self):
"""Set up test input cubes"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_generate_optical_flow_components:
"""Tests for the generate_optical_flow_components function. Optical flow velocity values are tested within the Test_optical_flow module; this class tests timestamps only."""
def setUp(self):
"""Set up test input cubes"""
self.iterations = 20
... | the_stack_v2_python_sparse | improver_tests/nowcasting/optical_flow/test_generate_optical_flow_components.py | metoppv/improver | train | 101 |
ca56b0c4517ab6c8def619e00399bd6299a95065 | [
"require_type(account, TealType.anytype)\nrequire_type(asset, TealType.uint64)\nreturn MaybeValue(Op.asset_holding_get, TealType.uint64, immediate_args=['AssetBalance'], args=[account, asset])",
"require_type(account, TealType.anytype)\nrequire_type(asset, TealType.uint64)\nreturn MaybeValue(Op.asset_holding_get,... | <|body_start_0|>
require_type(account, TealType.anytype)
require_type(asset, TealType.uint64)
return MaybeValue(Op.asset_holding_get, TealType.uint64, immediate_args=['AssetBalance'], args=[account, asset])
<|end_body_0|>
<|body_start_1|>
require_type(account, TealType.anytype)
... | AssetHolding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssetHolding:
def balance(cls, account: Expr, asset: Expr) -> MaybeValue:
"""Get the amount of an asset held by an account. Args: account: An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Tx... | stack_v2_sparse_classes_75kplus_train_072948 | 12,456 | permissive | [
{
"docstring": "Get the amount of an asset held by an account. Args: account: An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or is Txn.Sender, must be evaluated to bytes). asset: The ID of the asset ... | 2 | stack_v2_sparse_classes_30k_train_020837 | Implement the Python class `AssetHolding` described below.
Class description:
Implement the AssetHolding class.
Method signatures and docstrings:
- def balance(cls, account: Expr, asset: Expr) -> MaybeValue: Get the amount of an asset held by an account. Args: account: An index into Txn.Accounts that corresponds to t... | Implement the Python class `AssetHolding` described below.
Class description:
Implement the AssetHolding class.
Method signatures and docstrings:
- def balance(cls, account: Expr, asset: Expr) -> MaybeValue: Get the amount of an asset held by an account. Args: account: An index into Txn.Accounts that corresponds to t... | 670e637644630534883b4c2e6837ab34c56546b6 | <|skeleton|>
class AssetHolding:
def balance(cls, account: Expr, asset: Expr) -> MaybeValue:
"""Get the amount of an asset held by an account. Args: account: An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Tx... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AssetHolding:
def balance(cls, account: Expr, asset: Expr) -> MaybeValue:
"""Get the amount of an asset held by an account. Args: account: An index into Txn.Accounts that corresponds to the account to check, must be evaluated to uint64 (or, since v4, an account address that appears in Txn.Accounts or ... | the_stack_v2_python_sparse | pyteal/ast/asset.py | algorand/pyteal | train | 282 | |
55b6d61208261296be0b30f06ed30495dd5a8d6c | [
"children = []\nidx = [i for i in range(gene_size)]\nfor i in range(n):\n child = Individual()\n parent1, parent2 = npr.choice(parents, 2, replace=False)\n gene1 = copy.copy(parent1.getGene())\n gene2 = parent2.getGene()\n point = npr.choice(idx, 1)[0]\n if crate > npr.random():\n gene1[poi... | <|body_start_0|>
children = []
idx = [i for i in range(gene_size)]
for i in range(n):
child = Individual()
parent1, parent2 = npr.choice(parents, 2, replace=False)
gene1 = copy.copy(parent1.getGene())
gene2 = parent2.getGene()
point = n... | Crossover Class Crossover Algorithm * One point * Two points * Random points | Crossover | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crossover:
"""Crossover Class Crossover Algorithm * One point * Two points * Random points"""
def onePoint(self, parents, n, gene_size, crate):
"""One point crossover [imagine] parent1: [0, 1, 1] => crossover => child: [1(p1), 0(p2), 0(p2)] parent2: [1, 1, 0] [example] Crossover.Onep... | stack_v2_sparse_classes_75kplus_train_072949 | 4,896 | no_license | [
{
"docstring": "One point crossover [imagine] parent1: [0, 1, 1] => crossover => child: [1(p1), 0(p2), 0(p2)] parent2: [1, 1, 0] [example] Crossover.Onepoint(list.parents, 5) => [crossover the parents for individuals size] :param list[Individual] parents: Selected parents :param int n: Size of individuals :para... | 3 | stack_v2_sparse_classes_30k_train_039566 | Implement the Python class `Crossover` described below.
Class description:
Crossover Class Crossover Algorithm * One point * Two points * Random points
Method signatures and docstrings:
- def onePoint(self, parents, n, gene_size, crate): One point crossover [imagine] parent1: [0, 1, 1] => crossover => child: [1(p1), ... | Implement the Python class `Crossover` described below.
Class description:
Crossover Class Crossover Algorithm * One point * Two points * Random points
Method signatures and docstrings:
- def onePoint(self, parents, n, gene_size, crate): One point crossover [imagine] parent1: [0, 1, 1] => crossover => child: [1(p1), ... | 702e17e551f3e25ab2d3e0527d306d8551e5f5d1 | <|skeleton|>
class Crossover:
"""Crossover Class Crossover Algorithm * One point * Two points * Random points"""
def onePoint(self, parents, n, gene_size, crate):
"""One point crossover [imagine] parent1: [0, 1, 1] => crossover => child: [1(p1), 0(p2), 0(p2)] parent2: [1, 1, 0] [example] Crossover.Onep... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Crossover:
"""Crossover Class Crossover Algorithm * One point * Two points * Random points"""
def onePoint(self, parents, n, gene_size, crate):
"""One point crossover [imagine] parent1: [0, 1, 1] => crossover => child: [1(p1), 0(p2), 0(p2)] parent2: [1, 1, 0] [example] Crossover.Onepoint(list.par... | the_stack_v2_python_sparse | crossover.py | infordio-naka/ga | train | 0 |
86d70de6dac194bcb91ffd5bbbcd9a2ece6e1b29 | [
"super(CombinedCNNSpecialists, self).__init__()\nstride = 1\nmax_s = 2\nself.conv = nn.Sequential(nn.Conv2d(n_channels, 64, kernel_size=(3, 3), stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(kernel_size=(3, 3), stride=2, padding=1), nn.Conv2d(64, 128, kernel_size=(3, 3), stride=1, padding=1), nn.... | <|body_start_0|>
super(CombinedCNNSpecialists, self).__init__()
stride = 1
max_s = 2
self.conv = nn.Sequential(nn.Conv2d(n_channels, 64, kernel_size=(3, 3), stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(kernel_size=(3, 3), stride=2, padding=1), nn.Conv2d(64, 128, kern... | This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward. | CombinedCNNSpecialists | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombinedCNNSpecialists:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_channels, n_inputs):
"""Initializes MLP object. Args: n_input... | stack_v2_sparse_classes_75kplus_train_072950 | 6,082 | no_license | [
{
"docstring": "Initializes MLP object. Args: n_inputs: number of inputs. n_hidden: list of ints, specifies the number of units in each linear layer. If the list is empty, the MLP will not have any linear layers, and the model will simply perform a multinomial logistic regression. n_classes: number of classes o... | 2 | stack_v2_sparse_classes_30k_train_017290 | Implement the Python class `CombinedCNNSpecialists` described below.
Class description:
This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward.
Method signatures and docstrings:
- def __init__(self, n_c... | Implement the Python class `CombinedCNNSpecialists` described below.
Class description:
This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward.
Method signatures and docstrings:
- def __init__(self, n_c... | b060caa315f0c066410da9580e64d6db0222f2a8 | <|skeleton|>
class CombinedCNNSpecialists:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_channels, n_inputs):
"""Initializes MLP object. Args: n_input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CombinedCNNSpecialists:
"""This class implements a Multi-layer Perceptron in PyTorch. It handles the different layers and parameters of the model. Once initialized an MLP object can perform forward."""
def __init__(self, n_channels, n_inputs):
"""Initializes MLP object. Args: n_inputs: number of ... | the_stack_v2_python_sparse | STL-10/combined_shared_cnn_specialists/shared_cnn.py | VCharatsidis/Unsupervised-Clustering | train | 1 |
ae0c061e8dfe3ab35c3f18ce8519358a2172122c | [
"dummy: ListNode = ListNode(0)\ntemp = dummy\nwhile l1 != None and l2 != None:\n if l1.val <= l2.val:\n temp.next = l1\n l1 = l1.next\n temp = temp.next\n else:\n temp.next = l2\n l2 = l2.next\n temp = temp.next\nif l1 != None:\n temp.next = l1\nelif l2 != None:\n ... | <|body_start_0|>
dummy: ListNode = ListNode(0)
temp = dummy
while l1 != None and l2 != None:
if l1.val <= l2.val:
temp.next = l1
l1 = l1.next
temp = temp.next
else:
temp.next = l2
l2 = l2.next... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""merge the ListNode by compare each node val :param l1: :param l2: :return:"""
<|body_0|>
def mergeTwoListsRecursion(self, l1: ListNode, l2: ListNode) -> ListNode:
"""merge the ListNode by r... | stack_v2_sparse_classes_75kplus_train_072951 | 1,536 | no_license | [
{
"docstring": "merge the ListNode by compare each node val :param l1: :param l2: :return:",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "merge the ListNode by recursion :param l1: :param l2: :return:",
"name": "me... | 2 | stack_v2_sparse_classes_30k_train_026518 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: merge the ListNode by compare each node val :param l1: :param l2: :return:
- def mergeTwoListsRecursion(self, l1:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: merge the ListNode by compare each node val :param l1: :param l2: :return:
- def mergeTwoListsRecursion(self, l1:... | 7138db92a5fabf2347ff669a77268083dfced8da | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""merge the ListNode by compare each node val :param l1: :param l2: :return:"""
<|body_0|>
def mergeTwoListsRecursion(self, l1: ListNode, l2: ListNode) -> ListNode:
"""merge the ListNode by r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""merge the ListNode by compare each node val :param l1: :param l2: :return:"""
dummy: ListNode = ListNode(0)
temp = dummy
while l1 != None and l2 != None:
if l1.val <= l2.val:
... | the_stack_v2_python_sparse | leetcode/21_merge_two_sorted_lists.py | Merical/education_ai | train | 0 | |
64f5a3ba886686d1ea25444b4799d718c74c1b6f | [
"super(Q_net, self).__init__()\nself.feature_shape = feature_shape\nself.class_num = class_num\nself.condition_dim = condition_dim\nself.classifier = nn.Sequential(nn.Conv2d(self.feature_shape[0], self.feature_shape[0], 3, 1, 1, bias=False), nn.BatchNorm2d(self.feature_shape[0]), nn.LeakyReLU(0.2, True), nn.Conv2d(... | <|body_start_0|>
super(Q_net, self).__init__()
self.feature_shape = feature_shape
self.class_num = class_num
self.condition_dim = condition_dim
self.classifier = nn.Sequential(nn.Conv2d(self.feature_shape[0], self.feature_shape[0], 3, 1, 1, bias=False), nn.BatchNorm2d(self.featur... | Q_net | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Q_net:
def __init__(self, feature_shape, class_num, condition_dim):
"""x_feature: batch_size x feature_shape"""
<|body_0|>
def forward(self, x):
"""Input: x: batch_size x feature_shape tensor Return: pred_class: mu: log_var:"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_072952 | 17,132 | no_license | [
{
"docstring": "x_feature: batch_size x feature_shape",
"name": "__init__",
"signature": "def __init__(self, feature_shape, class_num, condition_dim)"
},
{
"docstring": "Input: x: batch_size x feature_shape tensor Return: pred_class: mu: log_var:",
"name": "forward",
"signature": "def fo... | 2 | stack_v2_sparse_classes_30k_val_001308 | Implement the Python class `Q_net` described below.
Class description:
Implement the Q_net class.
Method signatures and docstrings:
- def __init__(self, feature_shape, class_num, condition_dim): x_feature: batch_size x feature_shape
- def forward(self, x): Input: x: batch_size x feature_shape tensor Return: pred_clas... | Implement the Python class `Q_net` described below.
Class description:
Implement the Q_net class.
Method signatures and docstrings:
- def __init__(self, feature_shape, class_num, condition_dim): x_feature: batch_size x feature_shape
- def forward(self, x): Input: x: batch_size x feature_shape tensor Return: pred_clas... | 7e1109d4393fc7e141aaa17362bb00caf65c9780 | <|skeleton|>
class Q_net:
def __init__(self, feature_shape, class_num, condition_dim):
"""x_feature: batch_size x feature_shape"""
<|body_0|>
def forward(self, x):
"""Input: x: batch_size x feature_shape tensor Return: pred_class: mu: log_var:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Q_net:
def __init__(self, feature_shape, class_num, condition_dim):
"""x_feature: batch_size x feature_shape"""
super(Q_net, self).__init__()
self.feature_shape = feature_shape
self.class_num = class_num
self.condition_dim = condition_dim
self.classifier = nn.Se... | the_stack_v2_python_sparse | info_gan/info_gan.py | smallflyingpig/pytorch_examples | train | 1 | |
97fa7925d1cc7cf74a2d0f2e9cba9ca938ccee08 | [
"try:\n config_dict = {'server': 'https://cmsweb.cern.ch/', 'database': 'registration', 'cacheduration': 1}\n config_dict.update(cfg_dict)\n self.server = CouchServer(config_dict['server'])\n self.db = self.server.connectDatabase(config_dict['database'])\n if 'location' not in reg_info.keys():\n ... | <|body_start_0|>
try:
config_dict = {'server': 'https://cmsweb.cern.ch/', 'database': 'registration', 'cacheduration': 1}
config_dict.update(cfg_dict)
self.server = CouchServer(config_dict['server'])
self.db = self.server.connectDatabase(config_dict['database'])
... | Registration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Registration:
def __init__(self, cfg_dict={}, reg_info={}):
"""Initialise the regsvc for this component,"""
<|body_0|>
def report(self):
"""'Ping' the RegSvc with a doc containing the service doc's ID and a timestamp, this can be used to provide uptime information.""... | stack_v2_sparse_classes_75kplus_train_072953 | 2,691 | no_license | [
{
"docstring": "Initialise the regsvc for this component,",
"name": "__init__",
"signature": "def __init__(self, cfg_dict={}, reg_info={})"
},
{
"docstring": "'Ping' the RegSvc with a doc containing the service doc's ID and a timestamp, this can be used to provide uptime information.",
"name... | 2 | stack_v2_sparse_classes_30k_train_000088 | Implement the Python class `Registration` described below.
Class description:
Implement the Registration class.
Method signatures and docstrings:
- def __init__(self, cfg_dict={}, reg_info={}): Initialise the regsvc for this component,
- def report(self): 'Ping' the RegSvc with a doc containing the service doc's ID a... | Implement the Python class `Registration` described below.
Class description:
Implement the Registration class.
Method signatures and docstrings:
- def __init__(self, cfg_dict={}, reg_info={}): Initialise the regsvc for this component,
- def report(self): 'Ping' the RegSvc with a doc containing the service doc's ID a... | f4cb398de940560e40491ba676b704e1489d4682 | <|skeleton|>
class Registration:
def __init__(self, cfg_dict={}, reg_info={}):
"""Initialise the regsvc for this component,"""
<|body_0|>
def report(self):
"""'Ping' the RegSvc with a doc containing the service doc's ID and a timestamp, this can be used to provide uptime information.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Registration:
def __init__(self, cfg_dict={}, reg_info={}):
"""Initialise the regsvc for this component,"""
try:
config_dict = {'server': 'https://cmsweb.cern.ch/', 'database': 'registration', 'cacheduration': 1}
config_dict.update(cfg_dict)
self.server = Co... | the_stack_v2_python_sparse | src/python/WMCore/Services/Registration/Registration.py | PerilousApricot/WMCore | train | 1 | |
c119da4c0056a45c2c8ce8fd0c9ef1176f44753f | [
"self.all_goals = all_goals\nself.all_complexities = all_complexities\nself.min_examples = min_examples",
"new_goals = goals[:]\nif len(new_goals) == 0:\n return ([], None)\nif len(new_goals) == 1:\n return (new_goals, self.all_complexities[new_goals[0]])\nall_goals_good = False\nwhile not all_goals_good an... | <|body_start_0|>
self.all_goals = all_goals
self.all_complexities = all_complexities
self.min_examples = min_examples
<|end_body_0|>
<|body_start_1|>
new_goals = goals[:]
if len(new_goals) == 0:
return ([], None)
if len(new_goals) == 1:
return (ne... | A class that selects relevant parent goals for a rule. | GoalSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoalSelector:
"""A class that selects relevant parent goals for a rule."""
def __init__(self, all_goals, all_complexities, min_examples):
"""all_goals -- all possible goals all_complexities -- complexities for each goal min_examples -- minimal number of examples for each goal"""
... | stack_v2_sparse_classes_75kplus_train_072954 | 7,660 | no_license | [
{
"docstring": "all_goals -- all possible goals all_complexities -- complexities for each goal min_examples -- minimal number of examples for each goal",
"name": "__init__",
"signature": "def __init__(self, all_goals, all_complexities, min_examples)"
},
{
"docstring": "goals -- id of goals cover... | 3 | stack_v2_sparse_classes_30k_test_002030 | Implement the Python class `GoalSelector` described below.
Class description:
A class that selects relevant parent goals for a rule.
Method signatures and docstrings:
- def __init__(self, all_goals, all_complexities, min_examples): all_goals -- all possible goals all_complexities -- complexities for each goal min_exa... | Implement the Python class `GoalSelector` described below.
Class description:
A class that selects relevant parent goals for a rule.
Method signatures and docstrings:
- def __init__(self, all_goals, all_complexities, min_examples): all_goals -- all possible goals all_complexities -- complexities for each goal min_exa... | 3fffe80644c231c0e5e1d979dd1ca6e8df2351c9 | <|skeleton|>
class GoalSelector:
"""A class that selects relevant parent goals for a rule."""
def __init__(self, all_goals, all_complexities, min_examples):
"""all_goals -- all possible goals all_complexities -- complexities for each goal min_examples -- minimal number of examples for each goal"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoalSelector:
"""A class that selects relevant parent goals for a rule."""
def __init__(self, all_goals, all_complexities, min_examples):
"""all_goals -- all possible goals all_complexities -- complexities for each goal min_examples -- minimal number of examples for each goal"""
self.all_... | the_stack_v2_python_sparse | orangecontrib/gol/goal.py | martinmozina/orange3-gol | train | 0 |
39718b9f6590ac925cf2205047a8cf86fa0d7b2d | [
"out = []\nqueue = deque([root])\nwhile queue:\n node = queue.popleft()\n out.append(str(node.val) if node else '#')\n if node:\n queue.append(node.left)\n queue.append(node.right)\nreturn ' '.join(out).rstrip(' #')",
"if not data:\n return None\nout = data.split(' ')\nnodes_with_no = [T... | <|body_start_0|>
out = []
queue = deque([root])
while queue:
node = queue.popleft()
out.append(str(node.val) if node else '#')
if node:
queue.append(node.left)
queue.append(node.right)
return ' '.join(out).rstrip(' #')
<... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_072955 | 1,524 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_test_000034 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
out = []
queue = deque([root])
while queue:
node = queue.popleft()
out.append(str(node.val) if node else '#')
if node:
... | the_stack_v2_python_sparse | problems/serializeDeserializeTree.py | joddiy/leetcode | train | 1 | |
ff9db20a210d08843bcdc396d29305c3687bd5ae | [
"self.key = key\nself.title = title\nself.intro_description = intro_description\nself.outro_description = outro_description\nself.first_room = first_room\nif not convonodes_files:\n convonodes_files = []\nif not dialogevents_files:\n dialogevents_files = []\nif not events_files:\n events_files = []\nif not... | <|body_start_0|>
self.key = key
self.title = title
self.intro_description = intro_description
self.outro_description = outro_description
self.first_room = first_room
if not convonodes_files:
convonodes_files = []
if not dialogevents_files:
... | Chapter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chapter:
def __init__(self, key, title, intro_description, outro_description, map_files, first_room=None, convonodes_files=None, dialogevents_files=None, events_files=None, topics_files=None, end_conditions=None, chapter_state=None, alternate_intro=None):
""":param key: :param title: :pa... | stack_v2_sparse_classes_75kplus_train_072956 | 19,371 | permissive | [
{
"docstring": ":param key: :param title: :param intro_description: :param outro_description: :param map_files: :param first_room: :param convonodes_files: :param dialogevents_files: :param events_files: :param topics_files: :param end_conditions: :param chapter_state:",
"name": "__init__",
"signature":... | 6 | stack_v2_sparse_classes_30k_train_020707 | Implement the Python class `Chapter` described below.
Class description:
Implement the Chapter class.
Method signatures and docstrings:
- def __init__(self, key, title, intro_description, outro_description, map_files, first_room=None, convonodes_files=None, dialogevents_files=None, events_files=None, topics_files=Non... | Implement the Python class `Chapter` described below.
Class description:
Implement the Chapter class.
Method signatures and docstrings:
- def __init__(self, key, title, intro_description, outro_description, map_files, first_room=None, convonodes_files=None, dialogevents_files=None, events_files=None, topics_files=Non... | e44cc2f7ce19bbfa04de3a4fee959651024b276b | <|skeleton|>
class Chapter:
def __init__(self, key, title, intro_description, outro_description, map_files, first_room=None, convonodes_files=None, dialogevents_files=None, events_files=None, topics_files=None, end_conditions=None, chapter_state=None, alternate_intro=None):
""":param key: :param title: :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Chapter:
def __init__(self, key, title, intro_description, outro_description, map_files, first_room=None, convonodes_files=None, dialogevents_files=None, events_files=None, topics_files=None, end_conditions=None, chapter_state=None, alternate_intro=None):
""":param key: :param title: :param intro_desc... | the_stack_v2_python_sparse | chapters.py | Frankkie/Thesis-Project-IF-Game | train | 5 | |
3f952f8736fef69e586dd6895e4bc34485093dfa | [
"if not session:\n return None\ntry:\n cover_member = CoverMember.objects.get(cover_id=session.user['id'])\nexcept CoverMember.DoesNotExist:\n return None\ncover_member.update_member(session.user)\nreturn cover_member",
"try:\n return CoverMember.objects.get(pk=user_id)\nexcept CoverMember.DoesNotExis... | <|body_start_0|>
if not session:
return None
try:
cover_member = CoverMember.objects.get(cover_id=session.user['id'])
except CoverMember.DoesNotExist:
return None
cover_member.update_member(session.user)
return cover_member
<|end_body_0|>
<|bo... | An authentication backend for authentication Cover members that are already known to the system. | CoversiteAuthBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoversiteAuthBackend:
"""An authentication backend for authentication Cover members that are already known to the system."""
def authenticate(self, request, session=None):
"""Authenticates a known Cover Member based on the a CoverSession object. Updates the locally stored data of the... | stack_v2_sparse_classes_75kplus_train_072957 | 1,896 | no_license | [
{
"docstring": "Authenticates a known Cover Member based on the a CoverSession object. Updates the locally stored data of the member and returns an authenticated CoverMember object or None if no member could be authenticated.",
"name": "authenticate",
"signature": "def authenticate(self, request, sessio... | 2 | stack_v2_sparse_classes_30k_train_016284 | Implement the Python class `CoversiteAuthBackend` described below.
Class description:
An authentication backend for authentication Cover members that are already known to the system.
Method signatures and docstrings:
- def authenticate(self, request, session=None): Authenticates a known Cover Member based on the a Co... | Implement the Python class `CoversiteAuthBackend` described below.
Class description:
An authentication backend for authentication Cover members that are already known to the system.
Method signatures and docstrings:
- def authenticate(self, request, session=None): Authenticates a known Cover Member based on the a Co... | 90708a9c36269538610e5ffa588abf1a069d1672 | <|skeleton|>
class CoversiteAuthBackend:
"""An authentication backend for authentication Cover members that are already known to the system."""
def authenticate(self, request, session=None):
"""Authenticates a known Cover Member based on the a CoverSession object. Updates the locally stored data of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoversiteAuthBackend:
"""An authentication backend for authentication Cover members that are already known to the system."""
def authenticate(self, request, session=None):
"""Authenticates a known Cover Member based on the a CoverSession object. Updates the locally stored data of the member and r... | the_stack_v2_python_sparse | web/CoverAccounts/backends.py | StudCee/tutoring | train | 1 |
ba7d32f0c22dad5f9d3b537b5fe295d3b430a3d2 | [
"super().__init__(*args, **kwargs)\nself.add_argument('--config', action=ActionConfigFile, help='Path to a configuration file in json or yaml format.')\nself.callback_keys: List[str] = []\nself.optimizers_and_lr_schedulers: Dict[str, Tuple[Union[Type, Tuple[Type, ...]], str]] = {}",
"if callable(lightning_class) ... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.add_argument('--config', action=ActionConfigFile, help='Path to a configuration file in json or yaml format.')
self.callback_keys: List[str] = []
self.optimizers_and_lr_schedulers: Dict[str, Tuple[Union[Type, Tuple[Type, ...]], str]... | Extension of jsonargparse's ArgumentParser for pytorch-lightning. | LightningArgumentParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightningArgumentParser:
"""Extension of jsonargparse's ArgumentParser for pytorch-lightning."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize argument parser that supports configuration file input. For full details of accepted arguments see `ArgumentParser.__i... | stack_v2_sparse_classes_75kplus_train_072958 | 22,230 | permissive | [
{
"docstring": "Initialize argument parser that supports configuration file input. For full details of accepted arguments see `ArgumentParser.__init__ <https://jsonargparse.readthedocs.io/en/stable/#jsonargparse.core.ArgumentParser.__init__>`_.",
"name": "__init__",
"signature": "def __init__(self, *arg... | 4 | stack_v2_sparse_classes_30k_train_002134 | Implement the Python class `LightningArgumentParser` described below.
Class description:
Extension of jsonargparse's ArgumentParser for pytorch-lightning.
Method signatures and docstrings:
- def __init__(self, *args: Any, **kwargs: Any) -> None: Initialize argument parser that supports configuration file input. For f... | Implement the Python class `LightningArgumentParser` described below.
Class description:
Extension of jsonargparse's ArgumentParser for pytorch-lightning.
Method signatures and docstrings:
- def __init__(self, *args: Any, **kwargs: Any) -> None: Initialize argument parser that supports configuration file input. For f... | fc6c97a43d65b49561c896bf05bc1c75536d0dc0 | <|skeleton|>
class LightningArgumentParser:
"""Extension of jsonargparse's ArgumentParser for pytorch-lightning."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize argument parser that supports configuration file input. For full details of accepted arguments see `ArgumentParser.__i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LightningArgumentParser:
"""Extension of jsonargparse's ArgumentParser for pytorch-lightning."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize argument parser that supports configuration file input. For full details of accepted arguments see `ArgumentParser.__init__ <https:... | the_stack_v2_python_sparse | src/flash/core/utilities/lightning_cli.py | Lightning-Universe/lightning-flash | train | 58 |
ace5390ae2073f33f74daa9079b3792a97c139fb | [
"self.w = None\nself.finish_value = 10 ** (-5)\nself.eta = eta\nself.verbose = True",
"X, y = check_X_y(X, y, multi_output=False)\nself.X_train_, self.y_train_ = (np.copy(X), np.copy(y))\nn_samples, n_features = X.shape\nintercepted_X = BaseEstimator.add_columns(X)\nself.w = np.random.normal(0, 1, size=n_features... | <|body_start_0|>
self.w = None
self.finish_value = 10 ** (-5)
self.eta = eta
self.verbose = True
<|end_body_0|>
<|body_start_1|>
X, y = check_X_y(X, y, multi_output=False)
self.X_train_, self.y_train_ = (np.copy(X), np.copy(y))
n_samples, n_features = X.shape
... | simple perceptron model f(x) = sign(<w, x>) Attributes ---------- w : array, shape = (n_features,) weight variable | SimplePerceptron | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimplePerceptron:
"""simple perceptron model f(x) = sign(<w, x>) Attributes ---------- w : array, shape = (n_features,) weight variable"""
def __init__(self, eta=10 ** (-3), verbose=False):
"""Parameters ---------- eta : float learning rate when eta = 1 , eta is named eta=1の時固定増分誤り訂正... | stack_v2_sparse_classes_75kplus_train_072959 | 2,363 | no_license | [
{
"docstring": "Parameters ---------- eta : float learning rate when eta = 1 , eta is named eta=1の時固定増分誤り訂正法と呼ぶ",
"name": "__init__",
"signature": "def __init__(self, eta=10 ** (-3), verbose=False)"
},
{
"docstring": "Fit linear model with perceptron criterion. E_{p} = - \\\\Sigma_{n} \\\\mathbf... | 3 | stack_v2_sparse_classes_30k_test_002432 | Implement the Python class `SimplePerceptron` described below.
Class description:
simple perceptron model f(x) = sign(<w, x>) Attributes ---------- w : array, shape = (n_features,) weight variable
Method signatures and docstrings:
- def __init__(self, eta=10 ** (-3), verbose=False): Parameters ---------- eta : float ... | Implement the Python class `SimplePerceptron` described below.
Class description:
simple perceptron model f(x) = sign(<w, x>) Attributes ---------- w : array, shape = (n_features,) weight variable
Method signatures and docstrings:
- def __init__(self, eta=10 ** (-3), verbose=False): Parameters ---------- eta : float ... | 1eb2ef783fdc5b363e290e85beb83d3e15dff623 | <|skeleton|>
class SimplePerceptron:
"""simple perceptron model f(x) = sign(<w, x>) Attributes ---------- w : array, shape = (n_features,) weight variable"""
def __init__(self, eta=10 ** (-3), verbose=False):
"""Parameters ---------- eta : float learning rate when eta = 1 , eta is named eta=1の時固定増分誤り訂正... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimplePerceptron:
"""simple perceptron model f(x) = sign(<w, x>) Attributes ---------- w : array, shape = (n_features,) weight variable"""
def __init__(self, eta=10 ** (-3), verbose=False):
"""Parameters ---------- eta : float learning rate when eta = 1 , eta is named eta=1の時固定増分誤り訂正法と呼ぶ"""
... | the_stack_v2_python_sparse | sdnn/simple_perceptron.py | gatakaba/machine_learning | train | 2 |
7d35545b6372aec057a4a78c9d8a50f8c8eacd90 | [
"try:\n selectionSortK([1, 2, 3], 2)\nexcept:\n self.fail('Error while calling selectionSortK')",
"items = [3, 2, 4, 1, 5]\nselectionSortK(items, 0)\nself.assertEqual(items, [3, 2, 4, 1, 5], 'Calling selectionSortK with K=0 should do nothing!')",
"items = [3, 2, 4, 1, 5]\nselectionSortK(items, 0)\nif item... | <|body_start_0|>
try:
selectionSortK([1, 2, 3], 2)
except:
self.fail('Error while calling selectionSortK')
<|end_body_0|>
<|body_start_1|>
items = [3, 2, 4, 1, 5]
selectionSortK(items, 0)
self.assertEqual(items, [3, 2, 4, 1, 5], 'Calling selectionSortK wi... | TestProblem3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProblem3:
def test_API(self):
"""P3: Sanity Test: Is selectionSortK callable?"""
<|body_0|>
def test_doNothing(self):
"""P3: Does sorting the first k elements with k=0 do nothing?"""
<|body_1|>
def test_severalPasses(self):
"""P3: Sorting a d... | stack_v2_sparse_classes_75kplus_train_072960 | 11,207 | no_license | [
{
"docstring": "P3: Sanity Test: Is selectionSortK callable?",
"name": "test_API",
"signature": "def test_API(self)"
},
{
"docstring": "P3: Does sorting the first k elements with k=0 do nothing?",
"name": "test_doNothing",
"signature": "def test_doNothing(self)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_013051 | Implement the Python class `TestProblem3` described below.
Class description:
Implement the TestProblem3 class.
Method signatures and docstrings:
- def test_API(self): P3: Sanity Test: Is selectionSortK callable?
- def test_doNothing(self): P3: Does sorting the first k elements with k=0 do nothing?
- def test_several... | Implement the Python class `TestProblem3` described below.
Class description:
Implement the TestProblem3 class.
Method signatures and docstrings:
- def test_API(self): P3: Sanity Test: Is selectionSortK callable?
- def test_doNothing(self): P3: Does sorting the first k elements with k=0 do nothing?
- def test_several... | d4f32507a5f581ad8ee0ce84e6cd92daac0941d7 | <|skeleton|>
class TestProblem3:
def test_API(self):
"""P3: Sanity Test: Is selectionSortK callable?"""
<|body_0|>
def test_doNothing(self):
"""P3: Does sorting the first k elements with k=0 do nothing?"""
<|body_1|>
def test_severalPasses(self):
"""P3: Sorting a d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProblem3:
def test_API(self):
"""P3: Sanity Test: Is selectionSortK callable?"""
try:
selectionSortK([1, 2, 3], 2)
except:
self.fail('Error while calling selectionSortK')
def test_doNothing(self):
"""P3: Does sorting the first k elements with k=... | the_stack_v2_python_sparse | Homework5/hw5_test.py | pillowfication/ECS-32B | train | 1 | |
2917d4d981ea280b119b4d23c1d564f9870db7f4 | [
"key = self.request.get('key')\nif not self.assert_xsrf_token_or_fail(self.request, QUESTIONNAIRE_XSRF_TOKEN_NAME, {}):\n return\nuser = self.get_user()\nif user is None:\n return\nstudent = models.Student.get_enrolled_student_by_user(user)\nif student is None:\n return\nentity = StudentFormEntity.load_or_... | <|body_start_0|>
key = self.request.get('key')
if not self.assert_xsrf_token_or_fail(self.request, QUESTIONNAIRE_XSRF_TOKEN_NAME, {}):
return
user = self.get_user()
if user is None:
return
student = models.Student.get_enrolled_student_by_user(user)
... | The REST Handler provides GET and PUT methods for the form data. | QuestionnaireHandler | [
"Apache-2.0",
"CC-BY-3.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionnaireHandler:
"""The REST Handler provides GET and PUT methods for the form data."""
def get(self):
"""GET method is called when the page with the questionnaire loads."""
<|body_0|>
def post(self):
"""POST method called when the student submits answers.""... | stack_v2_sparse_classes_75kplus_train_072961 | 11,898 | permissive | [
{
"docstring": "GET method is called when the page with the questionnaire loads.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "POST method called when the student submits answers.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006021 | Implement the Python class `QuestionnaireHandler` described below.
Class description:
The REST Handler provides GET and PUT methods for the form data.
Method signatures and docstrings:
- def get(self): GET method is called when the page with the questionnaire loads.
- def post(self): POST method called when the stude... | Implement the Python class `QuestionnaireHandler` described below.
Class description:
The REST Handler provides GET and PUT methods for the form data.
Method signatures and docstrings:
- def get(self): GET method is called when the page with the questionnaire loads.
- def post(self): POST method called when the stude... | 64f5ea13a8d85b9ef057dddae888a427b1396df6 | <|skeleton|>
class QuestionnaireHandler:
"""The REST Handler provides GET and PUT methods for the form data."""
def get(self):
"""GET method is called when the page with the questionnaire loads."""
<|body_0|>
def post(self):
"""POST method called when the student submits answers.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionnaireHandler:
"""The REST Handler provides GET and PUT methods for the form data."""
def get(self):
"""GET method is called when the page with the questionnaire loads."""
key = self.request.get('key')
if not self.assert_xsrf_token_or_fail(self.request, QUESTIONNAIRE_XSRF_T... | the_stack_v2_python_sparse | coursebuilder/modules/questionnaire/questionnaire.py | ram8647/gcb-clone-v111 | train | 1 |
2cce7854ee27a022df4afb0c7c05990ba945a62f | [
"self.sheet = work_book[sheet_name]\nself.rows = list(self.sheet.rows)\nself.title = [column.value for column in self.rows[4]]\nself.case_infos = []\nself.default_host = self.sheet.cell(row=4, column=2).value\nself.login_info = CaseInfo()\nself.build_longin_info()\nself.build_request_info()",
"self.login_info.met... | <|body_start_0|>
self.sheet = work_book[sheet_name]
self.rows = list(self.sheet.rows)
self.title = [column.value for column in self.rows[4]]
self.case_infos = []
self.default_host = self.sheet.cell(row=4, column=2).value
self.login_info = CaseInfo()
self.build_lon... | CaseInfoHolder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseInfoHolder:
def __init__(self, work_book, sheet_name):
"""解析当前 sheet 页为 CaseInfo 对象列表 :param work_book: 整个工作簿 :param sheet_name: 当前 sheet 页"""
<|body_0|>
def build_longin_info(self):
"""构建请求登录的信息"""
<|body_1|>
def build_request_info(self):
""... | stack_v2_sparse_classes_75kplus_train_072962 | 8,311 | permissive | [
{
"docstring": "解析当前 sheet 页为 CaseInfo 对象列表 :param work_book: 整个工作簿 :param sheet_name: 当前 sheet 页",
"name": "__init__",
"signature": "def __init__(self, work_book, sheet_name)"
},
{
"docstring": "构建请求登录的信息",
"name": "build_longin_info",
"signature": "def build_longin_info(self)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_006345 | Implement the Python class `CaseInfoHolder` described below.
Class description:
Implement the CaseInfoHolder class.
Method signatures and docstrings:
- def __init__(self, work_book, sheet_name): 解析当前 sheet 页为 CaseInfo 对象列表 :param work_book: 整个工作簿 :param sheet_name: 当前 sheet 页
- def build_longin_info(self): 构建请求登录的信息
... | Implement the Python class `CaseInfoHolder` described below.
Class description:
Implement the CaseInfoHolder class.
Method signatures and docstrings:
- def __init__(self, work_book, sheet_name): 解析当前 sheet 页为 CaseInfo 对象列表 :param work_book: 整个工作簿 :param sheet_name: 当前 sheet 页
- def build_longin_info(self): 构建请求登录的信息
... | d7008343c25ec7f47acb670ae5c9b9b5f0593d63 | <|skeleton|>
class CaseInfoHolder:
def __init__(self, work_book, sheet_name):
"""解析当前 sheet 页为 CaseInfo 对象列表 :param work_book: 整个工作簿 :param sheet_name: 当前 sheet 页"""
<|body_0|>
def build_longin_info(self):
"""构建请求登录的信息"""
<|body_1|>
def build_request_info(self):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaseInfoHolder:
def __init__(self, work_book, sheet_name):
"""解析当前 sheet 页为 CaseInfo 对象列表 :param work_book: 整个工作簿 :param sheet_name: 当前 sheet 页"""
self.sheet = work_book[sheet_name]
self.rows = list(self.sheet.rows)
self.title = [column.value for column in self.rows[4]]
... | the_stack_v2_python_sparse | backend/util/temp_excel_handler.py | felixu1992/testing-platform | train | 0 | |
cc19112ee95a9d2bf915268c7a0c35acca1869c1 | [
"roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}\nz = 0\nfor i in range(0, len(s) - 1):\n if roman[s[i]] < roman[s[i + 1]]:\n z -= roman[s[i]]\n else:\n z += roman[s[i]]\nreturn z + roman[s[-1]]",
"from __builtin__ import xrange\nroman = {'M': 1000, 'D': 500, 'C': 100... | <|body_start_0|>
roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i + 1]]:
z -= roman[s[i]]
else:
z += roman[s[i]]
return z + roman[s[-1]]
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def romanToInt(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def rewrite(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
... | stack_v2_sparse_classes_75kplus_train_072963 | 1,507 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "romanToInt",
"signature": "def romanToInt(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "rewrite",
"signature": "def rewrite(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045054 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s): :type s: str :rtype: int
- def rewrite(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s): :type s: str :rtype: int
- def rewrite(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def romanToInt(self, s):
""":type s:... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def romanToInt(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def rewrite(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def romanToInt(self, s):
""":type s: str :rtype: int"""
roman = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i + 1]]:
z -= roman[s[i]]
else:
... | the_stack_v2_python_sparse | co_ms/13_Roman_to_Integer.py | vsdrun/lc_public | train | 6 | |
b6c6d9c6c0350a8cf5e1027aa8c843127d9c157e | [
"logs.log_info('You are using the vgCa channel type: Cav1.3')\nself.time_unit = 1000.0\nself.vrev = 113.0\nTexpt = 21.0\nself.m = 1.0 / (1 + np.exp((V - -30.0) / -6))\nself.h = 1.0 / (1 + np.exp((V - -80.0) / 6.4))\nself._mpower = 2\nself._hpower = 1",
"self._mInf = 1.0 / (1 + np.exp((V - -30.0) / -6))\nself._mTa... | <|body_start_0|>
logs.log_info('You are using the vgCa channel type: Cav1.3')
self.time_unit = 1000.0
self.vrev = 113.0
Texpt = 21.0
self.m = 1.0 / (1 + np.exp((V - -30.0) / -6))
self.h = 1.0 / (1 + np.exp((V - -80.0) / 6.4))
self._mpower = 2
self._hpower ... | Low voltage activating L-type calcium channel model from Avery et al. Reference: Avery RB. et al. Multiple channel types contribute to the low-voltage-activated calcium current in hippocampal CA3 pyramidal neurons. J. Neurosci., 1996 Sep 15 , 16 (5567-82). | Cav1p3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cav1p3:
"""Low voltage activating L-type calcium channel model from Avery et al. Reference: Avery RB. et al. Multiple channel types contribute to the low-voltage-activated calcium current in hippocampal CA3 pyramidal neurons. J. Neurosci., 1996 Sep 15 , 16 (5567-82)."""
def _init_state(self,... | stack_v2_sparse_classes_75kplus_train_072964 | 22,487 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `Cav1p3` described below.
Class description:
Low voltage activating L-type calcium channel model from Avery et al. Reference: Avery RB. et al. Multiple channel types contribute to the low-voltage-activated calcium current in hippocampal CA3 pyramidal neurons. J. Neurosci., 1996 Sep 15 , 16 (... | Implement the Python class `Cav1p3` described below.
Class description:
Low voltage activating L-type calcium channel model from Avery et al. Reference: Avery RB. et al. Multiple channel types contribute to the low-voltage-activated calcium current in hippocampal CA3 pyramidal neurons. J. Neurosci., 1996 Sep 15 , 16 (... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class Cav1p3:
"""Low voltage activating L-type calcium channel model from Avery et al. Reference: Avery RB. et al. Multiple channel types contribute to the low-voltage-activated calcium current in hippocampal CA3 pyramidal neurons. J. Neurosci., 1996 Sep 15 , 16 (5567-82)."""
def _init_state(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cav1p3:
"""Low voltage activating L-type calcium channel model from Avery et al. Reference: Avery RB. et al. Multiple channel types contribute to the low-voltage-activated calcium current in hippocampal CA3 pyramidal neurons. J. Neurosci., 1996 Sep 15 , 16 (5567-82)."""
def _init_state(self, V):
... | the_stack_v2_python_sparse | betse/science/channels/vg_ca.py | R-Stefano/betse-ml | train | 0 |
04e09c95b452b28a4575e817943c51407109db12 | [
"def _get_next_moves(move_id):\n if move_id:\n next_moves = _get_next_moves(fields.first(move_id.move_dest_ids))\n if next_moves:\n return move_id | next_moves\n else:\n return move_id\n return False\nself._check_change_permitted()\nres = super(ChangeProductionQty, s... | <|body_start_0|>
def _get_next_moves(move_id):
if move_id:
next_moves = _get_next_moves(fields.first(move_id.move_dest_ids))
if next_moves:
return move_id | next_moves
else:
return move_id
return Fals... | ChangeProductionQty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeProductionQty:
def change_prod_qty(self):
"""When the production quantity is changed, also change the quantity of related moves"""
<|body_0|>
def _check_change_permitted(self):
"""Check increase or decrease percentage is not more than 10%"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_072965 | 1,817 | no_license | [
{
"docstring": "When the production quantity is changed, also change the quantity of related moves",
"name": "change_prod_qty",
"signature": "def change_prod_qty(self)"
},
{
"docstring": "Check increase or decrease percentage is not more than 10%",
"name": "_check_change_permitted",
"sig... | 2 | stack_v2_sparse_classes_30k_train_017117 | Implement the Python class `ChangeProductionQty` described below.
Class description:
Implement the ChangeProductionQty class.
Method signatures and docstrings:
- def change_prod_qty(self): When the production quantity is changed, also change the quantity of related moves
- def _check_change_permitted(self): Check inc... | Implement the Python class `ChangeProductionQty` described below.
Class description:
Implement the ChangeProductionQty class.
Method signatures and docstrings:
- def change_prod_qty(self): When the production quantity is changed, also change the quantity of related moves
- def _check_change_permitted(self): Check inc... | c04e2b9730db07848c153d8245d2df65ec4e2c8f | <|skeleton|>
class ChangeProductionQty:
def change_prod_qty(self):
"""When the production quantity is changed, also change the quantity of related moves"""
<|body_0|>
def _check_change_permitted(self):
"""Check increase or decrease percentage is not more than 10%"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangeProductionQty:
def change_prod_qty(self):
"""When the production quantity is changed, also change the quantity of related moves"""
def _get_next_moves(move_id):
if move_id:
next_moves = _get_next_moves(fields.first(move_id.move_dest_ids))
if ne... | the_stack_v2_python_sparse | altinkaya_mrp/wizard/change_production_qty.py | aaltinisik/customaddons | train | 15 | |
fa44979042dbe3d67e3c6bdb19fd72f031e8aa7a | [
"super().__init__(name)\nif not all((i >= 0 for i in vocab)):\n raise ValueError('Negative vocabulary tokens are not supported.')\nself._dtype = dtype\nself._vocab_size = len(vocab) + 1\nvocab_lookup = np.zeros((np.max(vocab) + 1,), dtype=np.int32)\nvocab_lookup[vocab] = np.arange(1, len(vocab) + 1, dtype=np.int... | <|body_start_0|>
super().__init__(name)
if not all((i >= 0 for i in vocab)):
raise ValueError('Negative vocabulary tokens are not supported.')
self._dtype = dtype
self._vocab_size = len(vocab) + 1
vocab_lookup = np.zeros((np.max(vocab) + 1,), dtype=np.int32)
v... | Embedding module for sparse vocabulary. Supports unknown tokens that lay between 0 and max(vocab). | SparseOneHot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseOneHot:
"""Embedding module for sparse vocabulary. Supports unknown tokens that lay between 0 and max(vocab)."""
def __init__(self, vocab: Sequence[int], dtype: tf.DType=tf.float32, name: Optional[Text]=None):
"""Initializes the sparse one hot module. Args: vocab: A list of non... | stack_v2_sparse_classes_75kplus_train_072966 | 4,272 | permissive | [
{
"docstring": "Initializes the sparse one hot module. Args: vocab: A list of non-negative integer vocabulary tokens. embed_dim: Embedding dimension. name: An optional string name for the module.",
"name": "__init__",
"signature": "def __init__(self, vocab: Sequence[int], dtype: tf.DType=tf.float32, nam... | 2 | null | Implement the Python class `SparseOneHot` described below.
Class description:
Embedding module for sparse vocabulary. Supports unknown tokens that lay between 0 and max(vocab).
Method signatures and docstrings:
- def __init__(self, vocab: Sequence[int], dtype: tf.DType=tf.float32, name: Optional[Text]=None): Initiali... | Implement the Python class `SparseOneHot` described below.
Class description:
Embedding module for sparse vocabulary. Supports unknown tokens that lay between 0 and max(vocab).
Method signatures and docstrings:
- def __init__(self, vocab: Sequence[int], dtype: tf.DType=tf.float32, name: Optional[Text]=None): Initiali... | 8dca03e9be92e2d8297a4bc34248939af5c7ec3b | <|skeleton|>
class SparseOneHot:
"""Embedding module for sparse vocabulary. Supports unknown tokens that lay between 0 and max(vocab)."""
def __init__(self, vocab: Sequence[int], dtype: tf.DType=tf.float32, name: Optional[Text]=None):
"""Initializes the sparse one hot module. Args: vocab: A list of non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparseOneHot:
"""Embedding module for sparse vocabulary. Supports unknown tokens that lay between 0 and max(vocab)."""
def __init__(self, vocab: Sequence[int], dtype: tf.DType=tf.float32, name: Optional[Text]=None):
"""Initializes the sparse one hot module. Args: vocab: A list of non-negative int... | the_stack_v2_python_sparse | sc2_imitation_learning/common/layers.py | chscheller/sc2_imitation_learning | train | 10 |
206691c411c4523db8c1020b2047f28dfbf3ed9f | [
"filename, _ = os.path.splitext(os.path.basename(annopath))\nfilename = filename.replace('gt_', '')\nif self._image_ext:\n return os.path.join(self._icdar_dir, 'Images', filename + self._image_ext)\nelse:\n path = glob.glob(os.path.join(self._icdar_dir, 'Images', filename + '.*'))\n if len(path) != 1:\n ... | <|body_start_0|>
filename, _ = os.path.splitext(os.path.basename(annopath))
filename = filename.replace('gt_', '')
if self._image_ext:
return os.path.join(self._icdar_dir, 'Images', filename + self._image_ext)
else:
path = glob.glob(os.path.join(self._icdar_dir, '... | ICDARTextDetectionDatasetMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICDARTextDetectionDatasetMixin:
def _imgpath(self, annopath):
""":param annopath: path containing .txt :return: path of jpg"""
<|body_0|>
def _get_image(self, index):
""":param index: int :return: rgb image(ndarray)"""
<|body_1|>
def _get_target(self, in... | stack_v2_sparse_classes_75kplus_train_072967 | 6,369 | permissive | [
{
"docstring": ":param annopath: path containing .txt :return: path of jpg",
"name": "_imgpath",
"signature": "def _imgpath(self, annopath)"
},
{
"docstring": ":param index: int :return: rgb image(ndarray)",
"name": "_get_image",
"signature": "def _get_image(self, index)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_044270 | Implement the Python class `ICDARTextDetectionDatasetMixin` described below.
Class description:
Implement the ICDARTextDetectionDatasetMixin class.
Method signatures and docstrings:
- def _imgpath(self, annopath): :param annopath: path containing .txt :return: path of jpg
- def _get_image(self, index): :param index: ... | Implement the Python class `ICDARTextDetectionDatasetMixin` described below.
Class description:
Implement the ICDARTextDetectionDatasetMixin class.
Method signatures and docstrings:
- def _imgpath(self, annopath): :param annopath: path containing .txt :return: path of jpg
- def _get_image(self, index): :param index: ... | d82aa1191c14f328c62de85e391ac6fa1b4c7ee3 | <|skeleton|>
class ICDARTextDetectionDatasetMixin:
def _imgpath(self, annopath):
""":param annopath: path containing .txt :return: path of jpg"""
<|body_0|>
def _get_image(self, index):
""":param index: int :return: rgb image(ndarray)"""
<|body_1|>
def _get_target(self, in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ICDARTextDetectionDatasetMixin:
def _imgpath(self, annopath):
""":param annopath: path containing .txt :return: path of jpg"""
filename, _ = os.path.splitext(os.path.basename(annopath))
filename = filename.replace('gt_', '')
if self._image_ext:
return os.path.join(s... | the_stack_v2_python_sparse | dl/data/txtdetn/datasets/icdar.py | flyingGH/pytorch.dl | train | 0 | |
33112e4a63f4035ddb0defd25cda9086d12ef5d7 | [
"is_optional, game_name = _is_optional_game(basename)\nif is_optional:\n if game_name not in _AVAILABLE_GAMES:\n logging.info('Skipping %s because %s is not built in.', basename, game_name)\n return\nfile_path = os.path.join(path, basename)\nexpected, actual = generate_playthrough.replay(file_path)... | <|body_start_0|>
is_optional, game_name = _is_optional_game(basename)
if is_optional:
if game_name not in _AVAILABLE_GAMES:
logging.info('Skipping %s because %s is not built in.', basename, game_name)
return
file_path = os.path.join(path, basename)
... | PlaythroughTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaythroughTest:
def run_test(self, path, basename):
"""Instantiated for each test case in main, below."""
<|body_0|>
def test_all_games_tested(self):
"""Verify that every game is present in the playthroughs."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072968 | 4,203 | permissive | [
{
"docstring": "Instantiated for each test case in main, below.",
"name": "run_test",
"signature": "def run_test(self, path, basename)"
},
{
"docstring": "Verify that every game is present in the playthroughs.",
"name": "test_all_games_tested",
"signature": "def test_all_games_tested(sel... | 2 | stack_v2_sparse_classes_30k_train_037171 | Implement the Python class `PlaythroughTest` described below.
Class description:
Implement the PlaythroughTest class.
Method signatures and docstrings:
- def run_test(self, path, basename): Instantiated for each test case in main, below.
- def test_all_games_tested(self): Verify that every game is present in the play... | Implement the Python class `PlaythroughTest` described below.
Class description:
Implement the PlaythroughTest class.
Method signatures and docstrings:
- def run_test(self, path, basename): Instantiated for each test case in main, below.
- def test_all_games_tested(self): Verify that every game is present in the play... | 6f3551fd990053cf2287b380fb9ad0b2a2607c18 | <|skeleton|>
class PlaythroughTest:
def run_test(self, path, basename):
"""Instantiated for each test case in main, below."""
<|body_0|>
def test_all_games_tested(self):
"""Verify that every game is present in the playthroughs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlaythroughTest:
def run_test(self, path, basename):
"""Instantiated for each test case in main, below."""
is_optional, game_name = _is_optional_game(basename)
if is_optional:
if game_name not in _AVAILABLE_GAMES:
logging.info('Skipping %s because %s is not ... | the_stack_v2_python_sparse | open_spiel/integration_tests/playthrough_test.py | sarahperrin/open_spiel | train | 3 | |
1881dbc3cb4f9c790e7b4d323a563f9491a2c8d7 | [
"s_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\nflag = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}\ni, result = (0, 0)\ns_len = len(s)\nif s_len == 1:\n return s_dict.get(s[0])\nwhile i < s_len:\n if s[i:i + 2] in flag:\n result += flag.get(s[i:i + 2])\n ... | <|body_start_0|>
s_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
flag = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
i, result = (0, 0)
s_len = len(s)
if s_len == 1:
return s_dict.get(s[0])
while i < s_len:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def romanToInt(self, s):
"""将定义的和特殊定义的都放在字典序中。 首先一开始读取两个判断是否在特殊定义里面,如果不在就判断是否在普通定义里面,然后相加。 :type s: str :rtype: int"""
<|body_0|>
def romanToInt(self, s):
"""题目给出的罗马数字都是正确的。 所以我们可以从0开始判断,当前的如果比下一个小的话就说明这两个连续的是特殊的整数。 s[n] > s[n+1] 说明当前s[n]代表一个数 s[n] < s[n+1]... | stack_v2_sparse_classes_75kplus_train_072969 | 1,820 | no_license | [
{
"docstring": "将定义的和特殊定义的都放在字典序中。 首先一开始读取两个判断是否在特殊定义里面,如果不在就判断是否在普通定义里面,然后相加。 :type s: str :rtype: int",
"name": "romanToInt",
"signature": "def romanToInt(self, s)"
},
{
"docstring": "题目给出的罗马数字都是正确的。 所以我们可以从0开始判断,当前的如果比下一个小的话就说明这两个连续的是特殊的整数。 s[n] > s[n+1] 说明当前s[n]代表一个数 s[n] < s[n+1] 说明s[n]和s[n... | 2 | stack_v2_sparse_classes_30k_train_042318 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s): 将定义的和特殊定义的都放在字典序中。 首先一开始读取两个判断是否在特殊定义里面,如果不在就判断是否在普通定义里面,然后相加。 :type s: str :rtype: int
- def romanToInt(self, s): 题目给出的罗马数字都是正确的。 所以我们可以从0开始判断,当前的如果比下一个... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def romanToInt(self, s): 将定义的和特殊定义的都放在字典序中。 首先一开始读取两个判断是否在特殊定义里面,如果不在就判断是否在普通定义里面,然后相加。 :type s: str :rtype: int
- def romanToInt(self, s): 题目给出的罗马数字都是正确的。 所以我们可以从0开始判断,当前的如果比下一个... | f5de348cbc00fc24ca0282235fac6d819817d005 | <|skeleton|>
class Solution:
def romanToInt(self, s):
"""将定义的和特殊定义的都放在字典序中。 首先一开始读取两个判断是否在特殊定义里面,如果不在就判断是否在普通定义里面,然后相加。 :type s: str :rtype: int"""
<|body_0|>
def romanToInt(self, s):
"""题目给出的罗马数字都是正确的。 所以我们可以从0开始判断,当前的如果比下一个小的话就说明这两个连续的是特殊的整数。 s[n] > s[n+1] 说明当前s[n]代表一个数 s[n] < s[n+1]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def romanToInt(self, s):
"""将定义的和特殊定义的都放在字典序中。 首先一开始读取两个判断是否在特殊定义里面,如果不在就判断是否在普通定义里面,然后相加。 :type s: str :rtype: int"""
s_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
flag = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
i, res... | the_stack_v2_python_sparse | 10-20/13.py | hubogle/PythonCode | train | 0 | |
e4d2f703e437a3ffeb872fcf2ec0838ae7975942 | [
"super(Bed, self).__init__(image=Bed.image, x=games.mouse.x, bottom=games.screen.height)\nself.score = games.Text(value=0, size=25, color=color.pink, top=5, right=games.screen.width - 10)\ngames.screen.add(self.score)",
"self.x = games.mouse.x\nif self.left < 0:\n self.left = 0\nif self.right > games.screen.wi... | <|body_start_0|>
super(Bed, self).__init__(image=Bed.image, x=games.mouse.x, bottom=games.screen.height)
self.score = games.Text(value=0, size=25, color=color.pink, top=5, right=games.screen.width - 10)
games.screen.add(self.score)
<|end_body_0|>
<|body_start_1|>
self.x = games.mouse.x
... | łóżko sterowane myszką gracza służące do łapania spadających kotów | Bed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bed:
"""łóżko sterowane myszką gracza służące do łapania spadających kotów"""
def __init__(self):
"""Initialize Bed object and create Text object for score."""
<|body_0|>
def update(self):
"""Zmień pozycję na wyznaczoną przez współrzędną x myszy."""
<|bod... | stack_v2_sparse_classes_75kplus_train_072970 | 4,200 | no_license | [
{
"docstring": "Initialize Bed object and create Text object for score.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Zmień pozycję na wyznaczoną przez współrzędną x myszy.",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Sprawdź... | 3 | stack_v2_sparse_classes_30k_train_035197 | Implement the Python class `Bed` described below.
Class description:
łóżko sterowane myszką gracza służące do łapania spadających kotów
Method signatures and docstrings:
- def __init__(self): Initialize Bed object and create Text object for score.
- def update(self): Zmień pozycję na wyznaczoną przez współrzędną x my... | Implement the Python class `Bed` described below.
Class description:
łóżko sterowane myszką gracza służące do łapania spadających kotów
Method signatures and docstrings:
- def __init__(self): Initialize Bed object and create Text object for score.
- def update(self): Zmień pozycję na wyznaczoną przez współrzędną x my... | 1820285ced12a6296c44356203fd9a52367ba0d0 | <|skeleton|>
class Bed:
"""łóżko sterowane myszką gracza służące do łapania spadających kotów"""
def __init__(self):
"""Initialize Bed object and create Text object for score."""
<|body_0|>
def update(self):
"""Zmień pozycję na wyznaczoną przez współrzędną x myszy."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bed:
"""łóżko sterowane myszką gracza służące do łapania spadających kotów"""
def __init__(self):
"""Initialize Bed object and create Text object for score."""
super(Bed, self).__init__(image=Bed.image, x=games.mouse.x, bottom=games.screen.height)
self.score = games.Text(value=0, ... | the_stack_v2_python_sparse | 11 - grafika/KosmiczneKoty/kosmiczneKoty_theGame.py | justynast/python-dla-kazdego | train | 0 |
2a3e260cc743f647ee3862dedaac7184ec8114b7 | [
"if target < 0:\n return\nif target == 0:\n res.append(path)\n return\nfor i in range(begin, size):\n self.dfs(candidates, i, size, path + [candidates[i]], res, target - candidates[i])",
"size = len(candidates)\nif size == 0:\n return []\npath, res = ([], [])\nself.dfs(candidates, 0, size, path, re... | <|body_start_0|>
if target < 0:
return
if target == 0:
res.append(path)
return
for i in range(begin, size):
self.dfs(candidates, i, size, path + [candidates[i]], res, target - candidates[i])
<|end_body_0|>
<|body_start_1|>
size = len(candi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, candidates, begin, size, path, res, target):
"""回溯递归方法,避免重复需要剪枝。每一枝使用begin记录当前index位置从后回溯 回溯结束条件:target <= 0 & begin < len(candidates)"""
<|body_0|>
def combinationSum(self, candidates: list, target: int) -> list:
"""回溯"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_072971 | 1,433 | no_license | [
{
"docstring": "回溯递归方法,避免重复需要剪枝。每一枝使用begin记录当前index位置从后回溯 回溯结束条件:target <= 0 & begin < len(candidates)",
"name": "dfs",
"signature": "def dfs(self, candidates, begin, size, path, res, target)"
},
{
"docstring": "回溯",
"name": "combinationSum",
"signature": "def combinationSum(self, candid... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, candidates, begin, size, path, res, target): 回溯递归方法,避免重复需要剪枝。每一枝使用begin记录当前index位置从后回溯 回溯结束条件:target <= 0 & begin < len(candidates)
- def combinationSum(self, candi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, candidates, begin, size, path, res, target): 回溯递归方法,避免重复需要剪枝。每一枝使用begin记录当前index位置从后回溯 回溯结束条件:target <= 0 & begin < len(candidates)
- def combinationSum(self, candi... | d265eb981a7586d46d0ced3accc2ea186dc7691c | <|skeleton|>
class Solution:
def dfs(self, candidates, begin, size, path, res, target):
"""回溯递归方法,避免重复需要剪枝。每一枝使用begin记录当前index位置从后回溯 回溯结束条件:target <= 0 & begin < len(candidates)"""
<|body_0|>
def combinationSum(self, candidates: list, target: int) -> list:
"""回溯"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dfs(self, candidates, begin, size, path, res, target):
"""回溯递归方法,避免重复需要剪枝。每一枝使用begin记录当前index位置从后回溯 回溯结束条件:target <= 0 & begin < len(candidates)"""
if target < 0:
return
if target == 0:
res.append(path)
return
for i in range(beg... | the_stack_v2_python_sparse | HOT 100/39组合总和.py | odinfor/leetcode | train | 0 | |
325fbf053795413e392bdfa484e193cfefd49874 | [
"self.prefix_sum_array = []\nprefix_sum = 0\nfor weight in w:\n prefix_sum += weight\n self.prefix_sum_array.append(prefix_sum)\nself.total_sum = prefix_sum",
"from bisect import bisect_left\nprefix_sum = self.total_sum * random.random()\nreturn bisect_left(self.prefix_sum_array, prefix_sum)"
] | <|body_start_0|>
self.prefix_sum_array = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sum_array.append(prefix_sum)
self.total_sum = prefix_sum
<|end_body_0|>
<|body_start_1|>
from bisect import bisect_left
prefix_sum = self.... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefix_sum_array = []
prefix_sum = 0
for weight in w:
prefix_su... | stack_v2_sparse_classes_75kplus_train_072972 | 648 | permissive | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027767 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | bf03743a3676ca9a8c107f92cf3858b6887d0308 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.prefix_sum_array = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sum_array.append(prefix_sum)
self.total_sum = prefix_sum
def pickIndex(self):
""":r... | the_stack_v2_python_sparse | python/528_random_pick_with_weight.py | liaison/LeetCode | train | 17 | |
fe1cc95e1389adb73dd967b81a4e4041d0e6fa9a | [
"super(MixedLoss, self).__init__(mode)\nif not isinstance(losses, list):\n raise TypeError('`losses` must be a list!')\nif not isinstance(coef, list):\n raise TypeError('`coef` must be a list!')\nlen_losses = len(losses)\nlen_coef = len(coef)\nif len_losses != len_coef:\n raise ValueError('The length of `l... | <|body_start_0|>
super(MixedLoss, self).__init__(mode)
if not isinstance(losses, list):
raise TypeError('`losses` must be a list!')
if not isinstance(coef, list):
raise TypeError('`coef` must be a list!')
len_losses = len(losses)
len_coef = len(coef)
... | Weighted computations for multiple Loss. The advantage is that mixed loss training can be achieved without changing the networking code. Args: losses (list[nn.Layer]): A list consisting of multiple loss classes coef (list[float|int]): Weighting coefficient of multiple loss Returns: A callable object of MixedLoss. | MixedLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixedLoss:
"""Weighted computations for multiple Loss. The advantage is that mixed loss training can be achieved without changing the networking code. Args: losses (list[nn.Layer]): A list consisting of multiple loss classes coef (list[float|int]): Weighting coefficient of multiple loss Returns: ... | stack_v2_sparse_classes_75kplus_train_072973 | 2,624 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, mode, losses, coef)"
},
{
"docstring": "分类",
"name": "__clas__",
"signature": "def __clas__(self, logits, labels, info=None)"
},
{
"docstring": "分割",
"name": "__seg__",
"signature": "def __seg__(s... | 3 | stack_v2_sparse_classes_30k_val_001550 | Implement the Python class `MixedLoss` described below.
Class description:
Weighted computations for multiple Loss. The advantage is that mixed loss training can be achieved without changing the networking code. Args: losses (list[nn.Layer]): A list consisting of multiple loss classes coef (list[float|int]): Weighting... | Implement the Python class `MixedLoss` described below.
Class description:
Weighted computations for multiple Loss. The advantage is that mixed loss training can be achieved without changing the networking code. Args: losses (list[nn.Layer]): A list consisting of multiple loss classes coef (list[float|int]): Weighting... | f3932a934404899249f80098134df4b2d24e7d4e | <|skeleton|>
class MixedLoss:
"""Weighted computations for multiple Loss. The advantage is that mixed loss training can be achieved without changing the networking code. Args: losses (list[nn.Layer]): A list consisting of multiple loss classes coef (list[float|int]): Weighting coefficient of multiple loss Returns: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MixedLoss:
"""Weighted computations for multiple Loss. The advantage is that mixed loss training can be achieved without changing the networking code. Args: losses (list[nn.Layer]): A list consisting of multiple loss classes coef (list[float|int]): Weighting coefficient of multiple loss Returns: A callable ob... | the_stack_v2_python_sparse | CV/Effective Transformer-based Solution for RSNA Intracranial Hemorrhage Detection/easymia/optimizer/losses/mixed_loss.py | Weili-NLP/Research | train | 0 |
eb76c48b4098b66197a1f57073924a8d8bda6956 | [
"reader = csv.reader(data)\nnext(reader)\nreturn collections.Counter(map(lambda item: self.safe_name(item[4]), reader))",
"reader = csv.reader(data)\nnext(reader)\nenum = list()\nmiss = [\"extend_enum(cls, 'Unassigned_0x%s' % hex(value)[2:].upper().zfill(2), value)\", 'return cls(value)']\nfor item in reader:\n ... | <|body_start_0|>
reader = csv.reader(data)
next(reader)
return collections.Counter(map(lambda item: self.safe_name(item[4]), reader))
<|end_body_0|>
<|body_start_1|>
reader = csv.reader(data)
next(reader)
enum = list()
miss = ["extend_enum(cls, 'Unassigned_0x%s' ... | Destination Options and Hop-by-Hop Options | Option | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Option:
"""Destination Options and Hop-by-Hop Options"""
def count(self, data):
"""Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings."""
<|body_0|>
def process(self, data):
"""Process CSV data. Args: data (List[str]): CSV d... | stack_v2_sparse_classes_75kplus_train_072974 | 3,793 | permissive | [
{
"docstring": "Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.",
"name": "count",
"signature": "def count(self, data)"
},
{
"docstring": "Process CSV data. Args: data (List[str]): CSV data. Returns: List[str]: Enumeration fields. List[str]: Missing fie... | 2 | stack_v2_sparse_classes_30k_train_028551 | Implement the Python class `Option` described below.
Class description:
Destination Options and Hop-by-Hop Options
Method signatures and docstrings:
- def count(self, data): Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.
- def process(self, data): Process CSV data. Args: da... | Implement the Python class `Option` described below.
Class description:
Destination Options and Hop-by-Hop Options
Method signatures and docstrings:
- def count(self, data): Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings.
- def process(self, data): Process CSV data. Args: da... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class Option:
"""Destination Options and Hop-by-Hop Options"""
def count(self, data):
"""Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings."""
<|body_0|>
def process(self, data):
"""Process CSV data. Args: data (List[str]): CSV d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Option:
"""Destination Options and Hop-by-Hop Options"""
def count(self, data):
"""Count field records. Args: data (List[str]): CSV data. Returns: Counter: Field recordings."""
reader = csv.reader(data)
next(reader)
return collections.Counter(map(lambda item: self.safe_nam... | the_stack_v2_python_sparse | pcapkit/vendor/ipv6/option.py | stjordanis/PyPCAPKit | train | 0 |
2c86e4980cc4aa7ca84b3aebea1a7cd1254c959f | [
"if columns is not None:\n if isinstance(columns, list) or isinstance(columns, tuple):\n self.columns = columns\n else:\n raise NameError('Invalid type {}'.format(type(columns)))\nelse:\n self.columns = columns",
"if not isinstance(X, pd.core.frame.DataFrame):\n raise NameError('Invalid ... | <|body_start_0|>
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise NameError('Invalid type {}'.format(type(columns)))
else:
self.columns = columns
<|end_body_0|>
<|bo... | This transformer handles missing values. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FillNaTransformer_median/ | FillNaTransformer_median | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillNaTransformer_median:
"""This transformer handles missing values. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FillNaTransformer_median/"""
def __... | stack_v2_sparse_classes_75kplus_train_072975 | 18,127 | permissive | [
{
"docstring": "Init replace missing values.",
"name": "__init__",
"signature": "def __init__(self, columns=None)"
},
{
"docstring": "Gets the columns to make a replace missing values. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samples is the number... | 3 | stack_v2_sparse_classes_30k_train_052129 | Implement the Python class `FillNaTransformer_median` described below.
Class description:
This transformer handles missing values. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/F... | Implement the Python class `FillNaTransformer_median` described below.
Class description:
This transformer handles missing values. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/F... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class FillNaTransformer_median:
"""This transformer handles missing values. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FillNaTransformer_median/"""
def __... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FillNaTransformer_median:
"""This transformer handles missing values. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FillNaTransformer_median/"""
def __init__(self, ... | the_stack_v2_python_sparse | mlearner/preprocessing/replace_na.py | jaisenbe58r/MLearner | train | 9 |
bb9b51e9b5c998117125e72ca10c2970cab35843 | [
"super(Generator, self).__init__()\nself.ngpu = ngpu\nself.conditioning = nn.Linear(2, NOISE_LAYERS)\nself.merge = nn.Bilinear(NOISE_LAYERS, NOISE_LAYERS, NOISE_LAYERS)\nself.main = nn.Sequential(nn.ConvTranspose2d(NOISE_LAYERS, NGF * 8, 6, 1, 0, bias=False), nn.BatchNorm2d(NGF * 8), nn.ReLU(True), nn.ConvTranspose... | <|body_start_0|>
super(Generator, self).__init__()
self.ngpu = ngpu
self.conditioning = nn.Linear(2, NOISE_LAYERS)
self.merge = nn.Bilinear(NOISE_LAYERS, NOISE_LAYERS, NOISE_LAYERS)
self.main = nn.Sequential(nn.ConvTranspose2d(NOISE_LAYERS, NGF * 8, 6, 1, 0, bias=False), nn.Batch... | Implementation of initial conditional generator network of initial GAN Attributes: ngpu (int): number of gpus to use conditioning (torch.nn.modules.linear.Linear): linear transformation of conditions merge (torch.nn.modules.linear.Bilinear): bilinearly merges conditions with noise main (torch.nn.modules.container.Seque... | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Implementation of initial conditional generator network of initial GAN Attributes: ngpu (int): number of gpus to use conditioning (torch.nn.modules.linear.Linear): linear transformation of conditions merge (torch.nn.modules.linear.Bilinear): bilinearly merges conditions with noise m... | stack_v2_sparse_classes_75kplus_train_072976 | 4,071 | no_license | [
{
"docstring": "Creates initial generator and the sequence of operations it applies Parameters: ngpu (int): number of GPUs to use",
"name": "__init__",
"signature": "def __init__(self, ngpu)"
},
{
"docstring": "merges input noise and conditions, and forwards merged noise through the layers Param... | 2 | null | Implement the Python class `Generator` described below.
Class description:
Implementation of initial conditional generator network of initial GAN Attributes: ngpu (int): number of gpus to use conditioning (torch.nn.modules.linear.Linear): linear transformation of conditions merge (torch.nn.modules.linear.Bilinear): bi... | Implement the Python class `Generator` described below.
Class description:
Implementation of initial conditional generator network of initial GAN Attributes: ngpu (int): number of gpus to use conditioning (torch.nn.modules.linear.Linear): linear transformation of conditions merge (torch.nn.modules.linear.Bilinear): bi... | a0198c89317d4d5646cfe3ec2cfdaa1831ae06c5 | <|skeleton|>
class Generator:
"""Implementation of initial conditional generator network of initial GAN Attributes: ngpu (int): number of gpus to use conditioning (torch.nn.modules.linear.Linear): linear transformation of conditions merge (torch.nn.modules.linear.Bilinear): bilinearly merges conditions with noise m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Generator:
"""Implementation of initial conditional generator network of initial GAN Attributes: ngpu (int): number of gpus to use conditioning (torch.nn.modules.linear.Linear): linear transformation of conditions merge (torch.nn.modules.linear.Bilinear): bilinearly merges conditions with noise main (torch.nn... | the_stack_v2_python_sparse | src/networks/generator/generator.py | theovincent/HeightmapsGeneration | train | 1 |
769c3a66ce6a95e7a332e75240a327f9198ed6f6 | [
"Feature.__init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete)\nself.hgnc_id_list = None\nself.mod_id_list = None\nself.agr_gene_id = None\nself.promoted_gene_type = None",
"self.agr_gene_id = 'FB:{}'.format(self.uniquename)\nif type(self.hgnc_id_list) != list:\n log.warni... | <|body_start_0|>
Feature.__init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete)
self.hgnc_id_list = None
self.mod_id_list = None
self.agr_gene_id = None
self.promoted_gene_type = None
<|end_body_0|>
<|body_start_1|>
self.agr_gene_id =... | Define a FlyBase Gene object. | Gene | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gene:
"""Define a FlyBase Gene object."""
def __init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete):
"""Initialize a FlyBase Gene class object. See Feature for details."""
<|body_0|>
def pick_gene_id(self):
"""Pick between FB... | stack_v2_sparse_classes_75kplus_train_072977 | 26,965 | permissive | [
{
"docstring": "Initialize a FlyBase Gene class object. See Feature for details.",
"name": "__init__",
"signature": "def __init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete)"
},
{
"docstring": "Pick between FB, HGNC or other MOD ID to report.",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_008300 | Implement the Python class `Gene` described below.
Class description:
Define a FlyBase Gene object.
Method signatures and docstrings:
- def __init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete): Initialize a FlyBase Gene class object. See Feature for details.
- def pick_gene_id(s... | Implement the Python class `Gene` described below.
Class description:
Define a FlyBase Gene object.
Method signatures and docstrings:
- def __init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete): Initialize a FlyBase Gene class object. See Feature for details.
- def pick_gene_id(s... | 4ca26874eaa7e10c474d9d5036af50d52e75976d | <|skeleton|>
class Gene:
"""Define a FlyBase Gene object."""
def __init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete):
"""Initialize a FlyBase Gene class object. See Feature for details."""
<|body_0|>
def pick_gene_id(self):
"""Pick between FB... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Gene:
"""Define a FlyBase Gene object."""
def __init__(self, feature_id, organism_id, name, uniquename, feature_type, analysis, obsolete):
"""Initialize a FlyBase Gene class object. See Feature for details."""
Feature.__init__(self, feature_id, organism_id, name, uniquename, feature_type,... | the_stack_v2_python_sparse | harvdev_utils/psycopg_functions/fb_feature_classes.py | FlyBase/harvdev-utils | train | 2 |
05dc71bb312fa184ceb8e4f1e3ade6552287802c | [
"self.__bind = bind\nself.__connect = connect\nself.__status = False\nself.__thread = False\nself.__lock = _thread.allocate_lock()",
"self.__lock.acquire()\nself.__status = True\nif not self.__thread:\n self.__thread = True\n _thread.start_new_thread(self.__proxy, ())\nself.__lock.release()",
"self.__lock... | <|body_start_0|>
self.__bind = bind
self.__connect = connect
self.__status = False
self.__thread = False
self.__lock = _thread.allocate_lock()
<|end_body_0|>
<|body_start_1|>
self.__lock.acquire()
self.__status = True
if not self.__thread:
sel... | Proxy(bind, connect) -> Proxy | Proxy | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Proxy:
"""Proxy(bind, connect) -> Proxy"""
def __init__(self, bind, connect):
"""Initialize the Proxy object."""
<|body_0|>
def start(self):
"""Start the Proxy object."""
<|body_1|>
def stop(self):
"""Stop the Proxy object."""
<|body_... | stack_v2_sparse_classes_75kplus_train_072978 | 2,567 | permissive | [
{
"docstring": "Initialize the Proxy object.",
"name": "__init__",
"signature": "def __init__(self, bind, connect)"
},
{
"docstring": "Start the Proxy object.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Stop the Proxy object.",
"name": "stop",
"si... | 5 | stack_v2_sparse_classes_30k_train_046952 | Implement the Python class `Proxy` described below.
Class description:
Proxy(bind, connect) -> Proxy
Method signatures and docstrings:
- def __init__(self, bind, connect): Initialize the Proxy object.
- def start(self): Start the Proxy object.
- def stop(self): Stop the Proxy object.
- def __proxy(self): Private clas... | Implement the Python class `Proxy` described below.
Class description:
Proxy(bind, connect) -> Proxy
Method signatures and docstrings:
- def __init__(self, bind, connect): Initialize the Proxy object.
- def start(self): Start the Proxy object.
- def stop(self): Stop the Proxy object.
- def __proxy(self): Private clas... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class Proxy:
"""Proxy(bind, connect) -> Proxy"""
def __init__(self, bind, connect):
"""Initialize the Proxy object."""
<|body_0|>
def start(self):
"""Start the Proxy object."""
<|body_1|>
def stop(self):
"""Stop the Proxy object."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Proxy:
"""Proxy(bind, connect) -> Proxy"""
def __init__(self, bind, connect):
"""Initialize the Proxy object."""
self.__bind = bind
self.__connect = connect
self.__status = False
self.__thread = False
self.__lock = _thread.allocate_lock()
def start(sel... | the_stack_v2_python_sparse | recipes/Python/502204_Module_Running_Simple/recipe-502204.py | betty29/code-1 | train | 0 |
0158e834fbffc1a35336a530d965052a7b3bfa45 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | ObservacionPreCytgList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservacionPreCytgList:
def get(self):
"""To fetch several observations (preliminares de la CyTG). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (preliminar de la CyTG)."""
... | stack_v2_sparse_classes_75kplus_train_072979 | 16,123 | no_license | [
{
"docstring": "To fetch several observations (preliminares de la CyTG). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "To create an observation (preliminar de la CyTG).",
"name": "post",
"si... | 2 | stack_v2_sparse_classes_30k_test_002283 | Implement the Python class `ObservacionPreCytgList` described below.
Class description:
Implement the ObservacionPreCytgList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (preliminares de la CyTG). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages... | Implement the Python class `ObservacionPreCytgList` described below.
Class description:
Implement the ObservacionPreCytgList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (preliminares de la CyTG). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ObservacionPreCytgList:
def get(self):
"""To fetch several observations (preliminares de la CyTG). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (preliminar de la CyTG)."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObservacionPreCytgList:
def get(self):
"""To fetch several observations (preliminares de la CyTG). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/observaciones_pre_cytg.py | Telematica/knight-rider | train | 1 | |
cba5442b3b745736fc7902a385ef1dbd615b3363 | [
"self.error_message = {}\nevent_type_list = Operation('ModelEventType').read(name=event_type)\nif event_type_list:\n self.event_type_id = event_type_list[0].id\n self.event_type = event_type_list[0].name\nelse:\n self.error_message['message'] = 'Cannot log event because event type {} does not exist'.format... | <|body_start_0|>
self.error_message = {}
event_type_list = Operation('ModelEventType').read(name=event_type)
if event_type_list:
self.event_type_id = event_type_list[0].id
self.event_type = event_type_list[0].name
else:
self.error_message['message'] = ... | Functions called by the API for event objects. | MethodEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodEvent:
"""Functions called by the API for event objects."""
def __init__(self, event_type):
"""Initialize class."""
<|body_0|>
def log_event(self, indicator_id, batch_id, data_set=None):
"""Manage session status and event logging for the corresponding data ... | stack_v2_sparse_classes_75kplus_train_072980 | 4,207 | permissive | [
{
"docstring": "Initialize class.",
"name": "__init__",
"signature": "def __init__(self, event_type)"
},
{
"docstring": "Manage session status and event logging for the corresponding data quality indicator. Return event object. If event is Start: * Insert a new session * New session status is se... | 2 | stack_v2_sparse_classes_30k_train_012208 | Implement the Python class `MethodEvent` described below.
Class description:
Functions called by the API for event objects.
Method signatures and docstrings:
- def __init__(self, event_type): Initialize class.
- def log_event(self, indicator_id, batch_id, data_set=None): Manage session status and event logging for th... | Implement the Python class `MethodEvent` described below.
Class description:
Functions called by the API for event objects.
Method signatures and docstrings:
- def __init__(self, event_type): Initialize class.
- def log_event(self, indicator_id, batch_id, data_set=None): Manage session status and event logging for th... | eaa9f2df5536d1bac678571cee1040f0667fd25f | <|skeleton|>
class MethodEvent:
"""Functions called by the API for event objects."""
def __init__(self, event_type):
"""Initialize class."""
<|body_0|>
def log_event(self, indicator_id, batch_id, data_set=None):
"""Manage session status and event logging for the corresponding data ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MethodEvent:
"""Functions called by the API for event objects."""
def __init__(self, event_type):
"""Initialize class."""
self.error_message = {}
event_type_list = Operation('ModelEventType').read(name=event_type)
if event_type_list:
self.event_type_id = event_... | the_stack_v2_python_sparse | api/method_event.py | teddycarebears/data-quality | train | 0 |
5e5fff93fde5e7b9ec3346ee9239eb5ccce7c37c | [
"self.message = message\nif status:\n if status.upper() in STATES:\n self.status = status.upper()\n else:\n raise ValueError(f'{status} is not a recognised review state.')\nelse:\n self.status = None\nif timestamp:\n self.timestamp = timestamp\nelse:\n self.timestamp = datetime.now()",
... | <|body_start_0|>
self.message = message
if status:
if status.upper() in STATES:
self.status = status.upper()
else:
raise ValueError(f'{status} is not a recognised review state.')
else:
self.status = None
if timestamp:
... | A review message. | ReviewMessage | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewMessage:
"""A review message."""
def __init__(self, message, production, status=None, timestamp=None):
"""Review messages are individual messages related to the review of a production. Parameters ---------- message : str The review message. This can be free-form text. productio... | stack_v2_sparse_classes_75kplus_train_072981 | 3,873 | permissive | [
{
"docstring": "Review messages are individual messages related to the review of a production. Parameters ---------- message : str The review message. This can be free-form text. production : `Asimov.event.Production` The production which this message is attached to. state: str, {\"REJECTED\", \"APPROVED\", \"P... | 3 | stack_v2_sparse_classes_30k_train_000324 | Implement the Python class `ReviewMessage` described below.
Class description:
A review message.
Method signatures and docstrings:
- def __init__(self, message, production, status=None, timestamp=None): Review messages are individual messages related to the review of a production. Parameters ---------- message : str ... | Implement the Python class `ReviewMessage` described below.
Class description:
A review message.
Method signatures and docstrings:
- def __init__(self, message, production, status=None, timestamp=None): Review messages are individual messages related to the review of a production. Parameters ---------- message : str ... | a5ab19d8841d72a4c8754ebed91aafdbb8cdf73c | <|skeleton|>
class ReviewMessage:
"""A review message."""
def __init__(self, message, production, status=None, timestamp=None):
"""Review messages are individual messages related to the review of a production. Parameters ---------- message : str The review message. This can be free-form text. productio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReviewMessage:
"""A review message."""
def __init__(self, message, production, status=None, timestamp=None):
"""Review messages are individual messages related to the review of a production. Parameters ---------- message : str The review message. This can be free-form text. production : `Asimov.e... | the_stack_v2_python_sparse | asimov/review.py | transientlunatic/asimov | train | 3 |
2bb687a146058139522e0630c08b2505e73d2816 | [
"redirect_msg = self._MaybeRedirectToDomainDefaultProject(mr)\nlogging.info(redirect_msg)\ncan_create_project = permissions.CanCreateProject(mr.perms)\npipeline = projectsearch.ProjectSearchPipeline(mr, self.services)\nwith work_env.WorkEnv(mr, self.services) as we:\n starred_projects = we.ListStarredProjects()\... | <|body_start_0|>
redirect_msg = self._MaybeRedirectToDomainDefaultProject(mr)
logging.info(redirect_msg)
can_create_project = permissions.CanCreateProject(mr.perms)
pipeline = projectsearch.ProjectSearchPipeline(mr, self.services)
with work_env.WorkEnv(mr, self.services) as we:
... | HostingHome shows the project list and link to create a project. | HostingHome | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostingHome:
"""HostingHome shows the project list and link to create a project."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rend... | stack_v2_sparse_classes_75kplus_train_072982 | 3,972 | permissive | [
{
"docstring": "Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering the page.",
"name": "GatherPageData",
"signature": "def GatherPageData(self, mr)"
},
{
"docstring": "If the... | 2 | stack_v2_sparse_classes_30k_train_042898 | Implement the Python class `HostingHome` described below.
Class description:
HostingHome shows the project list and link to create a project.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from ... | Implement the Python class `HostingHome` described below.
Class description:
HostingHome shows the project list and link to create a project.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from ... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class HostingHome:
"""HostingHome shows the project list and link to create a project."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rend... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostingHome:
"""HostingHome shows the project list and link to create a project."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering the pag... | the_stack_v2_python_sparse | appengine/monorail/sitewide/hostinghome.py | xinghun61/infra | train | 2 |
2786438838b2f7e5ff20b9f1a8dd3d0e07ccb6a4 | [
"QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)\nself.setupUi(self)\nself.load_values()\nself.buttonBox.accepted.connect(self.save_values)",
"self.rbuttonConst.setChecked(self.dialogValues['rbuttonConst'])\nself.rbuttonFadeIn.setChecked(self.dialogValues['rbuttonFadeIn'])\nself.rbutt... | <|body_start_0|>
QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.setupUi(self)
self.load_values()
self.buttonBox.accepted.connect(self.save_values)
<|end_body_0|>
<|body_start_1|>
self.rbuttonConst.setChecked(self.dialogValues['rbuttonConst'])
... | Dialog to select a time-amplitude modulation. | ChangeVolumeDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeVolumeDialog:
"""Dialog to select a time-amplitude modulation."""
def __init__(self, parent=None):
"""Initialize the dialogs elements with their last value"""
<|body_0|>
def load_values(self):
"""Load into the dialog elements the previously or default value... | stack_v2_sparse_classes_75kplus_train_072983 | 2,816 | no_license | [
{
"docstring": "Initialize the dialogs elements with their last value",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Load into the dialog elements the previously or default values.",
"name": "load_values",
"signature": "def load_values(self)"
},... | 3 | null | Implement the Python class `ChangeVolumeDialog` described below.
Class description:
Dialog to select a time-amplitude modulation.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the dialogs elements with their last value
- def load_values(self): Load into the dialog elements the previo... | Implement the Python class `ChangeVolumeDialog` described below.
Class description:
Dialog to select a time-amplitude modulation.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the dialogs elements with their last value
- def load_values(self): Load into the dialog elements the previo... | 13ec0a591636ec42e771b40e42ac5d7c98243a94 | <|skeleton|>
class ChangeVolumeDialog:
"""Dialog to select a time-amplitude modulation."""
def __init__(self, parent=None):
"""Initialize the dialogs elements with their last value"""
<|body_0|>
def load_values(self):
"""Load into the dialog elements the previously or default value... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangeVolumeDialog:
"""Dialog to select a time-amplitude modulation."""
def __init__(self, parent=None):
"""Initialize the dialogs elements with their last value"""
QDialog.__init__(self, parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.setupUi(self)
self.load_va... | the_stack_v2_python_sparse | graphic_interface/dialogs/ChangeVolumeDialog.py | ECMora/SoundLab | train | 1 |
8d2b2a183b0917a94012e56b77fa2837e644c47c | [
"if len(nums) < 2:\n return 0\nminP = nums[0]\nprofit = 0\nfor p in nums:\n profit = max(profit, p - minP)\n minP = min(minP, p)\nreturn profit",
"maxprofit = 0\nfor i in range(len(nums) - 1):\n fit = max(nums[i + 1:]) - nums[i]\n if fit > maxprofit:\n maxprofit = fit\nreturn maxprofit"
] | <|body_start_0|>
if len(nums) < 2:
return 0
minP = nums[0]
profit = 0
for p in nums:
profit = max(profit, p - minP)
minP = min(minP, p)
return profit
<|end_body_0|>
<|body_start_1|>
maxprofit = 0
for i in range(len(nums) - 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_profit(self, nums):
""":param nums: list[int] :return: int"""
<|body_0|>
def max_profit_2(self, nums):
""":param nums:list[int] :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 2:
return 0
... | stack_v2_sparse_classes_75kplus_train_072984 | 1,554 | no_license | [
{
"docstring": ":param nums: list[int] :return: int",
"name": "max_profit",
"signature": "def max_profit(self, nums)"
},
{
"docstring": ":param nums:list[int] :return: int",
"name": "max_profit_2",
"signature": "def max_profit_2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001791 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, nums): :param nums: list[int] :return: int
- def max_profit_2(self, nums): :param nums:list[int] :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, nums): :param nums: list[int] :return: int
- def max_profit_2(self, nums): :param nums:list[int] :return: int
<|skeleton|>
class Solution:
def max_prof... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def max_profit(self, nums):
""":param nums: list[int] :return: int"""
<|body_0|>
def max_profit_2(self, nums):
""":param nums:list[int] :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def max_profit(self, nums):
""":param nums: list[int] :return: int"""
if len(nums) < 2:
return 0
minP = nums[0]
profit = 0
for p in nums:
profit = max(profit, p - minP)
minP = min(minP, p)
return profit
def max_... | the_stack_v2_python_sparse | leetcode/35_maxprofit_only.py | Yara7L/python_algorithm | train | 0 | |
23400dc51cc2c2b438e4e7c396bda68e063069ff | [
"self.model = model\nself.device = device\ntry:\n target_module = _nested_getattr(model, target_module)\nexcept nn.modules.module.ModuleAttributeError:\n raise ValueError(f'`model` does not have a submodule {target_module}')\nself.extractor = ActivationExtractor()\ntarget_module.register_forward_hook(self.ext... | <|body_start_0|>
self.model = model
self.device = device
try:
target_module = _nested_getattr(model, target_module)
except nn.modules.module.ModuleAttributeError:
raise ValueError(f'`model` does not have a submodule {target_module}')
self.extractor = Activ... | ActivationOp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationOp:
def __init__(self, model: nn.Module, target_module: str, device: int=None):
"""An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted ... | stack_v2_sparse_classes_75kplus_train_072985 | 2,708 | permissive | [
{
"docstring": "An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted target_module (str): the name of the submodule of `model` (i.e. an intermediate layer) that outputs t... | 2 | stack_v2_sparse_classes_30k_train_048374 | Implement the Python class `ActivationOp` described below.
Class description:
Implement the ActivationOp class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, target_module: str, device: int=None): An Operation that runs a forward pass over each example in the dataset and stores model activa... | Implement the Python class `ActivationOp` described below.
Class description:
Implement the ActivationOp class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, target_module: str, device: int=None): An Operation that runs a forward pass over each example in the dataset and stores model activa... | 8f844199b75420d2978f73b2535a2e3f83ca1836 | <|skeleton|>
class ActivationOp:
def __init__(self, model: nn.Module, target_module: str, device: int=None):
"""An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivationOp:
def __init__(self, model: nn.Module, target_module: str, device: int=None):
"""An Operation that runs a forward pass over each example in the dataset and stores model activations in a new column. Args: model (nn.Module): the torch model from which activations are extracted target_module ... | the_stack_v2_python_sparse | robustnessgym/ops/activation.py | sushmit0109/robustness-gym | train | 0 | |
575fb940fbf80f550afc03b4ecb26a620bd0bc9b | [
"if len(str(month)) == 1:\n month = '0' + str(month)\nself.url = 'http://www.ncdc.noaa.gov/crn/newmonthsummary?' + 'station_id=1007&yyyymm=' + str(year) + str(month) + '&format=csv'\nself.response = ''\nself.save_name = s_dir + 'barrow_4_ENE_' + str(year) + str(month) + '.csv'",
"while True:\n self.response... | <|body_start_0|>
if len(str(month)) == 1:
month = '0' + str(month)
self.url = 'http://www.ncdc.noaa.gov/crn/newmonthsummary?' + 'station_id=1007&yyyymm=' + str(year) + str(month) + '&format=csv'
self.response = ''
self.save_name = s_dir + 'barrow_4_ENE_' + str(year) + str(mon... | this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year. | NCDCCsv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NCDCCsv:
"""this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year."""
def __init__(self, year, month, s_dir=''):
"""initilizes the class"""
<|body_0|>
def get_csv(self):
"... | stack_v2_sparse_classes_75kplus_train_072986 | 6,837 | no_license | [
{
"docstring": "initilizes the class",
"name": "__init__",
"signature": "def __init__(self, year, month, s_dir='')"
},
{
"docstring": "gets the .csv from the noaa website",
"name": "get_csv",
"signature": "def get_csv(self)"
},
{
"docstring": "saves the data to a file",
"name... | 3 | stack_v2_sparse_classes_30k_train_036467 | Implement the Python class `NCDCCsv` described below.
Class description:
this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year.
Method signatures and docstrings:
- def __init__(self, year, month, s_dir=''): initilizes the clas... | Implement the Python class `NCDCCsv` described below.
Class description:
this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year.
Method signatures and docstrings:
- def __init__(self, year, month, s_dir=''): initilizes the clas... | 95d0c102d649c5b028d262f5254106f997a7c77a | <|skeleton|>
class NCDCCsv:
"""this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year."""
def __init__(self, year, month, s_dir=''):
"""initilizes the class"""
<|body_0|>
def get_csv(self):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NCDCCsv:
"""this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year."""
def __init__(self, year, month, s_dir=''):
"""initilizes the class"""
if len(str(month)) == 1:
month = '0' + str(mo... | the_stack_v2_python_sparse | barrow_monthly.py | rwspicer/csv_utilities | train | 1 |
8432e9e411e5f38948431962deabff79b2ce2c0d | [
"output = dict(**kwargs)\nfor k, v in kwargs.items():\n if isinstance(v, dict):\n output[k] = cls.make_vector(**v)\nreturn cls(**output)",
"output = default_value\nif path is None:\n return output\npath_items = path.split('.')\npath_item = path_items.pop(0)\nvalue = self.get(path_item, None)\nif valu... | <|body_start_0|>
output = dict(**kwargs)
for k, v in kwargs.items():
if isinstance(v, dict):
output[k] = cls.make_vector(**v)
return cls(**output)
<|end_body_0|>
<|body_start_1|>
output = default_value
if path is None:
return output
... | SettingsVector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SettingsVector:
def make_vector(cls, **kwargs):
"""This method returns a vector with all nested dicts converted to vectors too. This creates a vector which contains other vectors containing vectors ad-nauseum down into the depths of hell."""
<|body_0|>
def get_by_path(self, ... | stack_v2_sparse_classes_75kplus_train_072987 | 6,003 | no_license | [
{
"docstring": "This method returns a vector with all nested dicts converted to vectors too. This creates a vector which contains other vectors containing vectors ad-nauseum down into the depths of hell.",
"name": "make_vector",
"signature": "def make_vector(cls, **kwargs)"
},
{
"docstring": "Th... | 2 | null | Implement the Python class `SettingsVector` described below.
Class description:
Implement the SettingsVector class.
Method signatures and docstrings:
- def make_vector(cls, **kwargs): This method returns a vector with all nested dicts converted to vectors too. This creates a vector which contains other vectors contai... | Implement the Python class `SettingsVector` described below.
Class description:
Implement the SettingsVector class.
Method signatures and docstrings:
- def make_vector(cls, **kwargs): This method returns a vector with all nested dicts converted to vectors too. This creates a vector which contains other vectors contai... | c5703ffd73dbe26b44363bc3575f9cf18519274b | <|skeleton|>
class SettingsVector:
def make_vector(cls, **kwargs):
"""This method returns a vector with all nested dicts converted to vectors too. This creates a vector which contains other vectors containing vectors ad-nauseum down into the depths of hell."""
<|body_0|>
def get_by_path(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SettingsVector:
def make_vector(cls, **kwargs):
"""This method returns a vector with all nested dicts converted to vectors too. This creates a vector which contains other vectors containing vectors ad-nauseum down into the depths of hell."""
output = dict(**kwargs)
for k, v in kwargs.i... | the_stack_v2_python_sparse | backend/lib/settingstools.py | ja-odur/puzzled | train | 0 | |
59a99cb715211fc49202e6bd4aea9bdf92b1fd0e | [
"self.host = host\nself.port = port\nself.seeds = seeds\nself.dht = DHT(self.host, self.port, seeds=self.seeds)\nif storage_filename:\n self.storage = TrellusLocalStorage(storage_filename)\nelse:\n self.storage = {}\nif hasattr(self.storage, 'close'):\n atexit.register(self.storage.close)",
"object_seria... | <|body_start_0|>
self.host = host
self.port = port
self.seeds = seeds
self.dht = DHT(self.host, self.port, seeds=self.seeds)
if storage_filename:
self.storage = TrellusLocalStorage(storage_filename)
else:
self.storage = {}
if hasattr(self.s... | TrellusServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrellusServer:
def __init__(self, host='localhost', port=6161, seeds=[], storage_filename=None):
"""Initialise TrellusServer and start the DHT server"""
<|body_0|>
def publish(self, object, name=None):
"""Publish an object to trellus, get the hash of the object back"... | stack_v2_sparse_classes_75kplus_train_072988 | 1,778 | no_license | [
{
"docstring": "Initialise TrellusServer and start the DHT server",
"name": "__init__",
"signature": "def __init__(self, host='localhost', port=6161, seeds=[], storage_filename=None)"
},
{
"docstring": "Publish an object to trellus, get the hash of the object back",
"name": "publish",
"s... | 3 | stack_v2_sparse_classes_30k_train_052802 | Implement the Python class `TrellusServer` described below.
Class description:
Implement the TrellusServer class.
Method signatures and docstrings:
- def __init__(self, host='localhost', port=6161, seeds=[], storage_filename=None): Initialise TrellusServer and start the DHT server
- def publish(self, object, name=Non... | Implement the Python class `TrellusServer` described below.
Class description:
Implement the TrellusServer class.
Method signatures and docstrings:
- def __init__(self, host='localhost', port=6161, seeds=[], storage_filename=None): Initialise TrellusServer and start the DHT server
- def publish(self, object, name=Non... | b42bfcc325dda59f2ea3089c2daa1ba8338d0e31 | <|skeleton|>
class TrellusServer:
def __init__(self, host='localhost', port=6161, seeds=[], storage_filename=None):
"""Initialise TrellusServer and start the DHT server"""
<|body_0|>
def publish(self, object, name=None):
"""Publish an object to trellus, get the hash of the object back"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrellusServer:
def __init__(self, host='localhost', port=6161, seeds=[], storage_filename=None):
"""Initialise TrellusServer and start the DHT server"""
self.host = host
self.port = port
self.seeds = seeds
self.dht = DHT(self.host, self.port, seeds=self.seeds)
i... | the_stack_v2_python_sparse | src/server.py | kennib/trellus | train | 0 | |
bf7c07b1538d98730d4beb9170e21dcb8cd8d7ea | [
"conn, cursor = get_db_cursor()\nbuild = 'toy_build'\ntranscript_dict = talon.make_transcript_dict(cursor)\nconn.close()\nedges = (14, 15, 16)\ngene_ID, transcripts = talon.search_for_transcript_prefix(edges, transcript_dict)\nassert gene_ID == None\nconn.close()",
"conn, cursor = get_db_cursor()\nbuild = 'toy_bu... | <|body_start_0|>
conn, cursor = get_db_cursor()
build = 'toy_build'
transcript_dict = talon.make_transcript_dict(cursor)
conn.close()
edges = (14, 15, 16)
gene_ID, transcripts = talon.search_for_transcript_prefix(edges, transcript_dict)
assert gene_ID == None
... | TestSearchForPrefix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSearchForPrefix:
def test_find_no_match(self):
"""Example where the toy transcript database contains no matches for the edge set, because the edges are actually a suffix."""
<|body_0|>
def test_find_match(self):
"""Example where the toy transcript database contai... | stack_v2_sparse_classes_75kplus_train_072989 | 2,565 | permissive | [
{
"docstring": "Example where the toy transcript database contains no matches for the edge set, because the edges are actually a suffix.",
"name": "test_find_no_match",
"signature": "def test_find_no_match(self)"
},
{
"docstring": "Example where the toy transcript database contains exactly one p... | 4 | stack_v2_sparse_classes_30k_train_012202 | Implement the Python class `TestSearchForPrefix` described below.
Class description:
Implement the TestSearchForPrefix class.
Method signatures and docstrings:
- def test_find_no_match(self): Example where the toy transcript database contains no matches for the edge set, because the edges are actually a suffix.
- def... | Implement the Python class `TestSearchForPrefix` described below.
Class description:
Implement the TestSearchForPrefix class.
Method signatures and docstrings:
- def test_find_no_match(self): Example where the toy transcript database contains no matches for the edge set, because the edges are actually a suffix.
- def... | 8014faed5f982e5e106ec05239e47d65878e76c3 | <|skeleton|>
class TestSearchForPrefix:
def test_find_no_match(self):
"""Example where the toy transcript database contains no matches for the edge set, because the edges are actually a suffix."""
<|body_0|>
def test_find_match(self):
"""Example where the toy transcript database contai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSearchForPrefix:
def test_find_no_match(self):
"""Example where the toy transcript database contains no matches for the edge set, because the edges are actually a suffix."""
conn, cursor = get_db_cursor()
build = 'toy_build'
transcript_dict = talon.make_transcript_dict(curs... | the_stack_v2_python_sparse | archived/qtests/test_search_for_prefix.py | kopardev/TALON | train | 0 | |
46cd9f84e080b768279232e913c4a675ec288dba | [
"if not root:\n return []\nqueue = [root]\nindex = 0\nwhile index < len(queue):\n node = queue[index]\n if node:\n queue.append(node.left)\n queue.append(node.right)\n index += 1\nwhile not queue[-1]:\n queue.pop()\nreturn ','.join([str(node.val) if node else 'null' for node in queue])"... | <|body_start_0|>
if not root:
return []
queue = [root]
index = 0
while index < len(queue):
node = queue[index]
if node:
queue.append(node.left)
queue.append(node.right)
index += 1
while not queue[-1]:... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_072990 | 1,617 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_009898 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | cb2ed3524431aea2b204fe66797f9850bbe506a9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
queue = [root]
index = 0
while index < len(queue):
node = queue[index]
if node:
queue.a... | the_stack_v2_python_sparse | archive/python/Python/breadth_first_search/297.serialize-and-deserialize-binary-tree.py | linfengzhou/LeetCode | train | 0 | |
a738ee84820c1a24d5abe31b01dd30c56ba90da6 | [
"super(VitalsWidget, self).__init__('Vitals', parent)\nself.setAllowedAreas(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea | QtCore.Qt.DockWidgetArea.RightDockWidgetArea)\nself._initUI()",
"frame = QtGui.QFrame()\nself.setWidget(frame)\nlayout = QtGui.QVBoxLayout()\nframe.setLayout(layout)\nlayout.addWidget(QtGui.QL... | <|body_start_0|>
super(VitalsWidget, self).__init__('Vitals', parent)
self.setAllowedAreas(QtCore.Qt.DockWidgetArea.LeftDockWidgetArea | QtCore.Qt.DockWidgetArea.RightDockWidgetArea)
self._initUI()
<|end_body_0|>
<|body_start_1|>
frame = QtGui.QFrame()
self.setWidget(frame)
... | A dockable widget to display rover vitals. | VitalsWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VitalsWidget:
"""A dockable widget to display rover vitals."""
def __init__(self, parent=None):
"""Create and initialize a VitalsWidget. Args: parent (QWidget): Parent Qt widget."""
<|body_0|>
def _initUI(self):
"""Private method to setup the widget UI."""
... | stack_v2_sparse_classes_75kplus_train_072991 | 1,851 | no_license | [
{
"docstring": "Create and initialize a VitalsWidget. Args: parent (QWidget): Parent Qt widget.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Private method to setup the widget UI.",
"name": "_initUI",
"signature": "def _initUI(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001437 | Implement the Python class `VitalsWidget` described below.
Class description:
A dockable widget to display rover vitals.
Method signatures and docstrings:
- def __init__(self, parent=None): Create and initialize a VitalsWidget. Args: parent (QWidget): Parent Qt widget.
- def _initUI(self): Private method to setup the... | Implement the Python class `VitalsWidget` described below.
Class description:
A dockable widget to display rover vitals.
Method signatures and docstrings:
- def __init__(self, parent=None): Create and initialize a VitalsWidget. Args: parent (QWidget): Parent Qt widget.
- def _initUI(self): Private method to setup the... | b7f6adf76ab7e52eef585497ffd9ef93d6a0a4e0 | <|skeleton|>
class VitalsWidget:
"""A dockable widget to display rover vitals."""
def __init__(self, parent=None):
"""Create and initialize a VitalsWidget. Args: parent (QWidget): Parent Qt widget."""
<|body_0|>
def _initUI(self):
"""Private method to setup the widget UI."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VitalsWidget:
"""A dockable widget to display rover vitals."""
def __init__(self, parent=None):
"""Create and initialize a VitalsWidget. Args: parent (QWidget): Parent Qt widget."""
super(VitalsWidget, self).__init__('Vitals', parent)
self.setAllowedAreas(QtCore.Qt.DockWidgetArea.... | the_stack_v2_python_sparse | BaseStation/Views/VitalsWidget.py | ISU-MAVRIC/MAVRIC_Controller | train | 0 |
fed00da94dba24da15f00ee5aca3fb5ae305036c | [
"super().__init__()\nself.df = df\nself.indices = indices\nself.ratio_ben, self.ratio_mal, self.round = params\nself.model_name = model_name\nself.divide_fun = divide_fun\nself.n_jobs = n_jobs\nself.res_dir = res_dir\nself.compute_conf_score = compute_conf_score\nid = '{}-{}-{}'.format(self.ratio_ben, self.ratio_ma... | <|body_start_0|>
super().__init__()
self.df = df
self.indices = indices
self.ratio_ben, self.ratio_mal, self.round = params
self.model_name = model_name
self.divide_fun = divide_fun
self.n_jobs = n_jobs
self.res_dir = res_dir
self.compute_conf_scor... | Implement a thread as Actor. When instantiated ConsumerActor().start(df, params, model_name, divide_fun) the class stores the parameters needed for the experiment. Everytime a message is received the actor starts running the experiment. Message content is ignored. | ConsumerActor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerActor:
"""Implement a thread as Actor. When instantiated ConsumerActor().start(df, params, model_name, divide_fun) the class stores the parameters needed for the experiment. Everytime a message is received the actor starts running the experiment. Message content is ignored."""
def __... | stack_v2_sparse_classes_75kplus_train_072992 | 3,186 | no_license | [
{
"docstring": ":param df: tuple of pandas dataframe :param indices: store indices for four sets of packed_benign, unpacked_benign, packed_malicious, unpacked_malicious :param params: tuple of ratio of packed benign, ratio of packed malicious, experiment round :param model_name: name of the sklearn model used :... | 3 | stack_v2_sparse_classes_30k_train_049174 | Implement the Python class `ConsumerActor` described below.
Class description:
Implement a thread as Actor. When instantiated ConsumerActor().start(df, params, model_name, divide_fun) the class stores the parameters needed for the experiment. Everytime a message is received the actor starts running the experiment. Mes... | Implement the Python class `ConsumerActor` described below.
Class description:
Implement a thread as Actor. When instantiated ConsumerActor().start(df, params, model_name, divide_fun) the class stores the parameters needed for the experiment. Everytime a message is received the actor starts running the experiment. Mes... | f8424953618e154f52ec95a0d36522168b5cea97 | <|skeleton|>
class ConsumerActor:
"""Implement a thread as Actor. When instantiated ConsumerActor().start(df, params, model_name, divide_fun) the class stores the parameters needed for the experiment. Everytime a message is received the actor starts running the experiment. Message content is ignored."""
def __... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsumerActor:
"""Implement a thread as Actor. When instantiated ConsumerActor().start(df, params, model_name, divide_fun) the class stores the parameters needed for the experiment. Everytime a message is received the actor starts running the experiment. Message content is ignored."""
def __init__(self, ... | the_stack_v2_python_sparse | code/experiments/actor.py | Tor4k/packware | train | 0 |
a212e9d3903531976da6f89480c480ba0efc3547 | [
"self.shape = shape\nself.x_mask = x_mask\nself.y_mask = y_mask",
"self.rectangle_mask = np.zeros(self.shape)\nself.rectangle_mask[:] = False\nself.rectangle_mask[self.x_mask[0]:self.x_mask[1], self.y_mask[0]:self.y_mask[1]] = True\nreturn self.rectangle_mask",
"if array.shape[:2] != self.shape[:2]:\n raise ... | <|body_start_0|>
self.shape = shape
self.x_mask = x_mask
self.y_mask = y_mask
<|end_body_0|>
<|body_start_1|>
self.rectangle_mask = np.zeros(self.shape)
self.rectangle_mask[:] = False
self.rectangle_mask[self.x_mask[0]:self.x_mask[1], self.y_mask[0]:self.y_mask[1]] = Tru... | Numpy array with rectangle mask to be applied on 2d or 3d array. | RectangleMask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RectangleMask:
"""Numpy array with rectangle mask to be applied on 2d or 3d array."""
def __init__(self, shape: Tuple[int, int], x_mask: Tuple[int, int], y_mask: Tuple[int, int]):
""":param shape: (x_shape, y_shape) for the original array. :param x_mask: first and last indexes for th... | stack_v2_sparse_classes_75kplus_train_072993 | 3,143 | no_license | [
{
"docstring": ":param shape: (x_shape, y_shape) for the original array. :param x_mask: first and last indexes for the mask on the 0-axis. :param y_mask: first and last indexes for the mask on the 1-axis.",
"name": "__init__",
"signature": "def __init__(self, shape: Tuple[int, int], x_mask: Tuple[int, i... | 4 | stack_v2_sparse_classes_30k_train_054293 | Implement the Python class `RectangleMask` described below.
Class description:
Numpy array with rectangle mask to be applied on 2d or 3d array.
Method signatures and docstrings:
- def __init__(self, shape: Tuple[int, int], x_mask: Tuple[int, int], y_mask: Tuple[int, int]): :param shape: (x_shape, y_shape) for the ori... | Implement the Python class `RectangleMask` described below.
Class description:
Numpy array with rectangle mask to be applied on 2d or 3d array.
Method signatures and docstrings:
- def __init__(self, shape: Tuple[int, int], x_mask: Tuple[int, int], y_mask: Tuple[int, int]): :param shape: (x_shape, y_shape) for the ori... | 736ba8ecf1f4a1f8fe0ad46bdf964aff34238abe | <|skeleton|>
class RectangleMask:
"""Numpy array with rectangle mask to be applied on 2d or 3d array."""
def __init__(self, shape: Tuple[int, int], x_mask: Tuple[int, int], y_mask: Tuple[int, int]):
""":param shape: (x_shape, y_shape) for the original array. :param x_mask: first and last indexes for th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RectangleMask:
"""Numpy array with rectangle mask to be applied on 2d or 3d array."""
def __init__(self, shape: Tuple[int, int], x_mask: Tuple[int, int], y_mask: Tuple[int, int]):
""":param shape: (x_shape, y_shape) for the original array. :param x_mask: first and last indexes for the mask on the... | the_stack_v2_python_sparse | src/hyperpy/spectral/cube_crop.py | antoinelaborde/hyperpy | train | 2 |
0b6c0e1bb0892d143c175899d01a0ce325da472c | [
"kwargs = {}\nif visitor != creator:\n kwargs.update({'is_draft': False, 'is_private': False})\nreturn creator.diaries.filter(created__year=year, created__month=month, **kwargs).order_by('-created')",
"kwargs = {}\nif visitor != creator:\n kwargs.update({'is_draft': False, 'is_private': False})\nreturn crea... | <|body_start_0|>
kwargs = {}
if visitor != creator:
kwargs.update({'is_draft': False, 'is_private': False})
return creator.diaries.filter(created__year=year, created__month=month, **kwargs).order_by('-created')
<|end_body_0|>
<|body_start_1|>
kwargs = {}
if visitor !... | Adds diary-specific functions to query entries. | DiaryManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiaryManager:
"""Adds diary-specific functions to query entries."""
def get_for_month(self, creator, visitor, year, month):
"""Diary entries visible to `visitor` for given year and month. Fall back to today's year/month if not specified."""
<|body_0|>
def get_all(self, c... | stack_v2_sparse_classes_75kplus_train_072994 | 4,213 | no_license | [
{
"docstring": "Diary entries visible to `visitor` for given year and month. Fall back to today's year/month if not specified.",
"name": "get_for_month",
"signature": "def get_for_month(self, creator, visitor, year, month)"
},
{
"docstring": "Diary entries visible to `visitor` for entire history... | 2 | stack_v2_sparse_classes_30k_train_035221 | Implement the Python class `DiaryManager` described below.
Class description:
Adds diary-specific functions to query entries.
Method signatures and docstrings:
- def get_for_month(self, creator, visitor, year, month): Diary entries visible to `visitor` for given year and month. Fall back to today's year/month if not ... | Implement the Python class `DiaryManager` described below.
Class description:
Adds diary-specific functions to query entries.
Method signatures and docstrings:
- def get_for_month(self, creator, visitor, year, month): Diary entries visible to `visitor` for given year and month. Fall back to today's year/month if not ... | f06eb905e6b28c3cefb45ce27b49ad3e8ee87093 | <|skeleton|>
class DiaryManager:
"""Adds diary-specific functions to query entries."""
def get_for_month(self, creator, visitor, year, month):
"""Diary entries visible to `visitor` for given year and month. Fall back to today's year/month if not specified."""
<|body_0|>
def get_all(self, c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiaryManager:
"""Adds diary-specific functions to query entries."""
def get_for_month(self, creator, visitor, year, month):
"""Diary entries visible to `visitor` for given year and month. Fall back to today's year/month if not specified."""
kwargs = {}
if visitor != creator:
... | the_stack_v2_python_sparse | django/diary/models.py | ccarlos/code-samples | train | 0 |
e19366ba71fcf26deaf7d4f14b2c8de980ecb346 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AlterationResponse()",
"from .search_alteration import SearchAlteration\nfrom .search_alteration_type import SearchAlterationType\nfrom .search_alteration import SearchAlteration\nfrom .search_alteration_type import SearchAlterationTyp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AlterationResponse()
<|end_body_0|>
<|body_start_1|>
from .search_alteration import SearchAlteration
from .search_alteration_type import SearchAlterationType
from .search_alterat... | AlterationResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlterationResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_75kplus_train_072995 | 3,610 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AlterationResponse",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_018634 | Implement the Python class `AlterationResponse` described below.
Class description:
Implement the AlterationResponse class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse: Creates a new instance of the appropriate class based on disc... | Implement the Python class `AlterationResponse` described below.
Class description:
Implement the AlterationResponse class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AlterationResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlterationResponse:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AlterationResponse:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Al... | the_stack_v2_python_sparse | msgraph/generated/models/alteration_response.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
1d9fb56ced2174fa69cdd81fed0f9916137a7700 | [
"n = len(rooms)\nglobal num\nglobal visit\nnum = 0\nvisit = [False for i in range(n)]\nself.dfs(rooms, 0)\nreturn num == n",
"global visit\nglobal num\nvisit[x] = True\nnum += 1\nfor index in rooms[x]:\n if not visit[index]:\n self.dfs(rooms, index)",
"num, n = (0, len(rooms))\nvisit = [False for i in... | <|body_start_0|>
n = len(rooms)
global num
global visit
num = 0
visit = [False for i in range(n)]
self.dfs(rooms, 0)
return num == n
<|end_body_0|>
<|body_start_1|>
global visit
global num
visit[x] = True
num += 1
for index... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool:
"""是否访问所有房间 Args: nums: 房子钥匙数组 Returns: 布尔值"""
<|body_0|>
def dfs(self, rooms: List[List[int]], x: int) -> None:
"""深度优先遍历 Args: rooms: 房间 x: index Returns: None"""
<|body_1|>
def c... | stack_v2_sparse_classes_75kplus_train_072996 | 3,550 | permissive | [
{
"docstring": "是否访问所有房间 Args: nums: 房子钥匙数组 Returns: 布尔值",
"name": "can_visit_all_rooms",
"signature": "def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool"
},
{
"docstring": "深度优先遍历 Args: rooms: 房间 x: index Returns: None",
"name": "dfs",
"signature": "def dfs(self, rooms: List... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool: 是否访问所有房间 Args: nums: 房子钥匙数组 Returns: 布尔值
- def dfs(self, rooms: List[List[int]], x: int) -> None: 深度优先遍历 Args: room... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool: 是否访问所有房间 Args: nums: 房子钥匙数组 Returns: 布尔值
- def dfs(self, rooms: List[List[int]], x: int) -> None: 深度优先遍历 Args: room... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool:
"""是否访问所有房间 Args: nums: 房子钥匙数组 Returns: 布尔值"""
<|body_0|>
def dfs(self, rooms: List[List[int]], x: int) -> None:
"""深度优先遍历 Args: rooms: 房间 x: index Returns: None"""
<|body_1|>
def c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool:
"""是否访问所有房间 Args: nums: 房子钥匙数组 Returns: 布尔值"""
n = len(rooms)
global num
global visit
num = 0
visit = [False for i in range(n)]
self.dfs(rooms, 0)
return num == n
def d... | the_stack_v2_python_sparse | src/leetcodepython/array/keys_and_rooms_841.py | zhangyu345293721/leetcode | train | 101 | |
f5de43e4ee5fb189bcbfceb7e487bd84451c45ec | [
"print('Нужно ввести метод для поиска нового локатора (id/xpath...) !!!')\nglobal method\nwhile True:\n for cmd in ['Quit - Закрыть и не добавлять данные', 'YES - Добавить данные']:\n print(' %s - %s' % (cmd[:1], cmd))\n cmd = input('Пожалуйста, введите команду (Q/Y) ').upper()[:1]\n if cmd == 'Q':... | <|body_start_0|>
print('Нужно ввести метод для поиска нового локатора (id/xpath...) !!!')
global method
while True:
for cmd in ['Quit - Закрыть и не добавлять данные', 'YES - Добавить данные']:
print(' %s - %s' % (cmd[:1], cmd))
cmd = input('Пожалуйста, в... | DataBaseInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataBaseInterface:
def set_method(self, table_name: str, key: str):
"""Запись метода для поиска локатора в таблицу :param table_name: название таблицы :param key: ключ (название элемента) :rtype str :return: метод для поиска локатора"""
<|body_0|>
def set_value(self, table_n... | stack_v2_sparse_classes_75kplus_train_072997 | 2,667 | no_license | [
{
"docstring": "Запись метода для поиска локатора в таблицу :param table_name: название таблицы :param key: ключ (название элемента) :rtype str :return: метод для поиска локатора",
"name": "set_method",
"signature": "def set_method(self, table_name: str, key: str)"
},
{
"docstring": "Запись знач... | 2 | stack_v2_sparse_classes_30k_train_051472 | Implement the Python class `DataBaseInterface` described below.
Class description:
Implement the DataBaseInterface class.
Method signatures and docstrings:
- def set_method(self, table_name: str, key: str): Запись метода для поиска локатора в таблицу :param table_name: название таблицы :param key: ключ (название элем... | Implement the Python class `DataBaseInterface` described below.
Class description:
Implement the DataBaseInterface class.
Method signatures and docstrings:
- def set_method(self, table_name: str, key: str): Запись метода для поиска локатора в таблицу :param table_name: название таблицы :param key: ключ (название элем... | 3eabb10c2aff74c4808bd0476c2622c01e491350 | <|skeleton|>
class DataBaseInterface:
def set_method(self, table_name: str, key: str):
"""Запись метода для поиска локатора в таблицу :param table_name: название таблицы :param key: ключ (название элемента) :rtype str :return: метод для поиска локатора"""
<|body_0|>
def set_value(self, table_n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataBaseInterface:
def set_method(self, table_name: str, key: str):
"""Запись метода для поиска локатора в таблицу :param table_name: название таблицы :param key: ключ (название элемента) :rtype str :return: метод для поиска локатора"""
print('Нужно ввести метод для поиска нового локатора (id/... | the_stack_v2_python_sparse | mobileAutoTestsBasicFramework/model/database_model/database_interface.py | Yelisey/testsAppPy | train | 0 | |
bf44bef705f056479f0efebb33885a747a70deea | [
"self.project_id = project_id\nself.cluster_id = cluster_id\ntry:\n self.tool = Tool.objects.get(id=tool_id)\nexcept Tool.DoesNotExist:\n raise ValidationError(f'invalid tool_id({tool_id})')\nself.cmd = HelmCmd(project_id=project_id, cluster_id=cluster_id)",
"itool = InstalledTool.create(request_user.userna... | <|body_start_0|>
self.project_id = project_id
self.cluster_id = cluster_id
try:
self.tool = Tool.objects.get(id=tool_id)
except Tool.DoesNotExist:
raise ValidationError(f'invalid tool_id({tool_id})')
self.cmd = HelmCmd(project_id=project_id, cluster_id=clu... | 组件管理器: 管理组件的安装, 更新和卸载 | ToolManager | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"BSD-3-Clause",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToolManager:
"""组件管理器: 管理组件的安装, 更新和卸载"""
def __init__(self, project_id: str, cluster_id: str, tool_id: int):
"""初始化 :param project_id 项目 ID :param cluster_id 集群 ID :param tool_id 组件库中的组件 ID"""
<|body_0|>
def install(self, request_user, values: Optional[str]=None) -> Inst... | stack_v2_sparse_classes_75kplus_train_072998 | 6,700 | permissive | [
{
"docstring": "初始化 :param project_id 项目 ID :param cluster_id 集群 ID :param tool_id 组件库中的组件 ID",
"name": "__init__",
"signature": "def __init__(self, project_id: str, cluster_id: str, tool_id: int)"
},
{
"docstring": "安装组件 :param request_user: 操作者信息(request.user) :param values: 安装组件时的初始配置",
"... | 4 | stack_v2_sparse_classes_30k_train_032447 | Implement the Python class `ToolManager` described below.
Class description:
组件管理器: 管理组件的安装, 更新和卸载
Method signatures and docstrings:
- def __init__(self, project_id: str, cluster_id: str, tool_id: int): 初始化 :param project_id 项目 ID :param cluster_id 集群 ID :param tool_id 组件库中的组件 ID
- def install(self, request_user, val... | Implement the Python class `ToolManager` described below.
Class description:
组件管理器: 管理组件的安装, 更新和卸载
Method signatures and docstrings:
- def __init__(self, project_id: str, cluster_id: str, tool_id: int): 初始化 :param project_id 项目 ID :param cluster_id 集群 ID :param tool_id 组件库中的组件 ID
- def install(self, request_user, val... | 859a415ef35ea1c01f0ed040956afa849a4cb7be | <|skeleton|>
class ToolManager:
"""组件管理器: 管理组件的安装, 更新和卸载"""
def __init__(self, project_id: str, cluster_id: str, tool_id: int):
"""初始化 :param project_id 项目 ID :param cluster_id 集群 ID :param tool_id 组件库中的组件 ID"""
<|body_0|>
def install(self, request_user, values: Optional[str]=None) -> Inst... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ToolManager:
"""组件管理器: 管理组件的安装, 更新和卸载"""
def __init__(self, project_id: str, cluster_id: str, tool_id: int):
"""初始化 :param project_id 项目 ID :param cluster_id 集群 ID :param tool_id 组件库中的组件 ID"""
self.project_id = project_id
self.cluster_id = cluster_id
try:
self.... | the_stack_v2_python_sparse | bcs-ui/backend/container_service/cluster_tools/manager.py | DeveloperJim/bk-bcs | train | 5 |
0f9c22d0619771241895bda5077b516105d52d89 | [
"self.x = x\nself.y = y\nself.N = np.shape(x)[0]",
"prod = 0\nfor i in range(self.N):\n for j in range(self.N):\n prod = prod + self.x[i, j] * np.conj(self.y[i, j])\nreturn prod"
] | <|body_start_0|>
self.x = x
self.y = y
self.N = np.shape(x)[0]
<|end_body_0|>
<|body_start_1|>
prod = 0
for i in range(self.N):
for j in range(self.N):
prod = prod + self.x[i, j] * np.conj(self.y[i, j])
return prod
<|end_body_1|>
| 2—D inner-product | inner_prod_2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class inner_prod_2D:
"""2—D inner-product"""
def __init__(self, x, y):
"""x,y: two 2-D signals"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the inner product"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.x = x
self.y = y
... | stack_v2_sparse_classes_75kplus_train_072999 | 4,947 | no_license | [
{
"docstring": "x,y: two 2-D signals",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the inner product",
"name": "solve",
"signature": "def solve(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042217 | Implement the Python class `inner_prod_2D` described below.
Class description:
2—D inner-product
Method signatures and docstrings:
- def __init__(self, x, y): x,y: two 2-D signals
- def solve(self): \\\\\\ METHOD: Compute the inner product | Implement the Python class `inner_prod_2D` described below.
Class description:
2—D inner-product
Method signatures and docstrings:
- def __init__(self, x, y): x,y: two 2-D signals
- def solve(self): \\\\\\ METHOD: Compute the inner product
<|skeleton|>
class inner_prod_2D:
"""2—D inner-product"""
def __init... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class inner_prod_2D:
"""2—D inner-product"""
def __init__(self, x, y):
"""x,y: two 2-D signals"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the inner product"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class inner_prod_2D:
"""2—D inner-product"""
def __init__(self, x, y):
"""x,y: two 2-D signals"""
self.x = x
self.y = y
self.N = np.shape(x)[0]
def solve(self):
"""\\\\\\ METHOD: Compute the inner product"""
prod = 0
for i in range(self.N):
... | the_stack_v2_python_sparse | 2D Signal Processing and Image De-noising/discrete_signal.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.