blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
056a2b731e675b0d89fa705378f0f8160d5b4465 | [
"file_object = open('thefile', 'w')\nfile_object.write('abc:ALL:deny')\nfile_object.close()\nmock_launchcmd.return_value = open('thefile', 'r')\nreference = TcpBusiness()\nret_list = reference.getlistinfo('/etc/hosts.deny')\nself.assertListEqual(ret_list[0], ['abc', 'ALL', 'deny'])\nfile_object2 = open('thefile2', ... | <|body_start_0|>
file_object = open('thefile', 'w')
file_object.write('abc:ALL:deny')
file_object.close()
mock_launchcmd.return_value = open('thefile', 'r')
reference = TcpBusiness()
ret_list = reference.getlistinfo('/etc/hosts.deny')
self.assertListEqual(ret_list... | TestTcpCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTcpCase:
def test_getlistinfo(self, mock_launchcmd):
"""test the GET method :param mock_launchcmd: :return:"""
<|body_0|>
def test_putlistinfo(self, mock_open):
"""test the add method :param mock_open: :return:"""
<|body_1|>
def test_deletelistinfo(s... | stack_v2_sparse_classes_36k_train_034400 | 3,180 | no_license | [
{
"docstring": "test the GET method :param mock_launchcmd: :return:",
"name": "test_getlistinfo",
"signature": "def test_getlistinfo(self, mock_launchcmd)"
},
{
"docstring": "test the add method :param mock_open: :return:",
"name": "test_putlistinfo",
"signature": "def test_putlistinfo(s... | 3 | null | Implement the Python class `TestTcpCase` described below.
Class description:
Implement the TestTcpCase class.
Method signatures and docstrings:
- def test_getlistinfo(self, mock_launchcmd): test the GET method :param mock_launchcmd: :return:
- def test_putlistinfo(self, mock_open): test the add method :param mock_ope... | Implement the Python class `TestTcpCase` described below.
Class description:
Implement the TestTcpCase class.
Method signatures and docstrings:
- def test_getlistinfo(self, mock_launchcmd): test the GET method :param mock_launchcmd: :return:
- def test_putlistinfo(self, mock_open): test the add method :param mock_ope... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class TestTcpCase:
def test_getlistinfo(self, mock_launchcmd):
"""test the GET method :param mock_launchcmd: :return:"""
<|body_0|>
def test_putlistinfo(self, mock_open):
"""test the add method :param mock_open: :return:"""
<|body_1|>
def test_deletelistinfo(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTcpCase:
def test_getlistinfo(self, mock_launchcmd):
"""test the GET method :param mock_launchcmd: :return:"""
file_object = open('thefile', 'w')
file_object.write('abc:ALL:deny')
file_object.close()
mock_launchcmd.return_value = open('thefile', 'r')
referen... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/tcp/tests.py | sdtimothy8/Coding | train | 0 | |
146fa6ee6cf70eba66fbb92a0411b127ca328b30 | [
"ret = []\nnames = IdentitySearcher.get_batch_user_name(ProfileManager.get_profile_user_oids(profile_oid), channel_model)\nperm_dict = ProfileManager.get_user_permission_lv_dict(channel_model.id)\nremove_self = ProfilePermission.PRF_CONTROL_SELF in permissions\nremove_member = ProfilePermission.PRF_CONTROL_MEMBER i... | <|body_start_0|>
ret = []
names = IdentitySearcher.get_batch_user_name(ProfileManager.get_profile_user_oids(profile_oid), channel_model)
perm_dict = ProfileManager.get_user_permission_lv_dict(channel_model.id)
remove_self = ProfilePermission.PRF_CONTROL_SELF in permissions
remove... | Helper to process the profile data. | ProfileHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileHelper:
"""Helper to process the profile data."""
def get_user_profile_controls(channel_model, profile_oid: ObjectId, requester_oid: ObjectId, permissions: Set[ProfilePermission]) -> List[ProfileControlEntry]:
"""Check if the requester can perform certain actions on members wh... | stack_v2_sparse_classes_36k_train_034401 | 4,237 | permissive | [
{
"docstring": "Check if the requester can perform certain actions on members who have the certain profile. The **certain actions** mentioned above currently are: - Control the profile attaching status Actions are unable to perform on the users who have a higher permission level. Actions also cannot be performe... | 2 | stack_v2_sparse_classes_30k_train_005050 | Implement the Python class `ProfileHelper` described below.
Class description:
Helper to process the profile data.
Method signatures and docstrings:
- def get_user_profile_controls(channel_model, profile_oid: ObjectId, requester_oid: ObjectId, permissions: Set[ProfilePermission]) -> List[ProfileControlEntry]: Check i... | Implement the Python class `ProfileHelper` described below.
Class description:
Helper to process the profile data.
Method signatures and docstrings:
- def get_user_profile_controls(channel_model, profile_oid: ObjectId, requester_oid: ObjectId, permissions: Set[ProfilePermission]) -> List[ProfileControlEntry]: Check i... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class ProfileHelper:
"""Helper to process the profile data."""
def get_user_profile_controls(channel_model, profile_oid: ObjectId, requester_oid: ObjectId, permissions: Set[ProfilePermission]) -> List[ProfileControlEntry]:
"""Check if the requester can perform certain actions on members wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileHelper:
"""Helper to process the profile data."""
def get_user_profile_controls(channel_model, profile_oid: ObjectId, requester_oid: ObjectId, permissions: Set[ProfilePermission]) -> List[ProfileControlEntry]:
"""Check if the requester can perform certain actions on members who have the ce... | the_stack_v2_python_sparse | mongodb/helper/prof.py | RxJellyBot/Jelly-Bot | train | 5 |
e91db422cfa51cc16646b53f7c3e28bfa1eb264a | [
"if not self.numero_determina.data:\n self.errlist.append('Manca numero determina')\nif not self.data_determina.data:\n self.errlist.append('Manca data determina')\nif not self.nome_direttore.data:\n self.errlist.append('Manca nome direttore')\nif not self.capitolo.data:\n self.errlist.append('Manca ind... | <|body_start_0|>
if not self.numero_determina.data:
self.errlist.append('Manca numero determina')
if not self.data_determina.data:
self.errlist.append('Manca data determina')
if not self.nome_direttore.data:
self.errlist.append('Manca nome direttore')
... | form per definizione determina fase A | DeterminaA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeterminaA:
"""form per definizione determina fase A"""
def validate(self):
"""Validazione specifica per il form"""
<|body_0|>
def renderme(self, d_prat):
"""rendering del form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.numero_d... | stack_v2_sparse_classes_36k_train_034402 | 29,683 | no_license | [
{
"docstring": "Validazione specifica per il form",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "rendering del form",
"name": "renderme",
"signature": "def renderme(self, d_prat)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017232 | Implement the Python class `DeterminaA` described below.
Class description:
form per definizione determina fase A
Method signatures and docstrings:
- def validate(self): Validazione specifica per il form
- def renderme(self, d_prat): rendering del form | Implement the Python class `DeterminaA` described below.
Class description:
form per definizione determina fase A
Method signatures and docstrings:
- def validate(self): Validazione specifica per il form
- def renderme(self, d_prat): rendering del form
<|skeleton|>
class DeterminaA:
"""form per definizione deter... | 66f5899eaddc4e0bfcb24cfa04f8573d6dc2eb47 | <|skeleton|>
class DeterminaA:
"""form per definizione determina fase A"""
def validate(self):
"""Validazione specifica per il form"""
<|body_0|>
def renderme(self, d_prat):
"""rendering del form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeterminaA:
"""form per definizione determina fase A"""
def validate(self):
"""Validazione specifica per il form"""
if not self.numero_determina.data:
self.errlist.append('Manca numero determina')
if not self.data_determina.data:
self.errlist.append('Manca ... | the_stack_v2_python_sparse | bin/forms.py | lfini/acquisti | train | 0 |
3d51bbd22301245944d5baca5906efa0e09e1dbe | [
"super().__init__()\nif background_color is None:\n background_color = torch.full((3,), -1, dtype=torch.float32)\nself.register_buffer('bg_color', background_color)\nself.noise_std = noise_std",
"p_distances = z_vals[..., 1:] - z_vals[..., :-1]\nlast_elem = torch.as_tensor([10000000000.0])[None, :].expand(p_di... | <|body_start_0|>
super().__init__()
if background_color is None:
background_color = torch.full((3,), -1, dtype=torch.float32)
self.register_buffer('bg_color', background_color)
self.noise_std = noise_std
<|end_body_0|>
<|body_start_1|>
p_distances = z_vals[..., 1:] -... | Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given. nif_model = NeRFModel() renderer = Point... | NeRFAggregator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeRFAggregator:
"""Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given... | stack_v2_sparse_classes_36k_train_034403 | 4,738 | permissive | [
{
"docstring": "Args: background_color (torch.Tensor): The background color to be added for rendering. If set to None, no background will be added. Default is None. noise_std (float): The standard deviation of the noise to be added to alpha. Set 0 to disable the noise addition. Default is 0.",
"name": "__in... | 2 | stack_v2_sparse_classes_30k_train_004185 | Implement the Python class `NeRFAggregator` described below.
Class description:
Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block... | Implement the Python class `NeRFAggregator` described below.
Class description:
Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block... | da3680cce7e8fc4c194f13a1528cddbad9a18ab0 | <|skeleton|>
class NeRFAggregator:
"""Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeRFAggregator:
"""Color aggregation function. Takes the raw predictions obtained from a NIF model, the depth values and a ray direction to produce the final color of a pixel. Please refer to the original NeRF paper for more information. Usage: .. code-block:: python # Assume the models are given. nif_model =... | the_stack_v2_python_sparse | pynif3d/aggregation/nerf_aggregator.py | pfnet/pynif3d | train | 72 |
b6fca0b3e5f0295685a609a5d796d207779cb1ff | [
"self.src_model_path = src_model_path\nself.mfd_bin_width = mfd_bin_width\nself.owner_id = owner_id\nself.input_id = input_id\nself.src_reader = java.jclass('SourceModelReader')(self.src_model_path, self.mfd_bin_width)",
"results = []\nsource_data = self.src_reader.read()\nfor src in source_data:\n src.__javac... | <|body_start_0|>
self.src_model_path = src_model_path
self.mfd_bin_width = mfd_bin_width
self.owner_id = owner_id
self.input_id = input_id
self.src_reader = java.jclass('SourceModelReader')(self.src_model_path, self.mfd_bin_width)
<|end_body_0|>
<|body_start_1|>
results ... | Uses parsers (written in Java) to read a source model data from a file and injects the data into the appropriate database tables. | SourceModelLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceModelLoader:
"""Uses parsers (written in Java) to read a source model data from a file and injects the data into the appropriate database tables."""
def __init__(self, src_model_path, mfd_bin_width=DEFAULT_MFD_BIN_WIDTH, owner_id=1, input_id=None):
""":param src_model_path: pat... | stack_v2_sparse_classes_36k_train_034404 | 14,208 | no_license | [
{
"docstring": ":param src_model_path: path to a source model file :type src_model_path: str :param mfd_bin_width: Magnitude Frequency Distribution bin width :type mfd_bin_width: float :param owner_id: ID of an admin.organization entity in the database. By default, the default 'GEM Foundation' group will be use... | 2 | null | Implement the Python class `SourceModelLoader` described below.
Class description:
Uses parsers (written in Java) to read a source model data from a file and injects the data into the appropriate database tables.
Method signatures and docstrings:
- def __init__(self, src_model_path, mfd_bin_width=DEFAULT_MFD_BIN_WIDT... | Implement the Python class `SourceModelLoader` described below.
Class description:
Uses parsers (written in Java) to read a source model data from a file and injects the data into the appropriate database tables.
Method signatures and docstrings:
- def __init__(self, src_model_path, mfd_bin_width=DEFAULT_MFD_BIN_WIDT... | d253f09d7848e6cf32e8c7756551436da413176b | <|skeleton|>
class SourceModelLoader:
"""Uses parsers (written in Java) to read a source model data from a file and injects the data into the appropriate database tables."""
def __init__(self, src_model_path, mfd_bin_width=DEFAULT_MFD_BIN_WIDTH, owner_id=1, input_id=None):
""":param src_model_path: pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceModelLoader:
"""Uses parsers (written in Java) to read a source model data from a file and injects the data into the appropriate database tables."""
def __init__(self, src_model_path, mfd_bin_width=DEFAULT_MFD_BIN_WIDTH, owner_id=1, input_id=None):
""":param src_model_path: path to a source... | the_stack_v2_python_sparse | python-oq/openquake/utils/db/loader.py | arbeit/openquake-packages | train | 1 |
28a6665f30445d832a4187f201d23bfb8dae55f3 | [
"super(AverageMetric, self).__init__(result_folder, output_folder)\nself.node = node\nif result_file_name is None:\n self._result_file_name = self.DEFAULT_RESULTS_FILE\nelse:\n self._result_file_name = result_file_name\nif metric_file_name is None:\n self._metric_file_name = self.DEFAULT_OUTPUT_FILE\nelse:... | <|body_start_0|>
super(AverageMetric, self).__init__(result_folder, output_folder)
self.node = node
if result_file_name is None:
self._result_file_name = self.DEFAULT_RESULTS_FILE
else:
self._result_file_name = result_file_name
if metric_file_name is None:... | The AverageMetric class represents the computation of the average of a metric. It reads a file providing float or integer value and computes a simple average on these values. It creates an output file containing the minimum, average, and maximum. | AverageMetric | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AverageMetric:
"""The AverageMetric class represents the computation of the average of a metric. It reads a file providing float or integer value and computes a simple average on these values. It creates an output file containing the minimum, average, and maximum."""
def __init__(self, node,... | stack_v2_sparse_classes_36k_train_034405 | 5,082 | permissive | [
{
"docstring": "Create a AverageMetric object. @param node: ROS2 node @type node: rclpy.node.Node @param result_folder: The path on filesystem for the data to be analyzed @type result_folder: str @param output_folder: The path on filesystem for the output files after the computation of the metric @type output_f... | 3 | stack_v2_sparse_classes_30k_train_017824 | Implement the Python class `AverageMetric` described below.
Class description:
The AverageMetric class represents the computation of the average of a metric. It reads a file providing float or integer value and computes a simple average on these values. It creates an output file containing the minimum, average, and ma... | Implement the Python class `AverageMetric` described below.
Class description:
The AverageMetric class represents the computation of the average of a metric. It reads a file providing float or integer value and computes a simple average on these values. It creates an output file containing the minimum, average, and ma... | ff8950abbb72366ed3072de790c405de8875ecc3 | <|skeleton|>
class AverageMetric:
"""The AverageMetric class represents the computation of the average of a metric. It reads a file providing float or integer value and computes a simple average on these values. It creates an output file containing the minimum, average, and maximum."""
def __init__(self, node,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AverageMetric:
"""The AverageMetric class represents the computation of the average of a metric. It reads a file providing float or integer value and computes a simple average on these values. It creates an output file containing the minimum, average, and maximum."""
def __init__(self, node, result_folde... | the_stack_v2_python_sparse | src/tools/benchmark_tool/benchmark_tool/metric/average_metric.py | bytetok/vde | train | 0 |
8b6909a381b671b33ec56d4ad79674f0d7d068d9 | [
"super().__init__()\nself._subset = subset\nself._shuffle_data = shuffle_data\nself._data_dir = data_dir or DATA_ROOT\nself._dataset = None\nallowed_versions = ('max256', 'max512', 'max1024')\nif version not in allowed_versions:\n raise ValueError(f'Version {version} not one of the allowed versions: {allowed_ver... | <|body_start_0|>
super().__init__()
self._subset = subset
self._shuffle_data = shuffle_data
self._data_dir = data_dir or DATA_ROOT
self._dataset = None
allowed_versions = ('max256', 'max512', 'max1024')
if version not in allowed_versions:
raise ValueEr... | The untokenized raw dataset. | RawDataset | [
"CC-BY-SA-4.0",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawDataset:
"""The untokenized raw dataset."""
def __init__(self, subset: str='train', shuffle_data: bool=False, data_dir: str=None, version: str='max256'):
"""Constructor. Args: subset: which subset to load. shuffle_data: set to True to randomly shuffle the data. data_dir: if provid... | stack_v2_sparse_classes_36k_train_034406 | 24,788 | permissive | [
{
"docstring": "Constructor. Args: subset: which subset to load. shuffle_data: set to True to randomly shuffle the data. data_dir: if provided this will be used instead of the default location to look for data, it must contain files like `train.gz`, `valid.gz` and `test.gz`. version: which version of the data t... | 2 | null | Implement the Python class `RawDataset` described below.
Class description:
The untokenized raw dataset.
Method signatures and docstrings:
- def __init__(self, subset: str='train', shuffle_data: bool=False, data_dir: str=None, version: str='max256'): Constructor. Args: subset: which subset to load. shuffle_data: set ... | Implement the Python class `RawDataset` described below.
Class description:
The untokenized raw dataset.
Method signatures and docstrings:
- def __init__(self, subset: str='train', shuffle_data: bool=False, data_dir: str=None, version: str='max256'): Constructor. Args: subset: which subset to load. shuffle_data: set ... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class RawDataset:
"""The untokenized raw dataset."""
def __init__(self, subset: str='train', shuffle_data: bool=False, data_dir: str=None, version: str='max256'):
"""Constructor. Args: subset: which subset to load. shuffle_data: set to True to randomly shuffle the data. data_dir: if provid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawDataset:
"""The untokenized raw dataset."""
def __init__(self, subset: str='train', shuffle_data: bool=False, data_dir: str=None, version: str='max256'):
"""Constructor. Args: subset: which subset to load. shuffle_data: set to True to randomly shuffle the data. data_dir: if provided this will ... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/data/paired_dataset.py | sethuramanio/deepmind-research | train | 1 |
31ffd77e4e8f770f58ab9fa488ab14b3b3e51d75 | [
"kwargs = {}\nkwargs['status'] = SMS_CAMPAIGN_STATUS.START\ntday = datetime.utcnow().replace(tzinfo=utc)\nkwargs['startingdate__lte'] = datetime(tday.year, tday.month, tday.day, tday.hour, tday.minute, tday.second, tday.microsecond).replace(tzinfo=utc)\nkwargs['expirationdate__gte'] = datetime(tday.year, tday.month... | <|body_start_0|>
kwargs = {}
kwargs['status'] = SMS_CAMPAIGN_STATUS.START
tday = datetime.utcnow().replace(tzinfo=utc)
kwargs['startingdate__lte'] = datetime(tday.year, tday.month, tday.day, tday.hour, tday.minute, tday.second, tday.microsecond).replace(tzinfo=utc)
kwargs['expira... | SMSCampaign Manager | SMSCampaignManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMSCampaignManager:
"""SMSCampaign Manager"""
def get_running_sms_campaign(self):
"""Return all the active smscampaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
<|body_0|>
def get_expired_sms_campaign(self):
... | stack_v2_sparse_classes_36k_train_034407 | 23,219 | no_license | [
{
"docstring": "Return all the active smscampaigns which will be running based on the expiry date, the daily start/stop time and days of the week",
"name": "get_running_sms_campaign",
"signature": "def get_running_sms_campaign(self)"
},
{
"docstring": "Return all the smscampaigns which are expir... | 2 | stack_v2_sparse_classes_30k_val_000266 | Implement the Python class `SMSCampaignManager` described below.
Class description:
SMSCampaign Manager
Method signatures and docstrings:
- def get_running_sms_campaign(self): Return all the active smscampaigns which will be running based on the expiry date, the daily start/stop time and days of the week
- def get_ex... | Implement the Python class `SMSCampaignManager` described below.
Class description:
SMSCampaign Manager
Method signatures and docstrings:
- def get_running_sms_campaign(self): Return all the active smscampaigns which will be running based on the expiry date, the daily start/stop time and days of the week
- def get_ex... | 2923a7d974f362af91b7c7c8f2e208cb2353c921 | <|skeleton|>
class SMSCampaignManager:
"""SMSCampaign Manager"""
def get_running_sms_campaign(self):
"""Return all the active smscampaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
<|body_0|>
def get_expired_sms_campaign(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMSCampaignManager:
"""SMSCampaign Manager"""
def get_running_sms_campaign(self):
"""Return all the active smscampaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
kwargs = {}
kwargs['status'] = SMS_CAMPAIGN_STATUS.START
... | the_stack_v2_python_sparse | sms_module/models.py | goksie/TheFies | train | 0 |
453d1044b80466a8c8831f0b0aec92d202c01419 | [
"if not root:\n return ''\nfrom collections import deque\nq = deque([root])\nans = []\nwhile q:\n node = q.popleft()\n ans.append(str(node.val) if node else '#')\n if node:\n q.extend([node.left, node.right])\nreturn ','.join(ans)",
"data = json.dumps(data)\nif not data:\n return\nnodes = [T... | <|body_start_0|>
if not root:
return ''
from collections import deque
q = deque([root])
ans = []
while q:
node = q.popleft()
ans.append(str(node.val) if node else '#')
if node:
q.extend([node.left, node.right])
... | TreeCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeCreator:
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: list :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_034408 | 7,485 | 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: list :rtype: TreeNode",
"name": "deserialize",
"signature": "def deseriali... | 2 | stack_v2_sparse_classes_30k_train_001923 | Implement the Python class `TreeCreator` described below.
Class description:
Implement the TreeCreator 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:... | Implement the Python class `TreeCreator` described below.
Class description:
Implement the TreeCreator 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:... | 3d5a96d896ede3ea979783b8053487fe44e38969 | <|skeleton|>
class TreeCreator:
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: list :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeCreator:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
from collections import deque
q = deque([root])
ans = []
while q:
node = q.popleft()
ans.... | the_stack_v2_python_sparse | utils/util_funcs.py | lichangg/myleet | train | 1 | |
d6b7024ca1ea424ceefc9bf26e934ebec152892b | [
"super().__init__(screen, x, y, r, vx, vy, owner, samostrel)\nself.color = GREEN\nself.live = 1",
"for i in range(15):\n angle = randint(-6, 6) * math.pi / 6\n new_bullet = Idle(self.screen, self.x, self.y, 10, self.vx - 3 * math.sin(angle), self.vy + 3 * math.cos(angle), self.owner, 1)\n bullets.append(... | <|body_start_0|>
super().__init__(screen, x, y, r, vx, vy, owner, samostrel)
self.color = GREEN
self.live = 1
<|end_body_0|>
<|body_start_1|>
for i in range(15):
angle = randint(-6, 6) * math.pi / 6
new_bullet = Idle(self.screen, self.x, self.y, 10, self.vx - 3 *... | Осколочная граната, при попадании в цель или в стену разрывается, порождая осколки | Bomb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bomb:
"""Осколочная граната, при попадании в цель или в стену разрывается, порождая осколки"""
def __init__(self, screen: pygame.Surface, x: int, y: int, r: int, vx: int, vy: int, owner, samostrel):
"""Args: screen - экран, на котором отрисовывается объект x - начальное положение объ... | stack_v2_sparse_classes_36k_train_034409 | 25,132 | no_license | [
{
"docstring": "Args: screen - экран, на котором отрисовывается объект x - начальное положение объекта по горизонтали y - начальное положение объекта по вертикали r - радиус объекта vx - стартовая скорость по горизонтальной оси vy - стартовая скорость по вертикальной оси owner - объект, испустивший снаряд samos... | 2 | stack_v2_sparse_classes_30k_train_007736 | Implement the Python class `Bomb` described below.
Class description:
Осколочная граната, при попадании в цель или в стену разрывается, порождая осколки
Method signatures and docstrings:
- def __init__(self, screen: pygame.Surface, x: int, y: int, r: int, vx: int, vy: int, owner, samostrel): Args: screen - экран, на ... | Implement the Python class `Bomb` described below.
Class description:
Осколочная граната, при попадании в цель или в стену разрывается, порождая осколки
Method signatures and docstrings:
- def __init__(self, screen: pygame.Surface, x: int, y: int, r: int, vx: int, vy: int, owner, samostrel): Args: screen - экран, на ... | e9c955c890a9775431e9a27a494bea774fe2bbb2 | <|skeleton|>
class Bomb:
"""Осколочная граната, при попадании в цель или в стену разрывается, порождая осколки"""
def __init__(self, screen: pygame.Surface, x: int, y: int, r: int, vx: int, vy: int, owner, samostrel):
"""Args: screen - экран, на котором отрисовывается объект x - начальное положение объ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bomb:
"""Осколочная граната, при попадании в цель или в стену разрывается, порождая осколки"""
def __init__(self, screen: pygame.Surface, x: int, y: int, r: int, vx: int, vy: int, owner, samostrel):
"""Args: screen - экран, на котором отрисовывается объект x - начальное положение объекта по гориз... | the_stack_v2_python_sparse | lab 9/guns.py | GenosseBlaackberry/MIPT_B02-113 | train | 0 |
0f591060ca6a4a8fbb9328efdebdd6effe400bb5 | [
"self.__logger = State().getLogger('DetectionCore_Component_Logger')\nself.__logger.info('Starting __init__()', 'KeyDetector:__init__')\nself.__templateThreshold = templateThreshold\nself.__templateMethod = templateMethod\nself.__findCountersMode = findCountersMode\nself.__findCountersMethode = findCountersMethode\... | <|body_start_0|>
self.__logger = State().getLogger('DetectionCore_Component_Logger')
self.__logger.info('Starting __init__()', 'KeyDetector:__init__')
self.__templateThreshold = templateThreshold
self.__templateMethod = templateMethod
self.__findCountersMode = findCountersMode
... | KeyDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyDetector:
def __init__(self, templateThreshold=0.75, templateMethod=cv2.TM_CCOEFF_NORMED, findCountersMode=cv2.RETR_LIST, findCountersMethode=cv2.CHAIN_APPROX_NONE):
"""Konstruktor für den KeyDetector. :param templateThreshold: Der Wert den das Template-Matching mindestens erreichen m... | stack_v2_sparse_classes_36k_train_034410 | 3,357 | no_license | [
{
"docstring": "Konstruktor für den KeyDetector. :param templateThreshold: Der Wert den das Template-Matching mindestens erreichen muss, damit ein Bildauschnitt als der jeweilige Key erkannt wird :param templateMethod: Methode des Template-Matchers :param findCountersMode: Modus des Konturfindungs-Algorithmus :... | 2 | stack_v2_sparse_classes_30k_train_017613 | Implement the Python class `KeyDetector` described below.
Class description:
Implement the KeyDetector class.
Method signatures and docstrings:
- def __init__(self, templateThreshold=0.75, templateMethod=cv2.TM_CCOEFF_NORMED, findCountersMode=cv2.RETR_LIST, findCountersMethode=cv2.CHAIN_APPROX_NONE): Konstruktor für ... | Implement the Python class `KeyDetector` described below.
Class description:
Implement the KeyDetector class.
Method signatures and docstrings:
- def __init__(self, templateThreshold=0.75, templateMethod=cv2.TM_CCOEFF_NORMED, findCountersMode=cv2.RETR_LIST, findCountersMethode=cv2.CHAIN_APPROX_NONE): Konstruktor für ... | 3daaa72b193ebfb55894b47b6a752cdc2192bb6b | <|skeleton|>
class KeyDetector:
def __init__(self, templateThreshold=0.75, templateMethod=cv2.TM_CCOEFF_NORMED, findCountersMode=cv2.RETR_LIST, findCountersMethode=cv2.CHAIN_APPROX_NONE):
"""Konstruktor für den KeyDetector. :param templateThreshold: Der Wert den das Template-Matching mindestens erreichen m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeyDetector:
def __init__(self, templateThreshold=0.75, templateMethod=cv2.TM_CCOEFF_NORMED, findCountersMode=cv2.RETR_LIST, findCountersMethode=cv2.CHAIN_APPROX_NONE):
"""Konstruktor für den KeyDetector. :param templateThreshold: Der Wert den das Template-Matching mindestens erreichen muss, damit ein... | the_stack_v2_python_sparse | SheetMusicScanner/DetectionCore_Component/Detector/KeyDetector.py | jadeskon/score-scan | train | 0 | |
7f92d059921dbd85a167d832d012e59feff551e9 | [
"if not email:\n raise ValueError('Users must have an email address')\nif not username:\n raise ValueError('Users must have an username')\nuser = self.model(username=username, email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(u... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have an username')
user = self.model(username=username, email=self.normalize_email(email))
user.set_password(password)
user.sa... | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
def create_user(self, username, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, username, email, password):
"""Creates and saves a superuser with the give... | stack_v2_sparse_classes_36k_train_034411 | 4,781 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, username, email, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name"... | 2 | stack_v2_sparse_classes_30k_train_008318 | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, u... | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, u... | 95c22374f42e8156e43e31de3b6062f41258824b | <|skeleton|>
class CustomUserManager:
def create_user(self, username, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, username, email, password):
"""Creates and saves a superuser with the give... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
def create_user(self, username, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users... | the_stack_v2_python_sparse | core/models.py | josben/flo | train | 0 | |
c9f6e56b905f1445cd23c6ec4c6381b1b4c75850 | [
"self.coerce_mmap = coerce_mmap\nHasher.__init__(self, hash_name=hash_name)\nimport numpy as np\nself.np = np\nif hasattr(np, 'getbuffer'):\n self._getbuffer = np.getbuffer\nelse:\n self._getbuffer = memoryview",
"if isinstance(obj, self.np.ndarray) and (not obj.dtype.hasobject):\n if obj.shape == ():\n ... | <|body_start_0|>
self.coerce_mmap = coerce_mmap
Hasher.__init__(self, hash_name=hash_name)
import numpy as np
self.np = np
if hasattr(np, 'getbuffer'):
self._getbuffer = np.getbuffer
else:
self._getbuffer = memoryview
<|end_body_0|>
<|body_start_1... | Special case the hasher for when numpy is loaded. | NumpyHasher | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumpyHasher:
"""Special case the hasher for when numpy is loaded."""
def __init__(self, hash_name='md5', coerce_mmap=False):
"""Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no difference between np.memmap and np.ndarray objects."""
... | stack_v2_sparse_classes_36k_train_034412 | 10,535 | permissive | [
{
"docstring": "Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no difference between np.memmap and np.ndarray objects.",
"name": "__init__",
"signature": "def __init__(self, hash_name='md5', coerce_mmap=False)"
},
{
"docstring": "Subclass the save... | 2 | null | Implement the Python class `NumpyHasher` described below.
Class description:
Special case the hasher for when numpy is loaded.
Method signatures and docstrings:
- def __init__(self, hash_name='md5', coerce_mmap=False): Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no ... | Implement the Python class `NumpyHasher` described below.
Class description:
Special case the hasher for when numpy is loaded.
Method signatures and docstrings:
- def __init__(self, hash_name='md5', coerce_mmap=False): Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no ... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class NumpyHasher:
"""Special case the hasher for when numpy is loaded."""
def __init__(self, hash_name='md5', coerce_mmap=False):
"""Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no difference between np.memmap and np.ndarray objects."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumpyHasher:
"""Special case the hasher for when numpy is loaded."""
def __init__(self, hash_name='md5', coerce_mmap=False):
"""Parameters ---------- hash_name: string The hash algorithm to be used coerce_mmap: boolean Make no difference between np.memmap and np.ndarray objects."""
self.c... | the_stack_v2_python_sparse | contrib/python/joblib/joblib/hashing.py | catboost/catboost | train | 8,012 |
8541d3164920d4a53c67dc90f41ed4f4144cd48c | [
"if not root:\n return ''\ndata = '['\ndata += str(root.val)\nfor child in root.children:\n data += self.serialize(child)\ndata += ']'\nreturn data",
"stack = list()\ni = 0\nroot = None\nwhile i < len(data):\n if data[i] == ']':\n root = stack[-1]\n stack.pop()\n elif data[i].isdigit():\... | <|body_start_0|>
if not root:
return ''
data = '['
data += str(root.val)
for child in root.children:
data += self.serialize(child)
data += ']'
return data
<|end_body_0|>
<|body_start_1|>
stack = list()
i = 0
root = None
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_034413 | 1,498 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_010942 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 178546686aa3ae8f5da1ae845417f86fab9a644d | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
data = '['
data += str(root.val)
for child in root.children:
data += self.serialize(child)
data ... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree.py | JaylenZhang19/Leetcode | train | 0 | |
1db500821af8f97a36c71e60c3941f935c34e839 | [
"wealth = None\ntry:\n wealth = cls.objects.get(ip=ip)\nexcept ObjectDoesNotExist as e:\n wealth = Wealth()\n wealth.ip = ip\nwealth.name = name\nwealth.host_address = host_address\nwealth.service_role = service_role\nwealth.remark = '无'\nwealth.update_time = timezone.now().strftime('%Y-%m-%d %H:%M:%S')\nw... | <|body_start_0|>
wealth = None
try:
wealth = cls.objects.get(ip=ip)
except ObjectDoesNotExist as e:
wealth = Wealth()
wealth.ip = ip
wealth.name = name
wealth.host_address = host_address
wealth.service_role = service_role
wealth... | Wealth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wealth:
def create_or_replace(cls, ip, name, host_address, service_role):
"""创建新的服务器角色信息 :param ip:服务器IP地址 :param name:服务器名称 :param host_address:服务器所在地 :param service_role:服务器角色 :return: 创建成功与否的信息"""
<|body_0|>
def as_dict(self):
"""更新对象的类型为字典 :return: 字典"""
... | stack_v2_sparse_classes_36k_train_034414 | 13,402 | no_license | [
{
"docstring": "创建新的服务器角色信息 :param ip:服务器IP地址 :param name:服务器名称 :param host_address:服务器所在地 :param service_role:服务器角色 :return: 创建成功与否的信息",
"name": "create_or_replace",
"signature": "def create_or_replace(cls, ip, name, host_address, service_role)"
},
{
"docstring": "更新对象的类型为字典 :return: 字典",
"... | 2 | stack_v2_sparse_classes_30k_train_016990 | Implement the Python class `Wealth` described below.
Class description:
Implement the Wealth class.
Method signatures and docstrings:
- def create_or_replace(cls, ip, name, host_address, service_role): 创建新的服务器角色信息 :param ip:服务器IP地址 :param name:服务器名称 :param host_address:服务器所在地 :param service_role:服务器角色 :return: 创建成功与否... | Implement the Python class `Wealth` described below.
Class description:
Implement the Wealth class.
Method signatures and docstrings:
- def create_or_replace(cls, ip, name, host_address, service_role): 创建新的服务器角色信息 :param ip:服务器IP地址 :param name:服务器名称 :param host_address:服务器所在地 :param service_role:服务器角色 :return: 创建成功与否... | 4febccac57bfa5f7ef46f5f57e52206c8b0a57ac | <|skeleton|>
class Wealth:
def create_or_replace(cls, ip, name, host_address, service_role):
"""创建新的服务器角色信息 :param ip:服务器IP地址 :param name:服务器名称 :param host_address:服务器所在地 :param service_role:服务器角色 :return: 创建成功与否的信息"""
<|body_0|>
def as_dict(self):
"""更新对象的类型为字典 :return: 字典"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wealth:
def create_or_replace(cls, ip, name, host_address, service_role):
"""创建新的服务器角色信息 :param ip:服务器IP地址 :param name:服务器名称 :param host_address:服务器所在地 :param service_role:服务器角色 :return: 创建成功与否的信息"""
wealth = None
try:
wealth = cls.objects.get(ip=ip)
except ObjectDo... | the_stack_v2_python_sparse | item/dev/cmdb/asset/models.py | soulorman/Python | train | 0 | |
01ee5de6f5c8df5d76a4f35450635d65015d21b6 | [
"if UserProfile.objects.get(user=self.request.user).bidlist.filter(position__id=pk).count() > 0:\n return Response(status=status.HTTP_204_NO_CONTENT)\nelse:\n return Response(status=status.HTTP_404_NOT_FOUND)",
"bidcycle = BidCycle.objects.filter(active=True).latest('cycle_start_date')\nposition = get_objec... | <|body_start_0|>
if UserProfile.objects.get(user=self.request.user).bidlist.filter(position__id=pk).count() > 0:
return Response(status=status.HTTP_204_NO_CONTENT)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
<|end_body_0|>
<|body_start_1|>
bidcycle = BidCycle... | BidListPositionActionView | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidListPositionActionView:
def get(self, request, pk, format=None):
"""Indicates if the position is in the user's bidlist Returns 204 if the position is in the list, otherwise, 404"""
<|body_0|>
def put(self, request, pk, format=None):
"""Adds a position to the user'... | stack_v2_sparse_classes_36k_train_034415 | 5,290 | permissive | [
{
"docstring": "Indicates if the position is in the user's bidlist Returns 204 if the position is in the list, otherwise, 404",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},
{
"docstring": "Adds a position to the user's bid list",
"name": "put",
"signature": "d... | 3 | null | Implement the Python class `BidListPositionActionView` described below.
Class description:
Implement the BidListPositionActionView class.
Method signatures and docstrings:
- def get(self, request, pk, format=None): Indicates if the position is in the user's bidlist Returns 204 if the position is in the list, otherwis... | Implement the Python class `BidListPositionActionView` described below.
Class description:
Implement the BidListPositionActionView class.
Method signatures and docstrings:
- def get(self, request, pk, format=None): Indicates if the position is in the user's bidlist Returns 204 if the position is in the list, otherwis... | cf71acd2ea0957aa2d599da8e1185d8519d8b013 | <|skeleton|>
class BidListPositionActionView:
def get(self, request, pk, format=None):
"""Indicates if the position is in the user's bidlist Returns 204 if the position is in the list, otherwise, 404"""
<|body_0|>
def put(self, request, pk, format=None):
"""Adds a position to the user'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidListPositionActionView:
def get(self, request, pk, format=None):
"""Indicates if the position is in the user's bidlist Returns 204 if the position is in the list, otherwise, 404"""
if UserProfile.objects.get(user=self.request.user).bidlist.filter(position__id=pk).count() > 0:
re... | the_stack_v2_python_sparse | talentmap_api/bidding/views/bidlist.py | 18F/State-TalentMAP-API | train | 5 | |
e8dfa688a6a80534fbd70bbe5f0e916d4ec4344e | [
"bodies = []\nfor idx, body in enumerate(config.bodies):\n frozen = jnp.sum(vec_to_np(body.frozen.position) + vec_to_np(body.frozen.rotation))\n bodies.append(cls(idx=jnp.array(idx), inertia=jnp.linalg.inv(jnp.diag(vec_to_np(body.inertia))), mass=jnp.array(body.mass), active=jnp.array(jnp.sum(frozen) != 6)))\... | <|body_start_0|>
bodies = []
for idx, body in enumerate(config.bodies):
frozen = jnp.sum(vec_to_np(body.frozen.position) + vec_to_np(body.frozen.rotation))
bodies.append(cls(idx=jnp.array(idx), inertia=jnp.linalg.inv(jnp.diag(vec_to_np(body.inertia))), mass=jnp.array(body.mass), ... | A body is a solid, non-deformable object with some mass and shape. Attributes: idx: Index of where body is found in the system. inertia: (3, 3) Inverse Inertia matrix represented in body frame. mass: Mass of the body. active: whether the body is effected by physics calculations | Body | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Body:
"""A body is a solid, non-deformable object with some mass and shape. Attributes: idx: Index of where body is found in the system. inertia: (3, 3) Inverse Inertia matrix represented in body frame. mass: Mass of the body. active: whether the body is effected by physics calculations"""
d... | stack_v2_sparse_classes_36k_train_034416 | 3,793 | permissive | [
{
"docstring": "Returns Body from a brax config.",
"name": "from_config",
"signature": "def from_config(cls, config: config_pb2.Config) -> 'Body'"
},
{
"docstring": "Calculates updates to state information based on an impulse. Args: qp: State data of the system impulse: Impulse vector pos: Locat... | 2 | null | Implement the Python class `Body` described below.
Class description:
A body is a solid, non-deformable object with some mass and shape. Attributes: idx: Index of where body is found in the system. inertia: (3, 3) Inverse Inertia matrix represented in body frame. mass: Mass of the body. active: whether the body is eff... | Implement the Python class `Body` described below.
Class description:
A body is a solid, non-deformable object with some mass and shape. Attributes: idx: Index of where body is found in the system. inertia: (3, 3) Inverse Inertia matrix represented in body frame. mass: Mass of the body. active: whether the body is eff... | a4bb44a43d516c4229f105a9f936d8dd18fe762e | <|skeleton|>
class Body:
"""A body is a solid, non-deformable object with some mass and shape. Attributes: idx: Index of where body is found in the system. inertia: (3, 3) Inverse Inertia matrix represented in body frame. mass: Mass of the body. active: whether the body is effected by physics calculations"""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Body:
"""A body is a solid, non-deformable object with some mass and shape. Attributes: idx: Index of where body is found in the system. inertia: (3, 3) Inverse Inertia matrix represented in body frame. mass: Mass of the body. active: whether the body is effected by physics calculations"""
def from_confi... | the_stack_v2_python_sparse | brax/physics/bodies.py | Denys88/brax | train | 1 |
cfdbc94c0e37a3818b0ad8b4e38530a7ebb4088b | [
"if not args:\n args = [self.model]\ncursor = connection.cursor()\ntables = ', '.join(['%s WRITE' % connection.ops.quote_name(model._meta.db_table) for model in args])\nlogger.debug('LOCK TABLES %s' % tables)\ncursor.execute('LOCK TABLES %s' % tables)\nrow = cursor.fetchone()\nreturn row",
"cursor = connection... | <|body_start_0|>
if not args:
args = [self.model]
cursor = connection.cursor()
tables = ', '.join(['%s WRITE' % connection.ops.quote_name(model._meta.db_table) for model in args])
logger.debug('LOCK TABLES %s' % tables)
cursor.execute('LOCK TABLES %s' % tables)
... | Add lock/unlock functionality to manager. Example:: class Job(models.Model): manager = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP request can do this update at once. Job.objec... | LockingManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockingManager:
"""Add lock/unlock functionality to manager. Example:: class Job(models.Model): manager = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP req... | stack_v2_sparse_classes_36k_train_034417 | 2,944 | permissive | [
{
"docstring": "Lock table(s). Locks the object model table so that atomic update is possible. Simulatenous database access request pend until the lock is unlock()'ed. See http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html @param *args: Models to be locked - if None then self.model is used.",
"name": "... | 2 | stack_v2_sparse_classes_30k_val_001032 | Implement the Python class `LockingManager` described below.
Class description:
Add lock/unlock functionality to manager. Example:: class Job(models.Model): manager = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it belo... | Implement the Python class `LockingManager` described below.
Class description:
Add lock/unlock functionality to manager. Example:: class Job(models.Model): manager = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it belo... | b64106392fad596defc915b8235fe6e1d0013b5b | <|skeleton|>
class LockingManager:
"""Add lock/unlock functionality to manager. Example:: class Job(models.Model): manager = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LockingManager:
"""Add lock/unlock functionality to manager. Example:: class Job(models.Model): manager = LockingManager() counter = models.IntegerField(null=True, default=0) @staticmethod def do_atomic_update(job_id) ''' Updates job integer, keeping it below 5 ''' try: # Ensure only one HTTP request can do t... | the_stack_v2_python_sparse | django_toolkit/db/models.py | alexhayes/django-toolkit | train | 7 |
d4fdbccff1f1bb4f111ac3ce918ce566e4d8de35 | [
"lo, hi = (1, x)\nwhile lo <= hi:\n mid = lo + (hi - lo) // 2\n if mid * mid == x:\n return mid\n elif mid * mid > x:\n hi = mid - 1\n else:\n lo = mid + 1\nreturn hi",
"s0 = 1\ns1 = (s0 + x / s0) / 2\nwhile abs(s0 - s1) >= 1:\n s0 = s1\n s1 = (s0 + x / s0) / 2\nreturn int(s... | <|body_start_0|>
lo, hi = (1, x)
while lo <= hi:
mid = lo + (hi - lo) // 2
if mid * mid == x:
return mid
elif mid * mid > x:
hi = mid - 1
else:
lo = mid + 1
return hi
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""binary search"""
<|body_0|>
def mySqrt(self, x: int) -> int:
"""Newton's method: the problem can be translated into finding the root of f(s)=s^2-x=0 assume currently s is at s0, if we assume the root is at s1, then approx... | stack_v2_sparse_classes_36k_train_034418 | 1,404 | no_license | [
{
"docstring": "binary search",
"name": "mySqrt",
"signature": "def mySqrt(self, x: int) -> int"
},
{
"docstring": "Newton's method: the problem can be translated into finding the root of f(s)=s^2-x=0 assume currently s is at s0, if we assume the root is at s1, then approximately, (f(s1) - f(s0)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: binary search
- def mySqrt(self, x: int) -> int: Newton's method: the problem can be translated into finding the root of f(s)=s^2-x=0 assume curr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: binary search
- def mySqrt(self, x: int) -> int: Newton's method: the problem can be translated into finding the root of f(s)=s^2-x=0 assume curr... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""binary search"""
<|body_0|>
def mySqrt(self, x: int) -> int:
"""Newton's method: the problem can be translated into finding the root of f(s)=s^2-x=0 assume currently s is at s0, if we assume the root is at s1, then approx... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x: int) -> int:
"""binary search"""
lo, hi = (1, x)
while lo <= hi:
mid = lo + (hi - lo) // 2
if mid * mid == x:
return mid
elif mid * mid > x:
hi = mid - 1
else:
... | the_stack_v2_python_sparse | Leetcode 0069. Sqrt(x).py | Chaoran-sjsu/leetcode | train | 0 | |
5e8b9932734bec2eac26839189e7c997956ec95b | [
"if self.request.version == 'v6':\n return WorkspaceDetailsSerializerV6\nelif self.request.version == 'v7':\n return WorkspaceDetailsSerializerV6",
"if request.version == 'v6':\n return self._get_v6(request, workspace_id)\nelif request.version == 'v7':\n return self._get_v6(request, workspace_id)\nrai... | <|body_start_0|>
if self.request.version == 'v6':
return WorkspaceDetailsSerializerV6
elif self.request.version == 'v7':
return WorkspaceDetailsSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6':
return self._get_v6(request, workspace_id)... | This view is the endpoint for retrieving/updating details of a workspace. | WorkspaceDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspaceDetailsView:
"""This view is the endpoint for retrieving/updating details of a workspace."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def get(self, request, workspace_id):
... | stack_v2_sparse_classes_36k_train_034419 | 19,677 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Retrieves the details for a workspace and return them in JSON form :param request: the HTTP GET req... | 5 | stack_v2_sparse_classes_30k_train_010736 | Implement the Python class `WorkspaceDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of a workspace.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def ge... | Implement the Python class `WorkspaceDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of a workspace.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def ge... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class WorkspaceDetailsView:
"""This view is the endpoint for retrieving/updating details of a workspace."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def get(self, request, workspace_id):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkspaceDetailsView:
"""This view is the endpoint for retrieving/updating details of a workspace."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
if self.request.version == 'v6':
return WorkspaceDetail... | the_stack_v2_python_sparse | scale/storage/views.py | kfconsultant/scale | train | 0 |
f4d8b32220926433d2d1a23a2e1371ff284c648b | [
"super(SwinTransformerV2, self).__init__()\nself.patch_size: int = patch_size\nself.patch_embedding: nn.Module = PatchEmbedding(in_channels=in_channels, out_channels=embedding_channels, patch_size=patch_size)\npatch_resolution: Tuple[int, int] = (input_resolution[0] // patch_size, input_resolution[1] // patch_size)... | <|body_start_0|>
super(SwinTransformerV2, self).__init__()
self.patch_size: int = patch_size
self.patch_embedding: nn.Module = PatchEmbedding(in_channels=in_channels, out_channels=embedding_channels, patch_size=patch_size)
patch_resolution: Tuple[int, int] = (input_resolution[0] // patch... | This class implements the Swin Transformer without classification head. | SwinTransformerV2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwinTransformerV2:
"""This class implements the Swin Transformer without classification head."""
def __init__(self, in_channels: int, embedding_channels: int, depths: Tuple[int, ...], input_resolution: Tuple[int, int], number_of_heads: Tuple[int, ...], window_size: int=7, patch_size: int=4, ... | stack_v2_sparse_classes_36k_train_034420 | 41,159 | no_license | [
{
"docstring": "Constructor method :param in_channels: (int) Number of input channels :param depth: (int) Depth of the stage (number of layers) :param downscale: (bool) If true input is downsampled (see Fig. 3 or V1 paper) :param input_resolution: (Tuple[int, int]) Input resolution :param number_of_heads: (int)... | 3 | stack_v2_sparse_classes_30k_train_000743 | Implement the Python class `SwinTransformerV2` described below.
Class description:
This class implements the Swin Transformer without classification head.
Method signatures and docstrings:
- def __init__(self, in_channels: int, embedding_channels: int, depths: Tuple[int, ...], input_resolution: Tuple[int, int], numbe... | Implement the Python class `SwinTransformerV2` described below.
Class description:
This class implements the Swin Transformer without classification head.
Method signatures and docstrings:
- def __init__(self, in_channels: int, embedding_channels: int, depths: Tuple[int, ...], input_resolution: Tuple[int, int], numbe... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SwinTransformerV2:
"""This class implements the Swin Transformer without classification head."""
def __init__(self, in_channels: int, embedding_channels: int, depths: Tuple[int, ...], input_resolution: Tuple[int, int], number_of_heads: Tuple[int, ...], window_size: int=7, patch_size: int=4, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwinTransformerV2:
"""This class implements the Swin Transformer without classification head."""
def __init__(self, in_channels: int, embedding_channels: int, depths: Tuple[int, ...], input_resolution: Tuple[int, int], number_of_heads: Tuple[int, ...], window_size: int=7, patch_size: int=4, ff_feature_ra... | the_stack_v2_python_sparse | generated/test_ChristophReich1996_Swin_Transformer_V2.py | jansel/pytorch-jit-paritybench | train | 35 |
879ffbc10241dc43f05e36ca9cfd1218cf97d636 | [
"self._recursive = recursive\nnop = lambda: None\nskip = lambda arg: None\nself.link_callback = skip\nself.link_content_callback = skip\nself.ext_link_callback = skip\nself.redirect_callback = skip\nself.error_callback = skip\nself.nonhtml_callback = skip\nself.stop_callback = nop\nself.ext_link_test = have_same_ba... | <|body_start_0|>
self._recursive = recursive
nop = lambda: None
skip = lambda arg: None
self.link_callback = skip
self.link_content_callback = skip
self.ext_link_callback = skip
self.redirect_callback = skip
self.error_callback = skip
self.nonhtml_... | URL-redirects crawler | LinkCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkCrawler:
"""URL-redirects crawler"""
def __init__(self, recursive=True):
"""Constructor"""
<|body_0|>
def process(self, url):
"""Iterate the external links from url"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._recursive = recursive
... | stack_v2_sparse_classes_36k_train_034421 | 2,502 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, recursive=True)"
},
{
"docstring": "Iterate the external links from url",
"name": "process",
"signature": "def process(self, url)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008992 | Implement the Python class `LinkCrawler` described below.
Class description:
URL-redirects crawler
Method signatures and docstrings:
- def __init__(self, recursive=True): Constructor
- def process(self, url): Iterate the external links from url | Implement the Python class `LinkCrawler` described below.
Class description:
URL-redirects crawler
Method signatures and docstrings:
- def __init__(self, recursive=True): Constructor
- def process(self, url): Iterate the external links from url
<|skeleton|>
class LinkCrawler:
"""URL-redirects crawler"""
def... | aab6927de8424f0a8e9eb9b9a462a775555a80d5 | <|skeleton|>
class LinkCrawler:
"""URL-redirects crawler"""
def __init__(self, recursive=True):
"""Constructor"""
<|body_0|>
def process(self, url):
"""Iterate the external links from url"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkCrawler:
"""URL-redirects crawler"""
def __init__(self, recursive=True):
"""Constructor"""
self._recursive = recursive
nop = lambda: None
skip = lambda arg: None
self.link_callback = skip
self.link_content_callback = skip
self.ext_link_callback ... | the_stack_v2_python_sparse | lib/core/crawler.py | Silentsoul04/gtta-scripts | train | 0 |
b640eecb152b76a892aa3ca16dbae9d057601e6f | [
"if mod:\n spec = importlib.util.find_spec(mod)\n if spec is None:\n raise LookupError\n else:\n self.resource_dir = (Path(spec.origin).absolute().parent / 'resources').as_posix()\nelse:\n self.resource_dir = resource_dir",
"fname = str(resource_id)\nwhile True:\n fname_full = '{}{}/{... | <|body_start_0|>
if mod:
spec = importlib.util.find_spec(mod)
if spec is None:
raise LookupError
else:
self.resource_dir = (Path(spec.origin).absolute().parent / 'resources').as_posix()
else:
self.resource_dir = resource_dir... | Resource storage loader Usage example: from pyaltt.res import ResourceStorage from functools import partial rs = ResourceStorage(mod=mymod) rq = partial(rs.get, resource_subdir='sql', ext='sql') rq('object.select.data') - will load resource from (will try all variations until file is found): * sql/object.select.data.sq... | ResourceStorage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceStorage:
"""Resource storage loader Usage example: from pyaltt.res import ResourceStorage from functools import partial rs = ResourceStorage(mod=mymod) rq = partial(rs.get, resource_subdir='sql', ext='sql') rq('object.select.data') - will load resource from (will try all variations until ... | stack_v2_sparse_classes_36k_train_034422 | 2,786 | permissive | [
{
"docstring": "init resource storage for module If module is specified, set directory to module_dir/resources Args: resource_dir: resource directory or mod: module name Raises: LookupError: if module name is specified, but module is not found",
"name": "__init__",
"signature": "def __init__(self, resou... | 2 | stack_v2_sparse_classes_30k_train_000830 | Implement the Python class `ResourceStorage` described below.
Class description:
Resource storage loader Usage example: from pyaltt.res import ResourceStorage from functools import partial rs = ResourceStorage(mod=mymod) rq = partial(rs.get, resource_subdir='sql', ext='sql') rq('object.select.data') - will load resour... | Implement the Python class `ResourceStorage` described below.
Class description:
Resource storage loader Usage example: from pyaltt.res import ResourceStorage from functools import partial rs = ResourceStorage(mod=mymod) rq = partial(rs.get, resource_subdir='sql', ext='sql') rq('object.select.data') - will load resour... | da51459b01c6729a866ca2bb4731d94c031854d1 | <|skeleton|>
class ResourceStorage:
"""Resource storage loader Usage example: from pyaltt.res import ResourceStorage from functools import partial rs = ResourceStorage(mod=mymod) rq = partial(rs.get, resource_subdir='sql', ext='sql') rq('object.select.data') - will load resource from (will try all variations until ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceStorage:
"""Resource storage loader Usage example: from pyaltt.res import ResourceStorage from functools import partial rs = ResourceStorage(mod=mymod) rq = partial(rs.get, resource_subdir='sql', ext='sql') rq('object.select.data') - will load resource from (will try all variations until file is found... | the_stack_v2_python_sparse | pyaltt2/res.py | alttch/pyaltt2 | train | 1 |
1eaa369b85ea7d3e829bdb93c0bb1c4a6f956057 | [
"assert issubclass(paned.__class__, gi.repository.Gtk.Paned), u'GtkPaned manager type error'\nsetattr(self, '_last_position_%s' % paned.get_name(), paned.get_position())\nif resize_panel == 0:\n paned.set_position(paned.get_property('min-position'))\nelif resize_panel == 1:\n paned.set_position(paned.get_prop... | <|body_start_0|>
assert issubclass(paned.__class__, gi.repository.Gtk.Paned), u'GtkPaned manager type error'
setattr(self, '_last_position_%s' % paned.get_name(), paned.get_position())
if resize_panel == 0:
paned.set_position(paned.get_property('min-position'))
elif resize_pa... | GtkPaned manager. | iqGtkPanedManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqGtkPanedManager:
"""GtkPaned manager."""
def collapseGtkPanedPanel(self, paned, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True):
"""Collapse the paned panel. :param paned: GtkPaned object. :param toolbar: GtkToolBar object. :param collapse_tool: Col... | stack_v2_sparse_classes_36k_train_034423 | 3,161 | no_license | [
{
"docstring": "Collapse the paned panel. :param paned: GtkPaned object. :param toolbar: GtkToolBar object. :param collapse_tool: Collapse tool item. :param expand_tool: Expand tool item. :param resize_panel: Resizable panel index. :param redraw: Redrawing object? :return: True/False.",
"name": "collapseGtk... | 2 | stack_v2_sparse_classes_30k_train_007827 | Implement the Python class `iqGtkPanedManager` described below.
Class description:
GtkPaned manager.
Method signatures and docstrings:
- def collapseGtkPanedPanel(self, paned, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True): Collapse the paned panel. :param paned: GtkPaned object. :pa... | Implement the Python class `iqGtkPanedManager` described below.
Class description:
GtkPaned manager.
Method signatures and docstrings:
- def collapseGtkPanedPanel(self, paned, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True): Collapse the paned panel. :param paned: GtkPaned object. :pa... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqGtkPanedManager:
"""GtkPaned manager."""
def collapseGtkPanedPanel(self, paned, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True):
"""Collapse the paned panel. :param paned: GtkPaned object. :param toolbar: GtkToolBar object. :param collapse_tool: Col... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class iqGtkPanedManager:
"""GtkPaned manager."""
def collapseGtkPanedPanel(self, paned, toolbar=None, collapse_tool=None, expand_tool=None, resize_panel=0, redraw=True):
"""Collapse the paned panel. :param paned: GtkPaned object. :param toolbar: GtkToolBar object. :param collapse_tool: Collapse tool it... | the_stack_v2_python_sparse | iq/engine/gtk/gtkpaned_manager.py | XHermitOne/iq_framework | train | 1 |
f50f90d8f94c5880d5ce6c96c783d8ad357d1404 | [
"super().__init__()\nself._metric = metric\nself._threshold = threshold",
"value = logs.get(self._metric.value)\nif self._metric == Metric.ACCURACY:\n if value > self._threshold:\n self.model.stop_training = True\nelif self._metric == Metric.LOSS:\n if value < self._threshold:\n self.model.sto... | <|body_start_0|>
super().__init__()
self._metric = metric
self._threshold = threshold
<|end_body_0|>
<|body_start_1|>
value = logs.get(self._metric.value)
if self._metric == Metric.ACCURACY:
if value > self._threshold:
self.model.stop_training = True
... | Callback to stop training when a given metric exceeds or falls below a given threshold. The metric can be either Metric.ACCURACY or Metric.LOSS. If the metric is Metric.ACCURACY, then training stops when the model's accuracy exceeds the threshold. If the metric is Metric.LOSS, then training stops when the model's loss ... | ThresholdStopping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThresholdStopping:
"""Callback to stop training when a given metric exceeds or falls below a given threshold. The metric can be either Metric.ACCURACY or Metric.LOSS. If the metric is Metric.ACCURACY, then training stops when the model's accuracy exceeds the threshold. If the metric is Metric.LOS... | stack_v2_sparse_classes_36k_train_034424 | 2,493 | permissive | [
{
"docstring": "Initializes this callback. Arguments: metric: A Metric value to check for the threshold. threshold: A float value the metric is checked for.",
"name": "__init__",
"signature": "def __init__(self, metric: Metric, threshold)"
},
{
"docstring": "Called at the end of a training epoch... | 2 | stack_v2_sparse_classes_30k_train_011511 | Implement the Python class `ThresholdStopping` described below.
Class description:
Callback to stop training when a given metric exceeds or falls below a given threshold. The metric can be either Metric.ACCURACY or Metric.LOSS. If the metric is Metric.ACCURACY, then training stops when the model's accuracy exceeds the... | Implement the Python class `ThresholdStopping` described below.
Class description:
Callback to stop training when a given metric exceeds or falls below a given threshold. The metric can be either Metric.ACCURACY or Metric.LOSS. If the metric is Metric.ACCURACY, then training stops when the model's accuracy exceeds the... | e0627115e6b68d6b85244d484011bb3895ccf4ee | <|skeleton|>
class ThresholdStopping:
"""Callback to stop training when a given metric exceeds or falls below a given threshold. The metric can be either Metric.ACCURACY or Metric.LOSS. If the metric is Metric.ACCURACY, then training stops when the model's accuracy exceeds the threshold. If the metric is Metric.LOS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThresholdStopping:
"""Callback to stop training when a given metric exceeds or falls below a given threshold. The metric can be either Metric.ACCURACY or Metric.LOSS. If the metric is Metric.ACCURACY, then training stops when the model's accuracy exceeds the threshold. If the metric is Metric.LOSS, then train... | the_stack_v2_python_sparse | training/callbacks.py | TebogoNakampe/transfer-learning-for-sign-language-recognition | train | 0 |
c87a821998589271081652de8d965ed5a0e3385f | [
"if self.conn:\n for i in self._subscribe(no_ack, requeue):\n yield i\nelse:\n raise RuntimeError('No Connection Found')",
"for i in self.extract_from_queue(no_ack):\n yield i.payload\n if no_ack is False and requeue is False:\n i.ack()\n elif requeue is True:\n i.requeue()",
... | <|body_start_0|>
if self.conn:
for i in self._subscribe(no_ack, requeue):
yield i
else:
raise RuntimeError('No Connection Found')
<|end_body_0|>
<|body_start_1|>
for i in self.extract_from_queue(no_ack):
yield i.payload
if no_ack i... | Subscriber | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscriber:
def subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]:
"""重载数值"""
<|body_0|>
def _subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]:
"""重载数值"""
<|body_1|>
def extract_from_queue(self, no_ack: bo... | stack_v2_sparse_classes_36k_train_034425 | 1,457 | permissive | [
{
"docstring": "重载数值",
"name": "subscribe",
"signature": "def subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]"
},
{
"docstring": "重载数值",
"name": "_subscribe",
"signature": "def _subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]"
},
{
... | 3 | null | Implement the Python class `Subscriber` described below.
Class description:
Implement the Subscriber class.
Method signatures and docstrings:
- def subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]: 重载数值
- def _subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]: 重载数值
- d... | Implement the Python class `Subscriber` described below.
Class description:
Implement the Subscriber class.
Method signatures and docstrings:
- def subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]: 重载数值
- def _subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]: 重载数值
- d... | 36c3d1977df5851d8df54846f0bc84be2b86e962 | <|skeleton|>
class Subscriber:
def subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]:
"""重载数值"""
<|body_0|>
def _subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]:
"""重载数值"""
<|body_1|>
def extract_from_queue(self, no_ack: bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subscriber:
def subscribe(self, no_ack: bool=False, requeue: bool=False) -> Iterator[Any]:
"""重载数值"""
if self.conn:
for i in self._subscribe(no_ack, requeue):
yield i
else:
raise RuntimeError('No Connection Found')
def _subscribe(self, no_ac... | the_stack_v2_python_sparse | smorest_sfs/plugins/rpc/subscriber.py | ssfdust/yt-media | train | 2 | |
c9b35349b6916ecf5981f3cd0c7548abb28ba931 | [
"l = len(s)\nstep = 1\ncur = s[0:step]\nwhile step < l:\n if l % step == 0:\n i = 1\n while i < l // step:\n if s[step * i:step * i + step] != cur:\n break\n i += 1\n if i == l // step:\n return True\n step += 1\n cur = s[0:step]\nreturn ... | <|body_start_0|>
l = len(s)
step = 1
cur = s[0:step]
while step < l:
if l % step == 0:
i = 1
while i < l // step:
if s[step * i:step * i + step] != cur:
break
i += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = len(s)
step = 1
cur =... | stack_v2_sparse_classes_36k_train_034426 | 716 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "repeatedSubstringPattern",
"signature": "def repeatedSubstringPattern(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "repeatedSubstringPattern",
"signature": "def repeatedSubstringPattern(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003606 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
- def repeatedSubstringPattern(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def repeate... | 7c5e5fe76cee542f67cd7dd3a389470b02597548 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def repeatedSubstringPattern(self, s):
""":type s: str :rtype: bool"""
l = len(s)
step = 1
cur = s[0:step]
while step < l:
if l % step == 0:
i = 1
while i < l // step:
if s[step * i:step * i + ste... | the_stack_v2_python_sparse | 459. Repeated Substring Pattern.py | Mschikay/leetcode | train | 0 | |
e31d0103266d9bb803c1025672161d728d1fd08f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConditionalAccessTemplate()",
"from .conditional_access_policy_detail import ConditionalAccessPolicyDetail\nfrom .entity import Entity\nfrom .template_scenarios import TemplateScenarios\nfrom .conditional_access_policy_detail import Co... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ConditionalAccessTemplate()
<|end_body_0|>
<|body_start_1|>
from .conditional_access_policy_detail import ConditionalAccessPolicyDetail
from .entity import Entity
from .template_... | ConditionalAccessTemplate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalAccessTemplate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessTemplate:
"""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 c... | stack_v2_sparse_classes_36k_train_034427 | 3,136 | 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: ConditionalAccessTemplate",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrim... | 3 | null | Implement the Python class `ConditionalAccessTemplate` described below.
Class description:
Implement the ConditionalAccessTemplate class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessTemplate: Creates a new instance of the appropriat... | Implement the Python class `ConditionalAccessTemplate` described below.
Class description:
Implement the ConditionalAccessTemplate class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessTemplate: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConditionalAccessTemplate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessTemplate:
"""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 c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalAccessTemplate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessTemplate:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/conditional_access_template.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f4d7ef0a69dcd9d66018da5c73adc6338a00e4d4 | [
"super().__init__()\nself.ignore_index = ignore_index\nself.reduction = reduction\nself.smooth_factor = smooth_factor\nself.register_buffer('weight', weight)\nself.register_buffer('pos_weight', pos_weight)",
"if self.smooth_factor is not None:\n soft_targets = (1 - y_true) * self.smooth_factor + y_true * (1 - ... | <|body_start_0|>
super().__init__()
self.ignore_index = ignore_index
self.reduction = reduction
self.smooth_factor = smooth_factor
self.register_buffer('weight', weight)
self.register_buffer('pos_weight', pos_weight)
<|end_body_0|>
<|body_start_1|>
if self.smooth... | SoftBCEWithLogitsLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftBCEWithLogitsLoss:
def __init__(self, weight: Optional[torch.Tensor]=None, ignore_index: Optional[int]=-100, reduction: str='mean', smooth_factor: Optional[float]=None, pos_weight: Optional[torch.Tensor]=None):
"""Drop-in replacement for torch.nn.BCEWithLogitsLoss with few additions:... | stack_v2_sparse_classes_36k_train_034428 | 2,414 | permissive | [
{
"docstring": "Drop-in replacement for torch.nn.BCEWithLogitsLoss with few additions: ignore_index and label_smoothing Args: ignore_index: Specifies a target value that is ignored and does not contribute to the input gradient. smooth_factor: Factor to smooth target (e.g. if smooth_factor=0.1 then [1, 0, 1] -> ... | 2 | stack_v2_sparse_classes_30k_train_007601 | Implement the Python class `SoftBCEWithLogitsLoss` described below.
Class description:
Implement the SoftBCEWithLogitsLoss class.
Method signatures and docstrings:
- def __init__(self, weight: Optional[torch.Tensor]=None, ignore_index: Optional[int]=-100, reduction: str='mean', smooth_factor: Optional[float]=None, po... | Implement the Python class `SoftBCEWithLogitsLoss` described below.
Class description:
Implement the SoftBCEWithLogitsLoss class.
Method signatures and docstrings:
- def __init__(self, weight: Optional[torch.Tensor]=None, ignore_index: Optional[int]=-100, reduction: str='mean', smooth_factor: Optional[float]=None, po... | 6db76a1106426ac5b55f39fba68168f3bccae7f8 | <|skeleton|>
class SoftBCEWithLogitsLoss:
def __init__(self, weight: Optional[torch.Tensor]=None, ignore_index: Optional[int]=-100, reduction: str='mean', smooth_factor: Optional[float]=None, pos_weight: Optional[torch.Tensor]=None):
"""Drop-in replacement for torch.nn.BCEWithLogitsLoss with few additions:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftBCEWithLogitsLoss:
def __init__(self, weight: Optional[torch.Tensor]=None, ignore_index: Optional[int]=-100, reduction: str='mean', smooth_factor: Optional[float]=None, pos_weight: Optional[torch.Tensor]=None):
"""Drop-in replacement for torch.nn.BCEWithLogitsLoss with few additions: ignore_index ... | the_stack_v2_python_sparse | segmentation_models_pytorch/losses/soft_bce.py | qubvel/segmentation_models.pytorch | train | 8,150 | |
b717d1969e4adc725780c5426b55b88f995f85ee | [
"res = super(QCustomScrollArea, self).event(event)\nevent_t = event.type()\nif event_t == QEvent.Paint:\n color = QApplication.palette().color(QPalette.Window)\n tl = self.viewport().geometry().bottomRight()\n fw = self.frameWidth()\n br = self.rect().bottomRight() - QPoint(fw, fw)\n QPainter(self).f... | <|body_start_0|>
res = super(QCustomScrollArea, self).event(event)
event_t = event.type()
if event_t == QEvent.Paint:
color = QApplication.palette().color(QPalette.Window)
tl = self.viewport().geometry().bottomRight()
fw = self.frameWidth()
br = se... | A custom QScrollArea for use with the QtScrollArea. This subclass fixes some bugs related to size hints. | QCustomScrollArea | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCustomScrollArea:
"""A custom QScrollArea for use with the QtScrollArea. This subclass fixes some bugs related to size hints."""
def event(self, event):
"""A custom event handler for the scroll area. This handler dispatches layout requests and paints the empty corner between the scr... | stack_v2_sparse_classes_36k_train_034429 | 8,030 | permissive | [
{
"docstring": "A custom event handler for the scroll area. This handler dispatches layout requests and paints the empty corner between the scroll bars.",
"name": "event",
"signature": "def event(self, event)"
},
{
"docstring": "Set the widget for this scroll area. This is a reimplemented parent... | 3 | null | Implement the Python class `QCustomScrollArea` described below.
Class description:
A custom QScrollArea for use with the QtScrollArea. This subclass fixes some bugs related to size hints.
Method signatures and docstrings:
- def event(self, event): A custom event handler for the scroll area. This handler dispatches la... | Implement the Python class `QCustomScrollArea` described below.
Class description:
A custom QScrollArea for use with the QtScrollArea. This subclass fixes some bugs related to size hints.
Method signatures and docstrings:
- def event(self, event): A custom event handler for the scroll area. This handler dispatches la... | 1544e7fb371b8f941cfa2fde682795e479380284 | <|skeleton|>
class QCustomScrollArea:
"""A custom QScrollArea for use with the QtScrollArea. This subclass fixes some bugs related to size hints."""
def event(self, event):
"""A custom event handler for the scroll area. This handler dispatches layout requests and paints the empty corner between the scr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCustomScrollArea:
"""A custom QScrollArea for use with the QtScrollArea. This subclass fixes some bugs related to size hints."""
def event(self, event):
"""A custom event handler for the scroll area. This handler dispatches layout requests and paints the empty corner between the scroll bars."""
... | the_stack_v2_python_sparse | enaml/qt/qt_scroll_area.py | MatthieuDartiailh/enaml | train | 26 |
872f76f0e297e4dfffb49d9f6b3caa49c4321b05 | [
"self.nums = nums\n\ndef buildHelper(nums, start, end):\n if start > end:\n return None\n root = self.SegmentTreeNode(start, end, 0)\n if start == end:\n root.sum = nums[start]\n return root\n root.left = buildHelper(nums, start, (start + end) / 2)\n root.right = buildHelper(nums... | <|body_start_0|>
self.nums = nums
def buildHelper(nums, start, end):
if start > end:
return None
root = self.SegmentTreeNode(start, end, 0)
if start == end:
root.sum = nums[start]
return root
root.left = bui... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_034430 | 2,247 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 16ad99a6511543f0286559c483206c43ed655ddd | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
def buildHelper(nums, start, end):
if start > end:
return None
root = self.SegmentTreeNode(start, end, 0)
if start == end:
root.sum = nu... | the_stack_v2_python_sparse | range-sum-query-mutable.py | stella-shen/Leetcode | train | 0 | |
089999c449eae46d79e91689a2c2dc53a5c68d92 | [
"self.availability_set = availability_set\nself.azure_managed_disk_params = azure_managed_disk_params\nself.compute_options = compute_options\nself.data_transfer_info = data_transfer_info\nself.network_resource_group = network_resource_group\nself.network_security_group = network_security_group\nself.resource_group... | <|body_start_0|>
self.availability_set = availability_set
self.azure_managed_disk_params = azure_managed_disk_params
self.compute_options = compute_options
self.data_transfer_info = data_transfer_info
self.network_resource_group = network_resource_group
self.network_secur... | Implementation of the 'DeployVMsToAzureParams' model. Contains Azure specific information needed to identify various resources when converting and deploying a VM to Azure. Attributes: availability_set (EntityProto): Name of the Availability set in which the VM is to be restored. azure_managed_disk_params (AzureManagedD... | DeployVMsToAzureParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeployVMsToAzureParams:
"""Implementation of the 'DeployVMsToAzureParams' model. Contains Azure specific information needed to identify various resources when converting and deploying a VM to Azure. Attributes: availability_set (EntityProto): Name of the Availability set in which the VM is to be ... | stack_v2_sparse_classes_36k_train_034431 | 10,381 | permissive | [
{
"docstring": "Constructor for the DeployVMsToAzureParams class",
"name": "__init__",
"signature": "def __init__(self, availability_set=None, azure_managed_disk_params=None, compute_options=None, data_transfer_info=None, network_resource_group=None, network_security_group=None, resource_group=None, sto... | 2 | stack_v2_sparse_classes_30k_train_016022 | Implement the Python class `DeployVMsToAzureParams` described below.
Class description:
Implementation of the 'DeployVMsToAzureParams' model. Contains Azure specific information needed to identify various resources when converting and deploying a VM to Azure. Attributes: availability_set (EntityProto): Name of the Ava... | Implement the Python class `DeployVMsToAzureParams` described below.
Class description:
Implementation of the 'DeployVMsToAzureParams' model. Contains Azure specific information needed to identify various resources when converting and deploying a VM to Azure. Attributes: availability_set (EntityProto): Name of the Ava... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DeployVMsToAzureParams:
"""Implementation of the 'DeployVMsToAzureParams' model. Contains Azure specific information needed to identify various resources when converting and deploying a VM to Azure. Attributes: availability_set (EntityProto): Name of the Availability set in which the VM is to be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeployVMsToAzureParams:
"""Implementation of the 'DeployVMsToAzureParams' model. Contains Azure specific information needed to identify various resources when converting and deploying a VM to Azure. Attributes: availability_set (EntityProto): Name of the Availability set in which the VM is to be restored. azu... | the_stack_v2_python_sparse | cohesity_management_sdk/models/deploy_vms_to_azure_params.py | cohesity/management-sdk-python | train | 24 |
368f6af11c168552220469a2544d8c0b88f0ff25 | [
"context = req.environ['nova.context']\nauthorize(context)\nreturn volume_types.get_all_types(context)",
"context = req.environ['nova.context']\nauthorize(context)\nif not body or body == '':\n raise exc.HTTPUnprocessableEntity()\nvol_type = body.get('volume_type', None)\nif vol_type is None or vol_type == '':... | <|body_start_0|>
context = req.environ['nova.context']
authorize(context)
return volume_types.get_all_types(context)
<|end_body_0|>
<|body_start_1|>
context = req.environ['nova.context']
authorize(context)
if not body or body == '':
raise exc.HTTPUnprocessabl... | The volume types API controller for the Openstack API | VolumeTypesController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeTypesController:
"""The volume types API controller for the Openstack API"""
def index(self, req):
"""Returns the list of volume types"""
<|body_0|>
def create(self, req, body):
"""Creates a new volume type."""
<|body_1|>
def show(self, req, id... | stack_v2_sparse_classes_36k_train_034432 | 8,791 | permissive | [
{
"docstring": "Returns the list of volume types",
"name": "index",
"signature": "def index(self, req)"
},
{
"docstring": "Creates a new volume type.",
"name": "create",
"signature": "def create(self, req, body)"
},
{
"docstring": "Return a single volume type item",
"name": "... | 5 | stack_v2_sparse_classes_30k_train_003794 | Implement the Python class `VolumeTypesController` described below.
Class description:
The volume types API controller for the Openstack API
Method signatures and docstrings:
- def index(self, req): Returns the list of volume types
- def create(self, req, body): Creates a new volume type.
- def show(self, req, id): R... | Implement the Python class `VolumeTypesController` described below.
Class description:
The volume types API controller for the Openstack API
Method signatures and docstrings:
- def index(self, req): Returns the list of volume types
- def create(self, req, body): Creates a new volume type.
- def show(self, req, id): R... | d3de121d6ad35431fb63c20b2185f0f61ceb9e8e | <|skeleton|>
class VolumeTypesController:
"""The volume types API controller for the Openstack API"""
def index(self, req):
"""Returns the list of volume types"""
<|body_0|>
def create(self, req, body):
"""Creates a new volume type."""
<|body_1|>
def show(self, req, id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeTypesController:
"""The volume types API controller for the Openstack API"""
def index(self, req):
"""Returns the list of volume types"""
context = req.environ['nova.context']
authorize(context)
return volume_types.get_all_types(context)
def create(self, req, bo... | the_stack_v2_python_sparse | nova/api/openstack/compute/contrib/volumetypes.py | rcbops/nova-buildpackage | train | 0 |
07574c495be2a9acf06160ee7bd0cc81992cd2ae | [
"if len(nums) == 0:\n return 0\nmax_length = 0\ncur = 1\nfor i in range(len(nums) - 1):\n if nums[i] < nums[i + 1]:\n cur += 1\n else:\n max_length = cur if cur > max_length else max_length\n cur = 1\nreturn max_length if cur < max_length else cur",
"if len(nums) == 0:\n return 0\... | <|body_start_0|>
if len(nums) == 0:
return 0
max_length = 0
cur = 1
for i in range(len(nums) - 1):
if nums[i] < nums[i + 1]:
cur += 1
else:
max_length = cur if cur > max_length else max_length
cur = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
ret... | stack_v2_sparse_classes_36k_train_034433 | 1,034 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS1",
"signature": "def findLengthOfLCIS1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS",
"signature": "def findLengthOfLCIS(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015639 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS1(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS1(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
max_length = 0
cur = 1
for i in range(len(nums) - 1):
if nums[i] < nums[i + 1]:
cur += 1
else:
... | the_stack_v2_python_sparse | python/leetcode_bak/674_Longest_Continuous_Increasing_Subsequence.py | bobcaoge/my-code | train | 0 | |
fd67f2f14325c6d373d841f3e9913ff8b166a5d1 | [
"FeaturewiseDatasetMeasure.__init__(self, **kwargs)\nself.__pvalue = int(pvalue)\nself.__attr = attr",
"attrdata = eval('dataset.' + self.__attr)\nsamples = dataset.samples\npvalue_index = self.__pvalue\nresult = N.empty((dataset.nfeatures,), dtype=float)\nfor ifeature in xrange(dataset.nfeatures):\n samples_ ... | <|body_start_0|>
FeaturewiseDatasetMeasure.__init__(self, **kwargs)
self.__pvalue = int(pvalue)
self.__attr = attr
<|end_body_0|>
<|body_start_1|>
attrdata = eval('dataset.' + self.__attr)
samples = dataset.samples
pvalue_index = self.__pvalue
result = N.empty((d... | `FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me! | CorrCoef | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorrCoef:
"""`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!"""
def __init__(self, pvalue=False, attr='labels', **kwargs):
"""Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlat... | stack_v2_sparse_classes_36k_train_034434 | 2,394 | permissive | [
{
"docstring": "Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlation coefficient attr : basestring What attribut to correlate with",
"name": "__init__",
"signature": "def __init__(self, pvalue=False, attr='labels', **kwargs)"
},... | 2 | null | Implement the Python class `CorrCoef` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!
Method signatures and docstrings:
- def __init__(self, pvalue=False, attr='labels', **kwargs): Initialize :Parameters: pvalue : bool Either to report p-value of ... | Implement the Python class `CorrCoef` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!
Method signatures and docstrings:
- def __init__(self, pvalue=False, attr='labels', **kwargs): Initialize :Parameters: pvalue : bool Either to report p-value of ... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class CorrCoef:
"""`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!"""
def __init__(self, pvalue=False, attr='labels', **kwargs):
"""Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CorrCoef:
"""`FeaturewiseDatasetMeasure` that performs correlation with labels XXX: Explain me!"""
def __init__(self, pvalue=False, attr='labels', **kwargs):
"""Initialize :Parameters: pvalue : bool Either to report p-value of pearsons correlation coefficient instead of pure correlation coefficie... | the_stack_v2_python_sparse | mvpa/measures/corrcoef.py | gorlins/PyMVPA | train | 0 |
441dd413b6d64c694af41d14e8b07f708b1f7bd8 | [
"print('\\n//////////////////////////////////////////////////')\nprint('♪♪ BleGraphController Initialized ♪♪\\n')\nprint('deviceID')\nfor id in id_list:\n print(f' - {id}')\nprint('//////////////////////////////////////////////////\\n')\nself.id_list = id_list\nself.deviceControllers: list[DeviceController] = li... | <|body_start_0|>
print('\n//////////////////////////////////////////////////')
print('♪♪ BleGraphController Initialized ♪♪\n')
print('deviceID')
for id in id_list:
print(f' - {id}')
print('//////////////////////////////////////////////////\n')
self.id_list = i... | BleGraphController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BleGraphController:
def __init__(self, id_list: list[str], start_at: datetime, end_at: datetime):
"""id毎にBLE信号のグラフを生成するためのコントローラー @params list[str] id_list デバイスID"""
<|body_0|>
def get_graph_data(self, labels: list[str], colors: list[str]):
"""グラフデータを生成 { "デバイスID": [... | stack_v2_sparse_classes_36k_train_034435 | 2,623 | no_license | [
{
"docstring": "id毎にBLE信号のグラフを生成するためのコントローラー @params list[str] id_list デバイスID",
"name": "__init__",
"signature": "def __init__(self, id_list: list[str], start_at: datetime, end_at: datetime)"
},
{
"docstring": "グラフデータを生成 { \"デバイスID\": [ { \"x\": [], \"y\": [], \"color\": \"\", \"label\": \"\" },... | 3 | stack_v2_sparse_classes_30k_train_020327 | Implement the Python class `BleGraphController` described below.
Class description:
Implement the BleGraphController class.
Method signatures and docstrings:
- def __init__(self, id_list: list[str], start_at: datetime, end_at: datetime): id毎にBLE信号のグラフを生成するためのコントローラー @params list[str] id_list デバイスID
- def get_graph_da... | Implement the Python class `BleGraphController` described below.
Class description:
Implement the BleGraphController class.
Method signatures and docstrings:
- def __init__(self, id_list: list[str], start_at: datetime, end_at: datetime): id毎にBLE信号のグラフを生成するためのコントローラー @params list[str] id_list デバイスID
- def get_graph_da... | 0de2ee9c5af2e39f15952adf3df55c227d9a3bd0 | <|skeleton|>
class BleGraphController:
def __init__(self, id_list: list[str], start_at: datetime, end_at: datetime):
"""id毎にBLE信号のグラフを生成するためのコントローラー @params list[str] id_list デバイスID"""
<|body_0|>
def get_graph_data(self, labels: list[str], colors: list[str]):
"""グラフデータを生成 { "デバイスID": [... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BleGraphController:
def __init__(self, id_list: list[str], start_at: datetime, end_at: datetime):
"""id毎にBLE信号のグラフを生成するためのコントローラー @params list[str] id_list デバイスID"""
print('\n//////////////////////////////////////////////////')
print('♪♪ BleGraphController Initialized ♪♪\n')
pr... | the_stack_v2_python_sparse | src/controllers/graph/ble.py | Alesion30/elecon-py | train | 0 | |
6d465f9065f7f71f4107391ac7f276465be257b5 | [
"ans, lena, lenb = (0, len(A), len(B))\nmemo = [0] * (lenb + 1)\nfor i in range(lena):\n for j in reversed(range(lenb)):\n memo[j + 1] = memo[j] + 1 if B[j] == A[i] else 0\n ans = max(ans, memo[j + 1])\nreturn ans",
"ans, prev, t = (0, 0, 0)\nmemo = [0] * (len(B) + 1)\nfor i in range(len(A)):\n ... | <|body_start_0|>
ans, lena, lenb = (0, len(A), len(B))
memo = [0] * (lenb + 1)
for i in range(lena):
for j in reversed(range(lenb)):
memo[j + 1] = memo[j] + 1 if B[j] == A[i] else 0
ans = max(ans, memo[j + 1])
return ans
<|end_body_0|>
<|body_... | SolutionMaxLengthOfRepeatedSubarray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionMaxLengthOfRepeatedSubarray:
def findLength(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_0|>
def findLength1(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_034436 | 1,238 | no_license | [
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: int",
"name": "findLength",
"signature": "def findLength(self, A, B)"
},
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: int",
"name": "findLength1",
"signature": "def findLength1(self, A, B)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004332 | Implement the Python class `SolutionMaxLengthOfRepeatedSubarray` described below.
Class description:
Implement the SolutionMaxLengthOfRepeatedSubarray class.
Method signatures and docstrings:
- def findLength(self, A, B): :type A: List[int] :type B: List[int] :rtype: int
- def findLength1(self, A, B): :type A: List[i... | Implement the Python class `SolutionMaxLengthOfRepeatedSubarray` described below.
Class description:
Implement the SolutionMaxLengthOfRepeatedSubarray class.
Method signatures and docstrings:
- def findLength(self, A, B): :type A: List[int] :type B: List[int] :rtype: int
- def findLength1(self, A, B): :type A: List[i... | a07d8b3cfd5eadb3c3b2f4383cb8ffc32d52f928 | <|skeleton|>
class SolutionMaxLengthOfRepeatedSubarray:
def findLength(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_0|>
def findLength1(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionMaxLengthOfRepeatedSubarray:
def findLength(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int"""
ans, lena, lenb = (0, len(A), len(B))
memo = [0] * (lenb + 1)
for i in range(lena):
for j in reversed(range(lenb)):
memo[j + 1] =... | the_stack_v2_python_sparse | python/MaxLengthOfRepeatedSubarray.py | hellocomrade/happycoding | train | 5 | |
ef28dba2899646192d7caf2ae8c731db744294aa | [
"specs = super().getInputSpecification()\nspecs.name = 'outtruncation'\nspecs.description = 'limits the data to either positive or negative values by \"reflecting\" the\\n out-of-range values back into the desired range.'\ndomainType = InputTypes.makeEnumType('outDomain', 'outDomainType', ['p... | <|body_start_0|>
specs = super().getInputSpecification()
specs.name = 'outtruncation'
specs.description = 'limits the data to either positive or negative values by "reflecting" the\n out-of-range values back into the desired range.'
domainType = InputTypes.makeEnum... | Wrapper of scikit-learn's FunctionTransformer for limiting generated data to a specific range | OutTruncation | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutTruncation:
"""Wrapper of scikit-learn's FunctionTransformer for limiting generated data to a specific range"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, c... | stack_v2_sparse_classes_36k_train_034437 | 6,301 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Reads... | 2 | null | Implement the Python class `OutTruncation` described below.
Class description:
Wrapper of scikit-learn's FunctionTransformer for limiting generated data to a specific range
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class ... | Implement the Python class `OutTruncation` described below.
Class description:
Wrapper of scikit-learn's FunctionTransformer for limiting generated data to a specific range
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input data for class ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class OutTruncation:
"""Wrapper of scikit-learn's FunctionTransformer for limiting generated data to a specific range"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutTruncation:
"""Wrapper of scikit-learn's FunctionTransformer for limiting generated data to a specific range"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, None @ Out, specs, InputData.ParameterInput, class to use f... | the_stack_v2_python_sparse | ravenframework/TSA/Transformers/FunctionTransformers.py | idaholab/raven | train | 201 |
247a7e295102457b0525aba63539d97b050b025a | [
"super().__init__(model, dataset)\nself.entity_id_2_train_samples = {}\nfor h, r, t in dataset.train_samples:\n if h in self.entity_id_2_train_samples:\n self.entity_id_2_train_samples[h].append((h, r, t))\n else:\n self.entity_id_2_train_samples[h] = [(h, r, t)]\n if t in self.entity_id_2_tr... | <|body_start_0|>
super().__init__(model, dataset)
self.entity_id_2_train_samples = {}
for h, r, t in dataset.train_samples:
if h in self.entity_id_2_train_samples:
self.entity_id_2_train_samples[h].append((h, r, t))
else:
self.entity_id_2_t... | The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts . | NoPreFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoPreFilter:
"""The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts ."""
def __init__(self, model: Model, dataset: Dataset):
"""NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the mode... | stack_v2_sparse_classes_36k_train_034438 | 2,543 | no_license | [
{
"docstring": "NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the model",
"name": "__init__",
"signature": "def __init__(self, model: Model, dataset: Dataset)"
},
{
"docstring": "This method extracts the top k promising samples for i... | 2 | stack_v2_sparse_classes_30k_train_021413 | Implement the Python class `NoPreFilter` described below.
Class description:
The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts .
Method signatures and docstrings:
- def __init__(self, model: Model, dataset: Dataset): NoPreFilter object constructor. :param model: the model to e... | Implement the Python class `NoPreFilter` described below.
Class description:
The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts .
Method signatures and docstrings:
- def __init__(self, model: Model, dataset: Dataset): NoPreFilter object constructor. :param model: the model to e... | 9b408d1cef1a10c4bb8a32824eb3f8c90b9a8fb0 | <|skeleton|>
class NoPreFilter:
"""The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts ."""
def __init__(self, model: Model, dataset: Dataset):
"""NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoPreFilter:
"""The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts ."""
def __init__(self, model: Model, dataset: Dataset):
"""NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the model"""
... | the_stack_v2_python_sparse | prefilters/no_prefilter.py | AndRossi/Kelpie | train | 45 |
4d39cf7aa089e6ba0b4eddacfd3aa8241280e189 | [
"config = Utils().get_config_file('config.ini')\nowner = config.get('Repository', 'owner')\nrepository_name = config.get('Repository', 'repository_name')\nmock_res = {'open_pr_time': 119576.0}\ntype(mock_created_time).return_value = mock.PropertyMock(return_value=mock_res)\nmock_res = {'closed_pr_time': 44010646.0}... | <|body_start_0|>
config = Utils().get_config_file('config.ini')
owner = config.get('Repository', 'owner')
repository_name = config.get('Repository', 'repository_name')
mock_res = {'open_pr_time': 119576.0}
type(mock_created_time).return_value = mock.PropertyMock(return_value=mock... | Testcase for Repository | FetchingDataTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchingDataTest:
"""Testcase for Repository"""
def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_count, mock_closed_pull_reque... | stack_v2_sparse_classes_36k_train_034439 | 5,632 | no_license | [
{
"docstring": "test fetching_data method",
"name": "test_fetching_data",
"signature": "def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_c... | 2 | stack_v2_sparse_classes_30k_train_010182 | Implement the Python class `FetchingDataTest` described below.
Class description:
Testcase for Repository
Method signatures and docstrings:
- def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed... | Implement the Python class `FetchingDataTest` described below.
Class description:
Testcase for Repository
Method signatures and docstrings:
- def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed... | 4b31f2c7d87c3ad15c7ab8b71a94abdada1faf63 | <|skeleton|>
class FetchingDataTest:
"""Testcase for Repository"""
def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_count, mock_closed_pull_reque... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FetchingDataTest:
"""Testcase for Repository"""
def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_count, mock_closed_pull_request_time, mock... | the_stack_v2_python_sparse | unit_test/fetching_data_test.py | iamthebj/GitPred | train | 0 |
58ae81e9f7fa5036bfb1d1be1bcbd8d7556f33ac | [
"self.assertTrue(os.path.exists('./web_crawl.py'))\nself.assertTrue(os.path.exists('./fake_response.txt'))\nself.assertTrue(os.path.exists('./expected.txt'))\nself.assertTrue(os.path.exists('./output_from_fn.txt'))",
"a = Crawl()\nresult = {'https://kishore.com/about/', 'https://kishore.com/usa/'}\nwith open('fak... | <|body_start_0|>
self.assertTrue(os.path.exists('./web_crawl.py'))
self.assertTrue(os.path.exists('./fake_response.txt'))
self.assertTrue(os.path.exists('./expected.txt'))
self.assertTrue(os.path.exists('./output_from_fn.txt'))
<|end_body_0|>
<|body_start_1|>
a = Crawl()
... | Testing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Testing:
def test_file_present(self):
"""Checks if all test files are present in the current directory"""
<|body_0|>
def test_get_local_links(self, m):
"""get requests are mocked by giving the input text response from fake_response.txt file. This file contains both 1... | stack_v2_sparse_classes_36k_train_034440 | 2,499 | no_license | [
{
"docstring": "Checks if all test files are present in the current directory",
"name": "test_file_present",
"signature": "def test_file_present(self)"
},
{
"docstring": "get requests are mocked by giving the input text response from fake_response.txt file. This file contains both 1st and 3rd pa... | 3 | stack_v2_sparse_classes_30k_train_013316 | Implement the Python class `Testing` described below.
Class description:
Implement the Testing class.
Method signatures and docstrings:
- def test_file_present(self): Checks if all test files are present in the current directory
- def test_get_local_links(self, m): get requests are mocked by giving the input text res... | Implement the Python class `Testing` described below.
Class description:
Implement the Testing class.
Method signatures and docstrings:
- def test_file_present(self): Checks if all test files are present in the current directory
- def test_get_local_links(self, m): get requests are mocked by giving the input text res... | 1a7094d0dca08ef9f8a481565e8344043c662aa5 | <|skeleton|>
class Testing:
def test_file_present(self):
"""Checks if all test files are present in the current directory"""
<|body_0|>
def test_get_local_links(self, m):
"""get requests are mocked by giving the input text response from fake_response.txt file. This file contains both 1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Testing:
def test_file_present(self):
"""Checks if all test files are present in the current directory"""
self.assertTrue(os.path.exists('./web_crawl.py'))
self.assertTrue(os.path.exists('./fake_response.txt'))
self.assertTrue(os.path.exists('./expected.txt'))
self.asse... | the_stack_v2_python_sparse | web_crawler/test_web_crawl.py | SakthiKishore/Python | train | 0 | |
02d6b451b76c72a955636b7c85a78e206da281a3 | [
"self.normalized_payee_name = normalized_payee_name\nself.category = category\nself.best_representation = best_representation\nself.city = city\nself.state = state\nself.postal_code = postal_code\nself.country = country\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None... | <|body_start_0|>
self.normalized_payee_name = normalized_payee_name
self.category = category
self.best_representation = best_representation
self.city = city
self.state = state
self.postal_code = postal_code
self.country = country
self.additional_properties... | Implementation of the 'Categorization' model. Categorization Record Attributes: normalized_payee_name (string): A normalized payee, derived from the transaction’s description and memo fields. category (string): One of the values from Categories (assigned based on the payee name) best_representation (string): Combines t... | Categorization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Categorization:
"""Implementation of the 'Categorization' model. Categorization Record Attributes: normalized_payee_name (string): A normalized payee, derived from the transaction’s description and memo fields. category (string): One of the values from Categories (assigned based on the payee name... | stack_v2_sparse_classes_36k_train_034441 | 3,507 | permissive | [
{
"docstring": "Constructor for the Categorization class",
"name": "__init__",
"signature": "def __init__(self, normalized_payee_name=None, category=None, best_representation=None, country=None, city=None, state=None, postal_code=None, additional_properties={})"
},
{
"docstring": "Creates an ins... | 2 | null | Implement the Python class `Categorization` described below.
Class description:
Implementation of the 'Categorization' model. Categorization Record Attributes: normalized_payee_name (string): A normalized payee, derived from the transaction’s description and memo fields. category (string): One of the values from Categ... | Implement the Python class `Categorization` described below.
Class description:
Implementation of the 'Categorization' model. Categorization Record Attributes: normalized_payee_name (string): A normalized payee, derived from the transaction’s description and memo fields. category (string): One of the values from Categ... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class Categorization:
"""Implementation of the 'Categorization' model. Categorization Record Attributes: normalized_payee_name (string): A normalized payee, derived from the transaction’s description and memo fields. category (string): One of the values from Categories (assigned based on the payee name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Categorization:
"""Implementation of the 'Categorization' model. Categorization Record Attributes: normalized_payee_name (string): A normalized payee, derived from the transaction’s description and memo fields. category (string): One of the values from Categories (assigned based on the payee name) best_repres... | the_stack_v2_python_sparse | finicityapi/models/categorization.py | monarchmoney/finicity-python | train | 0 |
03a21476564e925c7fa26a88fc18fa47458a5342 | [
"def split_by(data, regexps):\n if not regexps:\n return list(data)\n regexp = self.REGEXPS[regexps[0]]\n splitted = regexp.split(data)\n tokens = []\n for i, split in enumerate(splitted):\n if i % 2 == 0:\n tokens += split_by(split, regexps[1:])\n else:\n t... | <|body_start_0|>
def split_by(data, regexps):
if not regexps:
return list(data)
regexp = self.REGEXPS[regexps[0]]
splitted = regexp.split(data)
tokens = []
for i, split in enumerate(splitted):
if i % 2 == 0:
... | Deals with the tokenization and untokenization of SMILES. | SMILESTokenizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMILESTokenizer:
"""Deals with the tokenization and untokenization of SMILES."""
def tokenize(self, data, with_begin_and_end=True):
"""Tokenizes a SMILES string."""
<|body_0|>
def untokenize(self, tokens):
"""Untokenizes a SMILES string."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_034442 | 30,063 | no_license | [
{
"docstring": "Tokenizes a SMILES string.",
"name": "tokenize",
"signature": "def tokenize(self, data, with_begin_and_end=True)"
},
{
"docstring": "Untokenizes a SMILES string.",
"name": "untokenize",
"signature": "def untokenize(self, tokens)"
}
] | 2 | null | Implement the Python class `SMILESTokenizer` described below.
Class description:
Deals with the tokenization and untokenization of SMILES.
Method signatures and docstrings:
- def tokenize(self, data, with_begin_and_end=True): Tokenizes a SMILES string.
- def untokenize(self, tokens): Untokenizes a SMILES string. | Implement the Python class `SMILESTokenizer` described below.
Class description:
Deals with the tokenization and untokenization of SMILES.
Method signatures and docstrings:
- def tokenize(self, data, with_begin_and_end=True): Tokenizes a SMILES string.
- def untokenize(self, tokens): Untokenizes a SMILES string.
<|s... | 75dab7a39cb122c37d617ee0170b9fb781efa23a | <|skeleton|>
class SMILESTokenizer:
"""Deals with the tokenization and untokenization of SMILES."""
def tokenize(self, data, with_begin_and_end=True):
"""Tokenizes a SMILES string."""
<|body_0|>
def untokenize(self, tokens):
"""Untokenizes a SMILES string."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMILESTokenizer:
"""Deals with the tokenization and untokenization of SMILES."""
def tokenize(self, data, with_begin_and_end=True):
"""Tokenizes a SMILES string."""
def split_by(data, regexps):
if not regexps:
return list(data)
regexp = self.REGEXPS... | the_stack_v2_python_sparse | molFlash-master/molflash/generator/utils/preprocess.py | xLeviackermanX/intern-bayeslab | train | 0 |
9e38d3e014609ec828d0c145f69e16d67b0298bb | [
"if data['type'] == 'personal':\n if not (data.get('given_name') or data.get('family_name')):\n messages = [_('Family name or given name must be filled.')]\n raise ValidationError({'given_name': messages, 'family_name': messages})\nelif data['type'] == 'organizational':\n if not data.get('name')... | <|body_start_0|>
if data['type'] == 'personal':
if not (data.get('given_name') or data.get('family_name')):
messages = [_('Family name or given name must be filled.')]
raise ValidationError({'given_name': messages, 'family_name': messages})
elif data['type'] =... | Person or Organization schema. | PersonOrOrganizationSchema | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonOrOrganizationSchema:
"""Person or Organization schema."""
def validate_names(self, data, **kwargs):
"""Validate names based on type."""
<|body_0|>
def update_names(self, data, **kwargs):
"""Update names for organization / person. Fill name from given_name ... | stack_v2_sparse_classes_36k_train_034443 | 13,845 | permissive | [
{
"docstring": "Validate names based on type.",
"name": "validate_names",
"signature": "def validate_names(self, data, **kwargs)"
},
{
"docstring": "Update names for organization / person. Fill name from given_name and family_name if person. Remove given_name and family_name if organization.",
... | 2 | stack_v2_sparse_classes_30k_train_020310 | Implement the Python class `PersonOrOrganizationSchema` described below.
Class description:
Person or Organization schema.
Method signatures and docstrings:
- def validate_names(self, data, **kwargs): Validate names based on type.
- def update_names(self, data, **kwargs): Update names for organization / person. Fill ... | Implement the Python class `PersonOrOrganizationSchema` described below.
Class description:
Person or Organization schema.
Method signatures and docstrings:
- def validate_names(self, data, **kwargs): Validate names based on type.
- def update_names(self, data, **kwargs): Update names for organization / person. Fill ... | 78ad536dbb95494967bf8de248cf922e5040e844 | <|skeleton|>
class PersonOrOrganizationSchema:
"""Person or Organization schema."""
def validate_names(self, data, **kwargs):
"""Validate names based on type."""
<|body_0|>
def update_names(self, data, **kwargs):
"""Update names for organization / person. Fill name from given_name ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonOrOrganizationSchema:
"""Person or Organization schema."""
def validate_names(self, data, **kwargs):
"""Validate names based on type."""
if data['type'] == 'personal':
if not (data.get('given_name') or data.get('family_name')):
messages = [_('Family name ... | the_stack_v2_python_sparse | invenio_rdm_records/services/schemas/metadata.py | tu-graz-library/invenio-rdm-records | train | 0 |
ced252d6a478d30342c219149952484f80f37301 | [
"self.action = action\nself.ticker = ticker\nself.quantity = init_quantity\nself.init_price = init_price\nself.init_commission = init_commission\nself.realised_pnl = 0\nself.unrealised_pnl = 0\nself.buys = 0\nself.sells = 0\nself.avg_bot = 0\nself.avg_sld = 0\nself.total_bot = 0\nself.total_sld = 0\nself.total_comm... | <|body_start_0|>
self.action = action
self.ticker = ticker
self.quantity = init_quantity
self.init_price = init_price
self.init_commission = init_commission
self.realised_pnl = 0
self.unrealised_pnl = 0
self.buys = 0
self.sells = 0
self.avg... | Position | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Position:
def __init__(self, action, ticker, init_quantity, init_price, init_commission, bid, ask):
"""Set up the initial "account" of the Position to be zero for most items, with the exception of the initial purchase/sale. Then calculate the initial values and finally update the market ... | stack_v2_sparse_classes_36k_train_034444 | 5,069 | no_license | [
{
"docstring": "Set up the initial \"account\" of the Position to be zero for most items, with the exception of the initial purchase/sale. Then calculate the initial values and finally update the market value of the transaction. :param action: :param ticker: :param init_quantity: :param init_price: :param init_... | 4 | stack_v2_sparse_classes_30k_train_005478 | Implement the Python class `Position` described below.
Class description:
Implement the Position class.
Method signatures and docstrings:
- def __init__(self, action, ticker, init_quantity, init_price, init_commission, bid, ask): Set up the initial "account" of the Position to be zero for most items, with the excepti... | Implement the Python class `Position` described below.
Class description:
Implement the Position class.
Method signatures and docstrings:
- def __init__(self, action, ticker, init_quantity, init_price, init_commission, bid, ask): Set up the initial "account" of the Position to be zero for most items, with the excepti... | 1dffb983ba3374f5f3a018e2b7d909bf5546947d | <|skeleton|>
class Position:
def __init__(self, action, ticker, init_quantity, init_price, init_commission, bid, ask):
"""Set up the initial "account" of the Position to be zero for most items, with the exception of the initial purchase/sale. Then calculate the initial values and finally update the market ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Position:
def __init__(self, action, ticker, init_quantity, init_price, init_commission, bid, ask):
"""Set up the initial "account" of the Position to be zero for most items, with the exception of the initial purchase/sale. Then calculate the initial values and finally update the market value of the t... | the_stack_v2_python_sparse | position.py | TheGiddy/Backtester | train | 0 | |
0a63d99f2be973908d934ba8710eb118294edaa7 | [
"self.parent = None\nself.value = value\nself._left = left\nself._right = right\nself.isLeftEvaluate = False\nself.isRightEvaluate = False\nif left:\n self.left.parent = self\nif right:\n self.right.parent = self",
"import random\nif not self.isLeftEvaluate:\n if random.random() < 0.5:\n value = r... | <|body_start_0|>
self.parent = None
self.value = value
self._left = left
self._right = right
self.isLeftEvaluate = False
self.isRightEvaluate = False
if left:
self.left.parent = self
if right:
self.right.parent = self
<|end_body_0|>... | Node class for a binary tree. | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
<|body_0|>
def left(self, value=None):
"""Return the left node, create if empty."""
<|body_1|>
def right(self, value=None):
... | stack_v2_sparse_classes_36k_train_034445 | 3,135 | no_license | [
{
"docstring": "Initialize the node.",
"name": "__init__",
"signature": "def __init__(self, value, left=None, right=None)"
},
{
"docstring": "Return the left node, create if empty.",
"name": "left",
"signature": "def left(self, value=None)"
},
{
"docstring": "Return the right nod... | 4 | stack_v2_sparse_classes_30k_train_018184 | Implement the Python class `Node` described below.
Class description:
Node class for a binary tree.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): Initialize the node.
- def left(self, value=None): Return the left node, create if empty.
- def right(self, value=None): Return the ... | Implement the Python class `Node` described below.
Class description:
Node class for a binary tree.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): Initialize the node.
- def left(self, value=None): Return the left node, create if empty.
- def right(self, value=None): Return the ... | 97eae3ee806756f4d646d600f434b1e68164ad34 | <|skeleton|>
class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
<|body_0|>
def left(self, value=None):
"""Return the left node, create if empty."""
<|body_1|>
def right(self, value=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
self.parent = None
self.value = value
self._left = left
self._right = right
self.isLeftEvaluate = False
self.isRightEvaluate = Fal... | the_stack_v2_python_sparse | Python/2019_05_11_Problem_116_Generate_Arbitrary_Large_Tree.py | BaoCaiH/Daily_Coding_Problem | train | 0 |
aae448fa8cba82d39ec70b39f682f36f28a5824b | [
"self.ip = ip\nif interface not in netifaces.interfaces():\n logger.error('Error: No valid interface detected for external %s : %s.', ip, interface)\n sys.exit(1)\nself.interface = interface",
"ip_packet = ethernet_packet.child()\ndelta_ttl = ip_packet.get_ip_ttl() - path\nip_packet.set_ip_ttl(delta_ttl)\ni... | <|body_start_0|>
self.ip = ip
if interface not in netifaces.interfaces():
logger.error('Error: No valid interface detected for external %s : %s.', ip, interface)
sys.exit(1)
self.interface = interface
<|end_body_0|>
<|body_start_1|>
ip_packet = ethernet_packet.ch... | Defines bindings of external machine interfaces to virtual ips in the network | External | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class External:
"""Defines bindings of external machine interfaces to virtual ips in the network"""
def __init__(self, ip, interface):
"""Function initialized an external machine in the network Args: ip : ip address of the machine in the network interface : network interface the machine is... | stack_v2_sparse_classes_36k_train_034446 | 28,024 | permissive | [
{
"docstring": "Function initialized an external machine in the network Args: ip : ip address of the machine in the network interface : network interface the machine is connected to",
"name": "__init__",
"signature": "def __init__(self, ip, interface)"
},
{
"docstring": "Function conveys traffic... | 2 | stack_v2_sparse_classes_30k_train_010006 | Implement the Python class `External` described below.
Class description:
Defines bindings of external machine interfaces to virtual ips in the network
Method signatures and docstrings:
- def __init__(self, ip, interface): Function initialized an external machine in the network Args: ip : ip address of the machine in... | Implement the Python class `External` described below.
Class description:
Defines bindings of external machine interfaces to virtual ips in the network
Method signatures and docstrings:
- def __init__(self, ip, interface): Function initialized an external machine in the network Args: ip : ip address of the machine in... | a2812eddff632eceb68b6d00872617f536132788 | <|skeleton|>
class External:
"""Defines bindings of external machine interfaces to virtual ips in the network"""
def __init__(self, ip, interface):
"""Function initialized an external machine in the network Args: ip : ip address of the machine in the network interface : network interface the machine is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class External:
"""Defines bindings of external machine interfaces to virtual ips in the network"""
def __init__(self, ip, interface):
"""Function initialized an external machine in the network Args: ip : ip address of the machine in the network interface : network interface the machine is connected to... | the_stack_v2_python_sparse | honeyd/core/element.py | kevindar/honeyd-python | train | 0 |
35faca9138d979f4bece0990ed5bdcc0421c5b15 | [
"url = [op_config['server'], 'api/adwords', op_config['group'], op_config['version'], self.__class__.__name__]\nif config['access']:\n url.insert(len(url) - 1, config['access'])\nself.__service = AdWordsWebService(headers, config, op_config, '/'.join(url), lock, logger)\nself._wsdl_types_map = WSDL_MAP[op_config... | <|body_start_0|>
url = [op_config['server'], 'api/adwords', op_config['group'], op_config['version'], self.__class__.__name__]
if config['access']:
url.insert(len(url) - 1, config['access'])
self.__service = AdWordsWebService(headers, config, op_config, '/'.join(url), lock, logger)
... | Wrapper for TargetingIdeaService. The TargetingIdeaService service provides a way to fetch ideas that match the specified query. | TargetingIdeaService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetingIdeaService:
"""Wrapper for TargetingIdeaService. The TargetingIdeaService service provides a way to fetch ideas that match the specified query."""
def __init__(self, headers, config, op_config, lock, logger):
"""Inits TargetingIdeaService. Args: headers: dict Dictionary obj... | stack_v2_sparse_classes_36k_train_034447 | 4,662 | permissive | [
{
"docstring": "Inits TargetingIdeaService. Args: headers: dict Dictionary object with populated authentication credentials. config: dict Dictionary object with populated configuration values. op_config: dict Dictionary object with additional configuration values for this operation. lock: thread.lock Thread loc... | 3 | null | Implement the Python class `TargetingIdeaService` described below.
Class description:
Wrapper for TargetingIdeaService. The TargetingIdeaService service provides a way to fetch ideas that match the specified query.
Method signatures and docstrings:
- def __init__(self, headers, config, op_config, lock, logger): Inits... | Implement the Python class `TargetingIdeaService` described below.
Class description:
Wrapper for TargetingIdeaService. The TargetingIdeaService service provides a way to fetch ideas that match the specified query.
Method signatures and docstrings:
- def __init__(self, headers, config, op_config, lock, logger): Inits... | 34197dfbdb01479f288611a0cb700e925c4e56ce | <|skeleton|>
class TargetingIdeaService:
"""Wrapper for TargetingIdeaService. The TargetingIdeaService service provides a way to fetch ideas that match the specified query."""
def __init__(self, headers, config, op_config, lock, logger):
"""Inits TargetingIdeaService. Args: headers: dict Dictionary obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetingIdeaService:
"""Wrapper for TargetingIdeaService. The TargetingIdeaService service provides a way to fetch ideas that match the specified query."""
def __init__(self, headers, config, op_config, lock, logger):
"""Inits TargetingIdeaService. Args: headers: dict Dictionary object with popu... | the_stack_v2_python_sparse | keygrabber/adwords/adwords_api_python_14.2.1/adspygoogle/adwords/TargetingIdeaService.py | MujaahidSalie/aranciulla | train | 0 |
73864b0b76e52e92f3183e1e54ace541408027df | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('xcao19', 'xcao19')\nurl = 'http://files.zillowstatic.com/research/public/Neighborhood/Neighborhood_Zhvi_2bedroom.csv'\ndf = pd.read_csv(url, encoding='ISO-8859-1')\njson_df = df.to_json(orient='records')... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url = 'http://files.zillowstatic.com/research/public/Neighborhood/Neighborhood_Zhvi_2bedroom.csv'
df = pd.read_csv(url, encodin... | homeValues | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class homeValues:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ha... | stack_v2_sparse_classes_36k_train_034448 | 3,260 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `homeValues` described below.
Class description:
Implement the homeValues class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime... | Implement the Python class `homeValues` described below.
Class description:
Implement the homeValues class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class homeValues:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class homeValues:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url = 'http:/... | the_stack_v2_python_sparse | xcao19/homeValues.py | maximega/course-2019-spr-proj | train | 2 | |
eb19c7a9cff9b7dc1453e01ab55ecb2222962c44 | [
"qubits = [v for v in ctls] + [v for v in ancis] + [tgt]\nn_c = len(ctls)\nn_a = len(ancis)\nsuper(CNXGate, self).__init__('cnx', (n_c, n_a), qubits, circ)\nif n_c == 1:\n self.cx(ctls[0], tgt)\nelif n_c == 2:\n self.ccx(ctls[0], ctls[1], tgt)\nelse:\n anci_idx = 0\n self.ccx(ctls[0], ctls[1], ancis[anc... | <|body_start_0|>
qubits = [v for v in ctls] + [v for v in ancis] + [tgt]
n_c = len(ctls)
n_a = len(ancis)
super(CNXGate, self).__init__('cnx', (n_c, n_a), qubits, circ)
if n_c == 1:
self.cx(ctls[0], tgt)
elif n_c == 2:
self.ccx(ctls[0], ctls[1], tg... | CNX gate. | CNXGate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNXGate:
"""CNX gate."""
def __init__(self, ctls, ancis, tgt, circ=None):
"""Create new CNX gate."""
<|body_0|>
def reapply(self, circ):
"""Reapply this gate to corresponding qubits in circ."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
qubits... | stack_v2_sparse_classes_36k_train_034449 | 2,745 | permissive | [
{
"docstring": "Create new CNX gate.",
"name": "__init__",
"signature": "def __init__(self, ctls, ancis, tgt, circ=None)"
},
{
"docstring": "Reapply this gate to corresponding qubits in circ.",
"name": "reapply",
"signature": "def reapply(self, circ)"
}
] | 2 | null | Implement the Python class `CNXGate` described below.
Class description:
CNX gate.
Method signatures and docstrings:
- def __init__(self, ctls, ancis, tgt, circ=None): Create new CNX gate.
- def reapply(self, circ): Reapply this gate to corresponding qubits in circ. | Implement the Python class `CNXGate` described below.
Class description:
CNX gate.
Method signatures and docstrings:
- def __init__(self, ctls, ancis, tgt, circ=None): Create new CNX gate.
- def reapply(self, circ): Reapply this gate to corresponding qubits in circ.
<|skeleton|>
class CNXGate:
"""CNX gate."""
... | ec0fb71899d9e37f96f82eaf79c7d6581df6c9a7 | <|skeleton|>
class CNXGate:
"""CNX gate."""
def __init__(self, ctls, ancis, tgt, circ=None):
"""Create new CNX gate."""
<|body_0|>
def reapply(self, circ):
"""Reapply this gate to corresponding qubits in circ."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNXGate:
"""CNX gate."""
def __init__(self, ctls, ancis, tgt, circ=None):
"""Create new CNX gate."""
qubits = [v for v in ctls] + [v for v in ancis] + [tgt]
n_c = len(ctls)
n_a = len(ancis)
super(CNXGate, self).__init__('cnx', (n_c, n_a), qubits, circ)
if n... | the_stack_v2_python_sparse | qiskit_aqua/grover/cnx.py | takehuge/aqua | train | 1 |
a45920c51abb76c40a23df484402e1ebf708fb15 | [
"self.items = items\nself.customer = customer\nself.payments = payments\nself.code = code\nself.customer_id = customer_id\nself.shipping = shipping\nself.metadata = metadata\nself.antifraud_enabled = antifraud_enabled\nself.ip = ip\nself.session_id = session_id\nself.location = location\nself.device = device\nself.... | <|body_start_0|>
self.items = items
self.customer = customer
self.payments = payments
self.code = code
self.customer_id = customer_id
self.shipping = shipping
self.metadata = metadata
self.antifraud_enabled = antifraud_enabled
self.ip = ip
... | Implementation of the 'Orders Request' model. TODO: type model description here. Attributes: items (list of CreateOrderItemRequest): Items customer (Customer8): TODO: type description here. payments (list of CreatePaymentRequest): Payment data code (string): The order code customer_id (string): The customer id shipping... | OrdersRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrdersRequest:
"""Implementation of the 'Orders Request' model. TODO: type model description here. Attributes: items (list of CreateOrderItemRequest): Items customer (Customer8): TODO: type description here. payments (list of CreatePaymentRequest): Payment data code (string): The order code custo... | stack_v2_sparse_classes_36k_train_034450 | 6,264 | permissive | [
{
"docstring": "Constructor for the OrdersRequest class",
"name": "__init__",
"signature": "def __init__(self, items=None, customer=None, payments=None, code=None, customer_id=None, metadata=None, closed=None, shipping=None, antifraud_enabled=None, ip=None, session_id=None, location=None, device=None, c... | 2 | null | Implement the Python class `OrdersRequest` described below.
Class description:
Implementation of the 'Orders Request' model. TODO: type model description here. Attributes: items (list of CreateOrderItemRequest): Items customer (Customer8): TODO: type description here. payments (list of CreatePaymentRequest): Payment d... | Implement the Python class `OrdersRequest` described below.
Class description:
Implementation of the 'Orders Request' model. TODO: type model description here. Attributes: items (list of CreateOrderItemRequest): Items customer (Customer8): TODO: type description here. payments (list of CreatePaymentRequest): Payment d... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class OrdersRequest:
"""Implementation of the 'Orders Request' model. TODO: type model description here. Attributes: items (list of CreateOrderItemRequest): Items customer (Customer8): TODO: type description here. payments (list of CreatePaymentRequest): Payment data code (string): The order code custo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrdersRequest:
"""Implementation of the 'Orders Request' model. TODO: type model description here. Attributes: items (list of CreateOrderItemRequest): Items customer (Customer8): TODO: type description here. payments (list of CreatePaymentRequest): Payment data code (string): The order code customer_id (strin... | the_stack_v2_python_sparse | mundiapi/models/orders_request.py | mundipagg/MundiAPI-PYTHON | train | 10 |
9bbcfcbbd619c3db0cea656765beec2e9d135b5b | [
"self.instruments: dict = {}\nself.parameters: dict = {}\nself.components: dict = {}\nself.config: dict = {}\nif timestamp is None:\n self.timestamp = ''\nelse:\n self.timestamp = '_'.join(a_tools.verify_timestamp(timestamp))",
"inst: dict[any, any] = {}\ncomponents: dict[any, any] = {}\nfor key, item in se... | <|body_start_0|>
self.instruments: dict = {}
self.parameters: dict = {}
self.components: dict = {}
self.config: dict = {}
if timestamp is None:
self.timestamp = ''
else:
self.timestamp = '_'.join(a_tools.verify_timestamp(timestamp))
<|end_body_0|>
... | Station class which mocks Station class of QCodes. Station contains all given instruments and parameters. | Station | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Station:
"""Station class which mocks Station class of QCodes. Station contains all given instruments and parameters."""
def __init__(self, timestamp: str=None):
"""Initialization of the station. Each station is characterized by the timestamp. Note that inside the station all instrum... | stack_v2_sparse_classes_36k_train_034451 | 22,740 | permissive | [
{
"docstring": "Initialization of the station. Each station is characterized by the timestamp. Note that inside the station all instruments are added to the components attribute. When snapshotting the station, the snapshot of the instruments can be found in the \"instrument\" keys and all other items of the com... | 3 | null | Implement the Python class `Station` described below.
Class description:
Station class which mocks Station class of QCodes. Station contains all given instruments and parameters.
Method signatures and docstrings:
- def __init__(self, timestamp: str=None): Initialization of the station. Each station is characterized b... | Implement the Python class `Station` described below.
Class description:
Station class which mocks Station class of QCodes. Station contains all given instruments and parameters.
Method signatures and docstrings:
- def __init__(self, timestamp: str=None): Initialization of the station. Each station is characterized b... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class Station:
"""Station class which mocks Station class of QCodes. Station contains all given instruments and parameters."""
def __init__(self, timestamp: str=None):
"""Initialization of the station. Each station is characterized by the timestamp. Note that inside the station all instrum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Station:
"""Station class which mocks Station class of QCodes. Station contains all given instruments and parameters."""
def __init__(self, timestamp: str=None):
"""Initialization of the station. Each station is characterized by the timestamp. Note that inside the station all instruments are adde... | the_stack_v2_python_sparse | pycqed/utilities/settings_manager.py | QudevETH/PycQED_py3 | train | 8 |
e2063b4154f217d2ff5041f56af8865f22ccaa65 | [
"challenges: List[Dict[str, Any]] = []\nchallenges = MasteryChallenges.Table(self, challenges)\nUtility.WriteFile(self, f'{self.eXAssets}/masteryChallenges.json', challenges)\nlog.info(f'Compiled {len(challenges):,} Mastery Challenges')",
"table: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{self.iXAssets}/stic... | <|body_start_0|>
challenges: List[Dict[str, Any]] = []
challenges = MasteryChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{self.eXAssets}/masteryChallenges.json', challenges)
log.info(f'Compiled {len(challenges):,} Mastery Challenges')
<|end_body_0|>
<|body_start_1|>
... | Mastery Challenges XAssets. | MasteryChallenges | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MasteryChallenges:
"""Mastery Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Mastery Challenges XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the sticker_book_challenges.cs... | stack_v2_sparse_classes_36k_train_034452 | 13,794 | permissive | [
{
"docstring": "Compile the Mastery Challenges XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the sticker_book_challenges.csv XAsset.",
"name": "Table",
"signature": "def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Di... | 2 | stack_v2_sparse_classes_30k_train_018775 | Implement the Python class `MasteryChallenges` described below.
Class description:
Mastery Challenges XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Mastery Challenges XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the stick... | Implement the Python class `MasteryChallenges` described below.
Class description:
Mastery Challenges XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Mastery Challenges XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the stick... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class MasteryChallenges:
"""Mastery Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Mastery Challenges XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the sticker_book_challenges.cs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MasteryChallenges:
"""Mastery Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Mastery Challenges XAssets."""
challenges: List[Dict[str, Any]] = []
challenges = MasteryChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{self.eXAssets}/mastery... | the_stack_v2_python_sparse | ModernWarfare/XAssets/challenges.py | dbuentello/Hyde | train | 0 |
8e46ceb5918427d5d3de200c810080586f8949f1 | [
"if self.static_root is None:\n self.static_root = 'static'\nif self.templates_root is None:\n self.templates_root = 'templates'\nif self.routes is None:\n self.routes = {}\nself.template_path = os.path.join(os.path.dirname(__file__), self.templates_root)\nself.env = Environment(autoescape=True, loader=Fil... | <|body_start_0|>
if self.static_root is None:
self.static_root = 'static'
if self.templates_root is None:
self.templates_root = 'templates'
if self.routes is None:
self.routes = {}
self.template_path = os.path.join(os.path.dirname(__file__), self.templ... | Small web server. | MicroServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicroServer:
"""Small web server."""
def __init__(self):
"""Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages."""
<|body_0|>
def __call__(self, environ, start_response):
"""This method is called by the HTTPS... | stack_v2_sparse_classes_36k_train_034453 | 3,922 | permissive | [
{
"docstring": "Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method is called by the HTTPServer when there is a request to be handled.",
"name": "__ca... | 6 | null | Implement the Python class `MicroServer` described below.
Class description:
Small web server.
Method signatures and docstrings:
- def __init__(self): Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages.
- def __call__(self, environ, start_response): This method i... | Implement the Python class `MicroServer` described below.
Class description:
Small web server.
Method signatures and docstrings:
- def __init__(self): Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages.
- def __call__(self, environ, start_response): This method i... | 1d650e49950d1987d052028139fcdfcb0bbfcc70 | <|skeleton|>
class MicroServer:
"""Small web server."""
def __init__(self):
"""Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages."""
<|body_0|>
def __call__(self, environ, start_response):
"""This method is called by the HTTPS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MicroServer:
"""Small web server."""
def __init__(self):
"""Initializes the class and configures the paths and the Jinja2 environment so it can find and render pages."""
if self.static_root is None:
self.static_root = 'static'
if self.templates_root is None:
... | the_stack_v2_python_sparse | 10_MicroServer_Login/micro_server.py | Rockfish/PythonCourse | train | 0 |
e37c7a2b403a5ea08a4c4dca7671bbb891921288 | [
"super(SelfAttention, self).__init__()\nif hidden_size % num_attention_heads != 0:\n raise ValueError('The hidden size (%d) is not a product of the number of attention heads (%d)' % (hidden_size, num_attention_heads))\nself.num_attention_heads = num_attention_heads\nself.head_size = int(hidden_size / num_attenti... | <|body_start_0|>
super(SelfAttention, self).__init__()
if hidden_size % num_attention_heads != 0:
raise ValueError('The hidden size (%d) is not a product of the number of attention heads (%d)' % (hidden_size, num_attention_heads))
self.num_attention_heads = num_attention_heads
... | Self-Attention | SelfAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self-Attention"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio):
"""Initialization"""
<|body_0|>
def score_transpose(self, x):
"""Score transpose"""
<|body_1|>
def forward(self, hidden_states, attenti... | stack_v2_sparse_classes_36k_train_034454 | 12,741 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio)"
},
{
"docstring": "Score transpose",
"name": "score_transpose",
"signature": "def score_transpose(self, x)"
},
{
"docstring": "Self-At... | 3 | null | Implement the Python class `SelfAttention` described below.
Class description:
Self-Attention
Method signatures and docstrings:
- def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio): Initialization
- def score_transpose(self, x): Score transpose
- def forward(self, hidden_states, attention_m... | Implement the Python class `SelfAttention` described below.
Class description:
Self-Attention
Method signatures and docstrings:
- def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio): Initialization
- def score_transpose(self, x): Score transpose
- def forward(self, hidden_states, attention_m... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class SelfAttention:
"""Self-Attention"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio):
"""Initialization"""
<|body_0|>
def score_transpose(self, x):
"""Score transpose"""
<|body_1|>
def forward(self, hidden_states, attenti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Self-Attention"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio):
"""Initialization"""
super(SelfAttention, self).__init__()
if hidden_size % num_attention_heads != 0:
raise ValueError('The hidden size (%d) is not a prod... | the_stack_v2_python_sparse | apps/drug_target_interaction/moltrans_dti/double_towers.py | PaddlePaddle/PaddleHelix | train | 771 |
70c5d1dc85fe674787b4771fb3621bee79549dfa | [
"self.positions = collections.deque()\nself.positions_set = set()\nself.positions.append((0, 0))\nself.positions_set.add((0, 0))\nself.width, self.height, self.food = (width, height, list(map(tuple, food)))\nself.moves = {'R': (0, 1), 'D': (1, 0), 'U': (-1, 0), 'L': (0, -1)}\nself.eaten = 0",
"cur_pos = self.posi... | <|body_start_0|>
self.positions = collections.deque()
self.positions_set = set()
self.positions.append((0, 0))
self.positions_set.add((0, 0))
self.width, self.height, self.food = (width, height, list(map(tuple, food)))
self.moves = {'R': (0, 1), 'D': (1, 0), 'U': (-1, 0),... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k_train_034455 | 1,958 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_003962 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | f27ba208b97ed2d92b4c059848cc60f6b90ce75e | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | LeetCode/353. Design Snake Game/Solution.py | nhatsmrt/AlgorithmPractice | train | 15 | |
e4255e5b9baaa877fefe3586fdc3fa9608695944 | [
"super(TesMainWindow, self).__init__()\nself.model = TesGuiModel()\nself.options_view = TesOptionsView()\nself.options_control = TesOptionsControl(self.model, self.options_view)\nself.main_control = TesMainControl(self.model, self)\nself.init_ui()\nself.options_control.update_view()\nself.options_view.measurement_b... | <|body_start_0|>
super(TesMainWindow, self).__init__()
self.model = TesGuiModel()
self.options_view = TesOptionsView()
self.options_control = TesOptionsControl(self.model, self.options_view)
self.main_control = TesMainControl(self.model, self)
self.init_ui()
self.... | A class that represents the main window layout. Attributes: model - The TES program model. options_view - The TesOptionsView object respresenting the options frame. options_control - The TesOptionsControl object representing the options controller. main_control - The TesMainControl object representing the main window c... | TesMainWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TesMainWindow:
"""A class that represents the main window layout. Attributes: model - The TES program model. options_view - The TesOptionsView object respresenting the options frame. options_control - The TesOptionsControl object representing the options controller. main_control - The TesMainCont... | stack_v2_sparse_classes_36k_train_034456 | 3,154 | no_license | [
{
"docstring": "Instance constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Initialize and add the UI elements to the window.",
"name": "init_ui",
"signature": "def init_ui(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002610 | Implement the Python class `TesMainWindow` described below.
Class description:
A class that represents the main window layout. Attributes: model - The TES program model. options_view - The TesOptionsView object respresenting the options frame. options_control - The TesOptionsControl object representing the options con... | Implement the Python class `TesMainWindow` described below.
Class description:
A class that represents the main window layout. Attributes: model - The TES program model. options_view - The TesOptionsView object respresenting the options frame. options_control - The TesOptionsControl object representing the options con... | 743167940f700374755ea273b90da66befae1ba4 | <|skeleton|>
class TesMainWindow:
"""A class that represents the main window layout. Attributes: model - The TES program model. options_view - The TesOptionsView object respresenting the options frame. options_control - The TesOptionsControl object representing the options controller. main_control - The TesMainCont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TesMainWindow:
"""A class that represents the main window layout. Attributes: model - The TES program model. options_view - The TesOptionsView object respresenting the options frame. options_control - The TesOptionsControl object representing the options controller. main_control - The TesMainControl object re... | the_stack_v2_python_sparse | tes/views/tes_main_window.py | max19951001/TES | train | 0 |
9417caf6ac83a47534fe489d4a6e970474db0986 | [
"import collections\nA = sorted(A, key=lambda a: abs(a))\ncount_A = collections.Counter(A)\nfor a in A:\n if count_A[a] >= 1:\n count_A[a] -= 1\n flag = count_A.get(a * 2, 0)\n if flag >= 1:\n count_A[a * 2] -= 1\n else:\n return False\nreturn True",
"from coll... | <|body_start_0|>
import collections
A = sorted(A, key=lambda a: abs(a))
count_A = collections.Counter(A)
for a in A:
if count_A[a] >= 1:
count_A[a] -= 1
flag = count_A.get(a * 2, 0)
if flag >= 1:
count_A[a * ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canReorderDoubled(self, A):
""":type A: List[int] :rtype: bool 400 ms"""
<|body_0|>
def canReorderDoubled_1(self, A):
""":type A: List[int] :rtype: bool 120ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections
A... | stack_v2_sparse_classes_36k_train_034457 | 2,474 | no_license | [
{
"docstring": ":type A: List[int] :rtype: bool 400 ms",
"name": "canReorderDoubled",
"signature": "def canReorderDoubled(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: bool 120ms",
"name": "canReorderDoubled_1",
"signature": "def canReorderDoubled_1(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014138 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReorderDoubled(self, A): :type A: List[int] :rtype: bool 400 ms
- def canReorderDoubled_1(self, A): :type A: List[int] :rtype: bool 120ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canReorderDoubled(self, A): :type A: List[int] :rtype: bool 400 ms
- def canReorderDoubled_1(self, A): :type A: List[int] :rtype: bool 120ms
<|skeleton|>
class Solution:
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def canReorderDoubled(self, A):
""":type A: List[int] :rtype: bool 400 ms"""
<|body_0|>
def canReorderDoubled_1(self, A):
""":type A: List[int] :rtype: bool 120ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canReorderDoubled(self, A):
""":type A: List[int] :rtype: bool 400 ms"""
import collections
A = sorted(A, key=lambda a: abs(a))
count_A = collections.Counter(A)
for a in A:
if count_A[a] >= 1:
count_A[a] -= 1
fla... | the_stack_v2_python_sparse | ArrayOfDoubledPairs_MID_954.py | 953250587/leetcode-python | train | 2 | |
b1bf98d5a2673a7878b261bdf63093cff0a8f234 | [
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nres = cm.api.get_import(cluster)\nreturn Response(res)",
"cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')\nserializer = self.post_serializer(data=request.data, context={'request': request, 'cluster': cluster})\nif serializer.is_valid():... | <|body_start_0|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
res = cm.api.get_import(cluster)
return Response(res)
<|end_body_0|>
<|body_start_1|>
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
serializer = self.post_serializer(data=request.data,... | ClusterImport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterImport:
def get(self, request, cluster_id):
"""List all imports avaliable for specified cluster"""
<|body_0|>
def post(self, request, cluster_id):
"""Update bind for cluster"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cluster = check_obj(... | stack_v2_sparse_classes_36k_train_034458 | 32,530 | permissive | [
{
"docstring": "List all imports avaliable for specified cluster",
"name": "get",
"signature": "def get(self, request, cluster_id)"
},
{
"docstring": "Update bind for cluster",
"name": "post",
"signature": "def post(self, request, cluster_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017182 | Implement the Python class `ClusterImport` described below.
Class description:
Implement the ClusterImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id): List all imports avaliable for specified cluster
- def post(self, request, cluster_id): Update bind for cluster | Implement the Python class `ClusterImport` described below.
Class description:
Implement the ClusterImport class.
Method signatures and docstrings:
- def get(self, request, cluster_id): List all imports avaliable for specified cluster
- def post(self, request, cluster_id): Update bind for cluster
<|skeleton|>
class ... | e1c67e3041437ad9e17dccc6c95c5ac02184eddb | <|skeleton|>
class ClusterImport:
def get(self, request, cluster_id):
"""List all imports avaliable for specified cluster"""
<|body_0|>
def post(self, request, cluster_id):
"""Update bind for cluster"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterImport:
def get(self, request, cluster_id):
"""List all imports avaliable for specified cluster"""
cluster = check_obj(Cluster, cluster_id, 'CLUSTER_NOT_FOUND')
res = cm.api.get_import(cluster)
return Response(res)
def post(self, request, cluster_id):
"""Upd... | the_stack_v2_python_sparse | api/cluster_views.py | amleshkov/adcm | train | 0 | |
23a515099dfd4e277a4aa2491af878b361ee320c | [
"following_user = check_user_profile(request)\ntry:\n followed_user = followed_user_profile(username, 'follow')\nexcept Profile.DoesNotExist:\n pass\nif following_user.id == followed_user.id:\n raise ValidationError('You cannot follow yourself')\nfollowing_user.follow(followed_user)\nserialize = self.seria... | <|body_start_0|>
following_user = check_user_profile(request)
try:
followed_user = followed_user_profile(username, 'follow')
except Profile.DoesNotExist:
pass
if following_user.id == followed_user.id:
raise ValidationError('You cannot follow yourself')... | FollowUnfollow | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowUnfollow:
def post(self, request, username):
"""This method handles following a user"""
<|body_0|>
def delete(self, request, username):
"""This method handles unfollowing a user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
following_user = ... | stack_v2_sparse_classes_36k_train_034459 | 6,939 | permissive | [
{
"docstring": "This method handles following a user",
"name": "post",
"signature": "def post(self, request, username)"
},
{
"docstring": "This method handles unfollowing a user",
"name": "delete",
"signature": "def delete(self, request, username)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000903 | Implement the Python class `FollowUnfollow` described below.
Class description:
Implement the FollowUnfollow class.
Method signatures and docstrings:
- def post(self, request, username): This method handles following a user
- def delete(self, request, username): This method handles unfollowing a user | Implement the Python class `FollowUnfollow` described below.
Class description:
Implement the FollowUnfollow class.
Method signatures and docstrings:
- def post(self, request, username): This method handles following a user
- def delete(self, request, username): This method handles unfollowing a user
<|skeleton|>
cl... | e89bee17668c0fc5db94fd70974145f39485c017 | <|skeleton|>
class FollowUnfollow:
def post(self, request, username):
"""This method handles following a user"""
<|body_0|>
def delete(self, request, username):
"""This method handles unfollowing a user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FollowUnfollow:
def post(self, request, username):
"""This method handles following a user"""
following_user = check_user_profile(request)
try:
followed_user = followed_user_profile(username, 'follow')
except Profile.DoesNotExist:
pass
if followi... | the_stack_v2_python_sparse | authors/apps/profiles/views.py | andela/ah-fulldeck | train | 0 | |
5c0bff5a96781a987bd91d03f093f0aff5eb2994 | [
"ans_string = ''\nfor string in strs:\n ans_string = ans_string + ''.join([chr(ord(x) + 1) for x in string]) + '\\n'\nreturn ans_string",
"ans_list = []\nfor string in s.split('\\n'):\n ans_list.append(''.join([chr(ord(x) - 1) for x in string]))\nreturn ans_list[:-1]"
] | <|body_start_0|>
ans_string = ''
for string in strs:
ans_string = ans_string + ''.join([chr(ord(x) + 1) for x in string]) + '\n'
return ans_string
<|end_body_0|>
<|body_start_1|>
ans_list = []
for string in s.split('\n'):
ans_list.append(''.join([chr(ord(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_034460 | 758 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_004425 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | ea45f9a2bb0a1f42642f5e4792357d9facc3ec52 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
ans_string = ''
for string in strs:
ans_string = ans_string + ''.join([chr(ord(x) + 1) for x in string]) + '\n'
return ans_string
def decode(sel... | the_stack_v2_python_sparse | 271. Encode and Decode Strings.py | vampypandya/LeetCode | train | 0 | |
49e2c04f9eeecfc3d50298252ff1d63548e55fee | [
"self.my_logger = set_logger(self.__class__.__name__)\nself.level = level\nif self.level <= 0:\n self.my_logger.warning('\\n\\tBackground level must be strictly positive.')\nelse:\n self.my_logger.info(f'\\n\\tBackground set to {level:.3f} ADU/s.')\nself.frame = frame",
"yy, xx = np.mgrid[0:parameters.CCD_I... | <|body_start_0|>
self.my_logger = set_logger(self.__class__.__name__)
self.level = level
if self.level <= 0:
self.my_logger.warning('\n\tBackground level must be strictly positive.')
else:
self.my_logger.info(f'\n\tBackground set to {level:.3f} ADU/s.')
se... | Class to model the background of the simulated image. The background model size is set with the parameters.CCD_IMSIZE global keyword. Attributes ---------- level: float The mean level of the background in image units. frame: array_like (x, y, smooth) right and upper limits in pixels of a vignetting frame, and the smoot... | BackgroundModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackgroundModel:
"""Class to model the background of the simulated image. The background model size is set with the parameters.CCD_IMSIZE global keyword. Attributes ---------- level: float The mean level of the background in image units. frame: array_like (x, y, smooth) right and upper limits in ... | stack_v2_sparse_classes_36k_train_034461 | 22,700 | permissive | [
{
"docstring": "Create a BackgroundModel instance. The background model size is set with the parameters.CCD_IMSIZE global keyword. Parameters ---------- level: float The mean level of the background in image units. frame: array_like, None (x, y, smooth) right and upper limits in pixels of a vignetting frame, an... | 3 | stack_v2_sparse_classes_30k_train_001093 | Implement the Python class `BackgroundModel` described below.
Class description:
Class to model the background of the simulated image. The background model size is set with the parameters.CCD_IMSIZE global keyword. Attributes ---------- level: float The mean level of the background in image units. frame: array_like (x... | Implement the Python class `BackgroundModel` described below.
Class description:
Class to model the background of the simulated image. The background model size is set with the parameters.CCD_IMSIZE global keyword. Attributes ---------- level: float The mean level of the background in image units. frame: array_like (x... | d227d0fe3c61cabbfdea42d520da5f44e01632aa | <|skeleton|>
class BackgroundModel:
"""Class to model the background of the simulated image. The background model size is set with the parameters.CCD_IMSIZE global keyword. Attributes ---------- level: float The mean level of the background in image units. frame: array_like (x, y, smooth) right and upper limits in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackgroundModel:
"""Class to model the background of the simulated image. The background model size is set with the parameters.CCD_IMSIZE global keyword. Attributes ---------- level: float The mean level of the background in image units. frame: array_like (x, y, smooth) right and upper limits in pixels of a v... | the_stack_v2_python_sparse | spectractor/simulation/image_simulation.py | LSSTDESC/Spectractor | train | 19 |
44ce195471ed5a8196cc2154f6b1da8408af20c8 | [
"self.lock = Lock()\nself.rate = rate\nself.ts = None\nself.count = 0",
"with self.lock:\n now = time.time()\n if self.ts is None:\n self.ts = now\n if now - self.ts >= 1.0:\n self.count = 0\n self.ts = now\n self.count += 1\n if self.count <= self.rate:\n return\n ti... | <|body_start_0|>
self.lock = Lock()
self.rate = rate
self.ts = None
self.count = 0
<|end_body_0|>
<|body_start_1|>
with self.lock:
now = time.time()
if self.ts is None:
self.ts = now
if now - self.ts >= 1.0:
sel... | Throttle Class | Throttle | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Throttle:
"""Throttle Class"""
def __init__(self, rate=150):
"""Create a throttle for a specific rate/sec"""
<|body_0|>
def __call__(self):
"""Return when the throttle limit is acceptable"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.lock... | stack_v2_sparse_classes_36k_train_034462 | 10,830 | permissive | [
{
"docstring": "Create a throttle for a specific rate/sec",
"name": "__init__",
"signature": "def __init__(self, rate=150)"
},
{
"docstring": "Return when the throttle limit is acceptable",
"name": "__call__",
"signature": "def __call__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004783 | Implement the Python class `Throttle` described below.
Class description:
Throttle Class
Method signatures and docstrings:
- def __init__(self, rate=150): Create a throttle for a specific rate/sec
- def __call__(self): Return when the throttle limit is acceptable | Implement the Python class `Throttle` described below.
Class description:
Throttle Class
Method signatures and docstrings:
- def __init__(self, rate=150): Create a throttle for a specific rate/sec
- def __call__(self): Return when the throttle limit is acceptable
<|skeleton|>
class Throttle:
"""Throttle Class"""... | 0f2e6a2d1c71f104b1522fd68ec01b9f9f3b92f9 | <|skeleton|>
class Throttle:
"""Throttle Class"""
def __init__(self, rate=150):
"""Create a throttle for a specific rate/sec"""
<|body_0|>
def __call__(self):
"""Return when the throttle limit is acceptable"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Throttle:
"""Throttle Class"""
def __init__(self, rate=150):
"""Create a throttle for a specific rate/sec"""
self.lock = Lock()
self.rate = rate
self.ts = None
self.count = 0
def __call__(self):
"""Return when the throttle limit is acceptable"""
... | the_stack_v2_python_sparse | apps/TCPB_-_Bulk_DNS_Lookup/src/app.py | ThreatConnect-Inc/threatconnect-playbooks | train | 76 |
969cd429a2f1ed38233465f3efcfcd2348eb8cdb | [
"logging.debug('%s', request)\ntry:\n _, result = _get_request_and_result(request.task_id, _VIEW, False)\nexcept ValueError:\n raise endpoints.BadRequestException('Invalid task ID')\nreturn message_conversion.task_result_to_rpc(result, request.include_performance_stats)",
"logging.debug('%s', request)\nrequ... | <|body_start_0|>
logging.debug('%s', request)
try:
_, result = _get_request_and_result(request.task_id, _VIEW, False)
except ValueError:
raise endpoints.BadRequestException('Invalid task ID')
return message_conversion.task_result_to_rpc(result, request.include_per... | Swarming's task-related API. | SwarmingTaskService | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwarmingTaskService:
"""Swarming's task-related API."""
def result(self, request):
"""Reports the result of the task corresponding to a task ID. It can be a 'run' ID specifying a specific retry or a 'summary' ID hidding the fact that a task may have been retried transparently, when a... | stack_v2_sparse_classes_36k_train_034463 | 42,982 | permissive | [
{
"docstring": "Reports the result of the task corresponding to a task ID. It can be a 'run' ID specifying a specific retry or a 'summary' ID hidding the fact that a task may have been retried transparently, when a bot reports BOT_DIED. A summary ID ends with '0', a run ID ends with '1' or '2'.",
"name": "r... | 4 | null | Implement the Python class `SwarmingTaskService` described below.
Class description:
Swarming's task-related API.
Method signatures and docstrings:
- def result(self, request): Reports the result of the task corresponding to a task ID. It can be a 'run' ID specifying a specific retry or a 'summary' ID hidding the fac... | Implement the Python class `SwarmingTaskService` described below.
Class description:
Swarming's task-related API.
Method signatures and docstrings:
- def result(self, request): Reports the result of the task corresponding to a task ID. It can be a 'run' ID specifying a specific retry or a 'summary' ID hidding the fac... | 10cc5fdcca53e2a1690867acbe6fce099273f092 | <|skeleton|>
class SwarmingTaskService:
"""Swarming's task-related API."""
def result(self, request):
"""Reports the result of the task corresponding to a task ID. It can be a 'run' ID specifying a specific retry or a 'summary' ID hidding the fact that a task may have been retried transparently, when a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwarmingTaskService:
"""Swarming's task-related API."""
def result(self, request):
"""Reports the result of the task corresponding to a task ID. It can be a 'run' ID specifying a specific retry or a 'summary' ID hidding the fact that a task may have been retried transparently, when a bot reports ... | the_stack_v2_python_sparse | appengine/swarming/handlers_endpoints.py | luci/luci-py | train | 84 |
27305e336eaf5d1bc015c9fdde7861eafcaec402 | [
"super().__init__(cost_func)\nself.support_for_bounds = True\nself._popt = None\nself._status = None\nself._maxiter = None",
"if self.minimizer == 'shgo':\n self._maxiter = 100\nelse:\n self._maxiter = 1000\nif self.value_ranges is None or np.any(np.isinf(self.value_ranges)):\n raise MissingBoundsError('... | <|body_start_0|>
super().__init__(cost_func)
self.support_for_bounds = True
self._popt = None
self._status = None
self._maxiter = None
<|end_body_0|>
<|body_start_1|>
if self.minimizer == 'shgo':
self._maxiter = 100
else:
self._maxiter = 1... | Controller for the Scipy fitting software. | ScipyGOController | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScipyGOController:
"""Controller for the Scipy fitting software."""
def __init__(self, cost_func):
"""Initialises variable used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_func.base_co... | stack_v2_sparse_classes_36k_train_034464 | 3,214 | permissive | [
{
"docstring": "Initialises variable used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_func.base_cost_func.CostFunc`",
"name": "__init__",
"signature": "def __init__(self, cost_func)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_011322 | Implement the Python class `ScipyGOController` described below.
Class description:
Controller for the Scipy fitting software.
Method signatures and docstrings:
- def __init__(self, cost_func): Initialises variable used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_fun... | Implement the Python class `ScipyGOController` described below.
Class description:
Controller for the Scipy fitting software.
Method signatures and docstrings:
- def __init__(self, cost_func): Initialises variable used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_fun... | 5ee7e66d963ebe9296c0a62c24b9616f6c65537e | <|skeleton|>
class ScipyGOController:
"""Controller for the Scipy fitting software."""
def __init__(self, cost_func):
"""Initialises variable used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_func.base_co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScipyGOController:
"""Controller for the Scipy fitting software."""
def __init__(self, cost_func):
"""Initialises variable used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_func.base_cost_func.CostF... | the_stack_v2_python_sparse | fitbenchmarking/controllers/scipy_go_controller.py | fitbenchmarking/fitbenchmarking | train | 15 |
82913eeca02f0d88b7a24185007fd1ff3fbb3f35 | [
"self._discovery_info: BluetoothServiceInfoBleak | None = None\nself._discovered_device: Aranet4Advertisement | None = None\nself._discovered_devices: dict[str, tuple[str, Aranet4Advertisement]] = {}",
"if not adv.manufacturer_data or adv.manufacturer_data.version < MIN_VERSION:\n raise AbortFlow('outdated_ver... | <|body_start_0|>
self._discovery_info: BluetoothServiceInfoBleak | None = None
self._discovered_device: Aranet4Advertisement | None = None
self._discovered_devices: dict[str, tuple[str, Aranet4Advertisement]] = {}
<|end_body_0|>
<|body_start_1|>
if not adv.manufacturer_data or adv.manuf... | Handle a config flow for Aranet. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Aranet."""
def __init__(self) -> None:
"""Set up a new config flow for Aranet."""
<|body_0|>
def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None:
"""Raise any configuration errors that apply to an a... | stack_v2_sparse_classes_36k_train_034465 | 4,638 | permissive | [
{
"docstring": "Set up a new config flow for Aranet.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Raise any configuration errors that apply to an advertisement.",
"name": "_raise_for_advertisement_errors",
"signature": "def _raise_for_advertisement_e... | 5 | stack_v2_sparse_classes_30k_test_001053 | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Aranet.
Method signatures and docstrings:
- def __init__(self) -> None: Set up a new config flow for Aranet.
- def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None: Raise any configuration erro... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Aranet.
Method signatures and docstrings:
- def __init__(self) -> None: Set up a new config flow for Aranet.
- def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None: Raise any configuration erro... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Aranet."""
def __init__(self) -> None:
"""Set up a new config flow for Aranet."""
<|body_0|>
def _raise_for_advertisement_errors(self, adv: Aranet4Advertisement) -> None:
"""Raise any configuration errors that apply to an a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle a config flow for Aranet."""
def __init__(self) -> None:
"""Set up a new config flow for Aranet."""
self._discovery_info: BluetoothServiceInfoBleak | None = None
self._discovered_device: Aranet4Advertisement | None = None
self._discovered_devices: dic... | the_stack_v2_python_sparse | homeassistant/components/aranet/config_flow.py | home-assistant/core | train | 35,501 |
1948aad05d7e89cd1b82015c8ab045a67269b214 | [
"dict = Counter(nums)\nfor key, value in dict.items():\n if value > 1:\n return key",
"tortoise = nums[0]\nhare = nums[0]\nwhile True:\n tortoise = nums[tortoise]\n hare = nums[nums[hare]]\n if tortoise == hare:\n break\nptr1 = nums[0]\nptr2 = tortoise\nwhile ptr1 != ptr2:\n ptr1 = nu... | <|body_start_0|>
dict = Counter(nums)
for key, value in dict.items():
if value > 1:
return key
<|end_body_0|>
<|body_start_1|>
tortoise = nums[0]
hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict = Counter(nums)
for key, va... | stack_v2_sparse_classes_36k_train_034466 | 1,088 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findDu... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
dict = Counter(nums)
for key, value in dict.items():
if value > 1:
return key
def findDuplicate2(self, nums):
""":type nums: List[int] :rtype: int"""
tortoi... | the_stack_v2_python_sparse | 287. Find the Duplicate Number/duplicate.py | Macielyoung/LeetCode | train | 1 | |
3d14c30c66305bf99117a896ed69b8d0cd701f4f | [
"signals = []\nfor candle in self.candles:\n candles_df = self.get_processed_df(candle.candles_df)\n last_row = candles_df.iloc[-1]\n sma_rsi_normalized = -1 * (last_row['RSI_21_SMA_10'].item() - 50) / 50\n bb_percentage_normalized = -1 * (last_row['BBP_21_2.0'].item() - 0.5) / 0.5\n signal_value = (... | <|body_start_0|>
signals = []
for candle in self.candles:
candles_df = self.get_processed_df(candle.candles_df)
last_row = candles_df.iloc[-1]
sma_rsi_normalized = -1 * (last_row['RSI_21_SMA_10'].item() - 50) / 50
bb_percentage_normalized = -1 * (last_row[... | MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal value. It defines the specific parameters and conf... | MultiTimeframeBBRSI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiTimeframeBBRSI:
"""MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal val... | stack_v2_sparse_classes_36k_train_034467 | 5,708 | permissive | [
{
"docstring": "Generates the trading signal based on the composed signal value from multiple timeframes. Returns: int: The trading signal (-1 for sell, 0 for hold, 1 for buy).",
"name": "get_signal",
"signature": "def get_signal(self)"
},
{
"docstring": "Retrieves the processed dataframe with B... | 3 | null | Implement the Python class `MultiTimeframeBBRSI` described below.
Class description:
MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute ... | Implement the Python class `MultiTimeframeBBRSI` described below.
Class description:
MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute ... | c3f101759ab7e7a2165cd23a3a3e94c90c642a9b | <|skeleton|>
class MultiTimeframeBBRSI:
"""MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiTimeframeBBRSI:
"""MultiTimeframeBBRSI strategy implementation based on the DirectionalStrategyBase. This strategy combines multiple timeframes of Bollinger Bands (BB) and Relative Strength Index (RSI) indicators to generate trading signals and execute trades based on the composed signal value. It define... | the_stack_v2_python_sparse | scripts/directional_strategy_bb_rsi_multi_timeframe.py | CoinAlpha/hummingbot | train | 135 |
c965cb91f7b05716a5d80b4568d14490f75c0b48 | [
"try:\n logger.info('测试登录用户的信息是否正确')\n self.login()\n self.click(self.userbtn)\n self.assertEqual(self.gettext(self.user_name), 'admin')\n self.assertEqual(self.gettext(self.user_type), '管理员')\nexcept Exception as msg:\n logger.error(u'异常原因:%s' % msg)\n self.driver.get_screenshot_as_file(os.pat... | <|body_start_0|>
try:
logger.info('测试登录用户的信息是否正确')
self.login()
self.click(self.userbtn)
self.assertEqual(self.gettext(self.user_name), 'admin')
self.assertEqual(self.gettext(self.user_type), '管理员')
except Exception as msg:
logger.e... | 首页的相关测试 | ManageTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageTest:
"""首页的相关测试"""
def test1_check_user(self):
"""测试登录用户的信息是否正确"""
<|body_0|>
def test2_logout(self):
"""退出系统测试"""
<|body_1|>
def test5_interaction_constraints1(self):
"""在录制过程中限制进入互动模块的测试"""
<|body_2|>
def test6_interacti... | stack_v2_sparse_classes_36k_train_034468 | 4,309 | no_license | [
{
"docstring": "测试登录用户的信息是否正确",
"name": "test1_check_user",
"signature": "def test1_check_user(self)"
},
{
"docstring": "退出系统测试",
"name": "test2_logout",
"signature": "def test2_logout(self)"
},
{
"docstring": "在录制过程中限制进入互动模块的测试",
"name": "test5_interaction_constraints1",
... | 4 | stack_v2_sparse_classes_30k_train_008649 | Implement the Python class `ManageTest` described below.
Class description:
首页的相关测试
Method signatures and docstrings:
- def test1_check_user(self): 测试登录用户的信息是否正确
- def test2_logout(self): 退出系统测试
- def test5_interaction_constraints1(self): 在录制过程中限制进入互动模块的测试
- def test6_interaction_constraints2(self): 在直播过程中限制进入互动模块的测试 | Implement the Python class `ManageTest` described below.
Class description:
首页的相关测试
Method signatures and docstrings:
- def test1_check_user(self): 测试登录用户的信息是否正确
- def test2_logout(self): 退出系统测试
- def test5_interaction_constraints1(self): 在录制过程中限制进入互动模块的测试
- def test6_interaction_constraints2(self): 在直播过程中限制进入互动模块的测试... | fd552eeb47fd4838c2c5caef4deea7480ab75ce9 | <|skeleton|>
class ManageTest:
"""首页的相关测试"""
def test1_check_user(self):
"""测试登录用户的信息是否正确"""
<|body_0|>
def test2_logout(self):
"""退出系统测试"""
<|body_1|>
def test5_interaction_constraints1(self):
"""在录制过程中限制进入互动模块的测试"""
<|body_2|>
def test6_interacti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageTest:
"""首页的相关测试"""
def test1_check_user(self):
"""测试登录用户的信息是否正确"""
try:
logger.info('测试登录用户的信息是否正确')
self.login()
self.click(self.userbtn)
self.assertEqual(self.gettext(self.user_name), 'admin')
self.assertEqual(self.gette... | the_stack_v2_python_sparse | test_case/D001_manage_test.py | luhuifnag/AVA_UIauto_test | train | 0 |
d2dc697b39b91d66ff8468df872febc845ed19ad | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, **kwargs)\nself.bn = nn.BatchNorm2d(out_channels)\nself.relu = nn.ReLU(inplace=True)",
"x = self.conv(features)\nx = self.bn(x)\nx = self.relu(x)\nreturn... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, **kwargs)
self.bn = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
<|end_body_0|>
... | BasicBlock2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock2D:
def __init__(self, in_channels, out_channels, **kwargs):
"""Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k_train_034469 | 1,038 | permissive | [
{
"docstring": "Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, **kwargs)"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_020740 | Implement the Python class `BasicBlock2D` described below.
Class description:
Implement the BasicBlock2D class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, **kwargs): Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of out... | Implement the Python class `BasicBlock2D` described below.
Class description:
Implement the BasicBlock2D class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, **kwargs): Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of out... | a904f61dffee3d4ba55fabbce7f4207a016fae0e | <|skeleton|>
class BasicBlock2D:
def __init__(self, in_channels, out_channels, **kwargs):
"""Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicBlock2D:
def __init__(self, in_channels, out_channels, **kwargs):
"""Initializes convolutional block Args: in_channels: int, Number of input channels out_channels: int, Number of output channels **kwargs: Dict, Extra arguments for nn.Conv2d"""
super().__init__()
self.in_channels =... | the_stack_v2_python_sparse | pcdet/models/model_utils/basic_block_2d.py | chenyilun95/DSGN2 | train | 65 | |
ee2c16e77bae27854b7f286bbcd6490cc65b4467 | [
"str_s = str_q[0:1]\nif str_s in CatConverter.mapper:\n str_q = str_q.replace(str_s, CatConverter.mapper[str_s])\nreturn str_q",
"if len(str_q) >= 3:\n str_s = str_q[0:2]\n if str_s in CatConverter.mapper.inv:\n str_q = str_q.replace(str_s, CatConverter.mapper.inv[str_s])\nreturn str_q",
"dict_q... | <|body_start_0|>
str_s = str_q[0:1]
if str_s in CatConverter.mapper:
str_q = str_q.replace(str_s, CatConverter.mapper[str_s])
return str_q
<|end_body_0|>
<|body_start_1|>
if len(str_q) >= 3:
str_s = str_q[0:2]
if str_s in CatConverter.mapper.inv:
... | Manages entries of .cat files | CatConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatConverter:
"""Manages entries of .cat files"""
def __decode_quant(str_q):
"""replace a -> -1, A -> 10, etc."""
<|body_0|>
def __encode_quant(str_q):
"""replace -1 -> a, 10 -> A, etc."""
<|body_1|>
def __read_quanta(str_quanta, int_fmt):
""... | stack_v2_sparse_classes_36k_train_034470 | 11,597 | no_license | [
{
"docstring": "replace a -> -1, A -> 10, etc.",
"name": "__decode_quant",
"signature": "def __decode_quant(str_q)"
},
{
"docstring": "replace -1 -> a, 10 -> A, etc.",
"name": "__encode_quant",
"signature": "def __encode_quant(str_q)"
},
{
"docstring": "convert quanta from .cat t... | 6 | stack_v2_sparse_classes_30k_test_000770 | Implement the Python class `CatConverter` described below.
Class description:
Manages entries of .cat files
Method signatures and docstrings:
- def __decode_quant(str_q): replace a -> -1, A -> 10, etc.
- def __encode_quant(str_q): replace -1 -> a, 10 -> A, etc.
- def __read_quanta(str_quanta, int_fmt): convert quanta... | Implement the Python class `CatConverter` described below.
Class description:
Manages entries of .cat files
Method signatures and docstrings:
- def __decode_quant(str_q): replace a -> -1, A -> 10, etc.
- def __encode_quant(str_q): replace -1 -> a, 10 -> A, etc.
- def __read_quanta(str_quanta, int_fmt): convert quanta... | 57bda76b211c8efd3bd24bd2895bd57ea855003e | <|skeleton|>
class CatConverter:
"""Manages entries of .cat files"""
def __decode_quant(str_q):
"""replace a -> -1, A -> 10, etc."""
<|body_0|>
def __encode_quant(str_q):
"""replace -1 -> a, 10 -> A, etc."""
<|body_1|>
def __read_quanta(str_quanta, int_fmt):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CatConverter:
"""Manages entries of .cat files"""
def __decode_quant(str_q):
"""replace a -> -1, A -> 10, etc."""
str_s = str_q[0:1]
if str_s in CatConverter.mapper:
str_q = str_q.replace(str_s, CatConverter.mapper[str_s])
return str_q
def __encode_quant(s... | the_stack_v2_python_sparse | pickett/converters.py | kiraboris/scanner | train | 0 |
12a7ec51b398f140b71eb5ca8a34aca67f02c0b4 | [
"self.n_states = n_states\nself.discount_factor = discount_factor\nself.conversation_metadata = conversation_metadata\nself.max_steps = max_steps\nself.eye_states = np.eye(self.n_states)",
"data_length = len(data)\nmax_steps = self.max_steps if data_length > self.max_steps else data_length\nmi = np.array([0 for n... | <|body_start_0|>
self.n_states = n_states
self.discount_factor = discount_factor
self.conversation_metadata = conversation_metadata
self.max_steps = max_steps
self.eye_states = np.eye(self.n_states)
<|end_body_0|>
<|body_start_1|>
data_length = len(data)
max_step... | FeatureExpectationExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExpectationExtractor:
def __init__(self, n_states: int, conversation_metadata: dict, max_steps: int=10000, discount_factor=0.95):
"""Will "play out" Markov chain / MDP to get feature expectations :param data: dict of conversation data :param n_states: number of possible states in ... | stack_v2_sparse_classes_36k_train_034471 | 2,670 | no_license | [
{
"docstring": "Will \"play out\" Markov chain / MDP to get feature expectations :param data: dict of conversation data :param n_states: number of possible states in the model :param conversation_metadata: metadata stating who is high and who is low :param max_steps: maximal amount of steps model will check or ... | 3 | stack_v2_sparse_classes_30k_train_000790 | Implement the Python class `FeatureExpectationExtractor` described below.
Class description:
Implement the FeatureExpectationExtractor class.
Method signatures and docstrings:
- def __init__(self, n_states: int, conversation_metadata: dict, max_steps: int=10000, discount_factor=0.95): Will "play out" Markov chain / M... | Implement the Python class `FeatureExpectationExtractor` described below.
Class description:
Implement the FeatureExpectationExtractor class.
Method signatures and docstrings:
- def __init__(self, n_states: int, conversation_metadata: dict, max_steps: int=10000, discount_factor=0.95): Will "play out" Markov chain / M... | 8e9748cdbdf6f0b2fad17e16e2d1092e6c822029 | <|skeleton|>
class FeatureExpectationExtractor:
def __init__(self, n_states: int, conversation_metadata: dict, max_steps: int=10000, discount_factor=0.95):
"""Will "play out" Markov chain / MDP to get feature expectations :param data: dict of conversation data :param n_states: number of possible states in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureExpectationExtractor:
def __init__(self, n_states: int, conversation_metadata: dict, max_steps: int=10000, discount_factor=0.95):
"""Will "play out" Markov chain / MDP to get feature expectations :param data: dict of conversation data :param n_states: number of possible states in the model :par... | the_stack_v2_python_sparse | src/inverse_reinforcement_learning/feature_expectations_extractor.py | bartekwojcik/DataPreprocessingMasters | train | 0 | |
cd7e4cee876a7990b6504f897ab59f87990538a5 | [
"super().__init__(name=name, description=description, file_origin=file_origin, **annotations)\nif channel_names is None:\n channel_names = np.array([], dtype='S')\nif channel_ids is None:\n channel_ids = np.array([], dtype='i')\nself.channel_names = np.array(channel_names)\nself.channel_ids = np.array(channel... | <|body_start_0|>
super().__init__(name=name, description=description, file_origin=file_origin, **annotations)
if channel_names is None:
channel_names = np.array([], dtype='S')
if channel_ids is None:
channel_ids = np.array([], dtype='i')
self.channel_names = np.ar... | A container for indexing/grouping data channels. This container has several purposes: * Grouping all :class:`AnalogSignal`\\s and :class:`IrregularlySampledSignal`\\s inside a :class:`Block` across :class:`Segment`\\s; * Indexing a subset of the channels within an :class:`AnalogSignal` and :class:`IrregularlySampledSig... | ChannelIndex | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelIndex:
"""A container for indexing/grouping data channels. This container has several purposes: * Grouping all :class:`AnalogSignal`\\s and :class:`IrregularlySampledSignal`\\s inside a :class:`Block` across :class:`Segment`\\s; * Indexing a subset of the channels within an :class:`AnalogS... | stack_v2_sparse_classes_36k_train_034472 | 8,869 | permissive | [
{
"docstring": "Initialize a new :class:`ChannelIndex` instance.",
"name": "__init__",
"signature": "def __init__(self, index, channel_names=None, channel_ids=None, name=None, description=None, file_origin=None, coordinates=None, **annotations)"
},
{
"docstring": "Get the item or slice :attr:`i`... | 2 | stack_v2_sparse_classes_30k_train_004653 | Implement the Python class `ChannelIndex` described below.
Class description:
A container for indexing/grouping data channels. This container has several purposes: * Grouping all :class:`AnalogSignal`\\s and :class:`IrregularlySampledSignal`\\s inside a :class:`Block` across :class:`Segment`\\s; * Indexing a subset of... | Implement the Python class `ChannelIndex` described below.
Class description:
A container for indexing/grouping data channels. This container has several purposes: * Grouping all :class:`AnalogSignal`\\s and :class:`IrregularlySampledSignal`\\s inside a :class:`Block` across :class:`Segment`\\s; * Indexing a subset of... | 7409f47b5debd4d2a75bbf0e77ac10562446c97a | <|skeleton|>
class ChannelIndex:
"""A container for indexing/grouping data channels. This container has several purposes: * Grouping all :class:`AnalogSignal`\\s and :class:`IrregularlySampledSignal`\\s inside a :class:`Block` across :class:`Segment`\\s; * Indexing a subset of the channels within an :class:`AnalogS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChannelIndex:
"""A container for indexing/grouping data channels. This container has several purposes: * Grouping all :class:`AnalogSignal`\\s and :class:`IrregularlySampledSignal`\\s inside a :class:`Block` across :class:`Segment`\\s; * Indexing a subset of the channels within an :class:`AnalogSignal` and :c... | the_stack_v2_python_sparse | neo/core/channelindex.py | deeptimittal12/python-neo | train | 1 |
1da137d60458ecfa4b85c5a2abb132204c701727 | [
"super(DisplaceAtoms, self).__init__(**kwargs)\nself.atoms = []\n' Atomic displacements. '",
"from ..crystal import Atom\nself.atoms.append(Atom(*args, **kwargs))\nreturn self",
"result = super(DisplaceAtoms, self).__repr__()\nindent = ' '.join(('' for i in xrange(result.find('('))))\nfor o in self.atoms:\n ... | <|body_start_0|>
super(DisplaceAtoms, self).__init__(**kwargs)
self.atoms = []
' Atomic displacements. '
<|end_body_0|>
<|body_start_1|>
from ..crystal import Atom
self.atoms.append(Atom(*args, **kwargs))
return self
<|end_body_1|>
<|body_start_2|>
result = supe... | Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The above creates a displacement operations f... | DisplaceAtoms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisplaceAtoms:
"""Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The ... | stack_v2_sparse_classes_36k_train_034473 | 24,102 | no_license | [
{
"docstring": "Creates a displacement field.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Adds a displacement to a given atom. At present, atom.type should be an index to an atom in the structure.",
"name": "add_atom",
"signature": "def add_atom(s... | 5 | null | Implement the Python class `DisplaceAtoms` described below.
Class description:
Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0... | Implement the Python class `DisplaceAtoms` described below.
Class description:
Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0... | 9c0ab667f94dc4629404a8ec99cbeaa323f0c8b3 | <|skeleton|>
class DisplaceAtoms:
"""Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DisplaceAtoms:
"""Displaces atoms. This keywords applies a displacement to a set of atoms, identified by their labels: >>> from pylada.dftcrystal import DisplaceAtoms >>> disp = DisplaceAtoms() \\ ... .add_atom(0, 0.01, 0.002, 1) \\ ... .add_atom(0, -0.01, 0.05, 5) >>> structure.append(disp) The above creates... | the_stack_v2_python_sparse | dftcrystal/geometry.py | Shibu778/LaDa | train | 0 |
2e7c9c6da54689d1f4eac4170df7df5feed3d4b1 | [
"query = request.GET.get('id', '')\nif query == '':\n return HttpResponseBadRequest('Bad request: No Id specified')\nevent = Event.get(query, DB)\nfor key in event.reported_by:\n if event.reported_by[key]['anonymous']:\n event.reported_by[key] = {'displayName': 'Anonymous', 'photoURL': 'https://crowdal... | <|body_start_0|>
query = request.GET.get('id', '')
if query == '':
return HttpResponseBadRequest('Bad request: No Id specified')
event = Event.get(query, DB)
for key in event.reported_by:
if event.reported_by[key]['anonymous']:
event.reported_by[ke... | API view class for events | EventView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventView:
"""API view class for events"""
def get(self, request):
"""Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contains the django request object] Returns: [HttpResponseBadReq... | stack_v2_sparse_classes_36k_train_034474 | 7,030 | no_license | [
{
"docstring": "Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contains the django request object] Returns: [HttpResponseBadRequest] -- [If event id is not given] [JsonResponse] -- [Containing the event data]"... | 2 | stack_v2_sparse_classes_30k_train_015799 | Implement the Python class `EventView` described below.
Class description:
API view class for events
Method signatures and docstrings:
- def get(self, request): Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contain... | Implement the Python class `EventView` described below.
Class description:
API view class for events
Method signatures and docstrings:
- def get(self, request): Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contain... | a55cb3595c975b61ea28aba4d06186828dde7daa | <|skeleton|>
class EventView:
"""API view class for events"""
def get(self, request):
"""Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contains the django request object] Returns: [HttpResponseBadReq... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventView:
"""API view class for events"""
def get(self, request):
"""Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contains the django request object] Returns: [HttpResponseBadRequest] -- [If ... | the_stack_v2_python_sparse | api/events/views.py | AOSSIE-Org/CrowdAlert-Web | train | 1 |
0bc299a6fbecb2b0478433fe30927c2aae2e6e86 | [
"self.df = df\nself.parsed_col = parsed_col\nself.feats_from_spacy_doc = feats_from_spacy_doc",
"category_col = 'Category'\nwhile category_col in self.df:\n category_col = 'Category_' + ''.join((np.random.choice(string.ascii_letters) for _ in range(5)))\nreturn CorpusFromParsedDocuments(self.df.assign(**{categ... | <|body_start_0|>
self.df = df
self.parsed_col = parsed_col
self.feats_from_spacy_doc = feats_from_spacy_doc
<|end_body_0|>
<|body_start_1|>
category_col = 'Category'
while category_col in self.df:
category_col = 'Category_' + ''.join((np.random.choice(string.ascii_le... | CorpusWithoutCategoriesFromParsedDocuments | [
"MIT",
"CC-BY-NC-SA-4.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorpusWithoutCategoriesFromParsedDocuments:
def __init__(self, df, parsed_col, feats_from_spacy_doc=FeatsFromSpacyDoc()):
"""Parameters ---------- df : pd.DataFrame contains category_col, and parse_col, were parsed col is entirely spacy docs parsed_col : str name of spacy parsed column i... | stack_v2_sparse_classes_36k_train_034475 | 1,276 | permissive | [
{
"docstring": "Parameters ---------- df : pd.DataFrame contains category_col, and parse_col, were parsed col is entirely spacy docs parsed_col : str name of spacy parsed column in convention_df feats_from_spacy_doc : FeatsFromSpacyDoc",
"name": "__init__",
"signature": "def __init__(self, df, parsed_co... | 2 | stack_v2_sparse_classes_30k_train_007388 | Implement the Python class `CorpusWithoutCategoriesFromParsedDocuments` described below.
Class description:
Implement the CorpusWithoutCategoriesFromParsedDocuments class.
Method signatures and docstrings:
- def __init__(self, df, parsed_col, feats_from_spacy_doc=FeatsFromSpacyDoc()): Parameters ---------- df : pd.Da... | Implement the Python class `CorpusWithoutCategoriesFromParsedDocuments` described below.
Class description:
Implement the CorpusWithoutCategoriesFromParsedDocuments class.
Method signatures and docstrings:
- def __init__(self, df, parsed_col, feats_from_spacy_doc=FeatsFromSpacyDoc()): Parameters ---------- df : pd.Da... | b41e3a875faf6dd886e49e524345202432db1b21 | <|skeleton|>
class CorpusWithoutCategoriesFromParsedDocuments:
def __init__(self, df, parsed_col, feats_from_spacy_doc=FeatsFromSpacyDoc()):
"""Parameters ---------- df : pd.DataFrame contains category_col, and parse_col, were parsed col is entirely spacy docs parsed_col : str name of spacy parsed column i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CorpusWithoutCategoriesFromParsedDocuments:
def __init__(self, df, parsed_col, feats_from_spacy_doc=FeatsFromSpacyDoc()):
"""Parameters ---------- df : pd.DataFrame contains category_col, and parse_col, were parsed col is entirely spacy docs parsed_col : str name of spacy parsed column in convention_d... | the_stack_v2_python_sparse | scattertext/CorpusWithoutCategoriesFromParsedDocuments.py | JasonKessler/scattertext | train | 2,187 | |
107c827bb61d2c09f7dafbb8f8e5937ba7f15c28 | [
"self.a = a\nself.b = b\nself.c = c\nself.d = d",
"s1 = data[:3]\ns2 = data[3:]\nreturn get_tree_length(self.a, self.b, self.c, self.d, s1, s2)",
"a = self.a\nb = self.b\nc = self.c\nd = self.d\ns1 = data[:3]\ns2 = data[3:]\ns1_gradient = normalized(s1 - a) + normalized(s1 - s2) + normalized(s1 - b)\ns2_gradien... | <|body_start_0|>
self.a = a
self.b = b
self.c = c
self.d = d
<|end_body_0|>
<|body_start_1|>
s1 = data[:3]
s2 = data[3:]
return get_tree_length(self.a, self.b, self.c, self.d, s1, s2)
<|end_body_1|>
<|body_start_2|>
a = self.a
b = self.b
... | Objective | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objective:
def __init__(self, a, b, c, d):
"""@param a: a tip on the left side of the steiner topology @param b: a tip on the left side of the steiner topology @param c: a tip on the right side of the steiner topology @param d: a tip on the right side of the steiner topology"""
<... | stack_v2_sparse_classes_36k_train_034476 | 5,603 | no_license | [
{
"docstring": "@param a: a tip on the left side of the steiner topology @param b: a tip on the left side of the steiner topology @param c: a tip on the right side of the steiner topology @param d: a tip on the right side of the steiner topology",
"name": "__init__",
"signature": "def __init__(self, a, ... | 3 | null | Implement the Python class `Objective` described below.
Class description:
Implement the Objective class.
Method signatures and docstrings:
- def __init__(self, a, b, c, d): @param a: a tip on the left side of the steiner topology @param b: a tip on the left side of the steiner topology @param c: a tip on the right s... | Implement the Python class `Objective` described below.
Class description:
Implement the Objective class.
Method signatures and docstrings:
- def __init__(self, a, b, c, d): @param a: a tip on the left side of the steiner topology @param b: a tip on the left side of the steiner topology @param c: a tip on the right s... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class Objective:
def __init__(self, a, b, c, d):
"""@param a: a tip on the left side of the steiner topology @param b: a tip on the left side of the steiner topology @param c: a tip on the right side of the steiner topology @param d: a tip on the right side of the steiner topology"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Objective:
def __init__(self, a, b, c, d):
"""@param a: a tip on the left side of the steiner topology @param b: a tip on the left side of the steiner topology @param c: a tip on the right side of the steiner topology @param d: a tip on the right side of the steiner topology"""
self.a = a
... | the_stack_v2_python_sparse | 20091021a.py | argriffing/xgcode | train | 1 | |
4a2451b6472d220d9c590f7ed3347f0091a2f559 | [
"if not root:\n return '#'\nvals = []\nqueue = collections.deque()\nqueue.append(root)\nvals.append(root.val)\nwhile queue:\n cur = queue.popleft()\n if cur.left:\n vals.append(cur.left.val)\n queue.append(cur.left)\n else:\n vals.append('#')\n if cur.right:\n vals.append(... | <|body_start_0|>
if not root:
return '#'
vals = []
queue = collections.deque()
queue.append(root)
vals.append(root.val)
while queue:
cur = queue.popleft()
if cur.left:
vals.append(cur.left.val)
queue.appe... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str beats 82.15%"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_034477 | 5,528 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str beats 82.15%",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "d... | 2 | null | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str beats 82.15%
- def deserialize(self, data): Decodes your encoded data to tree. :type da... | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str beats 82.15%
- def deserialize(self, data): Decodes your encoded data to tree. :type da... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str beats 82.15%"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str beats 82.15%"""
if not root:
return '#'
vals = []
queue = collections.deque()
queue.append(root)
vals.append(root.val)
while queue:
... | the_stack_v2_python_sparse | LeetCode/449_serialize_and_deserialize_bst.py | yao23/Machine_Learning_Playground | train | 12 | |
79bc9528800b8a2ace60e4eadc303367a3edbeff | [
"if model.has_built(obj):\n warnings.warn('Object %s has already been built.' % obj)\n return None\nfor obj_cls in type(obj).__mro__:\n if obj_cls in cls.builders:\n break\nelse:\n raise BuildError('Cannot build object of type %r' % type(obj).__name__)\nreturn cls.builders[obj_cls](model, obj, *a... | <|body_start_0|>
if model.has_built(obj):
warnings.warn('Object %s has already been built.' % obj)
return None
for obj_cls in type(obj).__mro__:
if obj_cls in cls.builders:
break
else:
raise BuildError('Cannot build object of type %... | Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule(model, my_rule, rule): ... registe... | Builder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
"""Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule... | stack_v2_sparse_classes_36k_train_034478 | 8,755 | no_license | [
{
"docstring": "Build ``obj`` into ``model``. This method looks up the appropriate build function for ``obj`` and calls it with the model and other arguments provided. Note that if a build function is not specified for a particular type (e.g., `.EnsembleArray`), the type's method resolution order will be examin... | 2 | stack_v2_sparse_classes_30k_train_015685 | Implement the Python class `Builder` described below.
Class description:
Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Bui... | Implement the Python class `Builder` described below.
Class description:
Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Bui... | ee72a44640cf81c56721f44fbad5b16e0643aa88 | <|skeleton|>
class Builder:
"""Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
"""Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule(model, my_ru... | the_stack_v2_python_sparse | gosmann_frontiers2017/optimized/builder/builder.py | ctn-archive/gosmann-frontiers2017 | train | 3 |
a0f494c2b48be27b09132b6613b7089bed6b4555 | [
"create_data = obj_in.dict()\ndb_obj = Message(**create_data)\ndb.add(db_obj)\ndb.commit()\nreturn db_obj",
"res = db.query(self.model).filter(Message.room_id == room_id).order_by(Message.timestamp.desc()).offset(skip).limit(limit).all()\nres.reverse()\nreturn res"
] | <|body_start_0|>
create_data = obj_in.dict()
db_obj = Message(**create_data)
db.add(db_obj)
db.commit()
return db_obj
<|end_body_0|>
<|body_start_1|>
res = db.query(self.model).filter(Message.room_id == room_id).order_by(Message.timestamp.desc()).offset(skip).limit(limit... | CRUDMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRUDMessage:
def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
"""Override base create function, so as to omit json encoder step"""
<|body_0|>
def get_multi_by_room(self, db: Session, *, room_id: int, skip: int=0, limit: int=100) -> List[Message]:
"... | stack_v2_sparse_classes_36k_train_034479 | 1,220 | no_license | [
{
"docstring": "Override base create function, so as to omit json encoder step",
"name": "create",
"signature": "def create(self, db: Session, *, obj_in: MessageCreate) -> Message"
},
{
"docstring": "Get messages for a given room. Messages are sorted in descending order, so that `limit` applies ... | 2 | stack_v2_sparse_classes_30k_train_003576 | Implement the Python class `CRUDMessage` described below.
Class description:
Implement the CRUDMessage class.
Method signatures and docstrings:
- def create(self, db: Session, *, obj_in: MessageCreate) -> Message: Override base create function, so as to omit json encoder step
- def get_multi_by_room(self, db: Session... | Implement the Python class `CRUDMessage` described below.
Class description:
Implement the CRUDMessage class.
Method signatures and docstrings:
- def create(self, db: Session, *, obj_in: MessageCreate) -> Message: Override base create function, so as to omit json encoder step
- def get_multi_by_room(self, db: Session... | d01eab579e33d2af6ab2c7d3a2587fab8b578ad1 | <|skeleton|>
class CRUDMessage:
def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
"""Override base create function, so as to omit json encoder step"""
<|body_0|>
def get_multi_by_room(self, db: Session, *, room_id: int, skip: int=0, limit: int=100) -> List[Message]:
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CRUDMessage:
def create(self, db: Session, *, obj_in: MessageCreate) -> Message:
"""Override base create function, so as to omit json encoder step"""
create_data = obj_in.dict()
db_obj = Message(**create_data)
db.add(db_obj)
db.commit()
return db_obj
def ge... | the_stack_v2_python_sparse | journeychat/crud/crud_message.py | dustinmichels/journeychat-backend | train | 0 | |
914af3d695eae3caca973ab151bb56569d8958a8 | [
"if len(nums) == 0:\n return 0\nif len(nums) == 1:\n return nums[0]\nif len(nums) == 2:\n return max(nums[0], nums[1])\na = self.simpleRob(nums[:-1])\nb = self.simpleRob(nums[1:])\nreturn max(a, b)",
"if len(nums) == 0:\n return 0\nincluded = nums[0]\nexcluded = 0\nfor i in range(1, len(nums)):\n t... | <|body_start_0|>
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
a = self.simpleRob(nums[:-1])
b = self.simpleRob(nums[1:])
return max(a, b)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def simpleRob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
return 0
if len(... | stack_v2_sparse_classes_36k_train_034480 | 1,074 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "simpleRob",
"signature": "def simpleRob(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019368 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def simpleRob(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def simpleRob(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | 1bd17e867d1d557a6ebbbd99f693d5fbd9f5b61e | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def simpleRob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
a = self.simpleRob(nums[:-1])
b = self.simple... | the_stack_v2_python_sparse | leetcode/213-house-robber-ii/main.py | shriharshs/AlgoDaily | train | 0 | |
1f04ce325fd89a54225483079179393d127d14cc | [
"self.type = type\nself.id = id\nself.token = token\nself.address = address\nself.expiration = expiration\nself.params = params\nself.resource_id = resource_id\nself.resource_uri = resource_uri",
"result = {'id': self.id, 'token': self.token, 'type': self.type, 'address': self.address}\nif self.params:\n resul... | <|body_start_0|>
self.type = type
self.id = id
self.token = token
self.address = address
self.expiration = expiration
self.params = params
self.resource_id = resource_id
self.resource_uri = resource_uri
<|end_body_0|>
<|body_start_1|>
result = {'i... | A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, A UUID for the channel. token: str, An arbitrary string associated with th... | Channel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Channel:
"""A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, A UUID for the channel. token: str, An ... | stack_v2_sparse_classes_36k_train_034481 | 10,067 | permissive | [
{
"docstring": "Create a new Channel. In user code, this Channel constructor will not typically be called manually since there are functions for creating channels for each specific type with a more customized set of arguments to pass. Args: type: str, The type of delivery mechanism used by this channel. For exa... | 3 | null | Implement the Python class `Channel` described below.
Class description:
A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, ... | Implement the Python class `Channel` described below.
Class description:
A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, ... | 975a95032ce5b7012d1772c7f1f5cfe606eae839 | <|skeleton|>
class Channel:
"""A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, A UUID for the channel. token: str, An ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Channel:
"""A Channel for notifications. Usually not constructed directly, instead it is returned from helper functions like new_webhook_channel(). Attributes: type: str, The type of delivery mechanism used by this channel. For example, 'web_hook'. id: str, A UUID for the channel. token: str, An arbitrary str... | the_stack_v2_python_sparse | courses/machine_learning/deepdive2/structured/labs/serving/application/lib/googleapiclient/channel.py | GoogleCloudPlatform/training-data-analyst | train | 7,311 |
1ad942e14fc35fc1fdb88bc36101297ef05d77a2 | [
"hints = driver_hints.Hints()\nif project_id:\n hints.add_filter('project_id', project_id)\nelse:\n hints.add_filter('domain_id', domain_id)\nhints.add_filter('service_id', service_id)\nhints.add_filter('resource_name', resource_name)\nhints.add_filter('region_id', region_id)\nlimits = PROVIDERS.unified_limit... | <|body_start_0|>
hints = driver_hints.Hints()
if project_id:
hints.add_filter('project_id', project_id)
else:
hints.add_filter('domain_id', domain_id)
hints.add_filter('service_id', service_id)
hints.add_filter('resource_name', resource_name)
hints... | StrictTwoLevelModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrictTwoLevelModel:
def _get_specified_limit_value(self, resource_name, service_id, region_id, project_id=None, domain_id=None):
"""Get the specified limit value. Try to give the resource limit first. If the specified limit is a domain limit and the resource limit value is None, get the... | stack_v2_sparse_classes_36k_train_034482 | 7,578 | permissive | [
{
"docstring": "Get the specified limit value. Try to give the resource limit first. If the specified limit is a domain limit and the resource limit value is None, get the related registered limit value instead.",
"name": "_get_specified_limit_value",
"signature": "def _get_specified_limit_value(self, r... | 3 | null | Implement the Python class `StrictTwoLevelModel` described below.
Class description:
Implement the StrictTwoLevelModel class.
Method signatures and docstrings:
- def _get_specified_limit_value(self, resource_name, service_id, region_id, project_id=None, domain_id=None): Get the specified limit value. Try to give the ... | Implement the Python class `StrictTwoLevelModel` described below.
Class description:
Implement the StrictTwoLevelModel class.
Method signatures and docstrings:
- def _get_specified_limit_value(self, resource_name, service_id, region_id, project_id=None, domain_id=None): Get the specified limit value. Try to give the ... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class StrictTwoLevelModel:
def _get_specified_limit_value(self, resource_name, service_id, region_id, project_id=None, domain_id=None):
"""Get the specified limit value. Try to give the resource limit first. If the specified limit is a domain limit and the resource limit value is None, get the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrictTwoLevelModel:
def _get_specified_limit_value(self, resource_name, service_id, region_id, project_id=None, domain_id=None):
"""Get the specified limit value. Try to give the resource limit first. If the specified limit is a domain limit and the resource limit value is None, get the related regis... | the_stack_v2_python_sparse | keystone/limit/models/strict_two_level.py | sapcc/keystone | train | 0 | |
0fb98998ddaeef5c4bbfdb856d3133c142f8a643 | [
"assert isinstance(request, HttpRequest)\nqapp_id = request.GET.get('qapp_id', None)\nqapp = Qapp.objects.get(id=qapp_id)\nsectiona = SectionA.objects.filter(qapp_id=qapp_id).first()\nselected_sectionb_types = sectiona.sectionb_type.all()\nedit_message = ''\nif not check_can_edit(qapp, request.user):\n edit_mess... | <|body_start_0|>
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_id)
sectiona = SectionA.objects.filter(qapp_id=qapp_id).first()
selected_sectionb_types = sectiona.sectionb_type.all()
edit_message = ''
... | Class for processing QAPP Section B information. | SectionBView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SectionBView:
"""Class for processing QAPP Section B information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section B."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request with a SectionB form fil... | stack_v2_sparse_classes_36k_train_034483 | 36,787 | no_license | [
{
"docstring": "Return the index page for QAPP Section B.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Process the post request with a SectionB form filled out.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `SectionBView` described below.
Class description:
Class for processing QAPP Section B information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section B.
- def post(self, request, *args, **kwargs): Process the post request wit... | Implement the Python class `SectionBView` described below.
Class description:
Class for processing QAPP Section B information.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the index page for QAPP Section B.
- def post(self, request, *args, **kwargs): Process the post request wit... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class SectionBView:
"""Class for processing QAPP Section B information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section B."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request with a SectionB form fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SectionBView:
"""Class for processing QAPP Section B information."""
def get(self, request, *args, **kwargs):
"""Return the index page for QAPP Section B."""
assert isinstance(request, HttpRequest)
qapp_id = request.GET.get('qapp_id', None)
qapp = Qapp.objects.get(id=qapp_... | the_stack_v2_python_sparse | DataSearch/qar5/views.py | USEPA/FoodWaste | train | 1 |
8be7b81dbbd117605c70d46cad6c744adbaf94d9 | [
"permission = super().has_change_permission(request, obj)\nif obj is not None:\n permission &= obj.owner == request.user or request.user.is_superuser\nreturn permission",
"permission = super().has_delete_permission(request, obj)\nif obj is not None:\n permission &= obj.owner == request.user or request.user.... | <|body_start_0|>
permission = super().has_change_permission(request, obj)
if obj is not None:
permission &= obj.owner == request.user or request.user.is_superuser
return permission
<|end_body_0|>
<|body_start_1|>
permission = super().has_delete_permission(request, obj)
... | DataSourceAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSourceAdmin:
def has_change_permission(self, request, obj=None) -> bool:
"""Does the user have permission to change this object?"""
<|body_0|>
def has_delete_permission(self, request, obj=None) -> bool:
"""Does the user have permission to delete this object?"""
... | stack_v2_sparse_classes_36k_train_034484 | 1,640 | permissive | [
{
"docstring": "Does the user have permission to change this object?",
"name": "has_change_permission",
"signature": "def has_change_permission(self, request, obj=None) -> bool"
},
{
"docstring": "Does the user have permission to delete this object?",
"name": "has_delete_permission",
"si... | 3 | null | Implement the Python class `DataSourceAdmin` described below.
Class description:
Implement the DataSourceAdmin class.
Method signatures and docstrings:
- def has_change_permission(self, request, obj=None) -> bool: Does the user have permission to change this object?
- def has_delete_permission(self, request, obj=None... | Implement the Python class `DataSourceAdmin` described below.
Class description:
Implement the DataSourceAdmin class.
Method signatures and docstrings:
- def has_change_permission(self, request, obj=None) -> bool: Does the user have permission to change this object?
- def has_delete_permission(self, request, obj=None... | 25a111ac7cf4b23fee50ad8eac6ea21564954859 | <|skeleton|>
class DataSourceAdmin:
def has_change_permission(self, request, obj=None) -> bool:
"""Does the user have permission to change this object?"""
<|body_0|>
def has_delete_permission(self, request, obj=None) -> bool:
"""Does the user have permission to delete this object?"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSourceAdmin:
def has_change_permission(self, request, obj=None) -> bool:
"""Does the user have permission to change this object?"""
permission = super().has_change_permission(request, obj)
if obj is not None:
permission &= obj.owner == request.user or request.user.is_su... | the_stack_v2_python_sparse | datasources/admin.py | PEDASI/PEDASI | train | 0 | |
bc573bbcfedf2e95ad4038a7799ec25146e5fbaf | [
"self._reqs = defaultdict(dict)\nfor t in partition_requests:\n self._reqs[t.topic_name][t.partition_id] = t.offsets_before",
"size = self.HEADER_LEN + 4 + 4\nfor topic, parts in iteritems(self._reqs):\n size += 2 + len(topic) + 4\n size += (4 + 8) * len(parts)\nreturn size",
"output = bytearray(len(se... | <|body_start_0|>
self._reqs = defaultdict(dict)
for t in partition_requests:
self._reqs[t.topic_name][t.partition_id] = t.offsets_before
<|end_body_0|>
<|body_start_1|>
size = self.HEADER_LEN + 4 + 4
for topic, parts in iteritems(self._reqs):
size += 2 + len(topi... | Specification:: ListOffsetRequest => ReplicaId [TopicName [Partition Time]] ReplicaId => int32 TopicName => string Partition => int32 Time => int64 | ListOffsetRequestV1 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListOffsetRequestV1:
"""Specification:: ListOffsetRequest => ReplicaId [TopicName [Partition Time]] ReplicaId => int32 TopicName => string Partition => int32 Time => int64"""
def __init__(self, partition_requests):
"""Create a new offset request"""
<|body_0|>
def __len__... | stack_v2_sparse_classes_36k_train_034485 | 7,022 | permissive | [
{
"docstring": "Create a new offset request",
"name": "__init__",
"signature": "def __init__(self, partition_requests)"
},
{
"docstring": "Length of the serialized message, in bytes",
"name": "__len__",
"signature": "def __len__(self)"
},
{
"docstring": "Serialize the message :re... | 3 | stack_v2_sparse_classes_30k_train_013464 | Implement the Python class `ListOffsetRequestV1` described below.
Class description:
Specification:: ListOffsetRequest => ReplicaId [TopicName [Partition Time]] ReplicaId => int32 TopicName => string Partition => int32 Time => int64
Method signatures and docstrings:
- def __init__(self, partition_requests): Create a ... | Implement the Python class `ListOffsetRequestV1` described below.
Class description:
Specification:: ListOffsetRequest => ReplicaId [TopicName [Partition Time]] ReplicaId => int32 TopicName => string Partition => int32 Time => int64
Method signatures and docstrings:
- def __init__(self, partition_requests): Create a ... | c7054bd05b127385b8c6f56a4e2241d92ff42ab4 | <|skeleton|>
class ListOffsetRequestV1:
"""Specification:: ListOffsetRequest => ReplicaId [TopicName [Partition Time]] ReplicaId => int32 TopicName => string Partition => int32 Time => int64"""
def __init__(self, partition_requests):
"""Create a new offset request"""
<|body_0|>
def __len__... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListOffsetRequestV1:
"""Specification:: ListOffsetRequest => ReplicaId [TopicName [Partition Time]] ReplicaId => int32 TopicName => string Partition => int32 Time => int64"""
def __init__(self, partition_requests):
"""Create a new offset request"""
self._reqs = defaultdict(dict)
f... | the_stack_v2_python_sparse | py_kafk/tar/pykafka-2.8.1-dev.1/pykafka/protocol/offset.py | liuansen/python-utils-class | train | 3 |
89bb95569b2c036cf44fa64b7ddcedfa740036f6 | [
"self.wave = wave\nself.flux = flux\nself.ivar = ivar\nself.mask = mask\nself.resolution_data = resolution_data\nself.fibermap = fibermap\nself.header = header\nself.meta = header\nself.scores = scores",
"if not isinstance(index, slice):\n index = np.atleast_1d(index)\nif self.scores is not None:\n scores =... | <|body_start_0|>
self.wave = wave
self.flux = flux
self.ivar = ivar
self.mask = mask
self.resolution_data = resolution_data
self.fibermap = fibermap
self.header = header
self.meta = header
self.scores = scores
<|end_body_0|>
<|body_start_1|>
... | Lightweight Frame object for regrouping This is intended for I/O without the overheads of float32 -> float64 conversion, correcting endianness, etc. | FrameLite | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrameLite:
"""Lightweight Frame object for regrouping This is intended for I/O without the overheads of float32 -> float64 conversion, correcting endianness, etc."""
def __init__(self, wave, flux, ivar, mask, resolution_data, fibermap, header, scores=None):
"""Create a new FrameLite ... | stack_v2_sparse_classes_36k_train_034486 | 28,251 | permissive | [
{
"docstring": "Create a new FrameLite object Args: wave: 1D array of wavlengths flux: 2D[nspec, nwave] fluxes ivar: 2D[nspec, nwave] inverse variances of flux mask: 2D[nspec, nwave] mask of flux; 0=good resolution_data 3D[nspec, ndiag, nwave] Resolution matrix diagonals fibermap: fibermap table header: FITS he... | 3 | stack_v2_sparse_classes_30k_train_019768 | Implement the Python class `FrameLite` described below.
Class description:
Lightweight Frame object for regrouping This is intended for I/O without the overheads of float32 -> float64 conversion, correcting endianness, etc.
Method signatures and docstrings:
- def __init__(self, wave, flux, ivar, mask, resolution_data... | Implement the Python class `FrameLite` described below.
Class description:
Lightweight Frame object for regrouping This is intended for I/O without the overheads of float32 -> float64 conversion, correcting endianness, etc.
Method signatures and docstrings:
- def __init__(self, wave, flux, ivar, mask, resolution_data... | d75d0540cd07df1bf46130338a33c2ced51fbead | <|skeleton|>
class FrameLite:
"""Lightweight Frame object for regrouping This is intended for I/O without the overheads of float32 -> float64 conversion, correcting endianness, etc."""
def __init__(self, wave, flux, ivar, mask, resolution_data, fibermap, header, scores=None):
"""Create a new FrameLite ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrameLite:
"""Lightweight Frame object for regrouping This is intended for I/O without the overheads of float32 -> float64 conversion, correcting endianness, etc."""
def __init__(self, wave, flux, ivar, mask, resolution_data, fibermap, header, scores=None):
"""Create a new FrameLite object Args: ... | the_stack_v2_python_sparse | py/desispec/pixgroup.py | desihub/desispec | train | 33 |
82bb39dbb7391161dd61f37312a2e56b4923b0f9 | [
"is_cloud_admin = self.helper.is_user_cloud_admin()\napps_user_is_admin_on = self.helper.get_owned_apps()\napp_name = self.request.get('appid')\nif not is_cloud_admin and app_name not in apps_user_is_admin_on:\n response = json.dumps({'error': True, 'message': 'Not authorized'})\n self.response.out.write(resp... | <|body_start_0|>
is_cloud_admin = self.helper.is_user_cloud_admin()
apps_user_is_admin_on = self.helper.get_owned_apps()
app_name = self.request.get('appid')
if not is_cloud_admin and app_name not in apps_user_is_admin_on:
response = json.dumps({'error': True, 'message': 'Not... | Class that returns datastore statistics in JSON such as the number of a certain entity kind and the amount of total bytes. | DatastoreStats | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatastoreStats:
"""Class that returns datastore statistics in JSON such as the number of a certain entity kind and the amount of total bytes."""
def get(self):
"""Handler for GET request for the datastore statistics. Returns: The JSON output for testing."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_034487 | 37,207 | permissive | [
{
"docstring": "Handler for GET request for the datastore statistics. Returns: The JSON output for testing.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Converts KindStat entities to a json string. Args: kind_entities: A list of stats.KindStat. Returns: A JSON string containi... | 2 | stack_v2_sparse_classes_30k_train_001757 | Implement the Python class `DatastoreStats` described below.
Class description:
Class that returns datastore statistics in JSON such as the number of a certain entity kind and the amount of total bytes.
Method signatures and docstrings:
- def get(self): Handler for GET request for the datastore statistics. Returns: T... | Implement the Python class `DatastoreStats` described below.
Class description:
Class that returns datastore statistics in JSON such as the number of a certain entity kind and the amount of total bytes.
Method signatures and docstrings:
- def get(self): Handler for GET request for the datastore statistics. Returns: T... | aa36e8dfaa295d53bec616ed07f91ec8c02fa4e1 | <|skeleton|>
class DatastoreStats:
"""Class that returns datastore statistics in JSON such as the number of a certain entity kind and the amount of total bytes."""
def get(self):
"""Handler for GET request for the datastore statistics. Returns: The JSON output for testing."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatastoreStats:
"""Class that returns datastore statistics in JSON such as the number of a certain entity kind and the amount of total bytes."""
def get(self):
"""Handler for GET request for the datastore statistics. Returns: The JSON output for testing."""
is_cloud_admin = self.helper.is... | the_stack_v2_python_sparse | AppDashboard/dashboard.py | shatterednirvana/appscale | train | 6 |
22e8fca9eb2d879568518a29ca2d88b53e5dc782 | [
"super(ContentMetadata, self).__init__(headers=headers, auth=auth)\nself.id = testXMLValue(elem.find(nspath_eval('wfs:Name', namespaces)))\nself.title = testXMLValue(elem.find(nspath_eval('wfs:Title', namespaces)))\nself.abstract = testXMLValue(elem.find(nspath_eval('wfs:Abstract', namespaces)))\nself.keywords = [f... | <|body_start_0|>
super(ContentMetadata, self).__init__(headers=headers, auth=auth)
self.id = testXMLValue(elem.find(nspath_eval('wfs:Name', namespaces)))
self.title = testXMLValue(elem.find(nspath_eval('wfs:Title', namespaces)))
self.abstract = testXMLValue(elem.find(nspath_eval('wfs:Abs... | Abstraction for WFS metadata. Implements IMetadata. | ContentMetadata | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentMetadata:
"""Abstraction for WFS metadata. Implements IMetadata."""
def __init__(self, elem, parse_remote_metadata=False, timeout=30, headers=None, auth=None):
"""."""
<|body_0|>
def parse_remote_metadata(self, timeout=30):
"""Parse remote metadata for Met... | stack_v2_sparse_classes_36k_train_034488 | 16,336 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, elem, parse_remote_metadata=False, timeout=30, headers=None, auth=None)"
},
{
"docstring": "Parse remote metadata for MetadataURL of format 'text/xml' and add it as metadataUrl['metadata']",
"name": "parse_remote_metada... | 2 | stack_v2_sparse_classes_30k_train_018672 | Implement the Python class `ContentMetadata` described below.
Class description:
Abstraction for WFS metadata. Implements IMetadata.
Method signatures and docstrings:
- def __init__(self, elem, parse_remote_metadata=False, timeout=30, headers=None, auth=None): .
- def parse_remote_metadata(self, timeout=30): Parse re... | Implement the Python class `ContentMetadata` described below.
Class description:
Abstraction for WFS metadata. Implements IMetadata.
Method signatures and docstrings:
- def __init__(self, elem, parse_remote_metadata=False, timeout=30, headers=None, auth=None): .
- def parse_remote_metadata(self, timeout=30): Parse re... | 94b68c3a497978404edf486140138e4b9e340aba | <|skeleton|>
class ContentMetadata:
"""Abstraction for WFS metadata. Implements IMetadata."""
def __init__(self, elem, parse_remote_metadata=False, timeout=30, headers=None, auth=None):
"""."""
<|body_0|>
def parse_remote_metadata(self, timeout=30):
"""Parse remote metadata for Met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContentMetadata:
"""Abstraction for WFS metadata. Implements IMetadata."""
def __init__(self, elem, parse_remote_metadata=False, timeout=30, headers=None, auth=None):
"""."""
super(ContentMetadata, self).__init__(headers=headers, auth=auth)
self.id = testXMLValue(elem.find(nspath_... | the_stack_v2_python_sparse | owslib/feature/wfs110.py | bird-house/OWSLib | train | 2 |
ea35685a504e74d994667b20fe9fd9fff5c30ce1 | [
"try:\n return self._client.roles().insert(customer=customer_id, body={'roleName': name, 'rolePrivileges': _ROLE_PRIVILEGES, 'roleDescription': _ROLE_DESCRIPTION, 'isSystemRole': False, 'isSuperAdminRole': False}).execute()\nexcept errors.HttpError as err:\n status = err.resp.status\n if status == http_sta... | <|body_start_0|>
try:
return self._client.roles().insert(customer=customer_id, body={'roleName': name, 'rolePrivileges': _ROLE_PRIVILEGES, 'roleDescription': _ROLE_DESCRIPTION, 'isSystemRole': False, 'isSuperAdminRole': False}).execute()
except errors.HttpError as err:
status = e... | Google Admin Directory API access. | DirectoryAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryAPI:
"""Google Admin Directory API access."""
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
"""Creates and inserts a new GSuite Admin Role. Args: name: str, the name of the new GSuite Admin Role. customer_id: str, the G Suite customer ID to insert the ro... | stack_v2_sparse_classes_36k_train_034489 | 6,478 | permissive | [
{
"docstring": "Creates and inserts a new GSuite Admin Role. Args: name: str, the name of the new GSuite Admin Role. customer_id: str, the G Suite customer ID to insert the role into. Returns: A dictionary object representing the new GSuite Admin Role. https://developers.google.com/admin-sdk/directory/v1/refere... | 2 | null | Implement the Python class `DirectoryAPI` described below.
Class description:
Google Admin Directory API access.
Method signatures and docstrings:
- def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'): Creates and inserts a new GSuite Admin Role. Args: name: str, the name of the new GSuite Admin Role. c... | Implement the Python class `DirectoryAPI` described below.
Class description:
Google Admin Directory API access.
Method signatures and docstrings:
- def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'): Creates and inserts a new GSuite Admin Role. Args: name: str, the name of the new GSuite Admin Role. c... | 91753e47aff26d78978ebe7aca70f4a7cbf6a3d4 | <|skeleton|>
class DirectoryAPI:
"""Google Admin Directory API access."""
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
"""Creates and inserts a new GSuite Admin Role. Args: name: str, the name of the new GSuite Admin Role. customer_id: str, the G Suite customer ID to insert the ro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectoryAPI:
"""Google Admin Directory API access."""
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
"""Creates and inserts a new GSuite Admin Role. Args: name: str, the name of the new GSuite Admin Role. customer_id: str, the G Suite customer ID to insert the role into. Retu... | the_stack_v2_python_sparse | loaner/deployments/lib/directory.py | ryangugcloudca/loaner | train | 0 |
469f78d625ccd566a6c66658c4edb7247a22eb5f | [
"if m != 2 or n != 2:\n raise ValueError('m must be 2 and n must be 2')\nsuper().__init__(m, n)",
"res = 0\nif i == 0:\n res = 10000.0 * x[0][0] * x[1][0] - 1\nelif i == 1:\n res = math.exp(-x[0][0]) + math.exp(-x[1][0]) - 1.0001\nreturn res",
"res = np.zeros((2, 1), dtype=np.float)\nif i == 0:\n re... | <|body_start_0|>
if m != 2 or n != 2:
raise ValueError('m must be 2 and n must be 2')
super().__init__(m, n)
<|end_body_0|>
<|body_start_1|>
res = 0
if i == 0:
res = 10000.0 * x[0][0] * x[1][0] - 1
elif i == 1:
res = math.exp(-x[0][0]) + math.... | PowellBadlyScaled | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PowellBadlyScaled:
def __init__(self, m=2, n=2):
""":param m: :param n:"""
<|body_0|>
def _r_i(self, x, i):
""":param x: :param i: :return:"""
<|body_1|>
def _dr_i(self, x, i):
""":param x: :param i: :return:"""
<|body_2|>
def _ddr_i... | stack_v2_sparse_classes_36k_train_034490 | 15,975 | permissive | [
{
"docstring": ":param m: :param n:",
"name": "__init__",
"signature": "def __init__(self, m=2, n=2)"
},
{
"docstring": ":param x: :param i: :return:",
"name": "_r_i",
"signature": "def _r_i(self, x, i)"
},
{
"docstring": ":param x: :param i: :return:",
"name": "_dr_i",
"... | 4 | stack_v2_sparse_classes_30k_train_005521 | Implement the Python class `PowellBadlyScaled` described below.
Class description:
Implement the PowellBadlyScaled class.
Method signatures and docstrings:
- def __init__(self, m=2, n=2): :param m: :param n:
- def _r_i(self, x, i): :param x: :param i: :return:
- def _dr_i(self, x, i): :param x: :param i: :return:
- d... | Implement the Python class `PowellBadlyScaled` described below.
Class description:
Implement the PowellBadlyScaled class.
Method signatures and docstrings:
- def __init__(self, m=2, n=2): :param m: :param n:
- def _r_i(self, x, i): :param x: :param i: :return:
- def _dr_i(self, x, i): :param x: :param i: :return:
- d... | d7786b7bd5f24af4ebb8fef43f63e7faa7d7569f | <|skeleton|>
class PowellBadlyScaled:
def __init__(self, m=2, n=2):
""":param m: :param n:"""
<|body_0|>
def _r_i(self, x, i):
""":param x: :param i: :return:"""
<|body_1|>
def _dr_i(self, x, i):
""":param x: :param i: :return:"""
<|body_2|>
def _ddr_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PowellBadlyScaled:
def __init__(self, m=2, n=2):
""":param m: :param n:"""
if m != 2 or n != 2:
raise ValueError('m must be 2 and n must be 2')
super().__init__(m, n)
def _r_i(self, x, i):
""":param x: :param i: :return:"""
res = 0
if i == 0:
... | the_stack_v2_python_sparse | testFunction.py | cxgoal-97/optimization | train | 9 | |
fbbb1b81165c35956eae0bcc8dd30ba008090e03 | [
"parser = ImageFile.Parser()\ntry:\n for chunk in tfile.chunks():\n parser.feed(chunk)\nexcept Exception as e:\n return (False, str(e))\nfinally:\n image = parser.close()\nreturn (True, image)",
"try:\n image = Image.open(tfile)\nexcept Exception as e:\n return (False, str(e))\nreturn (True,... | <|body_start_0|>
parser = ImageFile.Parser()
try:
for chunk in tfile.chunks():
parser.feed(chunk)
except Exception as e:
return (False, str(e))
finally:
image = parser.close()
return (True, image)
<|end_body_0|>
<|body_start_1|... | 该类提供一些常用的图片I/O操作方法,包括解析远程图片,打开或关闭本地图片等. | ImageIOTools | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageIOTools:
"""该类提供一些常用的图片I/O操作方法,包括解析远程图片,打开或关闭本地图片等."""
def parse(cls, tfile):
"""解析远程图片文件, 生成Image类型对象返回 params: file: 从request.FILES中获取的数据对象 returns: img: PIL Image Object"""
<|body_0|>
def open(cls, tfile):
"""通过指定的路径名和文件名打开文件系统内的图片 params: path: 文件所在的主目录 ... | stack_v2_sparse_classes_36k_train_034491 | 5,239 | no_license | [
{
"docstring": "解析远程图片文件, 生成Image类型对象返回 params: file: 从request.FILES中获取的数据对象 returns: img: PIL Image Object",
"name": "parse",
"signature": "def parse(cls, tfile)"
},
{
"docstring": "通过指定的路径名和文件名打开文件系统内的图片 params: path: 文件所在的主目录 filename:文件名 returns: img: PIL Image Object",
"name": "open",
... | 3 | stack_v2_sparse_classes_30k_train_018151 | Implement the Python class `ImageIOTools` described below.
Class description:
该类提供一些常用的图片I/O操作方法,包括解析远程图片,打开或关闭本地图片等.
Method signatures and docstrings:
- def parse(cls, tfile): 解析远程图片文件, 生成Image类型对象返回 params: file: 从request.FILES中获取的数据对象 returns: img: PIL Image Object
- def open(cls, tfile): 通过指定的路径名和文件名打开文件系统内的图片 pa... | Implement the Python class `ImageIOTools` described below.
Class description:
该类提供一些常用的图片I/O操作方法,包括解析远程图片,打开或关闭本地图片等.
Method signatures and docstrings:
- def parse(cls, tfile): 解析远程图片文件, 生成Image类型对象返回 params: file: 从request.FILES中获取的数据对象 returns: img: PIL Image Object
- def open(cls, tfile): 通过指定的路径名和文件名打开文件系统内的图片 pa... | 2386e0c28b4973f26e5b2513cee37f32b97f4ce6 | <|skeleton|>
class ImageIOTools:
"""该类提供一些常用的图片I/O操作方法,包括解析远程图片,打开或关闭本地图片等."""
def parse(cls, tfile):
"""解析远程图片文件, 生成Image类型对象返回 params: file: 从request.FILES中获取的数据对象 returns: img: PIL Image Object"""
<|body_0|>
def open(cls, tfile):
"""通过指定的路径名和文件名打开文件系统内的图片 params: path: 文件所在的主目录 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageIOTools:
"""该类提供一些常用的图片I/O操作方法,包括解析远程图片,打开或关闭本地图片等."""
def parse(cls, tfile):
"""解析远程图片文件, 生成Image类型对象返回 params: file: 从request.FILES中获取的数据对象 returns: img: PIL Image Object"""
parser = ImageFile.Parser()
try:
for chunk in tfile.chunks():
parser.fee... | the_stack_v2_python_sparse | tools/imageutils.py | kingzus/myweb | train | 0 |
bceefa6cd417ba55be1502cff3a23e6f78a7272f | [
"result = ''\nif pooltable in ['tp_threadpool', 'tp_threadpool_buffer_in', 'tp_threadpool_buffer_out']:\n sqlStr = \"\\nSELECT min(id) FROM %s WHERE component = :component AND\\nthread_pool_id = :thread_pool_id AND state='queued'\\n \" % pooltable\n result = self.execute(sqlStr, args)\nelse:\n sqlSt... | <|body_start_0|>
result = ''
if pooltable in ['tp_threadpool', 'tp_threadpool_buffer_in', 'tp_threadpool_buffer_out']:
sqlStr = "\nSELECT min(id) FROM %s WHERE component = :component AND\nthread_pool_id = :thread_pool_id AND state='queued'\n " % pooltable
result = self.exe... | _Queries_ This module implements the Oracle backend for the persistent threadpool. | Queries | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queries:
"""_Queries_ This module implements the Oracle backend for the persistent threadpool."""
def selectWork(self, args, pooltable='tp_threadpool'):
"""Select work that is not yet being processed."""
<|body_0|>
def updateWorkStatus(self, args, pooltable='tp_threadpoo... | stack_v2_sparse_classes_36k_train_034492 | 6,188 | permissive | [
{
"docstring": "Select work that is not yet being processed.",
"name": "selectWork",
"signature": "def selectWork(self, args, pooltable='tp_threadpool')"
},
{
"docstring": "Updates work status of work being processed.",
"name": "updateWorkStatus",
"signature": "def updateWorkStatus(self,... | 6 | stack_v2_sparse_classes_30k_train_016238 | Implement the Python class `Queries` described below.
Class description:
_Queries_ This module implements the Oracle backend for the persistent threadpool.
Method signatures and docstrings:
- def selectWork(self, args, pooltable='tp_threadpool'): Select work that is not yet being processed.
- def updateWorkStatus(sel... | Implement the Python class `Queries` described below.
Class description:
_Queries_ This module implements the Oracle backend for the persistent threadpool.
Method signatures and docstrings:
- def selectWork(self, args, pooltable='tp_threadpool'): Select work that is not yet being processed.
- def updateWorkStatus(sel... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class Queries:
"""_Queries_ This module implements the Oracle backend for the persistent threadpool."""
def selectWork(self, args, pooltable='tp_threadpool'):
"""Select work that is not yet being processed."""
<|body_0|>
def updateWorkStatus(self, args, pooltable='tp_threadpoo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queries:
"""_Queries_ This module implements the Oracle backend for the persistent threadpool."""
def selectWork(self, args, pooltable='tp_threadpool'):
"""Select work that is not yet being processed."""
result = ''
if pooltable in ['tp_threadpool', 'tp_threadpool_buffer_in', 'tp_... | the_stack_v2_python_sparse | src/python/WMCore/ThreadPool/Oracle/Queries.py | vkuznet/WMCore | train | 0 |
c01d79cb05b4f8c46a7f0024c397a22edf3aa765 | [
"lock = threading.Lock()\nthreads = []\nfor url in league_urls:\n t = threading.Thread(target=self.crawl_teams_per_league, args=(url, lock))\n t.start()\n threads.append(t)\nfor t in threads:\n t.join()\nreturn self.statistics['teams']",
"lock = threading.Lock()\nthreads = []\nfor url in league_result... | <|body_start_0|>
lock = threading.Lock()
threads = []
for url in league_urls:
t = threading.Thread(target=self.crawl_teams_per_league, args=(url, lock))
t.start()
threads.append(t)
for t in threads:
t.join()
return self.statistics['... | TODO: not using proper functions anymore TODO: document, fix bugs. TODO: Can be further improved by not blocking results / fixtures by eachother. | SRSCrawlerConcurrent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SRSCrawlerConcurrent:
"""TODO: not using proper functions anymore TODO: document, fix bugs. TODO: Can be further improved by not blocking results / fixtures by eachother."""
def crawl_teams(self, league_urls: List[str]):
"""TODO: write doc."""
<|body_0|>
def crawl_result... | stack_v2_sparse_classes_36k_train_034493 | 2,070 | no_license | [
{
"docstring": "TODO: write doc.",
"name": "crawl_teams",
"signature": "def crawl_teams(self, league_urls: List[str])"
},
{
"docstring": ":param league_results_urls: list of tuples [(league_shortcode, league_url), ..] :param deep_crawl: defaults to False. Set True to follow pagination :return: -... | 3 | stack_v2_sparse_classes_30k_train_009163 | Implement the Python class `SRSCrawlerConcurrent` described below.
Class description:
TODO: not using proper functions anymore TODO: document, fix bugs. TODO: Can be further improved by not blocking results / fixtures by eachother.
Method signatures and docstrings:
- def crawl_teams(self, league_urls: List[str]): TOD... | Implement the Python class `SRSCrawlerConcurrent` described below.
Class description:
TODO: not using proper functions anymore TODO: document, fix bugs. TODO: Can be further improved by not blocking results / fixtures by eachother.
Method signatures and docstrings:
- def crawl_teams(self, league_urls: List[str]): TOD... | 1aeb0ee82ba6052de9a0dee488393bcd79e7d98e | <|skeleton|>
class SRSCrawlerConcurrent:
"""TODO: not using proper functions anymore TODO: document, fix bugs. TODO: Can be further improved by not blocking results / fixtures by eachother."""
def crawl_teams(self, league_urls: List[str]):
"""TODO: write doc."""
<|body_0|>
def crawl_result... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SRSCrawlerConcurrent:
"""TODO: not using proper functions anymore TODO: document, fix bugs. TODO: Can be further improved by not blocking results / fixtures by eachother."""
def crawl_teams(self, league_urls: List[str]):
"""TODO: write doc."""
lock = threading.Lock()
threads = []
... | the_stack_v2_python_sparse | swissrugbystats/crawler/crawler/SRSCrawlerConcurrent.py | SwissRugbyStats/swissrugbystats_server | train | 0 |
6932fb4f94e7ff377c04f16b4c5410e511a1fde6 | [
"length = len(words)\nif length < 1:\n return 0\nmaxProduct = 0\nlstWord = []\nfor word in words:\n lstWord.append(set(word))\nfor i in xrange(length):\n for j in xrange(length):\n if i != j:\n if lstWord[i] & lstWord[j] == set([]):\n maxProduct = max(maxProduct, len(words[... | <|body_start_0|>
length = len(words)
if length < 1:
return 0
maxProduct = 0
lstWord = []
for word in words:
lstWord.append(set(word))
for i in xrange(length):
for j in xrange(length):
if i != j:
if ls... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def maxProduct2(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(words)
if length < 1:... | stack_v2_sparse_classes_36k_train_034494 | 2,119 | no_license | [
{
"docstring": ":type words: List[str] :rtype: int",
"name": "maxProduct",
"signature": "def maxProduct(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: int",
"name": "maxProduct2",
"signature": "def maxProduct2(self, words)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020611 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, words): :type words: List[str] :rtype: int
- def maxProduct2(self, words): :type words: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, words): :type words: List[str] :rtype: int
- def maxProduct2(self, words): :type words: List[str] :rtype: int
<|skeleton|>
class Solution:
def maxProdu... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def maxProduct2(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct(self, words):
""":type words: List[str] :rtype: int"""
length = len(words)
if length < 1:
return 0
maxProduct = 0
lstWord = []
for word in words:
lstWord.append(set(word))
for i in xrange(length):
... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00318.Maximum Product of Word Lengths.py | roger6blog/LeetCode | train | 0 | |
bb8d606dd6fab92e7a643bd2ffe8a380187e108f | [
"super().__init__(name=name)\nself._embed_dim = embed_dim\nself._num_layers = num_layers\nself._msg_hidden_size_factor = msg_hidden_size_factor\nself._use_layer_norm = use_layer_norm",
"nodes = hk.Linear(self._embed_dim)(graphs.nodes)\nedges = hk.Linear(self._embed_dim)(graphs.edges)\nnodes = hk.LayerNorm(axis=-1... | <|body_start_0|>
super().__init__(name=name)
self._embed_dim = embed_dim
self._num_layers = num_layers
self._msg_hidden_size_factor = msg_hidden_size_factor
self._use_layer_norm = use_layer_norm
<|end_body_0|>
<|body_start_1|>
nodes = hk.Linear(self._embed_dim)(graphs.no... | A single graph network for embedding graph data. | GraphEmbeddingModel | [
"Apache-2.0",
"CC-BY-SA-4.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphEmbeddingModel:
"""A single graph network for embedding graph data."""
def __init__(self, embed_dim: int, num_layers: int, msg_hidden_size_factor: int=2, use_layer_norm: bool=False, name: Optional[str]=None):
"""Constructor. Args: embed_dim: node embedding size. num_layers: numb... | stack_v2_sparse_classes_36k_train_034495 | 14,391 | permissive | [
{
"docstring": "Constructor. Args: embed_dim: node embedding size. num_layers: number of message passing layers to use. msg_hidden_size_factor: size of the message network hiddens as a factor of embed_dim. use_layer_norm: whether to apply layer norm on node updates. name: optional name for this module.",
"n... | 2 | null | Implement the Python class `GraphEmbeddingModel` described below.
Class description:
A single graph network for embedding graph data.
Method signatures and docstrings:
- def __init__(self, embed_dim: int, num_layers: int, msg_hidden_size_factor: int=2, use_layer_norm: bool=False, name: Optional[str]=None): Constructo... | Implement the Python class `GraphEmbeddingModel` described below.
Class description:
A single graph network for embedding graph data.
Method signatures and docstrings:
- def __init__(self, embed_dim: int, num_layers: int, msg_hidden_size_factor: int=2, use_layer_norm: bool=False, name: Optional[str]=None): Constructo... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class GraphEmbeddingModel:
"""A single graph network for embedding graph data."""
def __init__(self, embed_dim: int, num_layers: int, msg_hidden_size_factor: int=2, use_layer_norm: bool=False, name: Optional[str]=None):
"""Constructor. Args: embed_dim: node embedding size. num_layers: numb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphEmbeddingModel:
"""A single graph network for embedding graph data."""
def __init__(self, embed_dim: int, num_layers: int, msg_hidden_size_factor: int=2, use_layer_norm: bool=False, name: Optional[str]=None):
"""Constructor. Args: embed_dim: node embedding size. num_layers: number of message... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/model/embedding.py | sethuramanio/deepmind-research | train | 1 |
9d33930927138120c802e0913ce2cea7e8ed29d1 | [
"super().__init__()\nself.crop_scale = crop_scale\nassert isinstance(crop_scale, (list, tuple)) and len(crop_scale) == 2, crop_scale",
"assert isinstance(annotations, (list, tuple)), annotations\nassert all(('bbox' in x for x in annotations)), annotations\nassert all(('bbox_mode' in x for x in annotations)), anno... | <|body_start_0|>
super().__init__()
self.crop_scale = crop_scale
assert isinstance(crop_scale, (list, tuple)) and len(crop_scale) == 2, crop_scale
<|end_body_0|>
<|body_start_1|>
assert isinstance(annotations, (list, tuple)), annotations
assert all(('bbox' in x for x in annotati... | RandomInstanceCrop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomInstanceCrop:
def __init__(self, crop_scale=(0.8, 1.6)):
"""Generates a CropTransform centered around the instance. crop_scale: [low, high] relative crop scale around the instance, this determines how far to zoom in / out around the cropped instance"""
<|body_0|>
def g... | stack_v2_sparse_classes_36k_train_034496 | 8,917 | permissive | [
{
"docstring": "Generates a CropTransform centered around the instance. crop_scale: [low, high] relative crop scale around the instance, this determines how far to zoom in / out around the cropped instance",
"name": "__init__",
"signature": "def __init__(self, crop_scale=(0.8, 1.6))"
},
{
"docst... | 2 | null | Implement the Python class `RandomInstanceCrop` described below.
Class description:
Implement the RandomInstanceCrop class.
Method signatures and docstrings:
- def __init__(self, crop_scale=(0.8, 1.6)): Generates a CropTransform centered around the instance. crop_scale: [low, high] relative crop scale around the inst... | Implement the Python class `RandomInstanceCrop` described below.
Class description:
Implement the RandomInstanceCrop class.
Method signatures and docstrings:
- def __init__(self, crop_scale=(0.8, 1.6)): Generates a CropTransform centered around the instance. crop_scale: [low, high] relative crop scale around the inst... | 890e26619756579b1fe2e9dfde5194dded0228c9 | <|skeleton|>
class RandomInstanceCrop:
def __init__(self, crop_scale=(0.8, 1.6)):
"""Generates a CropTransform centered around the instance. crop_scale: [low, high] relative crop scale around the instance, this determines how far to zoom in / out around the cropped instance"""
<|body_0|>
def g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomInstanceCrop:
def __init__(self, crop_scale=(0.8, 1.6)):
"""Generates a CropTransform centered around the instance. crop_scale: [low, high] relative crop scale around the instance, this determines how far to zoom in / out around the cropped instance"""
super().__init__()
self.cro... | the_stack_v2_python_sparse | d2go/data/transforms/crop.py | Dinesh101041/d2go | train | 1 | |
6d630a1d642c165be92d9a1b29c563976f692ff1 | [
"gap3_session = self._check_valid()\nif not hasattr(self, '_gap_recfields'):\n s = str(gap3_session.eval('RecFields(%s)' % self._name))\n s = s.strip('[] ').replace('\\n', '')\n self._gap_recfields = [ss.strip('\" ') for ss in s.split(',')]\nreturn getattr(self, '_gap_recfields')",
"gap3_session = self._... | <|body_start_0|>
gap3_session = self._check_valid()
if not hasattr(self, '_gap_recfields'):
s = str(gap3_session.eval('RecFields(%s)' % self._name))
s = s.strip('[] ').replace('\n', '')
self._gap_recfields = [ss.strip('" ') for ss in s.split(',')]
return getat... | A GAP3 record .. NOTE:: This class should not be called directly, use GAP3Element instead. If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. AUTHORS: - Franco Saliola (Feb 2010) | GAP3Record | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAP3Record:
"""A GAP3 record .. NOTE:: This class should not be called directly, use GAP3Element instead. If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. AUTHORS: - Franco Saliola (Feb 2010)"""
def recfields(self):
"""Return a list o... | stack_v2_sparse_classes_36k_train_034497 | 34,820 | no_license | [
{
"docstring": "Return a list of the fields for the record. (Record fields are akin to object attributes in Sage.) OUTPUT: - list of strings - the field records EXAMPLES:: sage: S5 = gap3.SymmetricGroup(5) #optional - gap3 sage: S5.recfields() #optional - gap3 ['isDomain', 'isGroup', 'identity', 'generators', '... | 4 | null | Implement the Python class `GAP3Record` described below.
Class description:
A GAP3 record .. NOTE:: This class should not be called directly, use GAP3Element instead. If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. AUTHORS: - Franco Saliola (Feb 2010)
Method signatur... | Implement the Python class `GAP3Record` described below.
Class description:
A GAP3 record .. NOTE:: This class should not be called directly, use GAP3Element instead. If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. AUTHORS: - Franco Saliola (Feb 2010)
Method signatur... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class GAP3Record:
"""A GAP3 record .. NOTE:: This class should not be called directly, use GAP3Element instead. If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. AUTHORS: - Franco Saliola (Feb 2010)"""
def recfields(self):
"""Return a list o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GAP3Record:
"""A GAP3 record .. NOTE:: This class should not be called directly, use GAP3Element instead. If the corresponding GAP3 element is a GAP3 record, then the class is changed to a ``GAP3Record``. AUTHORS: - Franco Saliola (Feb 2010)"""
def recfields(self):
"""Return a list of the fields ... | the_stack_v2_python_sparse | sage/src/sage/interfaces/gap3.py | bopopescu/geosci | train | 0 |
b732ce91204b87f6eb432d8a58604f616ed58432 | [
"type_list = response.xpath('//nav[@class=\"nav area\"]//ul/li/a/@href').extract()\ntype_name = response.xpath('//nav[@class=\"nav area\"]//ul/li/a//text()').extract()\nfor self.n in type_name:\n if os.path.exists('C:\\\\Users\\\\fugui\\\\PycharmProjects\\\\mode\\\\Souhu\\\\Souhu\\\\spiders\\\\搜狐新闻') == False:\n... | <|body_start_0|>
type_list = response.xpath('//nav[@class="nav area"]//ul/li/a/@href').extract()
type_name = response.xpath('//nav[@class="nav area"]//ul/li/a//text()').extract()
for self.n in type_name:
if os.path.exists('C:\\Users\\fugui\\PycharmProjects\\mode\\Souhu\\Souhu\\spider... | Souhu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Souhu:
def parse(self, response):
"""获取初始页上方类型连接"""
<|body_0|>
def parse_1(self, response):
"""获取文章详情URL,进行筛选"""
<|body_1|>
def parse_detail(self, response):
"""获取文章详情信息"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
type_list ... | stack_v2_sparse_classes_36k_train_034498 | 2,417 | no_license | [
{
"docstring": "获取初始页上方类型连接",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "获取文章详情URL,进行筛选",
"name": "parse_1",
"signature": "def parse_1(self, response)"
},
{
"docstring": "获取文章详情信息",
"name": "parse_detail",
"signature": "def parse_detail(s... | 3 | stack_v2_sparse_classes_30k_train_008071 | Implement the Python class `Souhu` described below.
Class description:
Implement the Souhu class.
Method signatures and docstrings:
- def parse(self, response): 获取初始页上方类型连接
- def parse_1(self, response): 获取文章详情URL,进行筛选
- def parse_detail(self, response): 获取文章详情信息 | Implement the Python class `Souhu` described below.
Class description:
Implement the Souhu class.
Method signatures and docstrings:
- def parse(self, response): 获取初始页上方类型连接
- def parse_1(self, response): 获取文章详情URL,进行筛选
- def parse_detail(self, response): 获取文章详情信息
<|skeleton|>
class Souhu:
def parse(self, respon... | e581563045bb6cb16f08ebd564ae6375eedc16e0 | <|skeleton|>
class Souhu:
def parse(self, response):
"""获取初始页上方类型连接"""
<|body_0|>
def parse_1(self, response):
"""获取文章详情URL,进行筛选"""
<|body_1|>
def parse_detail(self, response):
"""获取文章详情信息"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Souhu:
def parse(self, response):
"""获取初始页上方类型连接"""
type_list = response.xpath('//nav[@class="nav area"]//ul/li/a/@href').extract()
type_name = response.xpath('//nav[@class="nav area"]//ul/li/a//text()').extract()
for self.n in type_name:
if os.path.exists('C:\\User... | the_stack_v2_python_sparse | 爬虫/Scrapy/Souhu/Souhu/spiders/souhu.py | libangchui/pyhtonProject | train | 0 | |
308a833a127afb963eaabb3a02a92313c3e05106 | [
"docs = []\nfor i in range(len(inputs)):\n docs.append({'input': inputs[i], 'ground_truth': ground_truth_field[i], 'ground_truth_slots': ground_truth_slots[i], 'ground_truth_labels': ground_truth_labels[i], 'generated': generated_field[i], 'generated_slots': generated_slots[i], 'generated_labels': generated_labe... | <|body_start_0|>
docs = []
for i in range(len(inputs)):
docs.append({'input': inputs[i], 'ground_truth': ground_truth_field[i], 'ground_truth_slots': ground_truth_slots[i], 'ground_truth_labels': ground_truth_labels[i], 'generated': generated_field[i], 'generated_slots': generated_slots[i], ... | DialogueClassificationMetrics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogueClassificationMetrics:
def save_predictions(filename, generated_labels, generated_slots, ground_truth_labels, ground_truth_slots, generated_field, ground_truth_field, inputs):
"""Save predictions as a jsonl file Args: Each arg is a list of strings (all args have the same length)"... | stack_v2_sparse_classes_36k_train_034499 | 7,110 | permissive | [
{
"docstring": "Save predictions as a jsonl file Args: Each arg is a list of strings (all args have the same length)",
"name": "save_predictions",
"signature": "def save_predictions(filename, generated_labels, generated_slots, ground_truth_labels, ground_truth_slots, generated_field, ground_truth_field,... | 3 | stack_v2_sparse_classes_30k_train_009175 | Implement the Python class `DialogueClassificationMetrics` described below.
Class description:
Implement the DialogueClassificationMetrics class.
Method signatures and docstrings:
- def save_predictions(filename, generated_labels, generated_slots, ground_truth_labels, ground_truth_slots, generated_field, ground_truth... | Implement the Python class `DialogueClassificationMetrics` described below.
Class description:
Implement the DialogueClassificationMetrics class.
Method signatures and docstrings:
- def save_predictions(filename, generated_labels, generated_slots, ground_truth_labels, ground_truth_slots, generated_field, ground_truth... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class DialogueClassificationMetrics:
def save_predictions(filename, generated_labels, generated_slots, ground_truth_labels, ground_truth_slots, generated_field, ground_truth_field, inputs):
"""Save predictions as a jsonl file Args: Each arg is a list of strings (all args have the same length)"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DialogueClassificationMetrics:
def save_predictions(filename, generated_labels, generated_slots, ground_truth_labels, ground_truth_slots, generated_field, ground_truth_field, inputs):
"""Save predictions as a jsonl file Args: Each arg is a list of strings (all args have the same length)"""
doc... | the_stack_v2_python_sparse | nemo/collections/nlp/metrics/dialogue_metrics.py | NVIDIA/NeMo | train | 7,957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.