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
cb587ea5f14cc99afa4c13a7874e5650a86fb91c
[ "self.name = name\nself.concepts = concepts\nself.eggs = eggs", "conceptList = ConceptList(name=self.name, concepts=self.concepts.values(), isWords=any([len(egg.words) > 0 for egg in self.eggs]))\nserver.db.session.add(conceptList)\nserver.db.session.commit()" ]
<|body_start_0|> self.name = name self.concepts = concepts self.eggs = eggs <|end_body_0|> <|body_start_1|> conceptList = ConceptList(name=self.name, concepts=self.concepts.values(), isWords=any([len(egg.words) > 0 for egg in self.eggs])) server.db.session.add(conceptList) ...
Class to load a concept list into the database
ConceptListLoader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConceptListLoader: """Class to load a concept list into the database""" def __init__(self, name, eggs, concepts): """Initialize the Concept List""" <|body_0|> def load(self): """Load the Concept List into the database""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_006600
635
no_license
[ { "docstring": "Initialize the Concept List", "name": "__init__", "signature": "def __init__(self, name, eggs, concepts)" }, { "docstring": "Load the Concept List into the database", "name": "load", "signature": "def load(self)" } ]
2
stack_v2_sparse_classes_30k_val_001073
Implement the Python class `ConceptListLoader` described below. Class description: Class to load a concept list into the database Method signatures and docstrings: - def __init__(self, name, eggs, concepts): Initialize the Concept List - def load(self): Load the Concept List into the database
Implement the Python class `ConceptListLoader` described below. Class description: Class to load a concept list into the database Method signatures and docstrings: - def __init__(self, name, eggs, concepts): Initialize the Concept List - def load(self): Load the Concept List into the database <|skeleton|> class Conc...
f08dc4465b7e4fb32235e1647c46edd4472f9093
<|skeleton|> class ConceptListLoader: """Class to load a concept list into the database""" def __init__(self, name, eggs, concepts): """Initialize the Concept List""" <|body_0|> def load(self): """Load the Concept List into the database""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConceptListLoader: """Class to load a concept list into the database""" def __init__(self, name, eggs, concepts): """Initialize the Concept List""" self.name = name self.concepts = concepts self.eggs = eggs def load(self): """Load the Concept List into the dat...
the_stack_v2_python_sparse
src/Import/concept_list_loader.py
cloew/VocabTester
train
0
f24ac3e0fdb91b8a4ff34b3af8197c8e2ce210da
[ "total, n = (0, len(nums))\nfor currBit in range(31):\n currOnes = 0\n for num in nums:\n currOnes += num >> currBit & 1\n total += currOnes * (n - currOnes)\nreturn total", "total = 0\nfor b in zip(*map('{:030b}'.format, nums)):\n zeros = b.count('0')\n total += zeros * (len(b) - zeros)\nre...
<|body_start_0|> total, n = (0, len(nums)) for currBit in range(31): currOnes = 0 for num in nums: currOnes += num >> currBit & 1 total += currOnes * (n - currOnes) return total <|end_body_0|> <|body_start_1|> total = 0 for b i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def totalHammingDistance(self, nums: List[int]) -> int: """According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with th...
stack_v2_sparse_classes_36k_train_006601
1,729
no_license
[ { "docstring": "According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with that bit as 0, then they could form k * (n - k) pairs of difference for that bi...
2
stack_v2_sparse_classes_30k_train_010669
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def totalHammingDistance(self, nums: List[int]) -> int: According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for ea...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def totalHammingDistance(self, nums: List[int]) -> int: According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for ea...
edb870f83f0c4568cce0cacec04ee70cf6b545bf
<|skeleton|> class Solution: def totalHammingDistance(self, nums: List[int]) -> int: """According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def totalHammingDistance(self, nums: List[int]) -> int: """According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with that bit as 0, t...
the_stack_v2_python_sparse
2020/total_hamming_distance.py
eronekogin/leetcode
train
0
16a8c6bfb0d1cb58f70f1415d4760111ed9da2c6
[ "mediator = UnattendedVolumeScannerMediator()\ntype(mock_volumesystem.return_value).number_of_volumes = 1\nvolume_system = dfvfs_volume_system.VolumeSystem()\nvolume_identifiers = ['apfs1']\nresult = mediator.GetAPFSVolumeIdentifiers(volume_system, volume_identifiers)\nself.assertEqual(result, volume_identifiers)",...
<|body_start_0|> mediator = UnattendedVolumeScannerMediator() type(mock_volumesystem.return_value).number_of_volumes = 1 volume_system = dfvfs_volume_system.VolumeSystem() volume_identifiers = ['apfs1'] result = mediator.GetAPFSVolumeIdentifiers(volume_system, volume_identifiers)...
Test the UnattendedVolumeScannerMediator class.
TestUnattendedVolumeScannerMediator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestUnattendedVolumeScannerMediator: """Test the UnattendedVolumeScannerMediator class.""" def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): """Test the GetAPFSVolumeIdentifiers function.""" <|body_0|> def testGetPartitionIdentifiers(self, mock_volumesystem): ...
stack_v2_sparse_classes_36k_train_006602
3,628
permissive
[ { "docstring": "Test the GetAPFSVolumeIdentifiers function.", "name": "testGetAPFSVolumeIdentifiers", "signature": "def testGetAPFSVolumeIdentifiers(self, mock_volumesystem)" }, { "docstring": "Test the GetPartitionIdentifiers function.", "name": "testGetPartitionIdentifiers", "signature...
4
stack_v2_sparse_classes_30k_train_003981
Implement the Python class `TestUnattendedVolumeScannerMediator` described below. Class description: Test the UnattendedVolumeScannerMediator class. Method signatures and docstrings: - def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): Test the GetAPFSVolumeIdentifiers function. - def testGetPartitionIdentifi...
Implement the Python class `TestUnattendedVolumeScannerMediator` described below. Class description: Test the UnattendedVolumeScannerMediator class. Method signatures and docstrings: - def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): Test the GetAPFSVolumeIdentifiers function. - def testGetPartitionIdentifi...
e73717549c6919e869ce4963449c36f227e3ccd6
<|skeleton|> class TestUnattendedVolumeScannerMediator: """Test the UnattendedVolumeScannerMediator class.""" def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): """Test the GetAPFSVolumeIdentifiers function.""" <|body_0|> def testGetPartitionIdentifiers(self, mock_volumesystem): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestUnattendedVolumeScannerMediator: """Test the UnattendedVolumeScannerMediator class.""" def testGetAPFSVolumeIdentifiers(self, mock_volumesystem): """Test the GetAPFSVolumeIdentifiers function.""" mediator = UnattendedVolumeScannerMediator() type(mock_volumesystem.return_value)...
the_stack_v2_python_sparse
turbinia/lib/dfvfs_classes_test.py
Ash515/turbinia
train
6
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f
[ "self.num_events = num_events\nself.num_areaperils = num_areaperils\nself.areaperils_per_event = areaperils_per_event\nself.num_intensity_bins = num_intensity_bins\nself.intensity_sparseness = intensity_sparseness\nself.no_intensity_uncertainty = no_intensity_uncertainty\nself.random_seed = random_seed\nself.file_n...
<|body_start_0|> self.num_events = num_events self.num_areaperils = num_areaperils self.areaperils_per_event = areaperils_per_event self.num_intensity_bins = num_intensity_bins self.intensity_sparseness = intensity_sparseness self.no_intensity_uncertainty = no_intensity_u...
Generate data for Footprint binary dummy model file. This file shows the intensity of a given event-areaperil combination. The binary footprint file footprint.bin requires the index file footprint.idx. Attributes: generate_data: Generate Footprint binary dummy model file data.
FootprintBinFile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FootprintBinFile: """Generate data for Footprint binary dummy model file. This file shows the intensity of a given event-areaperil combination. The binary footprint file footprint.bin requires the index file footprint.idx. Attributes: generate_data: Generate Footprint binary dummy model file data...
stack_v2_sparse_classes_36k_train_006603
39,722
permissive
[ { "docstring": "Initialise Footprint binary file class. Args: num_events (int): number of events. num_areaperils (int): number of areaperils. areaperils_per_event (int): number of areaperils impacted per event. num_intensity_bins (int): number of intensity bins. intensity_sparseness (float): percentage of bins ...
2
null
Implement the Python class `FootprintBinFile` described below. Class description: Generate data for Footprint binary dummy model file. This file shows the intensity of a given event-areaperil combination. The binary footprint file footprint.bin requires the index file footprint.idx. Attributes: generate_data: Generate...
Implement the Python class `FootprintBinFile` described below. Class description: Generate data for Footprint binary dummy model file. This file shows the intensity of a given event-areaperil combination. The binary footprint file footprint.bin requires the index file footprint.idx. Attributes: generate_data: Generate...
23e704c335629ccd010969b1090446cfa3f384d5
<|skeleton|> class FootprintBinFile: """Generate data for Footprint binary dummy model file. This file shows the intensity of a given event-areaperil combination. The binary footprint file footprint.bin requires the index file footprint.idx. Attributes: generate_data: Generate Footprint binary dummy model file data...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FootprintBinFile: """Generate data for Footprint binary dummy model file. This file shows the intensity of a given event-areaperil combination. The binary footprint file footprint.bin requires the index file footprint.idx. Attributes: generate_data: Generate Footprint binary dummy model file data.""" def...
the_stack_v2_python_sparse
oasislmf/computation/data/dummy_model/generate.py
OasisLMF/OasisLMF
train
122
becb301e17fde3f889cf889c6031a79b1ceb2d58
[ "server_ips, client_pods, _, _ = deploy_test_pods\nfor client_pod in client_pods:\n for ip in server_ips:\n LOG.tc_step('Ping the server pod ip {} from the client pod {}'.format(ip, client_pod))\n cmd = 'ping -c 3 {} -w 5'.format(ip)\n code, _ = kube_helper.exec_cmd_in_container(cmd=cmd, pod...
<|body_start_0|> server_ips, client_pods, _, _ = deploy_test_pods for client_pod in client_pods: for ip in server_ips: LOG.tc_step('Ping the server pod ip {} from the client pod {}'.format(ip, client_pod)) cmd = 'ping -c 3 {} -w 5'.format(ip) c...
TestPodtoPod
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPodtoPod: def test_pod_to_pod_connection(self, deploy_test_pods): """Verify Ping test between pods Args: deploy_test_pods(fixture): returns server_ips, client_pods, deployment_name, service_name Setup: - Label the nodes and add node selector to the deployment files if not simplex sys...
stack_v2_sparse_classes_36k_train_006604
9,514
no_license
[ { "docstring": "Verify Ping test between pods Args: deploy_test_pods(fixture): returns server_ips, client_pods, deployment_name, service_name Setup: - Label the nodes and add node selector to the deployment files if not simplex system - Copy the deployment files from localhost to active controller - Deploy serv...
3
null
Implement the Python class `TestPodtoPod` described below. Class description: Implement the TestPodtoPod class. Method signatures and docstrings: - def test_pod_to_pod_connection(self, deploy_test_pods): Verify Ping test between pods Args: deploy_test_pods(fixture): returns server_ips, client_pods, deployment_name, s...
Implement the Python class `TestPodtoPod` described below. Class description: Implement the TestPodtoPod class. Method signatures and docstrings: - def test_pod_to_pod_connection(self, deploy_test_pods): Verify Ping test between pods Args: deploy_test_pods(fixture): returns server_ips, client_pods, deployment_name, s...
6843a76513e4130037f12b04f850b819aa2af721
<|skeleton|> class TestPodtoPod: def test_pod_to_pod_connection(self, deploy_test_pods): """Verify Ping test between pods Args: deploy_test_pods(fixture): returns server_ips, client_pods, deployment_name, service_name Setup: - Label the nodes and add node selector to the deployment files if not simplex sys...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPodtoPod: def test_pod_to_pod_connection(self, deploy_test_pods): """Verify Ping test between pods Args: deploy_test_pods(fixture): returns server_ips, client_pods, deployment_name, service_name Setup: - Label the nodes and add node selector to the deployment files if not simplex system - Copy the...
the_stack_v2_python_sparse
automated-pytest-suite/testcases/functional/networking/test_pod_to_pod.py
starlingx/test
train
1
c90806433dca4f0579db5cec168b757695ec854a
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PasswordCredentialConfiguration()", "from .app_credential_restriction_type import AppCredentialRestrictionType\nfrom .app_credential_restriction_type import AppCredentialRestrictionType\nfields: Dict[str, Callable[[Any], None]] = {'max...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return PasswordCredentialConfiguration() <|end_body_0|> <|body_start_1|> from .app_credential_restriction_type import AppCredentialRestrictionType from .app_credential_restriction_type import A...
PasswordCredentialConfiguration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordCredentialConfiguration: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PasswordCredentialConfiguration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator...
stack_v2_sparse_classes_36k_train_006605
3,919
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: PasswordCredentialConfiguration", "name": "create_from_discriminator_value", "signature": "def create_from_d...
3
null
Implement the Python class `PasswordCredentialConfiguration` described below. Class description: Implement the PasswordCredentialConfiguration class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PasswordCredentialConfiguration: Creates a new instance...
Implement the Python class `PasswordCredentialConfiguration` described below. Class description: Implement the PasswordCredentialConfiguration class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PasswordCredentialConfiguration: Creates a new instance...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class PasswordCredentialConfiguration: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PasswordCredentialConfiguration: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PasswordCredentialConfiguration: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PasswordCredentialConfiguration: """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 cre...
the_stack_v2_python_sparse
msgraph/generated/models/password_credential_configuration.py
microsoftgraph/msgraph-sdk-python
train
135
c1c7798872c8df1ac923dfa7d0743dc9640cb5b4
[ "super(MultiModalSerializer, self).__init__(content_type=content_type)\nself.parquet_serializer = ParquetSerializer()\nself.numpy_serializer = NumpySerializer()", "if isinstance(data, pd.DataFrame):\n return self.parquet_serializer.serialize(data)\nif isinstance(data, np.ndarray):\n return self.numpy_serial...
<|body_start_0|> super(MultiModalSerializer, self).__init__(content_type=content_type) self.parquet_serializer = ParquetSerializer() self.numpy_serializer = NumpySerializer() <|end_body_0|> <|body_start_1|> if isinstance(data, pd.DataFrame): return self.parquet_serializer.se...
Serializer for multi-modal use case. When passed in a dataframe, the serializer will serialize the data to be parquet format. When passed in a numpy array, the serializer will serialize the data to be numpy format.
MultiModalSerializer
[ "Apache-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiModalSerializer: """Serializer for multi-modal use case. When passed in a dataframe, the serializer will serialize the data to be parquet format. When passed in a numpy array, the serializer will serialize the data to be numpy format.""" def __init__(self, content_type='application/x-pa...
stack_v2_sparse_classes_36k_train_006606
3,977
permissive
[ { "docstring": "Initialize a ``MultiModalSerializer`` instance. Args: content_type (str): The MIME type to signal to the inference endpoint when sending request data (default: \"application/x-parquet\"). To BE NOTICED, this content_type will not used by MultiModalSerializer as it doesn't support dynamic updatin...
2
null
Implement the Python class `MultiModalSerializer` described below. Class description: Serializer for multi-modal use case. When passed in a dataframe, the serializer will serialize the data to be parquet format. When passed in a numpy array, the serializer will serialize the data to be numpy format. Method signatures...
Implement the Python class `MultiModalSerializer` described below. Class description: Serializer for multi-modal use case. When passed in a dataframe, the serializer will serialize the data to be parquet format. When passed in a numpy array, the serializer will serialize the data to be numpy format. Method signatures...
43dae4b28531cde167598f104f582168b0a4141f
<|skeleton|> class MultiModalSerializer: """Serializer for multi-modal use case. When passed in a dataframe, the serializer will serialize the data to be parquet format. When passed in a numpy array, the serializer will serialize the data to be numpy format.""" def __init__(self, content_type='application/x-pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiModalSerializer: """Serializer for multi-modal use case. When passed in a dataframe, the serializer will serialize the data to be parquet format. When passed in a numpy array, the serializer will serialize the data to be numpy format.""" def __init__(self, content_type='application/x-parquet'): ...
the_stack_v2_python_sparse
advanced_functionality/autogluon-tabular-containers/serializers.py
aws/amazon-sagemaker-examples
train
4,797
fc199b93fc30a3e29c4ac2e0ddcd686242fd282b
[ "these_row_indices, these_column_indices = radar_utils.radar_sites_to_grid_points(grid_latitudes_deg_n=FIRST_GRID_LATITUDES_DEG_N, grid_longitudes_deg_e=FIRST_GRID_LONGITUDES_DEG_E)\nself.assertTrue(numpy.array_equal(these_row_indices, FIRST_ROW_INDICES))\nself.assertTrue(numpy.array_equal(these_column_indices, FIR...
<|body_start_0|> these_row_indices, these_column_indices = radar_utils.radar_sites_to_grid_points(grid_latitudes_deg_n=FIRST_GRID_LATITUDES_DEG_N, grid_longitudes_deg_e=FIRST_GRID_LONGITUDES_DEG_E) self.assertTrue(numpy.array_equal(these_row_indices, FIRST_ROW_INDICES)) self.assertTrue(numpy.arr...
Each method is a unit test for radar_utils.py.
RadarUtilsTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RadarUtilsTests: """Each method is a unit test for radar_utils.py.""" def test_radar_sites_to_grid_points_first(self): """Ensures correct output from radar_sites_to_grid_points. In this case, using first grid.""" <|body_0|> def test_radar_sites_to_grid_points_second(self...
stack_v2_sparse_classes_36k_train_006607
2,107
no_license
[ { "docstring": "Ensures correct output from radar_sites_to_grid_points. In this case, using first grid.", "name": "test_radar_sites_to_grid_points_first", "signature": "def test_radar_sites_to_grid_points_first(self)" }, { "docstring": "Ensures correct output from radar_sites_to_grid_points. In ...
2
null
Implement the Python class `RadarUtilsTests` described below. Class description: Each method is a unit test for radar_utils.py. Method signatures and docstrings: - def test_radar_sites_to_grid_points_first(self): Ensures correct output from radar_sites_to_grid_points. In this case, using first grid. - def test_radar_...
Implement the Python class `RadarUtilsTests` described below. Class description: Each method is a unit test for radar_utils.py. Method signatures and docstrings: - def test_radar_sites_to_grid_points_first(self): Ensures correct output from radar_sites_to_grid_points. In this case, using first grid. - def test_radar_...
cf5e9682bc3182305274132ae246bc72d994308f
<|skeleton|> class RadarUtilsTests: """Each method is a unit test for radar_utils.py.""" def test_radar_sites_to_grid_points_first(self): """Ensures correct output from radar_sites_to_grid_points. In this case, using first grid.""" <|body_0|> def test_radar_sites_to_grid_points_second(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RadarUtilsTests: """Each method is a unit test for radar_utils.py.""" def test_radar_sites_to_grid_points_first(self): """Ensures correct output from radar_sites_to_grid_points. In this case, using first grid.""" these_row_indices, these_column_indices = radar_utils.radar_sites_to_grid_po...
the_stack_v2_python_sparse
ml4convection/utils/radar_utils_test.py
thunderhoser/ml4convection
train
14
ba4dc2412b533cf212530b1270fac3ada2303f4b
[ "self.robot = hsrb_interface.Robot()\nself.rgbd_map = RGBD2Map()\nself.omni_base = self.robot.get('omni_base')\nself.whole_body = self.robot.get('whole_body')\nself.side = 'BOTTOM'\nself.cam = RGBD()\nself.com = COM()\nself.com.go_to_initial_state(self.whole_body)\nself.grasp_count = 0\nself.br = tf.TransformBroadc...
<|body_start_0|> self.robot = hsrb_interface.Robot() self.rgbd_map = RGBD2Map() self.omni_base = self.robot.get('omni_base') self.whole_body = self.robot.get('whole_body') self.side = 'BOTTOM' self.cam = RGBD() self.com = COM() self.com.go_to_initial_state...
CollectData
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CollectData: def __init__(self): """Class to run HSR lego task""" <|body_0|> def collect_data(self): """Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and try again. Delete any images saved after that, the run this "for ...
stack_v2_sparse_classes_36k_train_006608
5,598
no_license
[ { "docstring": "Class to run HSR lego task", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and try again. Delete any images saved after that, the run this \"for real\".", ...
2
stack_v2_sparse_classes_30k_train_014270
Implement the Python class `CollectData` described below. Class description: Implement the CollectData class. Method signatures and docstrings: - def __init__(self): Class to run HSR lego task - def collect_data(self): Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and t...
Implement the Python class `CollectData` described below. Class description: Implement the CollectData class. Method signatures and docstrings: - def __init__(self): Class to run HSR lego task - def collect_data(self): Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and t...
0f183702d6cfb56e3811a9acff92ce6d1829eaf8
<|skeleton|> class CollectData: def __init__(self): """Class to run HSR lego task""" <|body_0|> def collect_data(self): """Run this a few times to check that the rgb images are reasonable. If not, rearrange the setup and try again. Delete any images saved after that, the run this "for ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CollectData: def __init__(self): """Class to run HSR lego task""" self.robot = hsrb_interface.Robot() self.rgbd_map = RGBD2Map() self.omni_base = self.robot.get('omni_base') self.whole_body = self.robot.get('whole_body') self.side = 'BOTTOM' self.cam = R...
the_stack_v2_python_sparse
quick_img_collection/get_hsr_imgs.py
BerkeleyAutomation/siemens_challenge
train
6
0ada56b06e23165b3afebe63b76ab6dd310815ce
[ "if verbose:\n v = '-v'\nelse:\n v = ''\nif ignore_gsd:\n gsd = '--ignore-gsd'\nelse:\n gsd = ''\nif dtm:\n dem = '--dtm --dsm'\nelse:\n dem = ''\nif cutline:\n cl = ' --orthophoto-cutline '\nelse:\n cl = ''\nif log:\n if output_path == None:\n logpath = ' > ' + path_to_images + '/...
<|body_start_0|> if verbose: v = '-v' else: v = '' if ignore_gsd: gsd = '--ignore-gsd' else: gsd = '' if dtm: dem = '--dtm --dsm' else: dem = '' if cutline: cl = ' --orthophoto-cut...
ImageProcessing
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageProcessing: def ODM(path_to_images, verbose=True, ignore_gsd=True, dtm=True, texturing_data_term='area', texturing_nadir_weight=5, smrf_scalar=3, smrf_slope=0.15, smrf_threshold=0.2, resolution=5, cutline=True, log=True, output_path=None): """Python skin for ODM orthophoto creation....
stack_v2_sparse_classes_36k_train_006609
7,143
no_license
[ { "docstring": "Python skin for ODM orthophoto creation. Descriptions and more detail are found on ODM documentation pages at https://docs.opendronemap.org/arguments.html Parameters ---------- path_to_images : Path to ODM folder containing drone images. verbose : bool, optional Print additional messages to the ...
2
stack_v2_sparse_classes_30k_train_013670
Implement the Python class `ImageProcessing` described below. Class description: Implement the ImageProcessing class. Method signatures and docstrings: - def ODM(path_to_images, verbose=True, ignore_gsd=True, dtm=True, texturing_data_term='area', texturing_nadir_weight=5, smrf_scalar=3, smrf_slope=0.15, smrf_threshol...
Implement the Python class `ImageProcessing` described below. Class description: Implement the ImageProcessing class. Method signatures and docstrings: - def ODM(path_to_images, verbose=True, ignore_gsd=True, dtm=True, texturing_data_term='area', texturing_nadir_weight=5, smrf_scalar=3, smrf_slope=0.15, smrf_threshol...
c80f6f4ee16dc9e7eb257eb18afdea469d45410d
<|skeleton|> class ImageProcessing: def ODM(path_to_images, verbose=True, ignore_gsd=True, dtm=True, texturing_data_term='area', texturing_nadir_weight=5, smrf_scalar=3, smrf_slope=0.15, smrf_threshold=0.2, resolution=5, cutline=True, log=True, output_path=None): """Python skin for ODM orthophoto creation....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageProcessing: def ODM(path_to_images, verbose=True, ignore_gsd=True, dtm=True, texturing_data_term='area', texturing_nadir_weight=5, smrf_scalar=3, smrf_slope=0.15, smrf_threshold=0.2, resolution=5, cutline=True, log=True, output_path=None): """Python skin for ODM orthophoto creation. Descriptions ...
the_stack_v2_python_sparse
__RGB.py
t0m21/t0m21
train
0
283c6f90c1997c7114004350326be1de7b6141d9
[ "try:\n\n def generate(filters, vo):\n for rule in list_replication_rules(filters=filters, vo=vo):\n yield (dumps(rule, cls=APIEncoder) + '\\n')\n return try_stream(generate(filters=dict(request.args.items(multi=False)), vo=request.environ.get('vo')))\nexcept RuleNotFound as error:\n retu...
<|body_start_0|> try: def generate(filters, vo): for rule in list_replication_rules(filters=filters, vo=vo): yield (dumps(rule, cls=APIEncoder) + '\n') return try_stream(generate(filters=dict(request.args.items(multi=False)), vo=request.environ.get('v...
REST APIs for all rules.
AllRule
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllRule: """REST APIs for all rules.""" def get(self): """--- summary: Return all rules for a given account tags: - Rule responses: 200: description: OK content: application/json: schema: type: string 401: description: Invalid Auth Token 404: description: No rule found for the given ...
stack_v2_sparse_classes_36k_train_006610
31,808
permissive
[ { "docstring": "--- summary: Return all rules for a given account tags: - Rule responses: 200: description: OK content: application/json: schema: type: string 401: description: Invalid Auth Token 404: description: No rule found for the given id 406: description: Not Acceptable", "name": "get", "signatur...
2
null
Implement the Python class `AllRule` described below. Class description: REST APIs for all rules. Method signatures and docstrings: - def get(self): --- summary: Return all rules for a given account tags: - Rule responses: 200: description: OK content: application/json: schema: type: string 401: description: Invalid ...
Implement the Python class `AllRule` described below. Class description: REST APIs for all rules. Method signatures and docstrings: - def get(self): --- summary: Return all rules for a given account tags: - Rule responses: 200: description: OK content: application/json: schema: type: string 401: description: Invalid ...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class AllRule: """REST APIs for all rules.""" def get(self): """--- summary: Return all rules for a given account tags: - Rule responses: 200: description: OK content: application/json: schema: type: string 401: description: Invalid Auth Token 404: description: No rule found for the given ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllRule: """REST APIs for all rules.""" def get(self): """--- summary: Return all rules for a given account tags: - Rule responses: 200: description: OK content: application/json: schema: type: string 401: description: Invalid Auth Token 404: description: No rule found for the given id 406: descr...
the_stack_v2_python_sparse
lib/rucio/web/rest/flaskapi/v1/rules.py
rucio/rucio
train
232
e41166b3c962e369f1d4b50be2637ef4e63bb4e9
[ "files_l = []\nfor path, dirs, files in os.walk(startPath, topdown=True):\n level = path.replace(startPath, '').count(os.sep)\n indent = ' ' * 2 * level\n subindent = ' ' * 2 * (level + 1)\n for f in files:\n files_l.append(f)\n if not bSubTree:\n break\nreturn files_l", "lines_l = []...
<|body_start_0|> files_l = [] for path, dirs, files in os.walk(startPath, topdown=True): level = path.replace(startPath, '').count(os.sep) indent = ' ' * 2 * level subindent = ' ' * 2 * (level + 1) for f in files: files_l.append(f) ...
walkTrees
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class walkTrees: def listFiles(self, startPath, bSubTree=True): """Ref: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python :param startPath: :return:""" <|body_0|> def readLocalFile(self, filename): """Read a file in local FileSystem and re...
stack_v2_sparse_classes_36k_train_006611
5,258
no_license
[ { "docstring": "Ref: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python :param startPath: :return:", "name": "listFiles", "signature": "def listFiles(self, startPath, bSubTree=True)" }, { "docstring": "Read a file in local FileSystem and return its content as a l...
2
stack_v2_sparse_classes_30k_train_020244
Implement the Python class `walkTrees` described below. Class description: Implement the walkTrees class. Method signatures and docstrings: - def listFiles(self, startPath, bSubTree=True): Ref: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python :param startPath: :return: - def readLoc...
Implement the Python class `walkTrees` described below. Class description: Implement the walkTrees class. Method signatures and docstrings: - def listFiles(self, startPath, bSubTree=True): Ref: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python :param startPath: :return: - def readLoc...
77a568d90b23923c61956465b3e87771d31e70e7
<|skeleton|> class walkTrees: def listFiles(self, startPath, bSubTree=True): """Ref: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python :param startPath: :return:""" <|body_0|> def readLocalFile(self, filename): """Read a file in local FileSystem and re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class walkTrees: def listFiles(self, startPath, bSubTree=True): """Ref: https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python :param startPath: :return:""" files_l = [] for path, dirs, files in os.walk(startPath, topdown=True): level = path.replace(s...
the_stack_v2_python_sparse
python/libs_dev/Utils.py
Jeremy-Sung-Dev/staging
train
1
74b26613aa5e69863760bfda100f0ba2940b51c4
[ "super().__init__(**kwargs)\nself.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='LayerNorm')\nself.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)", "hidden_states, input_tensor = inputs\nhidden_states = self.dropout(hidden_states, training=training)\nhidden_stat...
<|body_start_0|> super().__init__(**kwargs) self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='LayerNorm') self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob) <|end_body_0|> <|body_start_1|> hidden_states, input_tensor = inputs ...
Output module.
TFFastSpeechOutput
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TFFastSpeechOutput: """Output module.""" def __init__(self, config, **kwargs): """Init variables.""" <|body_0|> def call(self, inputs, training=False): """Call logic.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super().__init__(**kwargs) ...
stack_v2_sparse_classes_36k_train_006612
17,606
permissive
[ { "docstring": "Init variables.", "name": "__init__", "signature": "def __init__(self, config, **kwargs)" }, { "docstring": "Call logic.", "name": "call", "signature": "def call(self, inputs, training=False)" } ]
2
null
Implement the Python class `TFFastSpeechOutput` described below. Class description: Output module. Method signatures and docstrings: - def __init__(self, config, **kwargs): Init variables. - def call(self, inputs, training=False): Call logic.
Implement the Python class `TFFastSpeechOutput` described below. Class description: Output module. Method signatures and docstrings: - def __init__(self, config, **kwargs): Init variables. - def call(self, inputs, training=False): Call logic. <|skeleton|> class TFFastSpeechOutput: """Output module.""" def _...
4343c409340c608a426cc6f0926fbe2c1661783e
<|skeleton|> class TFFastSpeechOutput: """Output module.""" def __init__(self, config, **kwargs): """Init variables.""" <|body_0|> def call(self, inputs, training=False): """Call logic.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TFFastSpeechOutput: """Output module.""" def __init__(self, config, **kwargs): """Init variables.""" super().__init__(**kwargs) self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name='LayerNorm') self.dropout = tf.keras.layers.Dropout(confi...
the_stack_v2_python_sparse
malaya_speech/train/model/fastspeech/model_aligner.py
Ariffleng/malaya-speech
train
0
a34aa0ac029e1e837a6825e5b278df8b62670135
[ "super().__init__(unique_id, model)\nself.pos = np.array(pos)\nself.speed = speed\nself.velocity = velocity\nself.vision = vision\nself.separation = separation\nself.cohere_factor = cohere\nself.separate_factor = separate", "cohere = np.zeros(2)\nif neighbors:\n for neighbor in neighbors:\n cohere += se...
<|body_start_0|> super().__init__(unique_id, model) self.pos = np.array(pos) self.speed = speed self.velocity = velocity self.vision = vision self.separation = separation self.cohere_factor = cohere self.separate_factor = separate <|end_body_0|> <|body_st...
A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other Boid.
Fish
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Fish: """A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance fr...
stack_v2_sparse_classes_36k_train_006613
6,233
no_license
[ { "docstring": "Create a new Boid (bird, fish) agent. Args: unique_id: Unique agent identifier. pos: Starting position speed: Distance to move per step. velocity: numpy vector for the Boid's direction of movement. vision: Radius to look around for nearby Boids. separation: Minimum distance to maintain from othe...
4
stack_v2_sparse_classes_30k_train_014646
Implement the Python class `Fish` described below. Class description: A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separati...
Implement the Python class `Fish` described below. Class description: A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separati...
18166af285d2a40f903bc178f5c37b7d758fb0bd
<|skeleton|> class Fish: """A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance fr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Fish: """A Boid-style agent. Boids have a vision that defines the radius in which they look for their neighbors to flock with. Their heading (a unit vector) and their interactions with their neighbors - cohering and avoiding - define their movement. Separation is their desired minimum distance from any other ...
the_stack_v2_python_sparse
alternative_models/shoal_model_noalign.py
sowasser/fish-shoaling-model
train
1
8aefad83a67c0968fd41023c71f4436442cd5671
[ "self.r = radius\nself.x = x_center\nself.y = y_center", "r = self.r * random.random() ** 0.5\na = random.random() * 360.0\nreturn [self.x + r * math.cos(a), self.y + r * math.sin(a)]\nr = float('inf')\nwhile r > self.r:\n dx = (random.random() * 2 - 1) * self.r\n dy = (random.random() * 2 - 1) * self.r\n ...
<|body_start_0|> self.r = radius self.x = x_center self.y = y_center <|end_body_0|> <|body_start_1|> r = self.r * random.random() ** 0.5 a = random.random() * 360.0 return [self.x + r * math.cos(a), self.y + r * math.sin(a)] r = float('inf') while r > sel...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def __init__(self, radius, x_center, y_center): """:type radius: float :type x_center: float :type y_center: float""" <|body_0|> def randPoint(self): """:rtype: List[float]""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.r = radius ...
stack_v2_sparse_classes_36k_train_006614
1,292
no_license
[ { "docstring": ":type radius: float :type x_center: float :type y_center: float", "name": "__init__", "signature": "def __init__(self, radius, x_center, y_center)" }, { "docstring": ":rtype: List[float]", "name": "randPoint", "signature": "def randPoint(self)" } ]
2
stack_v2_sparse_classes_30k_train_006021
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float - def randPoint(self): :rtype: List[float]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float - def randPoint(self): :rtype: List[float] <|skeleton|> class Sol...
36d7f9e967a62db77622e0888f61999d7f37579a
<|skeleton|> class Solution: def __init__(self, radius, x_center, y_center): """:type radius: float :type x_center: float :type y_center: float""" <|body_0|> def randPoint(self): """:rtype: List[float]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def __init__(self, radius, x_center, y_center): """:type radius: float :type x_center: float :type y_center: float""" self.r = radius self.x = x_center self.y = y_center def randPoint(self): """:rtype: List[float]""" r = self.r * random.random() *...
the_stack_v2_python_sparse
P0478.py
westgate458/LeetCode
train
0
143758b7a4c3091ebe280a532eb9e012acd08437
[ "super().__init__()\nself.extends: Sequence[Union[str, Dict[str, Any]]] = ''\nself.css: Optional[Union[Dict[str, Any], Combine]] = None", "new_obj = self.__class__(self)\nnew_obj.extends = extends\nnew_obj.css = css\nreturn new_obj" ]
<|body_start_0|> super().__init__() self.extends: Sequence[Union[str, Dict[str, Any]]] = '' self.css: Optional[Union[Dict[str, Any], Combine]] = None <|end_body_0|> <|body_start_1|> new_obj = self.__class__(self) new_obj.extends = extends new_obj.css = css return...
``Var`` that, when called, allows to extend a previously defined css dict. Attributes ---------- extends : Sequence[Union[str, Dict[str, Any]]] The list of css we extend. An extend can be the name of a previously defined "extend" (key starting with `%`) in the same css dict (same level or above), or directly a dict. Se...
Extend
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Extend: """``Var`` that, when called, allows to extend a previously defined css dict. Attributes ---------- extends : Sequence[Union[str, Dict[str, Any]]] The list of css we extend. An extend can be the name of a previously defined "extend" (key starting with `%`) in the same css dict (same level...
stack_v2_sparse_classes_36k_train_006615
44,402
permissive
[ { "docstring": "Init the var and its attributes. For the parameters, see ``str``.", "name": "__init__", "signature": "def __init__(self, _str_: str) -> None" }, { "docstring": "Allow to have a css key defined multiple times. Parameters ---------- extends : Tuple[Union[str, Dict[str, Any]]] The l...
2
stack_v2_sparse_classes_30k_train_008803
Implement the Python class `Extend` described below. Class description: ``Var`` that, when called, allows to extend a previously defined css dict. Attributes ---------- extends : Sequence[Union[str, Dict[str, Any]]] The list of css we extend. An extend can be the name of a previously defined "extend" (key starting wit...
Implement the Python class `Extend` described below. Class description: ``Var`` that, when called, allows to extend a previously defined css dict. Attributes ---------- extends : Sequence[Union[str, Dict[str, Any]]] The list of css we extend. An extend can be the name of a previously defined "extend" (key starting wit...
adeff652784f0d814835fd16a8cacab09f426922
<|skeleton|> class Extend: """``Var`` that, when called, allows to extend a previously defined css dict. Attributes ---------- extends : Sequence[Union[str, Dict[str, Any]]] The list of css we extend. An extend can be the name of a previously defined "extend" (key starting with `%`) in the same css dict (same level...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Extend: """``Var`` that, when called, allows to extend a previously defined css dict. Attributes ---------- extends : Sequence[Union[str, Dict[str, Any]]] The list of css we extend. An extend can be the name of a previously defined "extend" (key starting with `%`) in the same css dict (same level or above), o...
the_stack_v2_python_sparse
src/mixt/contrib/css/vars.py
twidi/mixt
train
37
536f92fbd41caf1fe602b81c53763013c7bb1888
[ "try:\n natController = NatController()\n json_data = json.loads(request.data.decode())\n natController.add_floating_ip(json_data)\n return Response(status=202)\nexcept Exception as err:\n return Response(json.dumps(str(err)), status=500, mimetype='application/json')", "try:\n natController = Na...
<|body_start_0|> try: natController = NatController() json_data = json.loads(request.data.decode()) natController.add_floating_ip(json_data) return Response(status=202) except Exception as err: return Response(json.dumps(str(err)), status=500, ...
Nat_FloatingIP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Nat_FloatingIP: def post(self): """Add a Floating IP""" <|body_0|> def get(self, id=None): """Get a Floating IP""" <|body_1|> def put(self, id): """Update a Floating IP""" <|body_2|> def delete(self, id): """Remove a Floating...
stack_v2_sparse_classes_36k_train_006616
7,153
no_license
[ { "docstring": "Add a Floating IP", "name": "post", "signature": "def post(self)" }, { "docstring": "Get a Floating IP", "name": "get", "signature": "def get(self, id=None)" }, { "docstring": "Update a Floating IP", "name": "put", "signature": "def put(self, id)" }, {...
4
stack_v2_sparse_classes_30k_train_006147
Implement the Python class `Nat_FloatingIP` described below. Class description: Implement the Nat_FloatingIP class. Method signatures and docstrings: - def post(self): Add a Floating IP - def get(self, id=None): Get a Floating IP - def put(self, id): Update a Floating IP - def delete(self, id): Remove a Floating IP
Implement the Python class `Nat_FloatingIP` described below. Class description: Implement the Nat_FloatingIP class. Method signatures and docstrings: - def post(self): Add a Floating IP - def get(self, id=None): Get a Floating IP - def put(self, id): Update a Floating IP - def delete(self, id): Remove a Floating IP ...
6070e3cb6bf957e04f5d8267db11f3296410e18e
<|skeleton|> class Nat_FloatingIP: def post(self): """Add a Floating IP""" <|body_0|> def get(self, id=None): """Get a Floating IP""" <|body_1|> def put(self, id): """Update a Floating IP""" <|body_2|> def delete(self, id): """Remove a Floating...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Nat_FloatingIP: def post(self): """Add a Floating IP""" try: natController = NatController() json_data = json.loads(request.data.decode()) natController.add_floating_ip(json_data) return Response(status=202) except Exception as err: ...
the_stack_v2_python_sparse
configuration-agent/nat/rest_api/resources/floating_ip.py
ReliableLion/frog4-configurable-vnf
train
0
6639980d40b86b4da55616ac2cf9b1c65fbc908e
[ "if sample_interval > window_interval:\n raise ValueError('expected the sample_interval, %r, to be less than or equal to the window_interval, %r' % (sample_interval, window_interval))\nif set((callable(x) for x in (add, remove, sample))) != set((True,)):\n raise TypeError('expected all of add, remove, and sam...
<|body_start_0|> if sample_interval > window_interval: raise ValueError('expected the sample_interval, %r, to be less than or equal to the window_interval, %r' % (sample_interval, window_interval)) if set((callable(x) for x in (add, remove, sample))) != set((True,)): raise TypeEr...
Sampling of user-maintained statistics using a sliding window of point process events. This object handles the timestamp bookkeeping and making of callbacks to support getting regular samples of statistics from point-process events using a sliding window. At construction the client specifies the numerical sampling inte...
PointProcessSamplingWindow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PointProcessSamplingWindow: """Sampling of user-maintained statistics using a sliding window of point process events. This object handles the timestamp bookkeeping and making of callbacks to support getting regular samples of statistics from point-process events using a sliding window. At constru...
stack_v2_sparse_classes_36k_train_006617
10,276
permissive
[ { "docstring": "The sample_interval and window_interval arguments are numerical specifiers for the sampling period and the length of the sliding event-window. Each of the add, remove, and sample callbacks must be callable. Both add() and remove() take two arguments, the timestamp for the event and the object th...
2
null
Implement the Python class `PointProcessSamplingWindow` described below. Class description: Sampling of user-maintained statistics using a sliding window of point process events. This object handles the timestamp bookkeeping and making of callbacks to support getting regular samples of statistics from point-process ev...
Implement the Python class `PointProcessSamplingWindow` described below. Class description: Sampling of user-maintained statistics using a sliding window of point process events. This object handles the timestamp bookkeeping and making of callbacks to support getting regular samples of statistics from point-process ev...
f270a1be86372b7044615e4fd82032029e123bc1
<|skeleton|> class PointProcessSamplingWindow: """Sampling of user-maintained statistics using a sliding window of point process events. This object handles the timestamp bookkeeping and making of callbacks to support getting regular samples of statistics from point-process events using a sliding window. At constru...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PointProcessSamplingWindow: """Sampling of user-maintained statistics using a sliding window of point process events. This object handles the timestamp bookkeeping and making of callbacks to support getting regular samples of statistics from point-process events using a sliding window. At construction the cli...
the_stack_v2_python_sparse
resources/Onyx-1.0.511/py/onyx/util/pointprocess.py
eternity668/speechAD
train
0
fd94796047c557b42d455180121d18b4c96ee72f
[ "ind = int(self.value) - 1\ncontent = self.context['content']\nsize = self.kwargs.get('size', False)\ncss_class = '{0}{1}'.format(' ' if 'class' in self.kwargs else '', self.kwargs.get('class', ''))\nimages = content.get_pictures()\nimage = images[ind] if 0 <= ind <= images.count() else None\nreturn {'image': image...
<|body_start_0|> ind = int(self.value) - 1 content = self.context['content'] size = self.kwargs.get('size', False) css_class = '{0}{1}'.format(' ' if 'class' in self.kwargs else '', self.kwargs.get('class', '')) images = content.get_pictures() image = images[ind] if 0 <= ...
Inline d'insertion d'images liées aux contenus Format : {{content_image index [css_class=name]}} Exemple : {{content_image 1 css_class="class1"}}
ContentPictureInline
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ContentPictureInline: """Inline d'insertion d'images liées aux contenus Format : {{content_image index [css_class=name]}} Exemple : {{content_image 1 css_class="class1"}}""" def get_context(self): """Renvoyer le contexte de rendu de l'inline""" <|body_0|> def get_templat...
stack_v2_sparse_classes_36k_train_006618
6,816
no_license
[ { "docstring": "Renvoyer le contexte de rendu de l'inline", "name": "get_context", "signature": "def get_context(self)" }, { "docstring": "Renvoyer le chemin du template", "name": "get_template_name", "signature": "def get_template_name(self)" } ]
2
stack_v2_sparse_classes_30k_train_012683
Implement the Python class `ContentPictureInline` described below. Class description: Inline d'insertion d'images liées aux contenus Format : {{content_image index [css_class=name]}} Exemple : {{content_image 1 css_class="class1"}} Method signatures and docstrings: - def get_context(self): Renvoyer le contexte de ren...
Implement the Python class `ContentPictureInline` described below. Class description: Inline d'insertion d'images liées aux contenus Format : {{content_image index [css_class=name]}} Exemple : {{content_image 1 css_class="class1"}} Method signatures and docstrings: - def get_context(self): Renvoyer le contexte de ren...
8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7
<|skeleton|> class ContentPictureInline: """Inline d'insertion d'images liées aux contenus Format : {{content_image index [css_class=name]}} Exemple : {{content_image 1 css_class="class1"}}""" def get_context(self): """Renvoyer le contexte de rendu de l'inline""" <|body_0|> def get_templat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ContentPictureInline: """Inline d'insertion d'images liées aux contenus Format : {{content_image index [css_class=name]}} Exemple : {{content_image 1 css_class="class1"}}""" def get_context(self): """Renvoyer le contexte de rendu de l'inline""" ind = int(self.value) - 1 content = ...
the_stack_v2_python_sparse
scoop/content/util/inlines.py
artscoop/scoop
train
0
c91bfc99e5f3aa1e16ecdc0fa9a5e04963829404
[ "fim = len(lista)\nfor i in range(fim - 1):\n posicao_minimo = i\n for j in range(i + 1, fim):\n if lista[j] < lista[posicao_minimo]:\n posicao_minimo = j\n lista[i], lista[posicao_minimo] = (lista[posicao_minimo], lista[i])", "fim = len(lista)\nfor i in range(fim - 1, 0, -1):\n for ...
<|body_start_0|> fim = len(lista) for i in range(fim - 1): posicao_minimo = i for j in range(i + 1, fim): if lista[j] < lista[posicao_minimo]: posicao_minimo = j lista[i], lista[posicao_minimo] = (lista[posicao_minimo], lista[i]) <|...
Ordenador
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ordenador: def selecao_direta(self, lista): """(self, list) --> list""" <|body_0|> def bolha(self, lista): """(self, list) --> list""" <|body_1|> def bolha_quick(self, lista): """(self, list) --> list""" <|body_2|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_006619
1,283
no_license
[ { "docstring": "(self, list) --> list", "name": "selecao_direta", "signature": "def selecao_direta(self, lista)" }, { "docstring": "(self, list) --> list", "name": "bolha", "signature": "def bolha(self, lista)" }, { "docstring": "(self, list) --> list", "name": "bolha_quick",...
3
stack_v2_sparse_classes_30k_train_004649
Implement the Python class `Ordenador` described below. Class description: Implement the Ordenador class. Method signatures and docstrings: - def selecao_direta(self, lista): (self, list) --> list - def bolha(self, lista): (self, list) --> list - def bolha_quick(self, lista): (self, list) --> list
Implement the Python class `Ordenador` described below. Class description: Implement the Ordenador class. Method signatures and docstrings: - def selecao_direta(self, lista): (self, list) --> list - def bolha(self, lista): (self, list) --> list - def bolha_quick(self, lista): (self, list) --> list <|skeleton|> class...
628383080fd44606c7ab1927b3dc3062b47c0c88
<|skeleton|> class Ordenador: def selecao_direta(self, lista): """(self, list) --> list""" <|body_0|> def bolha(self, lista): """(self, list) --> list""" <|body_1|> def bolha_quick(self, lista): """(self, list) --> list""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Ordenador: def selecao_direta(self, lista): """(self, list) --> list""" fim = len(lista) for i in range(fim - 1): posicao_minimo = i for j in range(i + 1, fim): if lista[j] < lista[posicao_minimo]: posicao_minimo = j ...
the_stack_v2_python_sparse
icc_pt2/week5/ordenadores.py
roque-brito/ICC-USP-Coursera
train
1
54a389c1eaf26bd058b12065b8975fc1cef6ea02
[ "super(DiceLoss, self).__init__()\nself.alpha = alpha\nself.gamma = gamma\nself.reduction = reduction", "prob = torch.softmax(output, dim=1)\nprob = torch.gather(prob, dim=1, index=target.unsqueeze(1)).squeeze(1)\nprob_with_factor = (1 - prob) ** self.alpha * prob\nloss = 1 - (2 * prob_with_factor + self.gamma) /...
<|body_start_0|> super(DiceLoss, self).__init__() self.alpha = alpha self.gamma = gamma self.reduction = reduction <|end_body_0|> <|body_start_1|> prob = torch.softmax(output, dim=1) prob = torch.gather(prob, dim=1, index=target.unsqueeze(1)).squeeze(1) prob_with...
DiceLoss implemented from 'Dice Loss for Data-imbalanced NLP Tasks' Useful in dealing with unbalanced data
DiceLoss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiceLoss: """DiceLoss implemented from 'Dice Loss for Data-imbalanced NLP Tasks' Useful in dealing with unbalanced data""" def __init__(self, alpha=0.6, gamma=0.0, reduction='mean'): """Args: alpha (float, optional): focus parameter: power of (1-p), finetune range(0.1~0.9). Defaults ...
stack_v2_sparse_classes_36k_train_006620
1,899
permissive
[ { "docstring": "Args: alpha (float, optional): focus parameter: power of (1-p), finetune range(0.1~0.9). Defaults to 0.6. gamma ([type], optional): smoothing factor, allow to 0. Defaults to 0.. reduction (str, optional): reduction manner. Defaults to 'mean'.", "name": "__init__", "signature": "def __ini...
2
stack_v2_sparse_classes_30k_val_000340
Implement the Python class `DiceLoss` described below. Class description: DiceLoss implemented from 'Dice Loss for Data-imbalanced NLP Tasks' Useful in dealing with unbalanced data Method signatures and docstrings: - def __init__(self, alpha=0.6, gamma=0.0, reduction='mean'): Args: alpha (float, optional): focus para...
Implement the Python class `DiceLoss` described below. Class description: DiceLoss implemented from 'Dice Loss for Data-imbalanced NLP Tasks' Useful in dealing with unbalanced data Method signatures and docstrings: - def __init__(self, alpha=0.6, gamma=0.0, reduction='mean'): Args: alpha (float, optional): focus para...
b4c049fd30db39b67984edfadc49b4354d52be83
<|skeleton|> class DiceLoss: """DiceLoss implemented from 'Dice Loss for Data-imbalanced NLP Tasks' Useful in dealing with unbalanced data""" def __init__(self, alpha=0.6, gamma=0.0, reduction='mean'): """Args: alpha (float, optional): focus parameter: power of (1-p), finetune range(0.1~0.9). Defaults ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiceLoss: """DiceLoss implemented from 'Dice Loss for Data-imbalanced NLP Tasks' Useful in dealing with unbalanced data""" def __init__(self, alpha=0.6, gamma=0.0, reduction='mean'): """Args: alpha (float, optional): focus parameter: power of (1-p), finetune range(0.1~0.9). Defaults to 0.6. gamma...
the_stack_v2_python_sparse
pasaie/losses/dice_loss.py
tracy-talent/AIPolicy
train
0
acbc10c8a9b1d7b93ed2bafad43ded7eab2257cd
[ "stk, ans = ([root], [])\nwhile stk:\n node = stk.pop()\n if node:\n ans.append(str(node.val))\n stk.append(node.right)\n stk.append(node.left)\n else:\n ans.append('#')\nreturn ' '.join(ans)", "vals = data.split()\ni, n = (-1, len(vals))\n\ndef recurse():\n nonlocal i\n ...
<|body_start_0|> stk, ans = ([root], []) while stk: node = stk.pop() if node: ans.append(str(node.val)) stk.append(node.right) stk.append(node.left) else: ans.append('#') return ' '.join(ans) <|en...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_006621
1,351
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
12f62a218e827e6be2578b206dee9ce256da8d3d
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" stk, ans = ([root], []) while stk: node = stk.pop() if node: ans.append(str(node.val)) stk.append(node.right) ...
the_stack_v2_python_sparse
Python3/0297_Serialize_And_Deserialize_Binary_Tree.py
kiranani/playground
train
0
0e36dc62490d5b419fe7adde8c849a6fd7fbe2d7
[ "myThread = threading.currentThread()\ndaoFactory = DAOFactory(package='WMCore.WMBS', logger=myThread.logger, dbinterface=myThread.dbi)\nstateDAO = daoFactory(classname='Jobs.NewestStateChangeForSub')\nresults = stateDAO.execute(subscription=self.subscription['id'])\nif len(results) > 0:\n for result in results:...
<|body_start_0|> myThread = threading.currentThread() daoFactory = DAOFactory(package='WMCore.WMBS', logger=myThread.logger, dbinterface=myThread.dbi) stateDAO = daoFactory(classname='Jobs.NewestStateChangeForSub') results = stateDAO.execute(subscription=self.subscription['id']) ...
_Periodic_ Periodically create jobs to process all files in a fileset. A job will not be created until the previous job has been completed and new data has arrived. Note that the period here refers to the amount of time between the end of a job and the creation of a new job.
Periodic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Periodic: """_Periodic_ Periodically create jobs to process all files in a fileset. A job will not be created until the previous job has been completed and new data has arrived. Note that the period here refers to the amount of time between the end of a job and the creation of a new job.""" ...
stack_v2_sparse_classes_36k_train_006622
3,497
no_license
[ { "docstring": "_outstandingJobs_ Determine whether or not there are outstanding jobs and whether or not enough time has elapsed from the previous job to warrant creating a new job.", "name": "outstandingJobs", "signature": "def outstandingJobs(self, jobPeriod)" }, { "docstring": "_algorithm_ Pr...
2
stack_v2_sparse_classes_30k_train_013423
Implement the Python class `Periodic` described below. Class description: _Periodic_ Periodically create jobs to process all files in a fileset. A job will not be created until the previous job has been completed and new data has arrived. Note that the period here refers to the amount of time between the end of a job ...
Implement the Python class `Periodic` described below. Class description: _Periodic_ Periodically create jobs to process all files in a fileset. A job will not be created until the previous job has been completed and new data has arrived. Note that the period here refers to the amount of time between the end of a job ...
2b8fe0434d60542c5d5360cbe5e918ac5db98720
<|skeleton|> class Periodic: """_Periodic_ Periodically create jobs to process all files in a fileset. A job will not be created until the previous job has been completed and new data has arrived. Note that the period here refers to the amount of time between the end of a job and the creation of a new job.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Periodic: """_Periodic_ Periodically create jobs to process all files in a fileset. A job will not be created until the previous job has been completed and new data has arrived. Note that the period here refers to the amount of time between the end of a job and the creation of a new job.""" def outstandi...
the_stack_v2_python_sparse
src/python/WMCore/JobSplitting/Periodic.py
dmwm/WMCore-legacy
train
0
54e71937ce218b74e17bcc84e203b6a331299a29
[ "self.pad_indx = pad_indx\nself.max_length = max_length\nself.device = device", "inputs: List[torch.Tensor] = [b[0] for b in batch]\ntargets: List[torch.Tensor] = [b[1] for b in batch]\nlengths_inputs = torch.tensor([s.size(0) for s in inputs], device=self.device)\nlengths_targets = torch.tensor([s.size(0) for s ...
<|body_start_0|> self.pad_indx = pad_indx self.max_length = max_length self.device = device <|end_body_0|> <|body_start_1|> inputs: List[torch.Tensor] = [b[0] for b in batch] targets: List[torch.Tensor] = [b[1] for b in batch] lengths_inputs = torch.tensor([s.size(0) for...
Seq2SeqCollator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Seq2SeqCollator: def __init__(self, pad_indx=0, max_length=-1, device='cpu'): """Collate function for seq2seq tasks * Perform padding * Calculate sequence lengths Args: pad_indx (int): Pad token index. Defaults to 0. max_length (int): Pad sequences to a fixed maximum length device (str):...
stack_v2_sparse_classes_36k_train_006623
7,167
permissive
[ { "docstring": "Collate function for seq2seq tasks * Perform padding * Calculate sequence lengths Args: pad_indx (int): Pad token index. Defaults to 0. max_length (int): Pad sequences to a fixed maximum length device (str): device of returned tensors. Leave this as \"cpu\". The LightningModule will handle the C...
2
stack_v2_sparse_classes_30k_train_018996
Implement the Python class `Seq2SeqCollator` described below. Class description: Implement the Seq2SeqCollator class. Method signatures and docstrings: - def __init__(self, pad_indx=0, max_length=-1, device='cpu'): Collate function for seq2seq tasks * Perform padding * Calculate sequence lengths Args: pad_indx (int):...
Implement the Python class `Seq2SeqCollator` described below. Class description: Implement the Seq2SeqCollator class. Method signatures and docstrings: - def __init__(self, pad_indx=0, max_length=-1, device='cpu'): Collate function for seq2seq tasks * Perform padding * Calculate sequence lengths Args: pad_indx (int):...
e4987310ed277abdec19462bdd749e2e7a000bec
<|skeleton|> class Seq2SeqCollator: def __init__(self, pad_indx=0, max_length=-1, device='cpu'): """Collate function for seq2seq tasks * Perform padding * Calculate sequence lengths Args: pad_indx (int): Pad token index. Defaults to 0. max_length (int): Pad sequences to a fixed maximum length device (str):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Seq2SeqCollator: def __init__(self, pad_indx=0, max_length=-1, device='cpu'): """Collate function for seq2seq tasks * Perform padding * Calculate sequence lengths Args: pad_indx (int): Pad token index. Defaults to 0. max_length (int): Pad sequences to a fixed maximum length device (str): device of ret...
the_stack_v2_python_sparse
slp/data/collators.py
georgepar/slp
train
26
e77bed2c319ef18fd212b6dee0cec9d7c061bcf8
[ "if not self.api:\n raise ValueError('RedditCommentFactory requires an api instance')\nif self.comment_id:\n return None\nreturn RedditTextPostFactory.create(api=self.api).id", "if not self.api:\n raise ValueError('RedditCommentFactory requires an api instance')\ncomment = self.api.create_comment(self.te...
<|body_start_0|> if not self.api: raise ValueError('RedditCommentFactory requires an api instance') if self.comment_id: return None return RedditTextPostFactory.create(api=self.api).id <|end_body_0|> <|body_start_1|> if not self.api: raise ValueError(...
Factory for comments
RedditCommentFactory
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedditCommentFactory: """Factory for comments""" def post_id(self): """Lazily create the post""" <|body_0|> def create_in_reddit(self, *args, **kwargs): """Lazily create the comment""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not self.api...
stack_v2_sparse_classes_36k_train_006624
16,744
permissive
[ { "docstring": "Lazily create the post", "name": "post_id", "signature": "def post_id(self)" }, { "docstring": "Lazily create the comment", "name": "create_in_reddit", "signature": "def create_in_reddit(self, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_013360
Implement the Python class `RedditCommentFactory` described below. Class description: Factory for comments Method signatures and docstrings: - def post_id(self): Lazily create the post - def create_in_reddit(self, *args, **kwargs): Lazily create the comment
Implement the Python class `RedditCommentFactory` described below. Class description: Factory for comments Method signatures and docstrings: - def post_id(self): Lazily create the post - def create_in_reddit(self, *args, **kwargs): Lazily create the comment <|skeleton|> class RedditCommentFactory: """Factory for...
ba7442482da97d463302658c0aac989567ee1241
<|skeleton|> class RedditCommentFactory: """Factory for comments""" def post_id(self): """Lazily create the post""" <|body_0|> def create_in_reddit(self, *args, **kwargs): """Lazily create the comment""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedditCommentFactory: """Factory for comments""" def post_id(self): """Lazily create the post""" if not self.api: raise ValueError('RedditCommentFactory requires an api instance') if self.comment_id: return None return RedditTextPostFactory.create(a...
the_stack_v2_python_sparse
channels/factories/reddit.py
mitodl/open-discussions
train
13
182149bb257971bc11799a4d521e5de50e7621ac
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingService()", "from .booking_price_type import BookingPriceType\nfrom .booking_question_assignment import BookingQuestionAssignment\nfrom .booking_reminder import BookingReminder\nfrom .booking_scheduling_policy import BookingSche...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return BookingService() <|end_body_0|> <|body_start_1|> from .booking_price_type import BookingPriceType from .booking_question_assignment import BookingQuestionAssignment from .booking...
Represents a particular service offered by a booking business.
BookingService
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BookingService: """Represents a particular service offered by a booking business.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingService: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pars...
stack_v2_sparse_classes_36k_train_006625
9,420
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: BookingService", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_valu...
3
stack_v2_sparse_classes_30k_test_000154
Implement the Python class `BookingService` described below. Class description: Represents a particular service offered by a booking business. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingService: Creates a new instance of the appropriate clas...
Implement the Python class `BookingService` described below. Class description: Represents a particular service offered by a booking business. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingService: Creates a new instance of the appropriate clas...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class BookingService: """Represents a particular service offered by a booking business.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingService: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The pars...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BookingService: """Represents a particular service offered by a booking business.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingService: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use...
the_stack_v2_python_sparse
msgraph/generated/models/booking_service.py
microsoftgraph/msgraph-sdk-python
train
135
53340980c9dfab87579ad5a890bba8bf61deaf70
[ "try:\n if (nr_model := Request.query.get(nr_id)):\n org_id = request.args.get('org_id', None)\n headers = {'Authorization': f'Bearer {jwt.get_token_auth_header()}', 'Content-Type': 'application/json'}\n auth_svc_url = current_app.config.get('AUTH_SVC_URL')\n auth_url = f'{auth_svc_ur...
<|body_start_0|> try: if (nr_model := Request.query.get(nr_id)): org_id = request.args.get('org_id', None) headers = {'Authorization': f'Bearer {jwt.get_token_auth_header()}', 'Content-Type': 'application/json'} auth_svc_url = current_app.config.get('A...
Name Request endpoint.
NameRequestResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NameRequestResource: """Name Request endpoint.""" def get(self, nr_id): """Name Request GET endpoint.""" <|body_0|> def put(self, nr_id): """NOT used for Existing Name Request updates that only change the Name Request. Use 'patch' instead. State changes handled i...
stack_v2_sparse_classes_36k_train_006626
22,574
permissive
[ { "docstring": "Name Request GET endpoint.", "name": "get", "signature": "def get(self, nr_id)" }, { "docstring": "NOT used for Existing Name Request updates that only change the Name Request. Use 'patch' instead. State changes handled include state changes to [DRAFT, COND_RESERVE, RESERVED, CON...
2
stack_v2_sparse_classes_30k_train_016077
Implement the Python class `NameRequestResource` described below. Class description: Name Request endpoint. Method signatures and docstrings: - def get(self, nr_id): Name Request GET endpoint. - def put(self, nr_id): NOT used for Existing Name Request updates that only change the Name Request. Use 'patch' instead. St...
Implement the Python class `NameRequestResource` described below. Class description: Name Request endpoint. Method signatures and docstrings: - def get(self, nr_id): Name Request GET endpoint. - def put(self, nr_id): NOT used for Existing Name Request updates that only change the Name Request. Use 'patch' instead. St...
0175587b7322a3e41076b8bd7a3976f486491a5c
<|skeleton|> class NameRequestResource: """Name Request endpoint.""" def get(self, nr_id): """Name Request GET endpoint.""" <|body_0|> def put(self, nr_id): """NOT used for Existing Name Request updates that only change the Name Request. Use 'patch' instead. State changes handled i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NameRequestResource: """Name Request endpoint.""" def get(self, nr_id): """Name Request GET endpoint.""" try: if (nr_model := Request.query.get(nr_id)): org_id = request.args.get('org_id', None) headers = {'Authorization': f'Bearer {jwt.get_toke...
the_stack_v2_python_sparse
api/namex/resources/name_requests/name_request.py
bcgov/namex
train
5
1c53fdfdd573772a41becca77a2bf69719d91326
[ "super().__init__(coordinator=coordinator, entry_id=entry_id, entry_name=entry_name)\nself.entity_description = description\nself._attr_unique_id = f'{entry_id}_{description.key}'", "sensor_type = self.entity_description.key\nvalue = self.coordinator.data['status'].get(sensor_type)\nif value is not None and 'UpTi...
<|body_start_0|> super().__init__(coordinator=coordinator, entry_id=entry_id, entry_name=entry_name) self.entity_description = description self._attr_unique_id = f'{entry_id}_{description.key}' <|end_body_0|> <|body_start_1|> sensor_type = self.entity_description.key value = sel...
Representation of a NZBGet sensor.
NZBGetSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NZBGetSensor: """Representation of a NZBGet sensor.""" def __init__(self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, description: SensorEntityDescription) -> None: """Initialize a new NZBGet sensor.""" <|body_0|> def native_value(self) -> S...
stack_v2_sparse_classes_36k_train_006627
4,749
permissive
[ { "docstring": "Initialize a new NZBGet sensor.", "name": "__init__", "signature": "def __init__(self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, description: SensorEntityDescription) -> None" }, { "docstring": "Return the state of the sensor.", "name": "native...
2
null
Implement the Python class `NZBGetSensor` described below. Class description: Representation of a NZBGet sensor. Method signatures and docstrings: - def __init__(self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, description: SensorEntityDescription) -> None: Initialize a new NZBGet senso...
Implement the Python class `NZBGetSensor` described below. Class description: Representation of a NZBGet sensor. Method signatures and docstrings: - def __init__(self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, description: SensorEntityDescription) -> None: Initialize a new NZBGet senso...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class NZBGetSensor: """Representation of a NZBGet sensor.""" def __init__(self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, description: SensorEntityDescription) -> None: """Initialize a new NZBGet sensor.""" <|body_0|> def native_value(self) -> S...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NZBGetSensor: """Representation of a NZBGet sensor.""" def __init__(self, coordinator: NZBGetDataUpdateCoordinator, entry_id: str, entry_name: str, description: SensorEntityDescription) -> None: """Initialize a new NZBGet sensor.""" super().__init__(coordinator=coordinator, entry_id=entry...
the_stack_v2_python_sparse
homeassistant/components/nzbget/sensor.py
home-assistant/core
train
35,501
1968a46a67377fed112b685c22fb731f81742e33
[ "all_guidance = StandardGuidancePage.objects.live().descendant_of(self).order_by('title')\nif filter_dict:\n filtered_guidance = self.filter_children(all_guidance, filter_dict)\nelse:\n filtered_guidance = all_guidance\nif search_query and filtered_guidance:\n queried_guidance = all_guidance.filter(id__in=...
<|body_start_0|> all_guidance = StandardGuidancePage.objects.live().descendant_of(self).order_by('title') if filter_dict: filtered_guidance = self.filter_children(all_guidance, filter_dict) else: filtered_guidance = all_guidance if search_query and filtered_guidan...
A model for standard guidance index page.
StandardGuidanceIndexPage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StandardGuidanceIndexPage: """A model for standard guidance index page.""" def get_guidance(self, request, filter_dict=None, search_query=None): """Return a filtered list of guidance.""" <|body_0|> def get_context(self, request, *args, **kwargs): """Overwrite the...
stack_v2_sparse_classes_36k_train_006628
14,810
permissive
[ { "docstring": "Return a filtered list of guidance.", "name": "get_guidance", "signature": "def get_guidance(self, request, filter_dict=None, search_query=None)" }, { "docstring": "Overwrite the default wagtail get_context function to allow for filtering based on params. Use the functions built ...
2
stack_v2_sparse_classes_30k_train_004502
Implement the Python class `StandardGuidanceIndexPage` described below. Class description: A model for standard guidance index page. Method signatures and docstrings: - def get_guidance(self, request, filter_dict=None, search_query=None): Return a filtered list of guidance. - def get_context(self, request, *args, **k...
Implement the Python class `StandardGuidanceIndexPage` described below. Class description: A model for standard guidance index page. Method signatures and docstrings: - def get_guidance(self, request, filter_dict=None, search_query=None): Return a filtered list of guidance. - def get_context(self, request, *args, **k...
4cf7be72b6b3d0c46dcadcc9d9904b471215ea81
<|skeleton|> class StandardGuidanceIndexPage: """A model for standard guidance index page.""" def get_guidance(self, request, filter_dict=None, search_query=None): """Return a filtered list of guidance.""" <|body_0|> def get_context(self, request, *args, **kwargs): """Overwrite the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StandardGuidanceIndexPage: """A model for standard guidance index page.""" def get_guidance(self, request, filter_dict=None, search_query=None): """Return a filtered list of guidance.""" all_guidance = StandardGuidancePage.objects.live().descendant_of(self).order_by('title') if fi...
the_stack_v2_python_sparse
iati_standard/models.py
IATI/IATI-Standard-Website
train
4
8b8961538e1186b2986dedc219514f95a19d06ad
[ "super(RBF, self).__init__()\nself.input_features = input_features\nself.output_features = output_features\nself.centers = nn.Parameter(torch.Tensor(centers))\nself.ncenter = len(self.centers)\nself.centers.requires_grad = opt_centers\nself.sigma = nn.Parameter(sigma * torch.ones(self.ncenter))\nself.sigma.requires...
<|body_start_0|> super(RBF, self).__init__() self.input_features = input_features self.output_features = output_features self.centers = nn.Parameter(torch.Tensor(centers)) self.ncenter = len(self.centers) self.centers.requires_grad = opt_centers self.sigma = nn.Pa...
RBF
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RBF: def __init__(self, input_features, output_features, centers, opt_centers=True, sigma=1.0, opt_sigma=True): """Radial Basis Function Layer in N dimension Args: input_features: input side output_features: output size centers : position of the centers opt_centers : optmize the center p...
stack_v2_sparse_classes_36k_train_006629
1,841
permissive
[ { "docstring": "Radial Basis Function Layer in N dimension Args: input_features: input side output_features: output size centers : position of the centers opt_centers : optmize the center positions sigma : strategy to get the sigma opt_sigma : optmize the std or not", "name": "__init__", "signature": "d...
2
stack_v2_sparse_classes_30k_train_000901
Implement the Python class `RBF` described below. Class description: Implement the RBF class. Method signatures and docstrings: - def __init__(self, input_features, output_features, centers, opt_centers=True, sigma=1.0, opt_sigma=True): Radial Basis Function Layer in N dimension Args: input_features: input side outpu...
Implement the Python class `RBF` described below. Class description: Implement the RBF class. Method signatures and docstrings: - def __init__(self, input_features, output_features, centers, opt_centers=True, sigma=1.0, opt_sigma=True): Radial Basis Function Layer in N dimension Args: input_features: input side outpu...
77de21577157601b4f4e5a01d27f95cdf0587d83
<|skeleton|> class RBF: def __init__(self, input_features, output_features, centers, opt_centers=True, sigma=1.0, opt_sigma=True): """Radial Basis Function Layer in N dimension Args: input_features: input side output_features: output size centers : position of the centers opt_centers : optmize the center p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RBF: def __init__(self, input_features, output_features, centers, opt_centers=True, sigma=1.0, opt_sigma=True): """Radial Basis Function Layer in N dimension Args: input_features: input side output_features: output size centers : position of the centers opt_centers : optmize the center positions sigma...
the_stack_v2_python_sparse
quantumdraw/wavefunction/rbf.py
NLESC-JCER/QuantumDraw
train
1
85e206c87ef1130bd50dc9f39373cfce16e61da2
[ "if not email:\n msg = 'Users must have an email address'\n raise ValueError(msg)\nuser = self.model(email=AgdaUserManager.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email, password=password)\nuser.is_admin = True\nuser.is_staff = ...
<|body_start_0|> if not email: msg = 'Users must have an email address' raise ValueError(msg) user = self.model(email=AgdaUserManager.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|>...
AgdaUserManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AgdaUserManager: def create_user(self, email, password=None): """Creates and saves a User with the . given email, favorite topping, and password.""" <|body_0|> def create_superuser(self, email, password): """Creates and saves a superuser with the given email, . favor...
stack_v2_sparse_classes_36k_train_006630
7,094
permissive
[ { "docstring": "Creates and saves a User with the . given email, favorite topping, and password.", "name": "create_user", "signature": "def create_user(self, email, password=None)" }, { "docstring": "Creates and saves a superuser with the given email, . favorite topping and password.", "name...
2
stack_v2_sparse_classes_30k_test_000951
Implement the Python class `AgdaUserManager` described below. Class description: Implement the AgdaUserManager class. Method signatures and docstrings: - def create_user(self, email, password=None): Creates and saves a User with the . given email, favorite topping, and password. - def create_superuser(self, email, pa...
Implement the Python class `AgdaUserManager` described below. Class description: Implement the AgdaUserManager class. Method signatures and docstrings: - def create_user(self, email, password=None): Creates and saves a User with the . given email, favorite topping, and password. - def create_superuser(self, email, pa...
a67e94b127ee7f97419152d5abe6a770bcee4f07
<|skeleton|> class AgdaUserManager: def create_user(self, email, password=None): """Creates and saves a User with the . given email, favorite topping, and password.""" <|body_0|> def create_superuser(self, email, password): """Creates and saves a superuser with the given email, . favor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AgdaUserManager: def create_user(self, email, password=None): """Creates and saves a User with the . given email, favorite topping, and password.""" if not email: msg = 'Users must have an email address' raise ValueError(msg) user = self.model(email=AgdaUserMana...
the_stack_v2_python_sparse
agda/profiles/models.py
NBISweden/agda
train
0
0fb98998ddaeef5c4bbfdb856d3133c142f8a643
[ "qapp_id = request.GET.get('qapp_id', 0)\nqapp = Qapp.objects.get(id=qapp_id)\nif check_can_edit(qapp, request.user):\n qapp_approval = QappApproval.objects.get(qapp=qapp)\n form = QappApprovalSignatureForm({'qapp': qapp, 'qapp_approval': qapp_approval})\n ctx = {'form': form, 'qapp_id': qapp_id}\n retu...
<|body_start_0|> qapp_id = request.GET.get('qapp_id', 0) qapp = Qapp.objects.get(id=qapp_id) if check_can_edit(qapp, request.user): qapp_approval = QappApproval.objects.get(qapp=qapp) form = QappApprovalSignatureForm({'qapp': qapp, 'qapp_approval': qapp_approval}) ...
Class for creating new QAPP Project Approval Signatures.
ProjectApprovalSignatureCreate
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectApprovalSignatureCreate: """Class for creating new QAPP Project Approval Signatures.""" def get(self, request, *args, **kwargs): """GET Project Approval Signature Create page. Return a view with an empty form for creating a new Approval Signature.""" <|body_0|> de...
stack_v2_sparse_classes_36k_train_006631
36,787
no_license
[ { "docstring": "GET Project Approval Signature Create page. Return a view with an empty form for creating a new Approval Signature.", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Process the post request with a new Project Lead form filled out.", "...
2
null
Implement the Python class `ProjectApprovalSignatureCreate` described below. Class description: Class for creating new QAPP Project Approval Signatures. Method signatures and docstrings: - def get(self, request, *args, **kwargs): GET Project Approval Signature Create page. Return a view with an empty form for creatin...
Implement the Python class `ProjectApprovalSignatureCreate` described below. Class description: Class for creating new QAPP Project Approval Signatures. Method signatures and docstrings: - def get(self, request, *args, **kwargs): GET Project Approval Signature Create page. Return a view with an empty form for creatin...
ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4
<|skeleton|> class ProjectApprovalSignatureCreate: """Class for creating new QAPP Project Approval Signatures.""" def get(self, request, *args, **kwargs): """GET Project Approval Signature Create page. Return a view with an empty form for creating a new Approval Signature.""" <|body_0|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectApprovalSignatureCreate: """Class for creating new QAPP Project Approval Signatures.""" def get(self, request, *args, **kwargs): """GET Project Approval Signature Create page. Return a view with an empty form for creating a new Approval Signature.""" qapp_id = request.GET.get('qapp...
the_stack_v2_python_sparse
DataSearch/qar5/views.py
USEPA/FoodWaste
train
1
77757e8284e30c20656b352b994b57920eb5479f
[ "self.cache = {}\nself.frequency = collections.defaultdict(list)\nself.capacity = capacity", "if key not in self.cache:\n return -1\nfor freq in self.frequency:\n if key in self.frequency[freq]:\n self.frequency[freq].remove(key)\n if not self.frequency[freq]:\n self.frequency.pop(f...
<|body_start_0|> self.cache = {} self.frequency = collections.defaultdict(list) self.capacity = capacity <|end_body_0|> <|body_start_1|> if key not in self.cache: return -1 for freq in self.frequency: if key in self.frequency[freq]: self.f...
LFUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k_train_006632
1,356
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
stack_v2_sparse_classes_30k_train_008175
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
2fe336e0de336f6d5f67b058ddb5cf50c9f00d4e
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LFUCache: def __init__(self, capacity): """:type capacity: int""" self.cache = {} self.frequency = collections.defaultdict(list) self.capacity = capacity def get(self, key): """:type key: int :rtype: int""" if key not in self.cache: return -1 ...
the_stack_v2_python_sparse
c++/460. LFU Cache.py
rhzx3519/leetcode
train
3
56363dae3a128fda6e2b76e2ff2cb1994d19dd3d
[ "self.metric = metric\nself.gram = None\nself.min_size = 2", "s_ = signal.reshape(-1, 1) if signal.ndim == 1 else signal\nif self.metric is None:\n covar = np.cov(s_.T)\n self.metric = inv(covar.reshape(1, 1) if covar.size == 1 else covar)\nself.gram = s_.dot(self.metric).dot(s_.T)\nreturn self", "if end ...
<|body_start_0|> self.metric = metric self.gram = None self.min_size = 2 <|end_body_0|> <|body_start_1|> s_ = signal.reshape(-1, 1) if signal.ndim == 1 else signal if self.metric is None: covar = np.cov(s_.T) self.metric = inv(covar.reshape(1, 1) if covar...
Mahalanobis-type cost function.
CostMl
[ "MIT", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CostMl: """Mahalanobis-type cost function.""" def __init__(self, metric=None): """Create a new instance. Args: metric (ndarray, optional): PSD matrix that defines a Mahalanobis-type pseudo distance. If None, defaults to the Mahalanobis matrix. Shape (n_features, n_features). Returns:...
stack_v2_sparse_classes_36k_train_006633
4,379
permissive
[ { "docstring": "Create a new instance. Args: metric (ndarray, optional): PSD matrix that defines a Mahalanobis-type pseudo distance. If None, defaults to the Mahalanobis matrix. Shape (n_features, n_features). Returns: self", "name": "__init__", "signature": "def __init__(self, metric=None)" }, { ...
3
stack_v2_sparse_classes_30k_train_017287
Implement the Python class `CostMl` described below. Class description: Mahalanobis-type cost function. Method signatures and docstrings: - def __init__(self, metric=None): Create a new instance. Args: metric (ndarray, optional): PSD matrix that defines a Mahalanobis-type pseudo distance. If None, defaults to the Mah...
Implement the Python class `CostMl` described below. Class description: Mahalanobis-type cost function. Method signatures and docstrings: - def __init__(self, metric=None): Create a new instance. Args: metric (ndarray, optional): PSD matrix that defines a Mahalanobis-type pseudo distance. If None, defaults to the Mah...
4c32e749912821ce9056ec8a708172904dfb9cfe
<|skeleton|> class CostMl: """Mahalanobis-type cost function.""" def __init__(self, metric=None): """Create a new instance. Args: metric (ndarray, optional): PSD matrix that defines a Mahalanobis-type pseudo distance. If None, defaults to the Mahalanobis matrix. Shape (n_features, n_features). Returns:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CostMl: """Mahalanobis-type cost function.""" def __init__(self, metric=None): """Create a new instance. Args: metric (ndarray, optional): PSD matrix that defines a Mahalanobis-type pseudo distance. If None, defaults to the Mahalanobis matrix. Shape (n_features, n_features). Returns: self""" ...
the_stack_v2_python_sparse
code/skoda/modified_ruptures_package/build/lib/ruptures/costs/costml.py
Hangwei12358/unified-activity-segmentation-and-recognition
train
2
7074bb683c67e86b230f1527de56851eaaf651af
[ "data = {'lessons': [], 'days': [], 'time_slots': [], 'auditoriums': [], 'student_groups': []}\nif exchange_format is ExchangeFormat.CSV:\n for filename in ['lessons', 'days', 'time_slots', 'auditoriums', 'student_groups']:\n csv_path = f\"{config['import_csv_path']}{filename}.csv\"\n with open(csv...
<|body_start_0|> data = {'lessons': [], 'days': [], 'time_slots': [], 'auditoriums': [], 'student_groups': []} if exchange_format is ExchangeFormat.CSV: for filename in ['lessons', 'days', 'time_slots', 'auditoriums', 'student_groups']: csv_path = f"{config['import_csv_path']...
Exchanger
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Exchanger: def import_data(exchange_format: ExchangeFormat) -> dict: """Import data from CSV/MongoDB/JSON""" <|body_0|> def export_data(data: list, exchange_format: ExchangeFormat) -> None: """Export data to CSV/MongoDB/JSON""" <|body_1|> def csv_to_json...
stack_v2_sparse_classes_36k_train_006634
2,550
no_license
[ { "docstring": "Import data from CSV/MongoDB/JSON", "name": "import_data", "signature": "def import_data(exchange_format: ExchangeFormat) -> dict" }, { "docstring": "Export data to CSV/MongoDB/JSON", "name": "export_data", "signature": "def export_data(data: list, exchange_format: Exchan...
3
stack_v2_sparse_classes_30k_train_016132
Implement the Python class `Exchanger` described below. Class description: Implement the Exchanger class. Method signatures and docstrings: - def import_data(exchange_format: ExchangeFormat) -> dict: Import data from CSV/MongoDB/JSON - def export_data(data: list, exchange_format: ExchangeFormat) -> None: Export data ...
Implement the Python class `Exchanger` described below. Class description: Implement the Exchanger class. Method signatures and docstrings: - def import_data(exchange_format: ExchangeFormat) -> dict: Import data from CSV/MongoDB/JSON - def export_data(data: list, exchange_format: ExchangeFormat) -> None: Export data ...
130871d446c8015dc1fbbd021791e94c84008d21
<|skeleton|> class Exchanger: def import_data(exchange_format: ExchangeFormat) -> dict: """Import data from CSV/MongoDB/JSON""" <|body_0|> def export_data(data: list, exchange_format: ExchangeFormat) -> None: """Export data to CSV/MongoDB/JSON""" <|body_1|> def csv_to_json...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Exchanger: def import_data(exchange_format: ExchangeFormat) -> dict: """Import data from CSV/MongoDB/JSON""" data = {'lessons': [], 'days': [], 'time_slots': [], 'auditoriums': [], 'student_groups': []} if exchange_format is ExchangeFormat.CSV: for filename in ['lessons', '...
the_stack_v2_python_sparse
automatic_scheduling/data_exchange.py
RedMoon32/CodeScetches
train
0
c73895a68ff318d2dd4bd60e2df825c26f76f46b
[ "logging.info('adding product to the Cart')\nself.driver.find_element(*ProductPageLocators.BTN_CART).click()\ntime.sleep(DRIVER_WAIT_TIME)\nreturn self", "logging.info('clicking Cart Link in top Bar')\ntime.sleep(DRIVER_WAIT_TIME)\nself.driver.find_element(*ProductPageLocators.GO_CART).click()\nreturn CartPage(se...
<|body_start_0|> logging.info('adding product to the Cart') self.driver.find_element(*ProductPageLocators.BTN_CART).click() time.sleep(DRIVER_WAIT_TIME) return self <|end_body_0|> <|body_start_1|> logging.info('clicking Cart Link in top Bar') time.sleep(DRIVER_WAIT_TIME)...
Product Page methods come here.
ProductPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProductPage: """Product Page methods come here.""" def add_to_cart(self) -> 'ProductPage': """Make webdriver add product to Cart. :return: Product Page Object with added product into Cart.""" <|body_0|> def goto_cart(self) -> 'CartPage': """Make webdriver go to C...
stack_v2_sparse_classes_36k_train_006635
1,355
no_license
[ { "docstring": "Make webdriver add product to Cart. :return: Product Page Object with added product into Cart.", "name": "add_to_cart", "signature": "def add_to_cart(self) -> 'ProductPage'" }, { "docstring": "Make webdriver go to Cart Page. :return: Cart Page Object.", "name": "goto_cart", ...
3
stack_v2_sparse_classes_30k_train_003557
Implement the Python class `ProductPage` described below. Class description: Product Page methods come here. Method signatures and docstrings: - def add_to_cart(self) -> 'ProductPage': Make webdriver add product to Cart. :return: Product Page Object with added product into Cart. - def goto_cart(self) -> 'CartPage': M...
Implement the Python class `ProductPage` described below. Class description: Product Page methods come here. Method signatures and docstrings: - def add_to_cart(self) -> 'ProductPage': Make webdriver add product to Cart. :return: Product Page Object with added product into Cart. - def goto_cart(self) -> 'CartPage': M...
6bb7214c6362aa27ddd4d3ece65e7e0fc3c46d93
<|skeleton|> class ProductPage: """Product Page methods come here.""" def add_to_cart(self) -> 'ProductPage': """Make webdriver add product to Cart. :return: Product Page Object with added product into Cart.""" <|body_0|> def goto_cart(self) -> 'CartPage': """Make webdriver go to C...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProductPage: """Product Page methods come here.""" def add_to_cart(self) -> 'ProductPage': """Make webdriver add product to Cart. :return: Product Page Object with added product into Cart.""" logging.info('adding product to the Cart') self.driver.find_element(*ProductPageLocators....
the_stack_v2_python_sparse
pages/product.py
Lv296TAQC/OpenCart_TA
train
0
ba18002aaabe090cabaf8c8dd270e858783b0f1b
[ "super(LoadPostgresStep, self).__init__(**kwargs)\nregion = POSTGRES_CONFIG[host_db_key]['REGION']\nrds_instance_id = POSTGRES_CONFIG[host_db_key]['RDS_INSTANCE_ID']\nuser = POSTGRES_CONFIG[host_db_key]['USERNAME']\npassword = POSTGRES_CONFIG[host_db_key]['PASSWORD']\ndatabase_node = self.create_pipeline_object(obj...
<|body_start_0|> super(LoadPostgresStep, self).__init__(**kwargs) region = POSTGRES_CONFIG[host_db_key]['REGION'] rds_instance_id = POSTGRES_CONFIG[host_db_key]['RDS_INSTANCE_ID'] user = POSTGRES_CONFIG[host_db_key]['USERNAME'] password = POSTGRES_CONFIG[host_db_key]['PASSWORD'] ...
Load Postgres Step class that helps load data into postgres
LoadPostgresStep
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadPostgresStep: """Load Postgres Step class that helps load data into postgres""" def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): """Constructor for the LoadPostgresStep class Args: table(path): table na...
stack_v2_sparse_classes_36k_train_006636
2,945
permissive
[ { "docstring": "Constructor for the LoadPostgresStep class Args: table(path): table name for load sql(str): sql query to be executed postgres_database(PostgresDatabase): database to excute the query output_path(str): s3 path where sql output should be saved **kwargs(optional): Keyword arguments directly passed ...
2
stack_v2_sparse_classes_30k_train_007274
Implement the Python class `LoadPostgresStep` described below. Class description: Load Postgres Step class that helps load data into postgres Method signatures and docstrings: - def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): Constructor f...
Implement the Python class `LoadPostgresStep` described below. Class description: Load Postgres Step class that helps load data into postgres Method signatures and docstrings: - def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): Constructor f...
797cb719e6c2abeda0751ada3339c72bfb19c8f2
<|skeleton|> class LoadPostgresStep: """Load Postgres Step class that helps load data into postgres""" def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): """Constructor for the LoadPostgresStep class Args: table(path): table na...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoadPostgresStep: """Load Postgres Step class that helps load data into postgres""" def __init__(self, table, postgres_database, host_db_key, insert_query, max_errors=None, replace_invalid_char=None, **kwargs): """Constructor for the LoadPostgresStep class Args: table(path): table name for load s...
the_stack_v2_python_sparse
dataduct/steps/load_postgres.py
EverFi/dataduct
train
3
4e401d7ea01ea9e86a7db28c1d8560b30c67ef8f
[ "if x < 0:\n return False\nif x < 10:\n return True\nr = self.reverse(x)\nreturn r == x", "s = str(x)\nstack = []\nfor i in range(0, len(s)):\n stack.append(s[i])\nr = ''\nfor j in range(0, len(stack)):\n n = stack.pop()\n if n == '-':\n r = '-' + r\n else:\n r += n\nresult = int(r...
<|body_start_0|> if x < 0: return False if x < 10: return True r = self.reverse(x) return r == x <|end_body_0|> <|body_start_1|> s = str(x) stack = [] for i in range(0, len(s)): stack.append(s[i]) r = '' for j i...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def reverse(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if x < 0: return False if x < 10: retur...
stack_v2_sparse_classes_36k_train_006637
823
no_license
[ { "docstring": ":type x: int :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, x)" }, { "docstring": ":type x: int :rtype: int", "name": "reverse", "signature": "def reverse(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_003239
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def reverse(self, x): :type x: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, x): :type x: int :rtype: bool - def reverse(self, x): :type x: int :rtype: int <|skeleton|> class Solution: def isPalindrome(self, x): """:ty...
d10b2e130d6fde73e00317d799d3c660c7bd2ce5
<|skeleton|> class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" <|body_0|> def reverse(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome(self, x): """:type x: int :rtype: bool""" if x < 0: return False if x < 10: return True r = self.reverse(x) return r == x def reverse(self, x): """:type x: int :rtype: int""" s = str(x) stac...
the_stack_v2_python_sparse
a9.py
love525150/leetcode-answer
train
0
fefa8ab3720fe963ea527224acff4fcf5abc7685
[ "with self.assertRaises(GitHubRepositoryNotFoundException):\n GitHubKeywords.get_releases('non-existing-repo')\nself.assertGreater(GitHubKeywords.get_releases('OneView-TestTools/tru'), 0)", "with self.assertRaises(exceptions.NonFatalError):\n GitHubKeywords.download_release('test')\nversion = '2.1.1.20'\nfi...
<|body_start_0|> with self.assertRaises(GitHubRepositoryNotFoundException): GitHubKeywords.get_releases('non-existing-repo') self.assertGreater(GitHubKeywords.get_releases('OneView-TestTools/tru'), 0) <|end_body_0|> <|body_start_1|> with self.assertRaises(exceptions.NonFatalError): ...
Unit tests for the main class
GitHubKeywordsUnitTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GitHubKeywordsUnitTests: """Unit tests for the main class""" def test_get_releases(self): """Test the get_releases method""" <|body_0|> def test_download_release(self): """Test the download_release method""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_006638
6,305
no_license
[ { "docstring": "Test the get_releases method", "name": "test_get_releases", "signature": "def test_get_releases(self)" }, { "docstring": "Test the download_release method", "name": "test_download_release", "signature": "def test_download_release(self)" } ]
2
null
Implement the Python class `GitHubKeywordsUnitTests` described below. Class description: Unit tests for the main class Method signatures and docstrings: - def test_get_releases(self): Test the get_releases method - def test_download_release(self): Test the download_release method
Implement the Python class `GitHubKeywordsUnitTests` described below. Class description: Unit tests for the main class Method signatures and docstrings: - def test_get_releases(self): Test the get_releases method - def test_download_release(self): Test the download_release method <|skeleton|> class GitHubKeywordsUni...
24a74926170cbdfafa47e972644e2fe5b627d8ff
<|skeleton|> class GitHubKeywordsUnitTests: """Unit tests for the main class""" def test_get_releases(self): """Test the get_releases method""" <|body_0|> def test_download_release(self): """Test the download_release method""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GitHubKeywordsUnitTests: """Unit tests for the main class""" def test_get_releases(self): """Test the get_releases method""" with self.assertRaises(GitHubRepositoryNotFoundException): GitHubKeywords.get_releases('non-existing-repo') self.assertGreater(GitHubKeywords.ge...
the_stack_v2_python_sparse
robo4.2/4.2/lib/python2.7/site-packages/RoboGalaxyLibrary/keywords/github.py
richa92/Jenkin_Regression_Testing
train
0
5f3160d27c2ab0bdad07ad88caf98c3ae68b4c31
[ "agenda = Agenda.objects.first()\nserializer = AgendaSerializer(instance=agenda)\ndata = serializer.data\nnew_serializer = AgendaSerializer(data=data)\nif not new_serializer.is_valid():\n print(new_serializer.errors)\nself.assertTrue(new_serializer.is_valid())\nnew_agenda = new_serializer.save()\nfor attr in ('d...
<|body_start_0|> agenda = Agenda.objects.first() serializer = AgendaSerializer(instance=agenda) data = serializer.data new_serializer = AgendaSerializer(data=data) if not new_serializer.is_valid(): print(new_serializer.errors) self.assertTrue(new_serializer.is...
AgendaTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AgendaTestCase: def test_agenda_serializer(self): """Test the agenda model serializer by serializing and deserializing an agenda object.""" <|body_0|> def test_get_all_agendas(self): """Test the enpoint to get all agendas""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_006639
1,381
no_license
[ { "docstring": "Test the agenda model serializer by serializing and deserializing an agenda object.", "name": "test_agenda_serializer", "signature": "def test_agenda_serializer(self)" }, { "docstring": "Test the enpoint to get all agendas", "name": "test_get_all_agendas", "signature": "d...
2
stack_v2_sparse_classes_30k_test_000369
Implement the Python class `AgendaTestCase` described below. Class description: Implement the AgendaTestCase class. Method signatures and docstrings: - def test_agenda_serializer(self): Test the agenda model serializer by serializing and deserializing an agenda object. - def test_get_all_agendas(self): Test the enpoi...
Implement the Python class `AgendaTestCase` described below. Class description: Implement the AgendaTestCase class. Method signatures and docstrings: - def test_agenda_serializer(self): Test the agenda model serializer by serializing and deserializing an agenda object. - def test_get_all_agendas(self): Test the enpoi...
dc96b1cc35b4ca49e5e0c80e6b31f8610fe31a26
<|skeleton|> class AgendaTestCase: def test_agenda_serializer(self): """Test the agenda model serializer by serializing and deserializing an agenda object.""" <|body_0|> def test_get_all_agendas(self): """Test the enpoint to get all agendas""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AgendaTestCase: def test_agenda_serializer(self): """Test the agenda model serializer by serializing and deserializing an agenda object.""" agenda = Agenda.objects.first() serializer = AgendaSerializer(instance=agenda) data = serializer.data new_serializer = AgendaSeria...
the_stack_v2_python_sparse
backend/crechesite/agenda/tests.py
bricekouetcheu/Les-lionceaux
train
1
63cbf8f1082846599d65faf5aabfe3207033e2a2
[ "filters_serializer = CompetitionFilterSerializer(data=request.query_params)\nfilters_serializer.is_valid(raise_exception=True)\ncompetitions = CompetitionService.get_competitions(filters=filters_serializer.validated_data)\nreturn get_paginated_response(pagination_class=HeaderLimitOffsetPagination, serializer_class...
<|body_start_0|> filters_serializer = CompetitionFilterSerializer(data=request.query_params) filters_serializer.is_valid(raise_exception=True) competitions = CompetitionService.get_competitions(filters=filters_serializer.validated_data) return get_paginated_response(pagination_class=Head...
CompetitionViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompetitionViewSet: def list(self, request: Request) -> Response: """List all :class:`Competition`\\s""" <|body_0|> def retrieve(self, request: Request, competition_id: Union[str, UUID]) -> Response: """Retrieve a specific :class:`Competition` based on it's ID :param...
stack_v2_sparse_classes_36k_train_006640
7,007
no_license
[ { "docstring": "List all :class:`Competition`\\\\s", "name": "list", "signature": "def list(self, request: Request) -> Response" }, { "docstring": "Retrieve a specific :class:`Competition` based on it's ID :param cpmpetition_id: The ID of the :class:`Competition` to retrieve", "name": "retri...
2
stack_v2_sparse_classes_30k_train_000513
Implement the Python class `CompetitionViewSet` described below. Class description: Implement the CompetitionViewSet class. Method signatures and docstrings: - def list(self, request: Request) -> Response: List all :class:`Competition`\\s - def retrieve(self, request: Request, competition_id: Union[str, UUID]) -> Res...
Implement the Python class `CompetitionViewSet` described below. Class description: Implement the CompetitionViewSet class. Method signatures and docstrings: - def list(self, request: Request) -> Response: List all :class:`Competition`\\s - def retrieve(self, request: Request, competition_id: Union[str, UUID]) -> Res...
3ae560565ae9ce7598a94fed4f7828f3c1675a35
<|skeleton|> class CompetitionViewSet: def list(self, request: Request) -> Response: """List all :class:`Competition`\\s""" <|body_0|> def retrieve(self, request: Request, competition_id: Union[str, UUID]) -> Response: """Retrieve a specific :class:`Competition` based on it's ID :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompetitionViewSet: def list(self, request: Request) -> Response: """List all :class:`Competition`\\s""" filters_serializer = CompetitionFilterSerializer(data=request.query_params) filters_serializer.is_valid(raise_exception=True) competitions = CompetitionService.get_competiti...
the_stack_v2_python_sparse
leaderboard/apis/rest_api.py
DurzoB5/Photocrowd-TT
train
0
bd17dba5719fda7dce24445538989e91c90c9ac4
[ "if l1 is None:\n return l2\nelif l2 is None:\n return l1\nelif l1.val < l2.val:\n l1.next = self.mergeTwoLists_1(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists_1(l1, l2.next)\n return l2", "prehead = ListNode(-1)\nprev = prehead\nwhile l1 and l2:\n if l1.val <= l2.val:\n ...
<|body_start_0|> if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists_1(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists_1(l1, l2.next) return l2 <|end_body_...
Solution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeTwoLists_1(self, l1, l2): """递归法 时间复杂度:O(n + m) :param l1: :param l2: :return:""" <|body_0|> def mergeTwoLists_2(self, l1, l2): """迭代法 时间复杂度:O(n + m) :param l1: :param l2: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> i...
stack_v2_sparse_classes_36k_train_006641
1,874
permissive
[ { "docstring": "递归法 时间复杂度:O(n + m) :param l1: :param l2: :return:", "name": "mergeTwoLists_1", "signature": "def mergeTwoLists_1(self, l1, l2)" }, { "docstring": "迭代法 时间复杂度:O(n + m) :param l1: :param l2: :return:", "name": "mergeTwoLists_2", "signature": "def mergeTwoLists_2(self, l1, l2...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeTwoLists_1(self, l1, l2): 递归法 时间复杂度:O(n + m) :param l1: :param l2: :return: - def mergeTwoLists_2(self, l1, l2): 迭代法 时间复杂度:O(n + m) :param l1: :param l2: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeTwoLists_1(self, l1, l2): 递归法 时间复杂度:O(n + m) :param l1: :param l2: :return: - def mergeTwoLists_2(self, l1, l2): 迭代法 时间复杂度:O(n + m) :param l1: :param l2: :return: <|ske...
62419b49000e79962bcdc99cd98afd2fb82ea345
<|skeleton|> class Solution: def mergeTwoLists_1(self, l1, l2): """递归法 时间复杂度:O(n + m) :param l1: :param l2: :return:""" <|body_0|> def mergeTwoLists_2(self, l1, l2): """迭代法 时间复杂度:O(n + m) :param l1: :param l2: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mergeTwoLists_1(self, l1, l2): """递归法 时间复杂度:O(n + m) :param l1: :param l2: :return:""" if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists_1(l1.next, l2) return l1 ...
the_stack_v2_python_sparse
LeetCode 热题 HOT 100/mergeTwoLists.py
MaoningGuan/LeetCode
train
3
3e5112860f873f2abd78975be460348cb3d565e8
[ "self._next_seq_id = 1\nself._node2seqid = {}\nself._seqid2nodes = defaultdict(list)\nself._prev_right = None", "from ..arch.sequence import Sequence\nfrom .pseudo_node import PseudoNode\nassert isinstance(left, PseudoNode)\nassert isinstance(right, PseudoNode)\nself._prev_right = right\nseq_id = self._node2seqid...
<|body_start_0|> self._next_seq_id = 1 self._node2seqid = {} self._seqid2nodes = defaultdict(list) self._prev_right = None <|end_body_0|> <|body_start_1|> from ..arch.sequence import Sequence from .pseudo_node import PseudoNode assert isinstance(left, PseudoNode)...
The cache that is used to implement creating node sequences with ">". It works by assigning and propagating forward a sequence ID for each node in the ">" chains, and packaging the observed node chains into sequence nodes that are returned to the caller. Behind the scenes, we create a global singleton of this class, wh...
GTCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GTCache: """The cache that is used to implement creating node sequences with ">". It works by assigning and propagating forward a sequence ID for each node in the ">" chains, and packaging the observed node chains into sequence nodes that are returned to the caller. Behind the scenes, we create a...
stack_v2_sparse_classes_36k_train_006642
2,203
no_license
[ { "docstring": "Create a \">\" node chain cache.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Evaluate one PseudoNode \">\" comparison, returning a new Sequence. The returned Sequence will be immediately thrown away unless this is the last comparison of the \">\" ch...
2
null
Implement the Python class `GTCache` described below. Class description: The cache that is used to implement creating node sequences with ">". It works by assigning and propagating forward a sequence ID for each node in the ">" chains, and packaging the observed node chains into sequence nodes that are returned to the...
Implement the Python class `GTCache` described below. Class description: The cache that is used to implement creating node sequences with ">". It works by assigning and propagating forward a sequence ID for each node in the ">" chains, and packaging the observed node chains into sequence nodes that are returned to the...
e60e8441d05789979e87ef87c8d2844c7d70ba72
<|skeleton|> class GTCache: """The cache that is used to implement creating node sequences with ">". It works by assigning and propagating forward a sequence ID for each node in the ">" chains, and packaging the observed node chains into sequence nodes that are returned to the caller. Behind the scenes, we create a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GTCache: """The cache that is used to implement creating node sequences with ">". It works by assigning and propagating forward a sequence ID for each node in the ">" chains, and packaging the observed node chains into sequence nodes that are returned to the caller. Behind the scenes, we create a global singl...
the_stack_v2_python_sparse
deepzen/node/base/gt_cache.py
knighton/deepzen
train
0
1567fefb4c8d2517dc1bd9549330c38cfff1d176
[ "self.name = 'flower_test'\nself.client = docker.from_env()\nself.adapter = DockerAdapter(name=self.name)", "containers = self.client.containers.list(filters={'label': f'adapter_name={self.name}'})\nfor container in containers:\n container.remove(force=True)\nself.client.close()", "instances = self.adapter.c...
<|body_start_0|> self.name = 'flower_test' self.client = docker.from_env() self.adapter = DockerAdapter(name=self.name) <|end_body_0|> <|body_start_1|> containers = self.client.containers.list(filters={'label': f'adapter_name={self.name}'}) for container in containers: ...
Test suite for class DockerAdapter. Required docker to be available on the host machine.
DockerAdapterIntegrationTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DockerAdapterIntegrationTestCase: """Test suite for class DockerAdapter. Required docker to be available on the host machine.""" def setUp(self) -> None: """Prepare tests.""" <|body_0|> def tearDown(self) -> None: """Cleanup tests.""" <|body_1|> def ...
stack_v2_sparse_classes_36k_train_006643
4,371
permissive
[ { "docstring": "Prepare tests.", "name": "setUp", "signature": "def setUp(self) -> None" }, { "docstring": "Cleanup tests.", "name": "tearDown", "signature": "def tearDown(self) -> None" }, { "docstring": "Create and start an instance.", "name": "test_create_instances", "...
6
null
Implement the Python class `DockerAdapterIntegrationTestCase` described below. Class description: Test suite for class DockerAdapter. Required docker to be available on the host machine. Method signatures and docstrings: - def setUp(self) -> None: Prepare tests. - def tearDown(self) -> None: Cleanup tests. - def test...
Implement the Python class `DockerAdapterIntegrationTestCase` described below. Class description: Test suite for class DockerAdapter. Required docker to be available on the host machine. Method signatures and docstrings: - def setUp(self) -> None: Prepare tests. - def tearDown(self) -> None: Cleanup tests. - def test...
55be690535e5f3feb33c888c3e4a586b7bdbf489
<|skeleton|> class DockerAdapterIntegrationTestCase: """Test suite for class DockerAdapter. Required docker to be available on the host machine.""" def setUp(self) -> None: """Prepare tests.""" <|body_0|> def tearDown(self) -> None: """Cleanup tests.""" <|body_1|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DockerAdapterIntegrationTestCase: """Test suite for class DockerAdapter. Required docker to be available on the host machine.""" def setUp(self) -> None: """Prepare tests.""" self.name = 'flower_test' self.client = docker.from_env() self.adapter = DockerAdapter(name=self.n...
the_stack_v2_python_sparse
src/py/flwr_experimental/ops/compute/docker_adapter_test.py
adap/flower
train
2,999
85b45fd5bbef7dcd84ae160184df36a34d4a1acd
[ "length = len(nums)\nif length == 0:\n return 0\nMax, Min = ([0] * length, [0] * length)\nresult = Max[0] = Min[0] = nums[0]\nfor i in range(1, length):\n Max[i] = max(max(nums[i], nums[i] * Max[i - 1]), nums[i] * Min[i - 1])\n Min[i] = min(min(nums[i], nums[i] * Max[i - 1]), nums[i] * Min[i - 1])\n res...
<|body_start_0|> length = len(nums) if length == 0: return 0 Max, Min = ([0] * length, [0] * length) result = Max[0] = Min[0] = nums[0] for i in range(1, length): Max[i] = max(max(nums[i], nums[i] * Max[i - 1]), nums[i] * Min[i - 1]) Min[i] = m...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct(self, nums): """数组为nums,因为可能存在负数,我们用Max来表示以nums[i]结尾的最大连续乘积值, 用Min表示以nums[i]结尾的最小连续乘积值。状态转移方程为: Max[i] = max{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} Min[i] = min{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} :type nums: List[int] :rtype: int""" <|body...
stack_v2_sparse_classes_36k_train_006644
1,890
no_license
[ { "docstring": "数组为nums,因为可能存在负数,我们用Max来表示以nums[i]结尾的最大连续乘积值, 用Min表示以nums[i]结尾的最小连续乘积值。状态转移方程为: Max[i] = max{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} Min[i] = min{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} :type nums: List[int] :rtype: int", "name": "maxProduct", "signature": "def maxProduct(self,...
2
stack_v2_sparse_classes_30k_train_001730
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums): 数组为nums,因为可能存在负数,我们用Max来表示以nums[i]结尾的最大连续乘积值, 用Min表示以nums[i]结尾的最小连续乘积值。状态转移方程为: Max[i] = max{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} Min[i] = min...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, nums): 数组为nums,因为可能存在负数,我们用Max来表示以nums[i]结尾的最大连续乘积值, 用Min表示以nums[i]结尾的最小连续乘积值。状态转移方程为: Max[i] = max{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} Min[i] = min...
215d513b3564a7a76db3d2b29e4acc341a68e8ee
<|skeleton|> class Solution: def maxProduct(self, nums): """数组为nums,因为可能存在负数,我们用Max来表示以nums[i]结尾的最大连续乘积值, 用Min表示以nums[i]结尾的最小连续乘积值。状态转移方程为: Max[i] = max{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} Min[i] = min{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} :type nums: List[int] :rtype: int""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProduct(self, nums): """数组为nums,因为可能存在负数,我们用Max来表示以nums[i]结尾的最大连续乘积值, 用Min表示以nums[i]结尾的最小连续乘积值。状态转移方程为: Max[i] = max{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} Min[i] = min{nums[i], nums[i]*Max[i-1], nums[i]*Min[i-1]} :type nums: List[int] :rtype: int""" length = len(nums) ...
the_stack_v2_python_sparse
python/dp/maximum-product-subarray.py
euxuoh/leetcode
train
0
3316157bbfd1532827ce99a1bce30a30dfb37d54
[ "if not re.search('^[a-zA-Z0-9._]+$', v):\n raise ValueError('must be alphanumeric')\nreturn v", "if not values.get('password_old'):\n raise ValueError('old password is required')\nreturn v", "if not values.get('password_new_1') or v != values['password_new_1']:\n raise ValueError('passwords do not mat...
<|body_start_0|> if not re.search('^[a-zA-Z0-9._]+$', v): raise ValueError('must be alphanumeric') return v <|end_body_0|> <|body_start_1|> if not values.get('password_old'): raise ValueError('old password is required') return v <|end_body_1|> <|body_start_2|> ...
User update schema.
UpdateUserIn
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateUserIn: """User update schema.""" def username_valid(cls, v: Any) -> Any: """Username validator. Args: v (Any): Username value. Raises: ValueError: Username invalid. Returns: Any: Username valid.""" <|body_0|> def passwords_match_1(cls, v: Any, values: Any, **kwarg...
stack_v2_sparse_classes_36k_train_006645
4,438
no_license
[ { "docstring": "Username validator. Args: v (Any): Username value. Raises: ValueError: Username invalid. Returns: Any: Username valid.", "name": "username_valid", "signature": "def username_valid(cls, v: Any) -> Any" }, { "docstring": "Check if filled password_new_1 and password_old. Args: v (An...
3
stack_v2_sparse_classes_30k_train_019979
Implement the Python class `UpdateUserIn` described below. Class description: User update schema. Method signatures and docstrings: - def username_valid(cls, v: Any) -> Any: Username validator. Args: v (Any): Username value. Raises: ValueError: Username invalid. Returns: Any: Username valid. - def passwords_match_1(c...
Implement the Python class `UpdateUserIn` described below. Class description: User update schema. Method signatures and docstrings: - def username_valid(cls, v: Any) -> Any: Username validator. Args: v (Any): Username value. Raises: ValueError: Username invalid. Returns: Any: Username valid. - def passwords_match_1(c...
8082d3ce9c999c79228a36aa160b4171140440cb
<|skeleton|> class UpdateUserIn: """User update schema.""" def username_valid(cls, v: Any) -> Any: """Username validator. Args: v (Any): Username value. Raises: ValueError: Username invalid. Returns: Any: Username valid.""" <|body_0|> def passwords_match_1(cls, v: Any, values: Any, **kwarg...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateUserIn: """User update schema.""" def username_valid(cls, v: Any) -> Any: """Username validator. Args: v (Any): Username value. Raises: ValueError: Username invalid. Returns: Any: Username valid.""" if not re.search('^[a-zA-Z0-9._]+$', v): raise ValueError('must be alpha...
the_stack_v2_python_sparse
app/users/schemas.py
douglaspands/api-server-py
train
2
6eb1789bf74663c0e332d464aa84c6d3be9bd06b
[ "if not root:\n return []\nleft = self.inorderTraversal(root.left)\nright = self.inorderTraversal(root.right)\nreturn left + [root.val] + right", "stack, path = ([], [])\nwhile root or stack:\n if root:\n stack.append(root)\n root = root.left\n else:\n node = stack.pop()\n pat...
<|body_start_0|> if not root: return [] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) return left + [root.val] + right <|end_body_0|> <|body_start_1|> stack, path = ([], []) while root or stack: if root: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def inorderTraversal1(self, root: TreeNode) -> List[int]: """思路: 递归 1。 终止条件: root 为空 2。 返回值 [root.val] 3. level task: 左 + 根 + 右""" <|body_0|> def inorderTraversal2(self, root: TreeNode) -> List[int]: """思路:非递归, 使用辅助stack,push root.left 直到找到根节点 node,此时放入结果, ...
stack_v2_sparse_classes_36k_train_006646
1,558
no_license
[ { "docstring": "思路: 递归 1。 终止条件: root 为空 2。 返回值 [root.val] 3. level task: 左 + 根 + 右", "name": "inorderTraversal1", "signature": "def inorderTraversal1(self, root: TreeNode) -> List[int]" }, { "docstring": "思路:非递归, 使用辅助stack,push root.left 直到找到根节点 node,此时放入结果, 使用 临时变量 为 tmp= node.right 注意: 中序遍历的非递...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderTraversal1(self, root: TreeNode) -> List[int]: 思路: 递归 1。 终止条件: root 为空 2。 返回值 [root.val] 3. level task: 左 + 根 + 右 - def inorderTraversal2(self, root: TreeNode) -> List...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def inorderTraversal1(self, root: TreeNode) -> List[int]: 思路: 递归 1。 终止条件: root 为空 2。 返回值 [root.val] 3. level task: 左 + 根 + 右 - def inorderTraversal2(self, root: TreeNode) -> List...
4994b8b19abcdbcc0bda2944350e325242fadfd1
<|skeleton|> class Solution: def inorderTraversal1(self, root: TreeNode) -> List[int]: """思路: 递归 1。 终止条件: root 为空 2。 返回值 [root.val] 3. level task: 左 + 根 + 右""" <|body_0|> def inorderTraversal2(self, root: TreeNode) -> List[int]: """思路:非递归, 使用辅助stack,push root.left 直到找到根节点 node,此时放入结果, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def inorderTraversal1(self, root: TreeNode) -> List[int]: """思路: 递归 1。 终止条件: root 为空 2。 返回值 [root.val] 3. level task: 左 + 根 + 右""" if not root: return [] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) return left ...
the_stack_v2_python_sparse
Week_02/inorder.py
NanZhang715/AlgorithmCHUNZHAO
train
0
766be83cc655ff0b53c0855b1d6f963f1da1f34b
[ "json_data = data()\ntry:\n parameter = loads(json_data)\nexcept ValueError:\n raise generate_http_error(400, 'ValueError', 'cannot decode json parameter dictionary')\ntry:\n bytes = parameter['bytes']\nexcept KeyError as exception:\n if exception.args[0] == 'type':\n raise generate_http_error(40...
<|body_start_0|> json_data = data() try: parameter = loads(json_data) except ValueError: raise generate_http_error(400, 'ValueError', 'cannot decode json parameter dictionary') try: bytes = parameter['bytes'] except KeyError as exception: ...
AccountLimit
GlobalAccountLimit
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GlobalAccountLimit: """AccountLimit""" def POST(self, account, rse_expression): """Create or update an account limit. HTTP Success: 201 Created HTTP Error: 400 Bad Request 401 Unauthorized 404 Not Found 500 Internal Error :param X-Rucio-Auth-Account: Account identifier. :param X-Ruci...
stack_v2_sparse_classes_36k_train_006647
7,903
permissive
[ { "docstring": "Create or update an account limit. HTTP Success: 201 Created HTTP Error: 400 Bad Request 401 Unauthorized 404 Not Found 500 Internal Error :param X-Rucio-Auth-Account: Account identifier. :param X-Rucio-Auth-Token: As an 32 character hex string. :param account: Account name. :param rse_expressio...
2
null
Implement the Python class `GlobalAccountLimit` described below. Class description: AccountLimit Method signatures and docstrings: - def POST(self, account, rse_expression): Create or update an account limit. HTTP Success: 201 Created HTTP Error: 400 Bad Request 401 Unauthorized 404 Not Found 500 Internal Error :para...
Implement the Python class `GlobalAccountLimit` described below. Class description: AccountLimit Method signatures and docstrings: - def POST(self, account, rse_expression): Create or update an account limit. HTTP Success: 201 Created HTTP Error: 400 Bad Request 401 Unauthorized 404 Not Found 500 Internal Error :para...
bf33d9441d3b4ff160a392eed56724f635a03fe6
<|skeleton|> class GlobalAccountLimit: """AccountLimit""" def POST(self, account, rse_expression): """Create or update an account limit. HTTP Success: 201 Created HTTP Error: 400 Bad Request 401 Unauthorized 404 Not Found 500 Internal Error :param X-Rucio-Auth-Account: Account identifier. :param X-Ruci...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GlobalAccountLimit: """AccountLimit""" def POST(self, account, rse_expression): """Create or update an account limit. HTTP Success: 201 Created HTTP Error: 400 Bad Request 401 Unauthorized 404 Not Found 500 Internal Error :param X-Rucio-Auth-Account: Account identifier. :param X-Rucio-Auth-Token:...
the_stack_v2_python_sparse
lib/rucio/web/rest/webpy/v1/account_limit.py
viveknigam3003/rucio
train
1
f2b5b652ce68aa1a4995c2e17f08c591db324878
[ "if not user_id or type(user_id) is not str:\n return None\nsession_id = str(uuid.uuid4())\nself.user_id_by_session_id[session_id] = user_id\nreturn session_id", "if not session_id or type(session_id) is not str:\n return None\nreturn self.user_id_by_session_id.get(session_id)", "session_id = self.session...
<|body_start_0|> if not user_id or type(user_id) is not str: return None session_id = str(uuid.uuid4()) self.user_id_by_session_id[session_id] = user_id return session_id <|end_body_0|> <|body_start_1|> if not session_id or type(session_id) is not str: re...
[summary] Args: Auth ([type]): [description]
SessionAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionAuth: """[summary] Args: Auth ([type]): [description]""" def create_session(self, user_id: str=None) -> str: """[summary] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description]""" <|body_0|> def user_id_for_session_id(self, ses...
stack_v2_sparse_classes_36k_train_006648
1,849
no_license
[ { "docstring": "[summary] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description]", "name": "create_session", "signature": "def create_session(self, user_id: str=None) -> str" }, { "docstring": "[summary] Args: session_id (str, optional): [description]. Defaul...
4
stack_v2_sparse_classes_30k_train_016047
Implement the Python class `SessionAuth` described below. Class description: [summary] Args: Auth ([type]): [description] Method signatures and docstrings: - def create_session(self, user_id: str=None) -> str: [summary] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description] - def ...
Implement the Python class `SessionAuth` described below. Class description: [summary] Args: Auth ([type]): [description] Method signatures and docstrings: - def create_session(self, user_id: str=None) -> str: [summary] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description] - def ...
55d35840c34ddd784dd37b69066a12577ff09247
<|skeleton|> class SessionAuth: """[summary] Args: Auth ([type]): [description]""" def create_session(self, user_id: str=None) -> str: """[summary] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description]""" <|body_0|> def user_id_for_session_id(self, ses...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionAuth: """[summary] Args: Auth ([type]): [description]""" def create_session(self, user_id: str=None) -> str: """[summary] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description]""" if not user_id or type(user_id) is not str: return No...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_auth.py
yacinekedidi/holbertonschool-web_back_end
train
0
4cfce08fe1704072db40910f9a2a4925956ccfdf
[ "super().__init__(name=name, metric=tf.metrics.Mean(name), model_selection_operator=model_selection_operator, logdir=logdir)\nself._inception_model = inception\nif 'softmax' not in self._inception_model.layers[-1].name.lower():\n self._inception_model = tf.keras.Sequential([self._inception_model, tf.keras.layers...
<|body_start_0|> super().__init__(name=name, metric=tf.metrics.Mean(name), model_selection_operator=model_selection_operator, logdir=logdir) self._inception_model = inception if 'softmax' not in self._inception_model.layers[-1].name.lower(): self._inception_model = tf.keras.Sequentia...
Inception Score Metric. This class is an implementation of the Inception Score technique for evaluating a GAN. See Improved Techniques for Training GANs [1]_. .. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498
InceptionScore
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InceptionScore: """Inception Score Metric. This class is an implementation of the Inception Score technique for evaluating a GAN. See Improved Techniques for Training GANs [1]_. .. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498""" def __init__(self, inception: tf....
stack_v2_sparse_classes_36k_train_006649
17,467
permissive
[ { "docstring": "Initialize the Metric. Args: inception (:py:class:`tf.keras.Model`): Keras Inception model. name (str): Name of the metric. model_selection_operator (:py:obj:`typing.Callable`): The operation that will be used when `model_selection` is triggered to compare the metrics, used by the `update_state`...
4
stack_v2_sparse_classes_30k_test_000395
Implement the Python class `InceptionScore` described below. Class description: Inception Score Metric. This class is an implementation of the Inception Score technique for evaluating a GAN. See Improved Techniques for Training GANs [1]_. .. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498 M...
Implement the Python class `InceptionScore` described below. Class description: Inception Score Metric. This class is an implementation of the Inception Score technique for evaluating a GAN. See Improved Techniques for Training GANs [1]_. .. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498 M...
92ac86fb0c962854e0d80c44165e0e7ff126b3c1
<|skeleton|> class InceptionScore: """Inception Score Metric. This class is an implementation of the Inception Score technique for evaluating a GAN. See Improved Techniques for Training GANs [1]_. .. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498""" def __init__(self, inception: tf....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InceptionScore: """Inception Score Metric. This class is an implementation of the Inception Score technique for evaluating a GAN. See Improved Techniques for Training GANs [1]_. .. [1] Improved Techniques for Training GANs https://arxiv.org/abs/1606.03498""" def __init__(self, inception: tf.keras.Model, ...
the_stack_v2_python_sparse
src/ashpy/metrics/gan.py
zurutech/ashpy
train
89
f3be0e187a009e1ad9bca6b2eee7b674b6b4a79b
[ "build = subprocess.run('docker build . -t arxiv/refextract', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=WORKDIR)\nif build.returncode != 0:\n raise RuntimeError('Failed to build image: %s' % build.stdout.decode('ascii'))\nprint('Built Docker image')\nstart = subprocess.run('docker run -d -p...
<|body_start_0|> build = subprocess.run('docker build . -t arxiv/refextract', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=WORKDIR) if build.returncode != 0: raise RuntimeError('Failed to build image: %s' % build.stdout.decode('ascii')) print('Built Docker image') ...
Build, run, and test the Dockerized RefExtract extractor.
TestRefExtractExtractor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRefExtractExtractor: """Build, run, and test the Dockerized RefExtract extractor.""" def setUpClass(cls): """Build the docker image and start it.""" <|body_0|> def tearDownClass(cls): """Tear down the container once all tests have run.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_006650
2,549
permissive
[ { "docstring": "Build the docker image and start it.", "name": "setUpClass", "signature": "def setUpClass(cls)" }, { "docstring": "Tear down the container once all tests have run.", "name": "tearDownClass", "signature": "def tearDownClass(cls)" }, { "docstring": "Pass a real arXi...
3
stack_v2_sparse_classes_30k_train_000985
Implement the Python class `TestRefExtractExtractor` described below. Class description: Build, run, and test the Dockerized RefExtract extractor. Method signatures and docstrings: - def setUpClass(cls): Build the docker image and start it. - def tearDownClass(cls): Tear down the container once all tests have run. - ...
Implement the Python class `TestRefExtractExtractor` described below. Class description: Build, run, and test the Dockerized RefExtract extractor. Method signatures and docstrings: - def setUpClass(cls): Build the docker image and start it. - def tearDownClass(cls): Tear down the container once all tests have run. - ...
a755aeaa864ff807ff16ae2c3960f9fee54d8dd8
<|skeleton|> class TestRefExtractExtractor: """Build, run, and test the Dockerized RefExtract extractor.""" def setUpClass(cls): """Build the docker image and start it.""" <|body_0|> def tearDownClass(cls): """Tear down the container once all tests have run.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestRefExtractExtractor: """Build, run, and test the Dockerized RefExtract extractor.""" def setUpClass(cls): """Build the docker image and start it.""" build = subprocess.run('docker build . -t arxiv/refextract', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=WORKDIR) ...
the_stack_v2_python_sparse
extractors/refextract/tests.py
arXiv/arxiv-references
train
8
4bf67507067c9a0156a304cfe91c78f3fbb404ff
[ "dim = len(paramRange)\ninitialPos = np.zeros((numParticles, dim))\nfor d in range(dim):\n low, high = paramRange[d]\n initialPos[:, d] = np.random.uniform(low, high, (numParticles,))\nreturn initialPos", "numParticles, dim = initialPos.shape\npos = initialPos.copy()\nvel = np.zeros(pos.shape)\nbestPos = in...
<|body_start_0|> dim = len(paramRange) initialPos = np.zeros((numParticles, dim)) for d in range(dim): low, high = paramRange[d] initialPos[:, d] = np.random.uniform(low, high, (numParticles,)) return initialPos <|end_body_0|> <|body_start_1|> numParticle...
Pso
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pso: def computeInitialPos(paramRange, numParticles): """Compute initial positions of particles by sampling for each component of each particle from the uniform distribution with end points specified for each component as an argument taken by this function. :param paramRange: list of 2-t...
stack_v2_sparse_classes_36k_train_006651
5,664
no_license
[ { "docstring": "Compute initial positions of particles by sampling for each component of each particle from the uniform distribution with end points specified for each component as an argument taken by this function. :param paramRange: list of 2-tuples (low, high) of length equal to the dimension of the paramet...
3
null
Implement the Python class `Pso` described below. Class description: Implement the Pso class. Method signatures and docstrings: - def computeInitialPos(paramRange, numParticles): Compute initial positions of particles by sampling for each component of each particle from the uniform distribution with end points specif...
Implement the Python class `Pso` described below. Class description: Implement the Pso class. Method signatures and docstrings: - def computeInitialPos(paramRange, numParticles): Compute initial positions of particles by sampling for each component of each particle from the uniform distribution with end points specif...
62f6fa0d5e832d2d1786eae729d9462b78d9b459
<|skeleton|> class Pso: def computeInitialPos(paramRange, numParticles): """Compute initial positions of particles by sampling for each component of each particle from the uniform distribution with end points specified for each component as an argument taken by this function. :param paramRange: list of 2-t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Pso: def computeInitialPos(paramRange, numParticles): """Compute initial positions of particles by sampling for each component of each particle from the uniform distribution with end points specified for each component as an argument taken by this function. :param paramRange: list of 2-tuples (low, hi...
the_stack_v2_python_sparse
ts/experimental/pso.py
tedlaw09/time_series_forecaster
train
1
62b33bf62ce4d87ded30504248ac66f7871778a0
[ "if namespace is None:\n self.use_main_ns = 1\nelse:\n self.use_main_ns = 0\n self.namespace = namespace\nif global_namespace is None:\n self.global_namespace = {}\nelse:\n self.global_namespace = global_namespace", "if self.use_main_ns:\n raise RuntimeError('Namespace must be provided!')\nif '....
<|body_start_0|> if namespace is None: self.use_main_ns = 1 else: self.use_main_ns = 0 self.namespace = namespace if global_namespace is None: self.global_namespace = {} else: self.global_namespace = global_namespace <|end_body_...
Completer
[ "EPL-1.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Completer: def __init__(self, namespace=None, global_namespace=None): """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__...
stack_v2_sparse_classes_36k_train_006652
6,762
permissive
[ { "docstring": "Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. An optional second namespace...
4
stack_v2_sparse_classes_30k_train_008931
Implement the Python class `Completer` described below. Class description: Implement the Completer class. Method signatures and docstrings: - def __init__(self, namespace=None, global_namespace=None): Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspec...
Implement the Python class `Completer` described below. Class description: Implement the Completer class. Method signatures and docstrings: - def __init__(self, namespace=None, global_namespace=None): Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspec...
05dbd4575d01a213f3f4d69aa4968473f2536142
<|skeleton|> class Completer: def __init__(self, namespace=None, global_namespace=None): """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Completer: def __init__(self, namespace=None, global_namespace=None): """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Names...
the_stack_v2_python_sparse
python/helpers/pydev/_pydev_bundle/_pydev_completer.py
JetBrains/intellij-community
train
16,288
d9448c1e87b0a5cbd5d97c6e7db1c247b9e5ef2a
[ "new_data = self._get_map_class_instance()\nif data is not None:\n for identity, value in data.items():\n new_data[identity] = self._create_child(self.TYPE, identity, value)\nself._data = new_data", "data = self._get_map_class_instance()\nfor key, value in self._data.items():\n if isinstance(value, F...
<|body_start_0|> new_data = self._get_map_class_instance() if data is not None: for identity, value in data.items(): new_data[identity] = self._create_child(self.TYPE, identity, value) self._data = new_data <|end_body_0|> <|body_start_1|> data = self._get_map...
Key Based Dictionary, where each item is of same type
KeyBasedListNode
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeyBasedListNode: """Key Based Dictionary, where each item is of same type""" def _set_data(self, data): """Set data for this object""" <|body_0|> def _get_data(self): """Get data""" <|body_1|> <|end_skeleton|> <|body_start_0|> new_data = self._...
stack_v2_sparse_classes_36k_train_006653
1,806
permissive
[ { "docstring": "Set data for this object", "name": "_set_data", "signature": "def _set_data(self, data)" }, { "docstring": "Get data", "name": "_get_data", "signature": "def _get_data(self)" } ]
2
stack_v2_sparse_classes_30k_train_019755
Implement the Python class `KeyBasedListNode` described below. Class description: Key Based Dictionary, where each item is of same type Method signatures and docstrings: - def _set_data(self, data): Set data for this object - def _get_data(self): Get data
Implement the Python class `KeyBasedListNode` described below. Class description: Key Based Dictionary, where each item is of same type Method signatures and docstrings: - def _set_data(self, data): Set data for this object - def _get_data(self): Get data <|skeleton|> class KeyBasedListNode: """Key Based Diction...
07f22780bcd8f06cb70431e85731c9743849c7d8
<|skeleton|> class KeyBasedListNode: """Key Based Dictionary, where each item is of same type""" def _set_data(self, data): """Set data for this object""" <|body_0|> def _get_data(self): """Get data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeyBasedListNode: """Key Based Dictionary, where each item is of same type""" def _set_data(self, data): """Set data for this object""" new_data = self._get_map_class_instance() if data is not None: for identity, value in data.items(): new_data[identity...
the_stack_v2_python_sparse
src/quick_scheme/nodes/key_based_list.py
mlasevich/QuickScheme
train
0
28b2e566f576a94370d8cb66b594a850c122ff39
[ "self.lower_wave = lower_wave\nself.upper_wave = upper_wave\nself.window_width = window_width\nTes.__init__(self, lower_temp, upper_temp)", "sam_radiance = measurement.sam.data.average_spectrum\nif measurement.dwr is None:\n dwr_radiance = np.zeros(len(sam_radiance))\nelse:\n dwr_radiance = measurement.dwr....
<|body_start_0|> self.lower_wave = lower_wave self.upper_wave = upper_wave self.window_width = window_width Tes.__init__(self, lower_temp, upper_temp) <|end_body_0|> <|body_start_1|> sam_radiance = measurement.sam.data.average_spectrum if measurement.dwr is None: ...
A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving window.
MovingWindow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovingWindow: """A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving...
stack_v2_sparse_classes_36k_train_006654
3,029
no_license
[ { "docstring": "MovingWindow instance constructor. Calls constructor for super class. Arguments: lower_temp - The minimum temperature in the range to be tested. upper_temp - The maximum temperature in the range to be tested. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper ...
2
stack_v2_sparse_classes_30k_train_010208
Implement the Python class `MovingWindow` described below. Class description: A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined....
Implement the Python class `MovingWindow` described below. Class description: A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined....
743167940f700374755ea273b90da66befae1ba4
<|skeleton|> class MovingWindow: """A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovingWindow: """A class that represents a moving window temperature emissivity separation object. Attributes: Inherited from Tes. lower_wave - The lower wavelength of the window being examined. upper_wave - The upper wavelength of the window being examined. window_width - The width of the moving window.""" ...
the_stack_v2_python_sparse
tes/models/tes_models/moving_window.py
max19951001/TES
train
0
7557204b340501465e6cd6bd1ff513a21b1091df
[ "if self.validate_data():\n try:\n open(self.name, 'wb').write(lxml.etree.tostring(self.xdata, pretty_print=True))\n return True\n except IOError:\n err = sys.exc_info()[1]\n logger.error('Failed to write %s: %s' % (self.name, err))\n return False\nelse:\n return False", ...
<|body_start_0|> if self.validate_data(): try: open(self.name, 'wb').write(lxml.etree.tostring(self.xdata, pretty_print=True)) return True except IOError: err = sys.exc_info()[1] logger.error('Failed to write %s: %s' % (self...
Class for properties files.
PropertyFile
[ "mpich2", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PropertyFile: """Class for properties files.""" def write(self): """Write the data in this data structure back to the property file""" <|body_0|> def validate_data(self): """ensure that the data in this object validates against the XML schema for this property fi...
stack_v2_sparse_classes_36k_train_006655
2,503
permissive
[ { "docstring": "Write the data in this data structure back to the property file", "name": "write", "signature": "def write(self)" }, { "docstring": "ensure that the data in this object validates against the XML schema for this property file (if a schema exists)", "name": "validate_data", ...
2
stack_v2_sparse_classes_30k_train_009213
Implement the Python class `PropertyFile` described below. Class description: Class for properties files. Method signatures and docstrings: - def write(self): Write the data in this data structure back to the property file - def validate_data(self): ensure that the data in this object validates against the XML schema...
Implement the Python class `PropertyFile` described below. Class description: Class for properties files. Method signatures and docstrings: - def write(self): Write the data in this data structure back to the property file - def validate_data(self): ensure that the data in this object validates against the XML schema...
826f385767ccf9f608fcfbe35e381a9dbc59db4b
<|skeleton|> class PropertyFile: """Class for properties files.""" def write(self): """Write the data in this data structure back to the property file""" <|body_0|> def validate_data(self): """ensure that the data in this object validates against the XML schema for this property fi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PropertyFile: """Class for properties files.""" def write(self): """Write the data in this data structure back to the property file""" if self.validate_data(): try: open(self.name, 'wb').write(lxml.etree.tostring(self.xdata, pretty_print=True)) ...
the_stack_v2_python_sparse
src/lib/Server/Plugins/Properties.py
mikemccllstr/bcfg2
train
1
cbbc7585c8bf00d3a1203d27c048a561e94a914d
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserRegistrationFeatureSummary()", "from .included_user_roles import IncludedUserRoles\nfrom .included_user_types import IncludedUserTypes\nfrom .user_registration_feature_count import UserRegistrationFeatureCount\nfrom .included_user_...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UserRegistrationFeatureSummary() <|end_body_0|> <|body_start_1|> from .included_user_roles import IncludedUserRoles from .included_user_types import IncludedUserTypes from .user_...
UserRegistrationFeatureSummary
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserRegistrationFeatureSummary: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationFeatureSummary: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v...
stack_v2_sparse_classes_36k_train_006656
4,327
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: UserRegistrationFeatureSummary", "name": "create_from_discriminator_value", "signature": "def create_from_di...
3
stack_v2_sparse_classes_30k_train_012094
Implement the Python class `UserRegistrationFeatureSummary` described below. Class description: Implement the UserRegistrationFeatureSummary class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationFeatureSummary: Creates a new instance of...
Implement the Python class `UserRegistrationFeatureSummary` described below. Class description: Implement the UserRegistrationFeatureSummary class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationFeatureSummary: Creates a new instance of...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UserRegistrationFeatureSummary: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationFeatureSummary: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserRegistrationFeatureSummary: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserRegistrationFeatureSummary: """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 creat...
the_stack_v2_python_sparse
msgraph/generated/models/user_registration_feature_summary.py
microsoftgraph/msgraph-sdk-python
train
135
3230f756a38bccd057ea74789406edeb20cf5342
[ "Node_wifi.__init__(self, name, **params)\nself.dpid = self.defaultDpid(dpid)\nself.opts = opts\nself.listenPort = listenPort\nif not self.inNamespace:\n self.controlIntf = Intf('lo', self, port=0)", "if dpid:\n dpid = dpid.replace(':', '')\n assert len(dpid) <= self.dpidLen and int(dpid, 16) >= 0\n r...
<|body_start_0|> Node_wifi.__init__(self, name, **params) self.dpid = self.defaultDpid(dpid) self.opts = opts self.listenPort = listenPort if not self.inNamespace: self.controlIntf = Intf('lo', self, port=0) <|end_body_0|> <|body_start_1|> if dpid: ...
A Switch is a Node that is running (or has execed?) an OpenFlow switch.
AP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AP: """A Switch is a Node that is running (or has execed?) an OpenFlow switch.""" def __init__(self, name, dpid=None, opts='', listenPort=None, **params): """dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opts: additional switch options listenPort: port to listen o...
stack_v2_sparse_classes_36k_train_006657
43,437
no_license
[ { "docstring": "dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opts: additional switch options listenPort: port to listen on for dpctl connections", "name": "__init__", "signature": "def __init__(self, name, dpid=None, opts='', listenPort=None, **params)" }, { "docstring": "Re...
2
stack_v2_sparse_classes_30k_train_013580
Implement the Python class `AP` described below. Class description: A Switch is a Node that is running (or has execed?) an OpenFlow switch. Method signatures and docstrings: - def __init__(self, name, dpid=None, opts='', listenPort=None, **params): dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opt...
Implement the Python class `AP` described below. Class description: A Switch is a Node that is running (or has execed?) an OpenFlow switch. Method signatures and docstrings: - def __init__(self, name, dpid=None, opts='', listenPort=None, **params): dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opt...
ceda976159f36e78d54657ce651494bf3088b5a1
<|skeleton|> class AP: """A Switch is a Node that is running (or has execed?) an OpenFlow switch.""" def __init__(self, name, dpid=None, opts='', listenPort=None, **params): """dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opts: additional switch options listenPort: port to listen o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AP: """A Switch is a Node that is running (or has execed?) an OpenFlow switch.""" def __init__(self, name, dpid=None, opts='', listenPort=None, **params): """dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opts: additional switch options listenPort: port to listen on for dpctl c...
the_stack_v2_python_sparse
node.py
sharath-maligera/sdn-tactical-network
train
3
6f9cfaca5979ec78138348407f71106617c4e796
[ "form = super().get_form(*args, **kwargs)\nform.fields['when'].widget.widgets[0].attrs = {'placeholder': f'Start Date and Time (YYYY-MM-DD HH:MM). Time zone is {settings.TIME_ZONE}.'}\nform.fields['when'].widget.widgets[1].attrs = {'placeholder': f'End Date and Time (YYYY-MM-DD HH:MM). Time zone is {settings.TIME_Z...
<|body_start_0|> form = super().get_form(*args, **kwargs) form.fields['when'].widget.widgets[0].attrs = {'placeholder': f'Start Date and Time (YYYY-MM-DD HH:MM). Time zone is {settings.TIME_ZONE}.'} form.fields['when'].widget.widgets[1].attrs = {'placeholder': f'End Date and Time (YYYY-MM-DD HH:...
A mixin with the stuff shared between EventSession{Create|Update}View
EventSessionFormViewMixin
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventSessionFormViewMixin: """A mixin with the stuff shared between EventSession{Create|Update}View""" def get_form(self, *args, **kwargs): """The default range widgets are a bit shit because they eat the help_text and have no indication of which field is for what. So we add a nice p...
stack_v2_sparse_classes_36k_train_006658
33,145
permissive
[ { "docstring": "The default range widgets are a bit shit because they eat the help_text and have no indication of which field is for what. So we add a nice placeholder. We also limit the event_location dropdown to only the current camps locations.", "name": "get_form", "signature": "def get_form(self, *...
2
stack_v2_sparse_classes_30k_train_016311
Implement the Python class `EventSessionFormViewMixin` described below. Class description: A mixin with the stuff shared between EventSession{Create|Update}View Method signatures and docstrings: - def get_form(self, *args, **kwargs): The default range widgets are a bit shit because they eat the help_text and have no ...
Implement the Python class `EventSessionFormViewMixin` described below. Class description: A mixin with the stuff shared between EventSession{Create|Update}View Method signatures and docstrings: - def get_form(self, *args, **kwargs): The default range widgets are a bit shit because they eat the help_text and have no ...
767deb7f58429e9162e0c2ef79be9f0f38f37ce1
<|skeleton|> class EventSessionFormViewMixin: """A mixin with the stuff shared between EventSession{Create|Update}View""" def get_form(self, *args, **kwargs): """The default range widgets are a bit shit because they eat the help_text and have no indication of which field is for what. So we add a nice p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EventSessionFormViewMixin: """A mixin with the stuff shared between EventSession{Create|Update}View""" def get_form(self, *args, **kwargs): """The default range widgets are a bit shit because they eat the help_text and have no indication of which field is for what. So we add a nice placeholder. W...
the_stack_v2_python_sparse
src/backoffice/views/program.py
bornhack/bornhack-website
train
9
a8996882ee32746b04d1fcc48eade03a1e647e4a
[ "if not isinstance(qubic, QubicAcquisition):\n raise TypeError('The first argument is not a QubicAcquisition.')\nif not isinstance(planck, PlanckAcquisition):\n raise TypeError('The second argument is not a PlanckAcquisition.')\nif qubic.scene is not planck.scene:\n raise ValueError('The Qubic and Planck s...
<|body_start_0|> if not isinstance(qubic, QubicAcquisition): raise TypeError('The first argument is not a QubicAcquisition.') if not isinstance(planck, PlanckAcquisition): raise TypeError('The second argument is not a PlanckAcquisition.') if qubic.scene is not planck.scen...
The QubicPlanckAcquisition class, which combines the Qubic and Planck acquisitions.
QubicPlanckAcquisition
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QubicPlanckAcquisition: """The QubicPlanckAcquisition class, which combines the Qubic and Planck acquisitions.""" def __init__(self, qubic, planck): """acq = QubicPlanckAcquisition(qubic_acquisition, planck_acquisition) Parameters ---------- qubic_acquisition : QubicAcquisition The Q...
stack_v2_sparse_classes_36k_train_006659
25,169
no_license
[ { "docstring": "acq = QubicPlanckAcquisition(qubic_acquisition, planck_acquisition) Parameters ---------- qubic_acquisition : QubicAcquisition The QUBIC acquisition. planck_acquisition : PlanckAcquisition The Planck acquisition.", "name": "__init__", "signature": "def __init__(self, qubic, planck)" },...
5
stack_v2_sparse_classes_30k_train_003705
Implement the Python class `QubicPlanckAcquisition` described below. Class description: The QubicPlanckAcquisition class, which combines the Qubic and Planck acquisitions. Method signatures and docstrings: - def __init__(self, qubic, planck): acq = QubicPlanckAcquisition(qubic_acquisition, planck_acquisition) Paramet...
Implement the Python class `QubicPlanckAcquisition` described below. Class description: The QubicPlanckAcquisition class, which combines the Qubic and Planck acquisitions. Method signatures and docstrings: - def __init__(self, qubic, planck): acq = QubicPlanckAcquisition(qubic_acquisition, planck_acquisition) Paramet...
cb9bb4493da5ce5427f33583025bc0e32291177e
<|skeleton|> class QubicPlanckAcquisition: """The QubicPlanckAcquisition class, which combines the Qubic and Planck acquisitions.""" def __init__(self, qubic, planck): """acq = QubicPlanckAcquisition(qubic_acquisition, planck_acquisition) Parameters ---------- qubic_acquisition : QubicAcquisition The Q...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QubicPlanckAcquisition: """The QubicPlanckAcquisition class, which combines the Qubic and Planck acquisitions.""" def __init__(self, qubic, planck): """acq = QubicPlanckAcquisition(qubic_acquisition, planck_acquisition) Parameters ---------- qubic_acquisition : QubicAcquisition The QUBIC acquisit...
the_stack_v2_python_sparse
qubic/acquisition.py
qubicsoft/qubic
train
14
47af6e5404cd7d963724cf11f1ba456313a8e394
[ "del kwargs\ndel calling_context\ninstance_dict = self._get_instance_dict(context)\nfor coil, s in settings.items():\n s = deepcopy(s)\n if not isinstance(coil, Driver):\n self.raise_config_error('Invalid coil name {}'.format(coil), 2, context=context)\n action = s.pop('action')\n try:\n d...
<|body_start_0|> del kwargs del calling_context instance_dict = self._get_instance_dict(context) for coil, s in settings.items(): s = deepcopy(s) if not isinstance(coil, Driver): self.raise_config_error('Invalid coil name {}'.format(coil), 2, conte...
Triggers coils based on config.
CoilPlayer
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoilPlayer: """Triggers coils based on config.""" def play(self, settings, context: str, calling_context: str, priority: int=0, **kwargs): """Enable, Pulse or disable coils.""" <|body_0|> def clear_context(self, context): """Disable enabled coils.""" <|bo...
stack_v2_sparse_classes_36k_train_006660
2,344
permissive
[ { "docstring": "Enable, Pulse or disable coils.", "name": "play", "signature": "def play(self, settings, context: str, calling_context: str, priority: int=0, **kwargs)" }, { "docstring": "Disable enabled coils.", "name": "clear_context", "signature": "def clear_context(self, context)" ...
3
null
Implement the Python class `CoilPlayer` described below. Class description: Triggers coils based on config. Method signatures and docstrings: - def play(self, settings, context: str, calling_context: str, priority: int=0, **kwargs): Enable, Pulse or disable coils. - def clear_context(self, context): Disable enabled c...
Implement the Python class `CoilPlayer` described below. Class description: Triggers coils based on config. Method signatures and docstrings: - def play(self, settings, context: str, calling_context: str, priority: int=0, **kwargs): Enable, Pulse or disable coils. - def clear_context(self, context): Disable enabled c...
9f90c8b1586363b65340017bfa3af5d56d32c6d9
<|skeleton|> class CoilPlayer: """Triggers coils based on config.""" def play(self, settings, context: str, calling_context: str, priority: int=0, **kwargs): """Enable, Pulse or disable coils.""" <|body_0|> def clear_context(self, context): """Disable enabled coils.""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CoilPlayer: """Triggers coils based on config.""" def play(self, settings, context: str, calling_context: str, priority: int=0, **kwargs): """Enable, Pulse or disable coils.""" del kwargs del calling_context instance_dict = self._get_instance_dict(context) for coil...
the_stack_v2_python_sparse
mpf/config_players/coil_player.py
missionpinball/mpf
train
191
fd1ecefba19f4e1864f000c945f919af09fb4d82
[ "if root is None:\n return struct.pack('i', 0)\nl = self.serialize(root.left)\nr = self.serialize(root.right)\nreturn struct.pack('i', len(l)) + struct.pack('i', root.val) + l + r", "len_l = struct.unpack('i', data[:4])[0]\nif len_l == 0:\n return None\ndata = data[4:]\nval = struct.unpack('i', data[:4])[0]...
<|body_start_0|> if root is None: return struct.pack('i', 0) l = self.serialize(root.left) r = self.serialize(root.right) return struct.pack('i', len(l)) + struct.pack('i', root.val) + l + r <|end_body_0|> <|body_start_1|> len_l = struct.unpack('i', data[:4])[0] ...
Codec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_006661
1,877
permissive
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
6095842ffe007a12ec8c2093850515aa4e046616
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if root is None: return struct.pack('i', 0) l = self.serialize(root.left) r = self.serialize(root.right) return struct.pack('i', len(l)) + struct.pack...
the_stack_v2_python_sparse
leetcode/serialize-and-deserialize-binary-tree/solution.py
mmcloughlin/problems
train
11
3db7feb1de79faab52114f4bd7c60039622595ab
[ "cpu_state_proto = cpu_state_pb2.ArmV7mCpuState()\ncpu_state_proto.pc = 3752712550\ncpu_state_proto.mmfar = 2939070858\ncpu_state_proto.r0 = 4088542641\ncpu_state_info = exception_analyzer.CortexMExceptionAnalyzer(cpu_state_proto)\nexpected_dump = '\\n'.join(('pc 0xdfadd966', 'mmfar 0xaf2ea98a', 'r0 ...
<|body_start_0|> cpu_state_proto = cpu_state_pb2.ArmV7mCpuState() cpu_state_proto.pc = 3752712550 cpu_state_proto.mmfar = 2939070858 cpu_state_proto.r0 = 4088542641 cpu_state_info = exception_analyzer.CortexMExceptionAnalyzer(cpu_state_proto) expected_dump = '\n'.join(('p...
Test larger state dumps.
TextDumpTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextDumpTest: """Test larger state dumps.""" def test_registers(self): """Validate output of general register dumps.""" <|body_0|> def test_dump_no_cfsr(self): """Validate basic CPU state dump.""" <|body_1|> def test_dump_with_cfsr(self): """...
stack_v2_sparse_classes_36k_train_006662
9,689
permissive
[ { "docstring": "Validate output of general register dumps.", "name": "test_registers", "signature": "def test_registers(self)" }, { "docstring": "Validate basic CPU state dump.", "name": "test_dump_no_cfsr", "signature": "def test_dump_no_cfsr(self)" }, { "docstring": "Validate C...
3
stack_v2_sparse_classes_30k_train_019067
Implement the Python class `TextDumpTest` described below. Class description: Test larger state dumps. Method signatures and docstrings: - def test_registers(self): Validate output of general register dumps. - def test_dump_no_cfsr(self): Validate basic CPU state dump. - def test_dump_with_cfsr(self): Validate CPU st...
Implement the Python class `TextDumpTest` described below. Class description: Test larger state dumps. Method signatures and docstrings: - def test_registers(self): Validate output of general register dumps. - def test_dump_no_cfsr(self): Validate basic CPU state dump. - def test_dump_with_cfsr(self): Validate CPU st...
7f3590b58e8398aad68c1e59702c459d2f8ca38e
<|skeleton|> class TextDumpTest: """Test larger state dumps.""" def test_registers(self): """Validate output of general register dumps.""" <|body_0|> def test_dump_no_cfsr(self): """Validate basic CPU state dump.""" <|body_1|> def test_dump_with_cfsr(self): """...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextDumpTest: """Test larger state dumps.""" def test_registers(self): """Validate output of general register dumps.""" cpu_state_proto = cpu_state_pb2.ArmV7mCpuState() cpu_state_proto.pc = 3752712550 cpu_state_proto.mmfar = 2939070858 cpu_state_proto.r0 = 40885426...
the_stack_v2_python_sparse
pw_cpu_exception_cortex_m/py/exception_analyzer_test.py
waelbarakat/pigweed
train
0
1ab7dcae5997e06b05eecfc318af2c4b1b7d72dd
[ "old_pypath = os.environ.get('PYTHONPATH', '')\nif not old_pypath:\n pypath = python_path\nelif python_path in old_pypath:\n pypath = old_pypath\nelse:\n pypath = old_pypath + ':' + python_path\nos.environ['PYTHONPATH'] = pypath\nself.dataflow_hook = dataflow_hook\nsuper().__init__(**kwargs)", "bucket_he...
<|body_start_0|> old_pypath = os.environ.get('PYTHONPATH', '') if not old_pypath: pypath = python_path elif python_path in old_pypath: pypath = old_pypath else: pypath = old_pypath + ':' + python_path os.environ['PYTHONPATH'] = pypath s...
A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3.
DataFlowPythonOperator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataFlowPythonOperator: """A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3.""" def __init__(self, python_path='', dataflow_hook=None, **kwargs): """Const...
stack_v2_sparse_classes_36k_train_006663
3,015
permissive
[ { "docstring": "Constructor. Args: python_path: Set PYTHONPATH to include this path before calling DataFlow. dataflow_hook: The DataFlow hook to use. If none, will automatically create. **kwargs: Additional args for super class.", "name": "__init__", "signature": "def __init__(self, python_path='', data...
2
stack_v2_sparse_classes_30k_train_011737
Implement the Python class `DataFlowPythonOperator` described below. Class description: A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3. Method signatures and docstrings: - def __init__(s...
Implement the Python class `DataFlowPythonOperator` described below. Class description: A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3. Method signatures and docstrings: - def __init__(s...
29b40262cf0bb5ef39b91765a074fe76fc2c8e03
<|skeleton|> class DataFlowPythonOperator: """A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3.""" def __init__(self, python_path='', dataflow_hook=None, **kwargs): """Const...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataFlowPythonOperator: """A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3.""" def __init__(self, python_path='', dataflow_hook=None, **kwargs): """Constructor. Args:...
the_stack_v2_python_sparse
contrib/plugins/operators/dataflow_py3_operator.py
Ressmann/driblet
train
0
36734cf3c512acf2f182a9646fa3739df805df66
[ "super().__init__(mt_constant, infinite_consuming=infinite_consuming, prefetch_count=prefetch_count)\nself.mt_endpoint = get_command(mt_constant)\nself.channel = get_channel_from_connection(self.connection)\nself.consume_schema_types = get_schema_types_from_file(mt_constant['command_json_file'])\nself.event_publish...
<|body_start_0|> super().__init__(mt_constant, infinite_consuming=infinite_consuming, prefetch_count=prefetch_count) self.mt_endpoint = get_command(mt_constant) self.channel = get_channel_from_connection(self.connection) self.consume_schema_types = get_schema_types_from_file(mt_constant[...
Class for simplifying consume message from MassTransit (MT) to Python, and send back event message
MTConsumer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MTConsumer: """Class for simplifying consume message from MassTransit (MT) to Python, and send back event message""" def __init__(self, mt_constant, infinite_consuming=False, prefetch_count=1): """Method for define all needed for consuming variables. :param mt_constant: dict with emu...
stack_v2_sparse_classes_36k_train_006664
14,450
permissive
[ { "docstring": "Method for define all needed for consuming variables. :param mt_constant: dict with emulation of MT interfaces", "name": "__init__", "signature": "def __init__(self, mt_constant, infinite_consuming=False, prefetch_count=1)" }, { "docstring": "Method which add event sender wrapper...
2
stack_v2_sparse_classes_30k_train_005056
Implement the Python class `MTConsumer` described below. Class description: Class for simplifying consume message from MassTransit (MT) to Python, and send back event message Method signatures and docstrings: - def __init__(self, mt_constant, infinite_consuming=False, prefetch_count=1): Method for define all needed f...
Implement the Python class `MTConsumer` described below. Class description: Class for simplifying consume message from MassTransit (MT) to Python, and send back event message Method signatures and docstrings: - def __init__(self, mt_constant, infinite_consuming=False, prefetch_count=1): Method for define all needed f...
0c9beacc4a98c3f55ed56969a8b7eb84c4209c21
<|skeleton|> class MTConsumer: """Class for simplifying consume message from MassTransit (MT) to Python, and send back event message""" def __init__(self, mt_constant, infinite_consuming=False, prefetch_count=1): """Method for define all needed for consuming variables. :param mt_constant: dict with emu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MTConsumer: """Class for simplifying consume message from MassTransit (MT) to Python, and send back event message""" def __init__(self, mt_constant, infinite_consuming=False, prefetch_count=1): """Method for define all needed for consuming variables. :param mt_constant: dict with emulation of MT ...
the_stack_v2_python_sparse
Source/sds_tools/mass_transit/MTMessageProcessor.py
ArqiSoft/ml-services
train
0
c32362a237de3cc389f85c7ae5e004c2bdb102fb
[ "super(mesh_to_mesh_petsc_dmda, self).__init__(fine_prob, coarse_prob, params)\nself.interp, _ = self.coarse_prob.init.createInterpolation(self.fine_prob.init)\nself.inject = self.coarse_prob.init.createInjection(self.fine_prob.init)", "if isinstance(F, petsc_vec):\n u_coarse = self.coarse_prob.dtype_u(self.co...
<|body_start_0|> super(mesh_to_mesh_petsc_dmda, self).__init__(fine_prob, coarse_prob, params) self.interp, _ = self.coarse_prob.init.createInterpolation(self.fine_prob.init) self.inject = self.coarse_prob.init.createInjection(self.fine_prob.init) <|end_body_0|> <|body_start_1|> if isin...
This implementation can restrict and prolong between PETSc DMDA grids
mesh_to_mesh_petsc_dmda
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class mesh_to_mesh_petsc_dmda: """This implementation can restrict and prolong between PETSc DMDA grids""" def __init__(self, fine_prob, coarse_prob, params): """Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators""...
stack_v2_sparse_classes_36k_train_006665
2,871
permissive
[ { "docstring": "Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators", "name": "__init__", "signature": "def __init__(self, fine_prob, coarse_prob, params)" }, { "docstring": "Restriction implementation Args: F: the fine l...
3
stack_v2_sparse_classes_30k_train_011904
Implement the Python class `mesh_to_mesh_petsc_dmda` described below. Class description: This implementation can restrict and prolong between PETSc DMDA grids Method signatures and docstrings: - def __init__(self, fine_prob, coarse_prob, params): Initialization routine Args: fine_prob: fine problem coarse_prob: coars...
Implement the Python class `mesh_to_mesh_petsc_dmda` described below. Class description: This implementation can restrict and prolong between PETSc DMDA grids Method signatures and docstrings: - def __init__(self, fine_prob, coarse_prob, params): Initialization routine Args: fine_prob: fine problem coarse_prob: coars...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class mesh_to_mesh_petsc_dmda: """This implementation can restrict and prolong between PETSc DMDA grids""" def __init__(self, fine_prob, coarse_prob, params): """Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class mesh_to_mesh_petsc_dmda: """This implementation can restrict and prolong between PETSc DMDA grids""" def __init__(self, fine_prob, coarse_prob, params): """Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators""" sup...
the_stack_v2_python_sparse
pySDC/implementations/transfer_classes/TransferPETScDMDA.py
Parallel-in-Time/pySDC
train
30
f331fc0a96e7748ba2b94549fc566f1452197cc7
[ "self.gradX, self.gradY, self.gradZ = gradient(self.interpModel)\nself.gradX /= self.dx\nself.gradY /= self.dy\nself.gradZ /= self.dz\nself.interpModel = ndimage.spline_filter(self.interpModel).astype('f')\nself.gradX = ndimage.spline_filter(self.gradX).astype('f')\nself.gradY = ndimage.spline_filter(self.gradY).as...
<|body_start_0|> self.gradX, self.gradY, self.gradZ = gradient(self.interpModel) self.gradX /= self.dx self.gradY /= self.dy self.gradZ /= self.dz self.interpModel = ndimage.spline_filter(self.interpModel).astype('f') self.gradX = ndimage.spline_filter(self.gradX).astype(...
CSInterpolator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CSInterpolator: def _precompute(self): """function which is called after model loading and can be overridden to allow for interpolation specific precomputations""" <|body_0|> def interp(self, X, Y, Z): """do actual interpolation at values given""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_006666
4,744
no_license
[ { "docstring": "function which is called after model loading and can be overridden to allow for interpolation specific precomputations", "name": "_precompute", "signature": "def _precompute(self)" }, { "docstring": "do actual interpolation at values given", "name": "interp", "signature":...
4
null
Implement the Python class `CSInterpolator` described below. Class description: Implement the CSInterpolator class. Method signatures and docstrings: - def _precompute(self): function which is called after model loading and can be overridden to allow for interpolation specific precomputations - def interp(self, X, Y,...
Implement the Python class `CSInterpolator` described below. Class description: Implement the CSInterpolator class. Method signatures and docstrings: - def _precompute(self): function which is called after model loading and can be overridden to allow for interpolation specific precomputations - def interp(self, X, Y,...
6596167034c727ad7dad0a741dd59e0e48f6852a
<|skeleton|> class CSInterpolator: def _precompute(self): """function which is called after model loading and can be overridden to allow for interpolation specific precomputations""" <|body_0|> def interp(self, X, Y, Z): """do actual interpolation at values given""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CSInterpolator: def _precompute(self): """function which is called after model loading and can be overridden to allow for interpolation specific precomputations""" self.gradX, self.gradY, self.gradZ = gradient(self.interpModel) self.gradX /= self.dx self.gradY /= self.dy ...
the_stack_v2_python_sparse
PYME/Analysis/FitFactories/Interpolators/CSInterpolator.py
WilliamRo/CLipPYME
train
3
6822781ca36c3c9b4770cd8d01325c30b46199be
[ "cities = City.objects.all()\nserializer = CitySerializer(cities, many=True, context={'request': request})\nreturn Response(serializer.data)", "city = City()\ncity.name = request.data['name']\ncountry = Country.objects.get(pk=request.data['country'])\ncity.country = country\ntry:\n city.save()\n serializer ...
<|body_start_0|> cities = City.objects.all() serializer = CitySerializer(cities, many=True, context={'request': request}) return Response(serializer.data) <|end_body_0|> <|body_start_1|> city = City() city.name = request.data['name'] country = Country.objects.get(pk=requ...
Blessipe city viewset
CityView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CityView: """Blessipe city viewset""" def list(self, request): """Handle GET requests to cities resource Returns: Response -- JSON serialized list of cities""" <|body_0|> def create(self, request): """Handle POST operations Returns: Response -- JSON serialized ci...
stack_v2_sparse_classes_36k_train_006667
4,616
no_license
[ { "docstring": "Handle GET requests to cities resource Returns: Response -- JSON serialized list of cities", "name": "list", "signature": "def list(self, request)" }, { "docstring": "Handle POST operations Returns: Response -- JSON serialized city instance", "name": "create", "signature"...
5
stack_v2_sparse_classes_30k_train_020727
Implement the Python class `CityView` described below. Class description: Blessipe city viewset Method signatures and docstrings: - def list(self, request): Handle GET requests to cities resource Returns: Response -- JSON serialized list of cities - def create(self, request): Handle POST operations Returns: Response ...
Implement the Python class `CityView` described below. Class description: Blessipe city viewset Method signatures and docstrings: - def list(self, request): Handle GET requests to cities resource Returns: Response -- JSON serialized list of cities - def create(self, request): Handle POST operations Returns: Response ...
c32f40f862cb06354d9f987d79e199faa239d3c5
<|skeleton|> class CityView: """Blessipe city viewset""" def list(self, request): """Handle GET requests to cities resource Returns: Response -- JSON serialized list of cities""" <|body_0|> def create(self, request): """Handle POST operations Returns: Response -- JSON serialized ci...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CityView: """Blessipe city viewset""" def list(self, request): """Handle GET requests to cities resource Returns: Response -- JSON serialized list of cities""" cities = City.objects.all() serializer = CitySerializer(cities, many=True, context={'request': request}) return R...
the_stack_v2_python_sparse
blessipeapi/views/city.py
gqgonzales/blessipe-api
train
0
3baf54048bf49f4b2732dcf2d26625afe20929d7
[ "fulltext = db.session.query(Fulltext).get(id)\nif not fulltext:\n return not_found_error('<Fulltext(id={})> not found'.format(id))\nif g.current_user.reviews.filter_by(id=fulltext.review_id).one_or_none() is None:\n return forbidden_error('{} forbidden to upload fulltext files to this review'.format(g.curren...
<|body_start_0|> fulltext = db.session.query(Fulltext).get(id) if not fulltext: return not_found_error('<Fulltext(id={})> not found'.format(id)) if g.current_user.reviews.filter_by(id=fulltext.review_id).one_or_none() is None: return forbidden_error('{} forbidden to uploa...
FulltextUploadResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FulltextUploadResource: def post(self, id, uploaded_file, test): """upload fulltext content file for a single fulltext by id""" <|body_0|> def delete(self, id, test): """delete fulltext content file for a single fulltext by id""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_006668
6,589
no_license
[ { "docstring": "upload fulltext content file for a single fulltext by id", "name": "post", "signature": "def post(self, id, uploaded_file, test)" }, { "docstring": "delete fulltext content file for a single fulltext by id", "name": "delete", "signature": "def delete(self, id, test)" } ...
2
null
Implement the Python class `FulltextUploadResource` described below. Class description: Implement the FulltextUploadResource class. Method signatures and docstrings: - def post(self, id, uploaded_file, test): upload fulltext content file for a single fulltext by id - def delete(self, id, test): delete fulltext conten...
Implement the Python class `FulltextUploadResource` described below. Class description: Implement the FulltextUploadResource class. Method signatures and docstrings: - def post(self, id, uploaded_file, test): upload fulltext content file for a single fulltext by id - def delete(self, id, test): delete fulltext conten...
37936769dd7c4de05e44508eeb5eaf7b8cdf1c14
<|skeleton|> class FulltextUploadResource: def post(self, id, uploaded_file, test): """upload fulltext content file for a single fulltext by id""" <|body_0|> def delete(self, id, test): """delete fulltext content file for a single fulltext by id""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FulltextUploadResource: def post(self, id, uploaded_file, test): """upload fulltext content file for a single fulltext by id""" fulltext = db.session.query(Fulltext).get(id) if not fulltext: return not_found_error('<Fulltext(id={})> not found'.format(id)) if g.curre...
the_stack_v2_python_sparse
colandr/api/resources/fulltext_uploads.py
datakind/permanent-colandr-back
train
13
71213041bdc45d804b8dc65f0b06b263066990e2
[ "self.name = name\nself.contents = contents\nself.structure_type = st\nself.graph = graph\nself.in_node = None\nself.out_node = None\nif self.structure_type in 'actor':\n self.in_node = self.name\n self.out_node = self.name\nelif self.structure_type == 'pipeline':\n if self.contents:\n self.in_node ...
<|body_start_0|> self.name = name self.contents = contents self.structure_type = st self.graph = graph self.in_node = None self.out_node = None if self.structure_type in 'actor': self.in_node = self.name self.out_node = self.name el...
Implementation of a structure in an SSDF graph
Structure
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Structure: """Implementation of a structure in an SSDF graph""" def __init__(self, graph, st='pipeline', name='', contents=None): """Create an SSDF graph structure :param graph: graph to which the new structure will be added. :param st: type of the new structure. :param name: identif...
stack_v2_sparse_classes_36k_train_006669
5,383
permissive
[ { "docstring": "Create an SSDF graph structure :param graph: graph to which the new structure will be added. :param st: type of the new structure. :param name: identifier of the new structure. :param contents: the identifiers of the structures comprising the new structure.", "name": "__init__", "signatu...
2
stack_v2_sparse_classes_30k_train_009110
Implement the Python class `Structure` described below. Class description: Implementation of a structure in an SSDF graph Method signatures and docstrings: - def __init__(self, graph, st='pipeline', name='', contents=None): Create an SSDF graph structure :param graph: graph to which the new structure will be added. :...
Implement the Python class `Structure` described below. Class description: Implementation of a structure in an SSDF graph Method signatures and docstrings: - def __init__(self, graph, st='pipeline', name='', contents=None): Create an SSDF graph structure :param graph: graph to which the new structure will be added. :...
fc65bea693e0e842e9af16529cede181e53878f8
<|skeleton|> class Structure: """Implementation of a structure in an SSDF graph""" def __init__(self, graph, st='pipeline', name='', contents=None): """Create an SSDF graph structure :param graph: graph to which the new structure will be added. :param st: type of the new structure. :param name: identif...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Structure: """Implementation of a structure in an SSDF graph""" def __init__(self, graph, st='pipeline', name='', contents=None): """Create an SSDF graph structure :param graph: graph to which the new structure will be added. :param st: type of the new structure. :param name: identifier of the ne...
the_stack_v2_python_sparse
graph/ssdf.py
LaminarIR/framework
train
3
31f18fb187c2ead6571fa728d17f1cbd18f4ae57
[ "Panel.__init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, 'Navigation Panel')\nself.action = action\nself.map_position_x = 0\nself.map_position_y = 0\nmiddle_y = self.pos_y + self.height / 2 - self.height * NAV_ARROW_HEIGHT / 2\nmiddle_x = self.pos_x + self.width / 2 - self.width * NAV_ARROW_WI...
<|body_start_0|> Panel.__init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, 'Navigation Panel') self.action = action self.map_position_x = 0 self.map_position_y = 0 middle_y = self.pos_y + self.height / 2 - self.height * NAV_ARROW_HEIGHT / 2 middle_x = ...
This class represents an instance of panel containing navigation items.
NavigationPanel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NavigationPanel: """This class represents an instance of panel containing navigation items.""" def __init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, action): """Constructor. :param pos_x: x position on screen :param pos_y: y position on screen :param width: pane...
stack_v2_sparse_classes_36k_train_006670
3,574
permissive
[ { "docstring": "Constructor. :param pos_x: x position on screen :param pos_y: y position on screen :param width: panel's width :param height: panel's height :param action: action performed when navigation arrow is clicked", "name": "__init__", "signature": "def __init__(self, pos_x, pos_y, width, height...
2
null
Implement the Python class `NavigationPanel` described below. Class description: This class represents an instance of panel containing navigation items. Method signatures and docstrings: - def __init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, action): Constructor. :param pos_x: x position on scr...
Implement the Python class `NavigationPanel` described below. Class description: This class represents an instance of panel containing navigation items. Method signatures and docstrings: - def __init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, action): Constructor. :param pos_x: x position on scr...
afd03f0d15da5843429141e726e113b2ba329f8a
<|skeleton|> class NavigationPanel: """This class represents an instance of panel containing navigation items.""" def __init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, action): """Constructor. :param pos_x: x position on screen :param pos_y: y position on screen :param width: pane...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NavigationPanel: """This class represents an instance of panel containing navigation items.""" def __init__(self, pos_x, pos_y, width, height, texture_path, blit_surface, action): """Constructor. :param pos_x: x position on screen :param pos_y: y position on screen :param width: panel's width :pa...
the_stack_v2_python_sparse
citySimNGView/MapView/Panels/NavigationPanel.py
DarthThanatos/citySimNG
train
0
e0272dfb545c57ea7d6c7fb2fca2f8f7b6b22f18
[ "super(ArrangementLogic, self).__init__(auth, sid, cid)\nif isinstance(aid, PracticeArrangement):\n self.arrangement = aid\nelse:\n self.arrangement = self.get_arrangement_model(aid)", "if not aid:\n return None\narrangement = PracticeArrangement.objects.get_once(aid)\nif not arrangement or arrangement.c...
<|body_start_0|> super(ArrangementLogic, self).__init__(auth, sid, cid) if isinstance(aid, PracticeArrangement): self.arrangement = aid else: self.arrangement = self.get_arrangement_model(aid) <|end_body_0|> <|body_start_1|> if not aid: return None ...
ArrangementLogic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArrangementLogic: def __init__(self, auth, sid, cid, aid=''): """INIT :param auth: :param sid: :param cid: :param aid:""" <|body_0|> def get_arrangement_model(self, aid): """获取排课model :param aid: :return:""" <|body_1|> def get_arrangement_info(self): ...
stack_v2_sparse_classes_36k_train_006671
1,893
no_license
[ { "docstring": "INIT :param auth: :param sid: :param cid: :param aid:", "name": "__init__", "signature": "def __init__(self, auth, sid, cid, aid='')" }, { "docstring": "获取排课model :param aid: :return:", "name": "get_arrangement_model", "signature": "def get_arrangement_model(self, aid)" ...
4
null
Implement the Python class `ArrangementLogic` described below. Class description: Implement the ArrangementLogic class. Method signatures and docstrings: - def __init__(self, auth, sid, cid, aid=''): INIT :param auth: :param sid: :param cid: :param aid: - def get_arrangement_model(self, aid): 获取排课model :param aid: :r...
Implement the Python class `ArrangementLogic` described below. Class description: Implement the ArrangementLogic class. Method signatures and docstrings: - def __init__(self, auth, sid, cid, aid=''): INIT :param auth: :param sid: :param cid: :param aid: - def get_arrangement_model(self, aid): 获取排课model :param aid: :r...
7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b
<|skeleton|> class ArrangementLogic: def __init__(self, auth, sid, cid, aid=''): """INIT :param auth: :param sid: :param cid: :param aid:""" <|body_0|> def get_arrangement_model(self, aid): """获取排课model :param aid: :return:""" <|body_1|> def get_arrangement_info(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArrangementLogic: def __init__(self, auth, sid, cid, aid=''): """INIT :param auth: :param sid: :param cid: :param aid:""" super(ArrangementLogic, self).__init__(auth, sid, cid) if isinstance(aid, PracticeArrangement): self.arrangement = aid else: self.ar...
the_stack_v2_python_sparse
FireHydrant/server/practice/logics/arrangement.py
shoogoome/FireHydrant
train
4
fff7b890da23348a6c8b6afa9e22bb9afec32872
[ "article = ArticleInst.fetch(slug)\ntry:\n comment = Comment.objects.get(pk=id, article=article)\nexcept Comment.DoesNotExist:\n data = {'error': f'Comment of ID {id} nonexistent'}\n status_ = status.HTTP_404_NOT_FOUND\nelse:\n serializer = self.serializer_class(comment)\n status_ = status.HTTP_200_O...
<|body_start_0|> article = ArticleInst.fetch(slug) try: comment = Comment.objects.get(pk=id, article=article) except Comment.DoesNotExist: data = {'error': f'Comment of ID {id} nonexistent'} status_ = status.HTTP_404_NOT_FOUND else: seriali...
Creates, Updates and Deletes a single comment
CommentAPIView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentAPIView: """Creates, Updates and Deletes a single comment""" def get(self, request, slug, id): """Fetches a comment on an article""" <|body_0|> def update(self, request, slug, id): """Updates an existing comment""" <|body_1|> def destroy(self,...
stack_v2_sparse_classes_36k_train_006672
10,918
permissive
[ { "docstring": "Fetches a comment on an article", "name": "get", "signature": "def get(self, request, slug, id)" }, { "docstring": "Updates an existing comment", "name": "update", "signature": "def update(self, request, slug, id)" }, { "docstring": "Removes a comment from an arti...
4
stack_v2_sparse_classes_30k_train_005940
Implement the Python class `CommentAPIView` described below. Class description: Creates, Updates and Deletes a single comment Method signatures and docstrings: - def get(self, request, slug, id): Fetches a comment on an article - def update(self, request, slug, id): Updates an existing comment - def destroy(self, req...
Implement the Python class `CommentAPIView` described below. Class description: Creates, Updates and Deletes a single comment Method signatures and docstrings: - def get(self, request, slug, id): Fetches a comment on an article - def update(self, request, slug, id): Updates an existing comment - def destroy(self, req...
b80ad485339dbb02b74d9b2093543bf8173d51de
<|skeleton|> class CommentAPIView: """Creates, Updates and Deletes a single comment""" def get(self, request, slug, id): """Fetches a comment on an article""" <|body_0|> def update(self, request, slug, id): """Updates an existing comment""" <|body_1|> def destroy(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentAPIView: """Creates, Updates and Deletes a single comment""" def get(self, request, slug, id): """Fetches a comment on an article""" article = ArticleInst.fetch(slug) try: comment = Comment.objects.get(pk=id, article=article) except Comment.DoesNotExist:...
the_stack_v2_python_sparse
authors/apps/comments/views.py
deferral/ah-django
train
1
f9244ce8cf0cb88bffeb9c890dc97da0fea29fe3
[ "neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0))\nx, y = (abs(dividend), abs(divisor))\nzgen = range(y, x, y)\nzlen = len(zgen)\nif y > x:\n return 0\nif x == y:\n return -1 if neg else 1\nif zgen[-1] + y <= x:\n zlen += 1\nif neg:\n return 0 - zlen\nreturn min(max(-21474836...
<|body_start_0|> neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0)) x, y = (abs(dividend), abs(divisor)) zgen = range(y, x, y) zlen = len(zgen) if y > x: return 0 if x == y: return -1 if neg else 1 if zgen[-1] + y ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def divide(self, dividend, divisor): """:type dividend: int :type divisor: int :rtype: int""" <|body_0|> def divide_work(self, dividend, divisor): """:type dividend: int :type divisor: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_006673
2,372
no_license
[ { "docstring": ":type dividend: int :type divisor: int :rtype: int", "name": "divide", "signature": "def divide(self, dividend, divisor)" }, { "docstring": ":type dividend: int :type divisor: int :rtype: int", "name": "divide_work", "signature": "def divide_work(self, dividend, divisor)"...
2
stack_v2_sparse_classes_30k_train_019554
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def divide(self, dividend, divisor): :type dividend: int :type divisor: int :rtype: int - def divide_work(self, dividend, divisor): :type dividend: int :type divisor: int :rtype:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def divide(self, dividend, divisor): :type dividend: int :type divisor: int :rtype: int - def divide_work(self, dividend, divisor): :type dividend: int :type divisor: int :rtype:...
3f0ffd519404165fd1a735441b212c801fd1ad1e
<|skeleton|> class Solution: def divide(self, dividend, divisor): """:type dividend: int :type divisor: int :rtype: int""" <|body_0|> def divide_work(self, dividend, divisor): """:type dividend: int :type divisor: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def divide(self, dividend, divisor): """:type dividend: int :type divisor: int :rtype: int""" neg = (dividend < 0 or divisor < 0) and (not (dividend < 0 and divisor < 0)) x, y = (abs(dividend), abs(divisor)) zgen = range(y, x, y) zlen = len(zgen) if y ...
the_stack_v2_python_sparse
Problems/0001_0099/0029_Divide_Two_Integers/project_Python3/Divide_Two_Integers.py
NobuyukiInoue/LeetCode
train
0
d8e0cec2d7f80ca0e42e17752c6adfd4c9658e8e
[ "ds.add(pipe_name='orig', pipe_type='mf')\ncdp.mol[0].name = 'Ap4Aase'\ncdp.mol.add_item(mol_name='RNA')\ncdp.mol[0].res[0].num = 1\ncdp.mol[0].res.add_item(res_num=2, res_name='Glu')\ncdp.mol[0].res.add_item(res_num=4, res_name='Pro')\ncdp.mol[0].res[0].spin[0].name = 'NH'\ncdp.mol[0].res[0].spin[0].num = 60\ncdp....
<|body_start_0|> ds.add(pipe_name='orig', pipe_type='mf') cdp.mol[0].name = 'Ap4Aase' cdp.mol.add_item(mol_name='RNA') cdp.mol[0].res[0].num = 1 cdp.mol[0].res.add_item(res_num=2, res_name='Glu') cdp.mol[0].res.add_item(res_num=4, res_name='Pro') cdp.mol[0].res[0]...
Unit tests for the functions of the 'pipe_control.selection' module.
Test_selection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test_selection: """Unit tests for the functions of the 'pipe_control.selection' module.""" def setUp(self): """Set up some residues and spins for testing their selection and deselection.""" <|body_0|> def test_reverse(self): """Test spin system selection reversal...
stack_v2_sparse_classes_36k_train_006674
4,126
no_license
[ { "docstring": "Set up some residues and spins for testing their selection and deselection.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test spin system selection reversal. The function tested is pipe_control.selection.reverse().", "name": "test_reverse", "signat...
2
null
Implement the Python class `Test_selection` described below. Class description: Unit tests for the functions of the 'pipe_control.selection' module. Method signatures and docstrings: - def setUp(self): Set up some residues and spins for testing their selection and deselection. - def test_reverse(self): Test spin syst...
Implement the Python class `Test_selection` described below. Class description: Unit tests for the functions of the 'pipe_control.selection' module. Method signatures and docstrings: - def setUp(self): Set up some residues and spins for testing their selection and deselection. - def test_reverse(self): Test spin syst...
c317326ddeacd1a1c608128769676899daeae531
<|skeleton|> class Test_selection: """Unit tests for the functions of the 'pipe_control.selection' module.""" def setUp(self): """Set up some residues and spins for testing their selection and deselection.""" <|body_0|> def test_reverse(self): """Test spin system selection reversal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test_selection: """Unit tests for the functions of the 'pipe_control.selection' module.""" def setUp(self): """Set up some residues and spins for testing their selection and deselection.""" ds.add(pipe_name='orig', pipe_type='mf') cdp.mol[0].name = 'Ap4Aase' cdp.mol.add_it...
the_stack_v2_python_sparse
test_suite/unit_tests/_pipe_control/test_selection.py
jlec/relax
train
4
351cb3a3bf7348bdaf05dab2e109e3567874f0a1
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jgrishey', 'jgrishey')\nif trial:\n crimes = list(repo['jgrishey.crime'].find(None, ['lat', 'long']))[:20]\nelse:\n crimes = list(repo['jgrishey.crime'].find(None, ['lat', 'long']))\ncrimes = np.ar...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('jgrishey', 'jgrishey') if trial: crimes = list(repo['jgrishey.crime'].find(None, ['lat', 'long']))[:20] else: crimes = lis...
kMeansCrime
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class kMeansCrime: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything h...
stack_v2_sparse_classes_36k_train_006675
3,668
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
stack_v2_sparse_classes_30k_train_011747
Implement the Python class `kMeansCrime` described below. Class description: Implement the kMeansCrime class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi...
Implement the Python class `kMeansCrime` described below. Class description: Implement the kMeansCrime class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime=None, endTi...
0df485d0469c5451ebdcd684bed2a0960ba3ab84
<|skeleton|> class kMeansCrime: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everything h...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class kMeansCrime: 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('jgrishey', 'jgrishey') if trial...
the_stack_v2_python_sparse
jgrishey/kMeansCrime.py
lingyigu/course-2017-spr-proj
train
0
0b3484f7d2692e39751cb995b88ee51339c4cb4d
[ "if opt is None:\n opt = {}\nadmm.ADMMTwoBlockCnstrnt.Options.__init__(self, opt)", "admm.ADMMTwoBlockCnstrnt.Options.__setitem__(self, key, value)\nif key == 'AuxVarObj':\n if value is True:\n self['fEvalX'] = False\n self['gEvalY'] = True\n else:\n self['fEvalX'] = True\n se...
<|body_start_0|> if opt is None: opt = {} admm.ADMMTwoBlockCnstrnt.Options.__init__(self, opt) <|end_body_0|> <|body_start_1|> admm.ADMMTwoBlockCnstrnt.Options.__setitem__(self, key, value) if key == 'AuxVarObj': if value is True: self['fEvalX'] =...
ConvCnstrMODMaskDcplBase algorithm options Options include all of those defined in :class:`.ADMMTwoBlockCnstrnt.Options`, together with additional options: ``LinSolveCheck`` : Flag indicating whether to compute relative residual of X step solver. ``ZeroMean`` : Flag indicating whether the solution dictionary :math:`\\{...
Options
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Options: """ConvCnstrMODMaskDcplBase algorithm options Options include all of those defined in :class:`.ADMMTwoBlockCnstrnt.Options`, together with additional options: ``LinSolveCheck`` : Flag indicating whether to compute relative residual of X step solver. ``ZeroMean`` : Flag indicating whether...
stack_v2_sparse_classes_36k_train_006676
39,880
permissive
[ { "docstring": "Parameters ---------- opt : dict or None, optional (default None) ConvCnstrMODMaskDcpl algorithm options", "name": "__init__", "signature": "def __init__(self, opt=None)" }, { "docstring": "Set options 'fEvalX' and 'gEvalY' appropriately when option 'AuxVarObj' is set.", "nam...
2
null
Implement the Python class `Options` described below. Class description: ConvCnstrMODMaskDcplBase algorithm options Options include all of those defined in :class:`.ADMMTwoBlockCnstrnt.Options`, together with additional options: ``LinSolveCheck`` : Flag indicating whether to compute relative residual of X step solver....
Implement the Python class `Options` described below. Class description: ConvCnstrMODMaskDcplBase algorithm options Options include all of those defined in :class:`.ADMMTwoBlockCnstrnt.Options`, together with additional options: ``LinSolveCheck`` : Flag indicating whether to compute relative residual of X step solver....
5a64fbe456f3a117275c45ee1f10c60d6e133915
<|skeleton|> class Options: """ConvCnstrMODMaskDcplBase algorithm options Options include all of those defined in :class:`.ADMMTwoBlockCnstrnt.Options`, together with additional options: ``LinSolveCheck`` : Flag indicating whether to compute relative residual of X step solver. ``ZeroMean`` : Flag indicating whether...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Options: """ConvCnstrMODMaskDcplBase algorithm options Options include all of those defined in :class:`.ADMMTwoBlockCnstrnt.Options`, together with additional options: ``LinSolveCheck`` : Flag indicating whether to compute relative residual of X step solver. ``ZeroMean`` : Flag indicating whether the solution...
the_stack_v2_python_sparse
benchmarks/other/sporco/admm/ccmodmd.py
tomMoral/dicodile
train
17
ba742a4109302b4a02b092c8a0a3da2d63fa7074
[ "self.d = {}\nself.cap = capacity\nself.head = Node(-1, -1, None)\nList.initHead(self.head)", "if key not in self.d:\n return -1\nself.d[key].hit()\nreturn self.d[key].value", "if self.cap == 0:\n return\nif key in self.d:\n self.d[key].hit()\n self.d[key].value = value\nelse:\n if len(self.d) >=...
<|body_start_0|> self.d = {} self.cap = capacity self.head = Node(-1, -1, None) List.initHead(self.head) <|end_body_0|> <|body_start_1|> if key not in self.d: return -1 self.d[key].hit() return self.d[key].value <|end_body_1|> <|body_start_2|> ...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_006677
1,549
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
stack_v2_sparse_classes_30k_train_019051
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
929dde1723fb2f54870c8a9badc80fc23e8400d3
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.d = {} self.cap = capacity self.head = Node(-1, -1, None) List.initHead(self.head) def get(self, key): """:rtype: int""" if key not in self.d: return -1 self....
the_stack_v2_python_sparse
_algorithms_challenges/leetcode/lc-all-solutions/146.lru-cache/lru-cache.py
syurskyi/Algorithms_and_Data_Structure
train
4
2383696c78264179d7b4af7dc8a6d12b37cdcec0
[ "if network.successor_edges is None:\n return False\nif src in network.names_dict.values():\n return BellmanFord.bellman_ford_existing_src(network, src)\nelse:\n return BellmanFord.bellman_ford_external_source(network)", "if type(src) == str:\n src_idx = network.names_dict[src]\nelse:\n src_idx = s...
<|body_start_0|> if network.successor_edges is None: return False if src in network.names_dict.values(): return BellmanFord.bellman_ford_existing_src(network, src) else: return BellmanFord.bellman_ford_external_source(network) <|end_body_0|> <|body_start_1|> ...
----------------------------------------------------------------- A class to hold several variants of the Bellman Ford algorithm, each implemented as a static method. ----------------------------------------------------------------- Methods ------- bellman_ford_wrapper bellman_ford_existing_src bellman_ford_external_so...
BellmanFord
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BellmanFord: """----------------------------------------------------------------- A class to hold several variants of the Bellman Ford algorithm, each implemented as a static method. ----------------------------------------------------------------- Methods ------- bellman_ford_wrapper bellman_for...
stack_v2_sparse_classes_36k_train_006678
5,278
no_license
[ { "docstring": "------------------------------------------------------------------------ A static method that calls one of the Bellman Ford variants depending on if the source is in the network or no. ------------------------------------------------------------------------ Parameters ---------- network: STN The...
3
stack_v2_sparse_classes_30k_train_005027
Implement the Python class `BellmanFord` described below. Class description: ----------------------------------------------------------------- A class to hold several variants of the Bellman Ford algorithm, each implemented as a static method. ----------------------------------------------------------------- Methods -...
Implement the Python class `BellmanFord` described below. Class description: ----------------------------------------------------------------- A class to hold several variants of the Bellman Ford algorithm, each implemented as a static method. ----------------------------------------------------------------- Methods -...
596d35ecd303717292b89612501a24082f8017a2
<|skeleton|> class BellmanFord: """----------------------------------------------------------------- A class to hold several variants of the Bellman Ford algorithm, each implemented as a static method. ----------------------------------------------------------------- Methods ------- bellman_ford_wrapper bellman_for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BellmanFord: """----------------------------------------------------------------- A class to hold several variants of the Bellman Ford algorithm, each implemented as a static method. ----------------------------------------------------------------- Methods ------- bellman_ford_wrapper bellman_ford_existing_sr...
the_stack_v2_python_sparse
src/bellman_ford.py
JKBehrens/temporal-networks
train
0
43605a863d914c979c17b5a9d8673c12532194af
[ "self.A = A\nself.i = 0\nself.q = 0", "while self.i < len(self.A):\n if self.q + n > self.A[self.i]:\n n -= self.A[self.i] - self.q\n self.q = 0\n self.i += 2\n else:\n self.q += n\n return self.A[self.i + 1]\nreturn -1" ]
<|body_start_0|> self.A = A self.i = 0 self.q = 0 <|end_body_0|> <|body_start_1|> while self.i < len(self.A): if self.q + n > self.A[self.i]: n -= self.A[self.i] - self.q self.q = 0 self.i += 2 else: ...
RLEIterator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RLEIterator: def __init__(self, A): """:type A: List[int]""" <|body_0|> def next(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.A = A self.i = 0 self.q = 0 <|end_body_0|> <|body_start_1|> ...
stack_v2_sparse_classes_36k_train_006679
4,011
permissive
[ { "docstring": ":type A: List[int]", "name": "__init__", "signature": "def __init__(self, A)" }, { "docstring": ":type n: int :rtype: int", "name": "next", "signature": "def next(self, n)" } ]
2
stack_v2_sparse_classes_30k_val_000330
Implement the Python class `RLEIterator` described below. Class description: Implement the RLEIterator class. Method signatures and docstrings: - def __init__(self, A): :type A: List[int] - def next(self, n): :type n: int :rtype: int
Implement the Python class `RLEIterator` described below. Class description: Implement the RLEIterator class. Method signatures and docstrings: - def __init__(self, A): :type A: List[int] - def next(self, n): :type n: int :rtype: int <|skeleton|> class RLEIterator: def __init__(self, A): """:type A: Lis...
0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c
<|skeleton|> class RLEIterator: def __init__(self, A): """:type A: List[int]""" <|body_0|> def next(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RLEIterator: def __init__(self, A): """:type A: List[int]""" self.A = A self.i = 0 self.q = 0 def next(self, n): """:type n: int :rtype: int""" while self.i < len(self.A): if self.q + n > self.A[self.i]: n -= self.A[self.i] - sel...
the_stack_v2_python_sparse
cs15211/RLEIterator.py
JulyKikuAkita/PythonPrac
train
1
e4bbc4a5f44d764a3ecffe1e2aacd4f9f3f73c19
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MessageRule()", "from .entity import Entity\nfrom .message_rule_actions import MessageRuleActions\nfrom .message_rule_predicates import MessageRulePredicates\nfrom .entity import Entity\nfrom .message_rule_actions import MessageRuleAct...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return MessageRule() <|end_body_0|> <|body_start_1|> from .entity import Entity from .message_rule_actions import MessageRuleActions from .message_rule_predicates import MessageRulePred...
MessageRule
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MessageRule: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MessageRule: """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: Me...
stack_v2_sparse_classes_36k_train_006680
4,267
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: MessageRule", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(p...
3
null
Implement the Python class `MessageRule` described below. Class description: Implement the MessageRule class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MessageRule: Creates a new instance of the appropriate class based on discriminator value Args:...
Implement the Python class `MessageRule` described below. Class description: Implement the MessageRule class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MessageRule: Creates a new instance of the appropriate class based on discriminator value Args:...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class MessageRule: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MessageRule: """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: Me...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MessageRule: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MessageRule: """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: MessageRule""" ...
the_stack_v2_python_sparse
msgraph/generated/models/message_rule.py
microsoftgraph/msgraph-sdk-python
train
135
b8256f95c39afc197ce2f01e2848aea49fd8a021
[ "converted_value: Any = value\nif type_ == IconNetworkValueType.MAX_STEP_LIMITS:\n converted_value: dict = {}\n for key, value in value.items():\n if isinstance(key, str):\n if key == 'invoke':\n converted_value[IconScoreContextType.INVOKE] = value\n elif key == 'qu...
<|body_start_0|> converted_value: Any = value if type_ == IconNetworkValueType.MAX_STEP_LIMITS: converted_value: dict = {} for key, value in value.items(): if isinstance(key, str): if key == 'invoke': converted_value[Ico...
ValueConverter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValueConverter: def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': """Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:""" <|body_0|> def conver...
stack_v2_sparse_classes_36k_train_006681
8,639
permissive
[ { "docstring": "Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:", "name": "convert_for_icon_service", "signature": "def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value'" },...
2
null
Implement the Python class `ValueConverter` described below. Class description: Implement the ValueConverter class. Method signatures and docstrings: - def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': Convert IconNetwork value data type for icon service. Some data need to be convert...
Implement the Python class `ValueConverter` described below. Class description: Implement the ValueConverter class. Method signatures and docstrings: - def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': Convert IconNetwork value data type for icon service. Some data need to be convert...
dfa61fcc42425390a0398ada42ce2121278eec08
<|skeleton|> class ValueConverter: def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': """Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:""" <|body_0|> def conver...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValueConverter: def convert_for_icon_service(type_: 'IconNetworkValueType', value: Any) -> 'Value': """Convert IconNetwork value data type for icon service. Some data need to be converted for enhancing efficiency. :param type_: :param value: :return:""" converted_value: Any = value if ...
the_stack_v2_python_sparse
iconservice/inv/container.py
icon-project/icon-service
train
53
d62197fc468aea2d55644b4711c1aeeb42b086be
[ "self.stack = []\nself.stack_2 = []\nself.max_size = 5", "while self.stack != []:\n self.stack_2.append(self.stack.pop())\nself.stack.append(item)\nwhile self.stack_2 != []:\n self.stack.append(self.stack_2.pop())", "if len(self.stack) == 0:\n print('Underflow')\nelse:\n self.stack.pop()", "if sel...
<|body_start_0|> self.stack = [] self.stack_2 = [] self.max_size = 5 <|end_body_0|> <|body_start_1|> while self.stack != []: self.stack_2.append(self.stack.pop()) self.stack.append(item) while self.stack_2 != []: self.stack.append(self.stack_2.pop...
This class contains function for queue implementation using stack
Stack
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Stack: """This class contains function for queue implementation using stack""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> def push(self, item): """This function inserts the element into the que...
stack_v2_sparse_classes_36k_train_006682
1,806
no_license
[ { "docstring": "Constructor function. Argument: self -- represents the object of the class.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "This function inserts the element into the queue. Argument: self -- represents the object of the class. item -- integer value, re...
4
null
Implement the Python class `Stack` described below. Class description: This class contains function for queue implementation using stack Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represents the object of the class. - def push(self, item): This function inserts the...
Implement the Python class `Stack` described below. Class description: This class contains function for queue implementation using stack Method signatures and docstrings: - def __init__(self): Constructor function. Argument: self -- represents the object of the class. - def push(self, item): This function inserts the...
6870426104aef417086788221dad29e887ddfe3f
<|skeleton|> class Stack: """This class contains function for queue implementation using stack""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" <|body_0|> def push(self, item): """This function inserts the element into the que...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Stack: """This class contains function for queue implementation using stack""" def __init__(self): """Constructor function. Argument: self -- represents the object of the class.""" self.stack = [] self.stack_2 = [] self.max_size = 5 def push(self, item): """Th...
the_stack_v2_python_sparse
Data Structure/03. Queue/04. Implement Queue Using Stack/py_code.py
Slothfulwave612/Coding-Problems
train
5
e6a20f7df1cf39eb998de2e8c2b5d29ec7cef548
[ "username = self.normalize_email(username)\nemail = username\nself._validate_username(email)\nuser = self.create_user(username=email, email=email, password=None, first_name=first_name, last_name=last_name, **extra_fields)\nuser.set_unusable_password()\nuser.save()\nToken._default_manager.get_or_create(user=user)\nr...
<|body_start_0|> username = self.normalize_email(username) email = username self._validate_username(email) user = self.create_user(username=email, email=email, password=None, first_name=first_name, last_name=last_name, **extra_fields) user.set_unusable_password() user.sav...
ApiUserManager
[ "Apache-2.0", "CC-BY-SA-4.0", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ApiUserManager: def create_api_user(self, username, first_name='', last_name='', **extra_fields): """Create and return an API-only user. Raise ValidationError.""" <|body_0|> def _validate_username(self, email): """Validate username. If invalid, raise a ValidationErro...
stack_v2_sparse_classes_36k_train_006683
29,469
permissive
[ { "docstring": "Create and return an API-only user. Raise ValidationError.", "name": "create_api_user", "signature": "def create_api_user(self, username, first_name='', last_name='', **extra_fields)" }, { "docstring": "Validate username. If invalid, raise a ValidationError", "name": "_valida...
2
stack_v2_sparse_classes_30k_train_001094
Implement the Python class `ApiUserManager` described below. Class description: Implement the ApiUserManager class. Method signatures and docstrings: - def create_api_user(self, username, first_name='', last_name='', **extra_fields): Create and return an API-only user. Raise ValidationError. - def _validate_username(...
Implement the Python class `ApiUserManager` described below. Class description: Implement the ApiUserManager class. Method signatures and docstrings: - def create_api_user(self, username, first_name='', last_name='', **extra_fields): Create and return an API-only user. Raise ValidationError. - def _validate_username(...
eec05bb0f796d743e408a1b402df8abfc8344669
<|skeleton|> class ApiUserManager: def create_api_user(self, username, first_name='', last_name='', **extra_fields): """Create and return an API-only user. Raise ValidationError.""" <|body_0|> def _validate_username(self, email): """Validate username. If invalid, raise a ValidationErro...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ApiUserManager: def create_api_user(self, username, first_name='', last_name='', **extra_fields): """Create and return an API-only user. Raise ValidationError.""" username = self.normalize_email(username) email = username self._validate_username(email) user = self.creat...
the_stack_v2_python_sparse
vulnerabilities/models.py
nexB/vulnerablecode
train
371
0c9925080ff4ff3e11acb75f3631c5e77d82e794
[ "try:\n jd = jc.load_obj_json('{}')\n jd.dir = baseid\n jd.table = table\n jd.nn_id = nnid\n jd.datadesc = 'Y'\n jd.preprocess = '2'\n netconf.save_format(nnid, str(request.body, 'utf-8'))\n result = netconf.update_network(jd)\n return_data = {'status': '200', 'result': result}\n retur...
<|body_start_0|> try: jd = jc.load_obj_json('{}') jd.dir = baseid jd.table = table jd.nn_id = nnid jd.datadesc = 'Y' jd.preprocess = '2' netconf.save_format(nnid, str(request.body, 'utf-8')) result = netconf.update_n...
1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/label/{label}/ - post /a...
ImageFileFormat
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageFileFormat: """1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{...
stack_v2_sparse_classes_36k_train_006684
4,138
no_license
[ { "docstring": "- desc : create a format data - desc : update data format information <textfield> <font size = 1> { \"x_size\": 100 , \"y_size\": 100 } </font> </textfield> --- parameters: - name: body paramType: body pytype: json", "name": "post", "signature": "def post(self, request, baseid, table, nn...
4
stack_v2_sparse_classes_30k_train_001048
Implement the Python class `ImageFileFormat` described below. Class description: 1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb...
Implement the Python class `ImageFileFormat` described below. Class description: 1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb...
ef058737f391de817c74398ef9a5d3a28f973c98
<|skeleton|> class ImageFileFormat: """1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageFileFormat: """1. Name : ImageFileFormat (step 6) 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{baseid}/table...
the_stack_v2_python_sparse
tfmsarest/views/imagefile_format.py
TensorMSA/tensormsa_old
train
6
2dd1c95b57b7cde00bd1a19ff04f9f81697c4519
[ "defaultURL = 'https://cmssdt.cern.ch/SDT/cgi-bin/ReleasesXML'\nurl = url or defaultURL\nparsedUrl = urlparse(url)\nself.cFileUrlPath = parsedUrl.path.replace('/', '_')\nself.tcArgs = kwargs\nself.tcArgs.setdefault('anytype', 1)\nself.tcArgs.setdefault('anyarch', 1)\nconfigDict = configDict or {}\nconfigDict.setdef...
<|body_start_0|> defaultURL = 'https://cmssdt.cern.ch/SDT/cgi-bin/ReleasesXML' url = url or defaultURL parsedUrl = urlparse(url) self.cFileUrlPath = parsedUrl.path.replace('/', '_') self.tcArgs = kwargs self.tcArgs.setdefault('anytype', 1) self.tcArgs.setdefault('...
Class which provides interface to CMS TagCollector web-service. Provides non-deprecated CMSSW releases in all their ScramArchs (not only prod)
TagCollector
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TagCollector: """Class which provides interface to CMS TagCollector web-service. Provides non-deprecated CMSSW releases in all their ScramArchs (not only prod)""" def __init__(self, url=None, logger=None, configDict=None, **kwargs): """responseType will be either xml or json""" ...
stack_v2_sparse_classes_36k_train_006685
4,022
permissive
[ { "docstring": "responseType will be either xml or json", "name": "__init__", "signature": "def __init__(self, url=None, logger=None, configDict=None, **kwargs)" }, { "docstring": "_getResult_ retrieve JSON/XML formatted information given the service name and the argument dictionaries TODO: Prob...
6
null
Implement the Python class `TagCollector` described below. Class description: Class which provides interface to CMS TagCollector web-service. Provides non-deprecated CMSSW releases in all their ScramArchs (not only prod) Method signatures and docstrings: - def __init__(self, url=None, logger=None, configDict=None, **...
Implement the Python class `TagCollector` described below. Class description: Class which provides interface to CMS TagCollector web-service. Provides non-deprecated CMSSW releases in all their ScramArchs (not only prod) Method signatures and docstrings: - def __init__(self, url=None, logger=None, configDict=None, **...
de110ccf6fc63ef5589b4e871ef4d51d5bce7a25
<|skeleton|> class TagCollector: """Class which provides interface to CMS TagCollector web-service. Provides non-deprecated CMSSW releases in all their ScramArchs (not only prod)""" def __init__(self, url=None, logger=None, configDict=None, **kwargs): """responseType will be either xml or json""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TagCollector: """Class which provides interface to CMS TagCollector web-service. Provides non-deprecated CMSSW releases in all their ScramArchs (not only prod)""" def __init__(self, url=None, logger=None, configDict=None, **kwargs): """responseType will be either xml or json""" defaultURL...
the_stack_v2_python_sparse
src/python/WMCore/Services/TagCollector/TagCollector.py
vkuznet/WMCore
train
0
526e5ca3596733572d1ea9beccfc470142857fc9
[ "if len(prices) <= 1:\n return 0\nK, n = (2, len(prices))\ndp = [[[0] * 2 for _ in range(K + 1)] for _ in range(len(prices))]\nfor i in range(n):\n for k in range(K, 0, -1):\n if i - 1 == -1:\n dp[i][k][0] = 0\n dp[i][k][1] = -prices[0]\n continue\n dp[i][k][0] =...
<|body_start_0|> if len(prices) <= 1: return 0 K, n = (2, len(prices)) dp = [[[0] * 2 for _ in range(K + 1)] for _ in range(len(prices))] for i in range(n): for k in range(K, 0, -1): if i - 1 == -1: dp[i][k][0] = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfitDpPattern(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfitDpPattern2(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> def maxProfit(self, prices): """:type prices: List[in...
stack_v2_sparse_classes_36k_train_006686
5,100
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfitDpPattern", "signature": "def maxProfitDpPattern(self, prices)" }, { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfitDpPattern2", "signature": "def maxProfitDpPattern2(self, prices)" }, { ...
4
stack_v2_sparse_classes_30k_train_012573
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfitDpPattern(self, prices): :type prices: List[int] :rtype: int - def maxProfitDpPattern2(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, price...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfitDpPattern(self, prices): :type prices: List[int] :rtype: int - def maxProfitDpPattern2(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, price...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def maxProfitDpPattern(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfitDpPattern2(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> def maxProfit(self, prices): """:type prices: List[in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfitDpPattern(self, prices): """:type prices: List[int] :rtype: int""" if len(prices) <= 1: return 0 K, n = (2, len(prices)) dp = [[[0] * 2 for _ in range(K + 1)] for _ in range(len(prices))] for i in range(n): for k in range(K...
the_stack_v2_python_sparse
B/BestTimetoBuyandSellStockIII.py
bssrdf/pyleet
train
2
deddc093edcbd0ecbe5e5a821330de0d03642b86
[ "if not reservation.is_within_allowed_period_for_reservation() and (not (reservation.special or reservation.event)):\n return 'Reservasjoner kan bare lages {:} dager frem i tid'.format(reservation.reservation_future_limit_days)\nif self.request.user.has_perm('make_queue.can_create_event_reservation') and form.cl...
<|body_start_0|> if not reservation.is_within_allowed_period_for_reservation() and (not (reservation.special or reservation.event)): return 'Reservasjoner kan bare lages {:} dager frem i tid'.format(reservation.reservation_future_limit_days) if self.request.user.has_perm('make_queue.can_crea...
Base abstract class for the reservation create or change view
ReservationCreateOrChangeView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReservationCreateOrChangeView: """Base abstract class for the reservation create or change view""" def get_error_message(self, form, reservation): """Generates the correct error message for the given form :param reservation: The reservation to generate an error message for :param for...
stack_v2_sparse_classes_36k_train_006687
12,808
permissive
[ { "docstring": "Generates the correct error message for the given form :param reservation: The reservation to generate an error message for :param form: The form to generate an error message for :return: The error message", "name": "get_error_message", "signature": "def get_error_message(self, form, res...
5
stack_v2_sparse_classes_30k_train_012162
Implement the Python class `ReservationCreateOrChangeView` described below. Class description: Base abstract class for the reservation create or change view Method signatures and docstrings: - def get_error_message(self, form, reservation): Generates the correct error message for the given form :param reservation: Th...
Implement the Python class `ReservationCreateOrChangeView` described below. Class description: Base abstract class for the reservation create or change view Method signatures and docstrings: - def get_error_message(self, form, reservation): Generates the correct error message for the given form :param reservation: Th...
1d190a86e3277315804bfcc0b8f9abd4f9c1d780
<|skeleton|> class ReservationCreateOrChangeView: """Base abstract class for the reservation create or change view""" def get_error_message(self, form, reservation): """Generates the correct error message for the given form :param reservation: The reservation to generate an error message for :param for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReservationCreateOrChangeView: """Base abstract class for the reservation create or change view""" def get_error_message(self, form, reservation): """Generates the correct error message for the given form :param reservation: The reservation to generate an error message for :param form: The form t...
the_stack_v2_python_sparse
make_queue/views/reservation/reservation.py
mahoyen/web
train
0
474d6defe342c21c896ba1e794ae2f6d956ad20c
[ "self.ipmidriver = ipmidriver if ipmidriver is not None else IPMIDriver.IPMIDriver()\nself.username = username\nself.password = password\nself.ip = ipAddress\nself.netmask = netmask\nself.gateway = gateway\nself.channel = channel\nself.restart = self._convertStringToBool(restart)", "if any([self.username, self.pa...
<|body_start_0|> self.ipmidriver = ipmidriver if ipmidriver is not None else IPMIDriver.IPMIDriver() self.username = username self.password = password self.ip = ipAddress self.netmask = netmask self.gateway = gateway self.channel = channel self.restart = s...
IPMIController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IPMIController: def __init__(self, ipmidriver=None, username=None, password=None, ipAddress=None, netmask=None, gateway=None, channel=None, restart=None): """IPMIController initializer @param ipmidriver: ipmi driver @type ipmidriver: IPMIDriver @param username: user name @type username: ...
stack_v2_sparse_classes_36k_train_006688
3,722
permissive
[ { "docstring": "IPMIController initializer @param ipmidriver: ipmi driver @type ipmidriver: IPMIDriver @param username: user name @type username: string @param password: password @type password: string @param ipAddress: ip address for ipmi network configuration @type ipAddress: string @param netmask: netmask @t...
5
stack_v2_sparse_classes_30k_train_013337
Implement the Python class `IPMIController` described below. Class description: Implement the IPMIController class. Method signatures and docstrings: - def __init__(self, ipmidriver=None, username=None, password=None, ipAddress=None, netmask=None, gateway=None, channel=None, restart=None): IPMIController initializer ...
Implement the Python class `IPMIController` described below. Class description: Implement the IPMIController class. Method signatures and docstrings: - def __init__(self, ipmidriver=None, username=None, password=None, ipAddress=None, netmask=None, gateway=None, channel=None, restart=None): IPMIController initializer ...
bfe44cc51b4825fdb0a7607d10ac1cdb97aba1fb
<|skeleton|> class IPMIController: def __init__(self, ipmidriver=None, username=None, password=None, ipAddress=None, netmask=None, gateway=None, channel=None, restart=None): """IPMIController initializer @param ipmidriver: ipmi driver @type ipmidriver: IPMIDriver @param username: user name @type username: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IPMIController: def __init__(self, ipmidriver=None, username=None, password=None, ipAddress=None, netmask=None, gateway=None, channel=None, restart=None): """IPMIController initializer @param ipmidriver: ipmi driver @type ipmidriver: IPMIDriver @param username: user name @type username: string @param ...
the_stack_v2_python_sparse
inaugurator/IPMIController.py
Stratoscale/inaugurator
train
1
3f9cecea547108d807bb1f2fb55d1adf8feebad1
[ "lp = LinearPolicy(2, 1)\nself.assertEqual(lp.d_state, 2)\nself.assertEqual(lp.d_action, 1)\nself.assertEqual(lp.par_dim, 2)\nself.assertIs(lp._par_space, None)\nself.assertFalse(lp.initialized)\nself.assertIs(lp._parameters, None)\nself.assertTrue(lp.biased)\nself.assertEqual(lp._bias, 0)\nself.assertIs(lp._par, N...
<|body_start_0|> lp = LinearPolicy(2, 1) self.assertEqual(lp.d_state, 2) self.assertEqual(lp.d_action, 1) self.assertEqual(lp.par_dim, 2) self.assertIs(lp._par_space, None) self.assertFalse(lp.initialized) self.assertIs(lp._parameters, None) self.assertTru...
Test the Linear Policy.
TestLinearPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLinearPolicy: """Test the Linear Policy.""" def test_initialization(self): """Test: LINEARPOLICY: initialization.""" <|body_0|> def test_discrete_map(self): """Test: DISCRETELINEARPOLICY: map.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_006689
5,830
permissive
[ { "docstring": "Test: LINEARPOLICY: initialization.", "name": "test_initialization", "signature": "def test_initialization(self)" }, { "docstring": "Test: DISCRETELINEARPOLICY: map.", "name": "test_discrete_map", "signature": "def test_discrete_map(self)" } ]
2
null
Implement the Python class `TestLinearPolicy` described below. Class description: Test the Linear Policy. Method signatures and docstrings: - def test_initialization(self): Test: LINEARPOLICY: initialization. - def test_discrete_map(self): Test: DISCRETELINEARPOLICY: map.
Implement the Python class `TestLinearPolicy` described below. Class description: Test the Linear Policy. Method signatures and docstrings: - def test_initialization(self): Test: LINEARPOLICY: initialization. - def test_discrete_map(self): Test: DISCRETELINEARPOLICY: map. <|skeleton|> class TestLinearPolicy: """...
8500c8dd90a2b59a91b988a3c83e529f6c69332f
<|skeleton|> class TestLinearPolicy: """Test the Linear Policy.""" def test_initialization(self): """Test: LINEARPOLICY: initialization.""" <|body_0|> def test_discrete_map(self): """Test: DISCRETELINEARPOLICY: map.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestLinearPolicy: """Test the Linear Policy.""" def test_initialization(self): """Test: LINEARPOLICY: initialization.""" lp = LinearPolicy(2, 1) self.assertEqual(lp.d_state, 2) self.assertEqual(lp.d_action, 1) self.assertEqual(lp.par_dim, 2) self.assertIs(l...
the_stack_v2_python_sparse
Safe-RL/Safe-RL-Benchmark/SafeRLBench/policy/test.py
chauncygu/Safe-Reinforcement-Learning-Baselines
train
233
9fd618352946074d33d51f9f9d44cacad03a6966
[ "if not key and (not name):\n raise ValueError('Must pass either a Key or key name into `%s.get`.' % cls.kind())\nif name:\n return cls.__adapter__._get(cls.__keyclass__(cls.kind(), name), **kwargs)\nif isinstance(key, basestring):\n key = cls.__keyclass__.from_urlsafe(key)\nelif isinstance(key, (list, tup...
<|body_start_0|> if not key and (not name): raise ValueError('Must pass either a Key or key name into `%s.get`.' % cls.kind()) if name: return cls.__adapter__._get(cls.__keyclass__(cls.kind(), name), **kwargs) if isinstance(key, basestring): key = cls.__keycla...
Provides bridged methods between `model.Model` and the Adapter API.
AdaptedModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdaptedModel: """Provides bridged methods between `model.Model` and the Adapter API.""" def get(cls, key=None, name=None, **kwargs): """Retrieve a persisted version of this model via the current datastore adapter.""" <|body_0|> def query(cls, *args, **kwargs): ""...
stack_v2_sparse_classes_36k_train_006690
9,479
permissive
[ { "docstring": "Retrieve a persisted version of this model via the current datastore adapter.", "name": "get", "signature": "def get(cls, key=None, name=None, **kwargs)" }, { "docstring": "Start building a new `model.Query` object, if the underlying adapter implements `IndexedModelAdapter`.", ...
4
stack_v2_sparse_classes_30k_train_002276
Implement the Python class `AdaptedModel` described below. Class description: Provides bridged methods between `model.Model` and the Adapter API. Method signatures and docstrings: - def get(cls, key=None, name=None, **kwargs): Retrieve a persisted version of this model via the current datastore adapter. - def query(c...
Implement the Python class `AdaptedModel` described below. Class description: Provides bridged methods between `model.Model` and the Adapter API. Method signatures and docstrings: - def get(cls, key=None, name=None, **kwargs): Retrieve a persisted version of this model via the current datastore adapter. - def query(c...
cfc4ef00ec67df97e08b57222ca16aa9f2659a3e
<|skeleton|> class AdaptedModel: """Provides bridged methods between `model.Model` and the Adapter API.""" def get(cls, key=None, name=None, **kwargs): """Retrieve a persisted version of this model via the current datastore adapter.""" <|body_0|> def query(cls, *args, **kwargs): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AdaptedModel: """Provides bridged methods between `model.Model` and the Adapter API.""" def get(cls, key=None, name=None, **kwargs): """Retrieve a persisted version of this model via the current datastore adapter.""" if not key and (not name): raise ValueError('Must pass eithe...
the_stack_v2_python_sparse
canteen/model/adapter/core.py
ianjw11/canteen
train
0
6e87d7064119070ec564201a936b8feb20ae70ba
[ "key = super(AppUser, self).put(**kwargs)\ncache_key = 'user|%s' % self.email\nrediscache.delete(cache_key)", "key = super(AppUser, self).key.delete(**kwargs)\ncache_key = 'user|%s' % self.email\nrediscache.delete(cache_key)", "cache_key = 'user|%s' % email\ncached_app_user = rediscache.get(cache_key)\nif cache...
<|body_start_0|> key = super(AppUser, self).put(**kwargs) cache_key = 'user|%s' % self.email rediscache.delete(cache_key) <|end_body_0|> <|body_start_1|> key = super(AppUser, self).key.delete(**kwargs) cache_key = 'user|%s' % self.email rediscache.delete(cache_key) <|end...
Describes a user for permission checking.
AppUser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AppUser: """Describes a user for permission checking.""" def put(self, **kwargs): """when we update an AppUser, also delete in rediscache.""" <|body_0|> def delete(self, **kwargs): """when we delete an AppUser, also delete in rediscache.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_006691
8,866
permissive
[ { "docstring": "when we update an AppUser, also delete in rediscache.", "name": "put", "signature": "def put(self, **kwargs)" }, { "docstring": "when we delete an AppUser, also delete in rediscache.", "name": "delete", "signature": "def delete(self, **kwargs)" }, { "docstring": "...
3
null
Implement the Python class `AppUser` described below. Class description: Describes a user for permission checking. Method signatures and docstrings: - def put(self, **kwargs): when we update an AppUser, also delete in rediscache. - def delete(self, **kwargs): when we delete an AppUser, also delete in rediscache. - de...
Implement the Python class `AppUser` described below. Class description: Describes a user for permission checking. Method signatures and docstrings: - def put(self, **kwargs): when we update an AppUser, also delete in rediscache. - def delete(self, **kwargs): when we delete an AppUser, also delete in rediscache. - de...
17f9886d064da5bda84006d5866077727646fff2
<|skeleton|> class AppUser: """Describes a user for permission checking.""" def put(self, **kwargs): """when we update an AppUser, also delete in rediscache.""" <|body_0|> def delete(self, **kwargs): """when we delete an AppUser, also delete in rediscache.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AppUser: """Describes a user for permission checking.""" def put(self, **kwargs): """when we update an AppUser, also delete in rediscache.""" key = super(AppUser, self).put(**kwargs) cache_key = 'user|%s' % self.email rediscache.delete(cache_key) def delete(self, **kw...
the_stack_v2_python_sparse
internals/user_models.py
GoogleChrome/chromium-dashboard
train
574
e1608f7260d1ba139f6fb23ed0fc469174f681ee
[ "if self._nlp is None:\n config = SpacyConfig()\n nlp = spacy.load(config.name)\n self._nlp = nlp\nreturn self._nlp", "if self._sess is None:\n db_config = MySQLConfig()\n engine = sa.create_engine(f'mysql://{db_config.user}:{db_config.password}@{db_config.host}: {db_config.port}...
<|body_start_0|> if self._nlp is None: config = SpacyConfig() nlp = spacy.load(config.name) self._nlp = nlp return self._nlp <|end_body_0|> <|body_start_1|> if self._sess is None: db_config = MySQLConfig() engine = sa.create_engine(f'm...
Ml Base Task
MlTask
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MlTask: """Ml Base Task""" def nlp(self): """Returns spacy language model""" <|body_0|> def sess(self): """Returns SQLAlchemy Session""" <|body_1|> <|end_skeleton|> <|body_start_0|> if self._nlp is None: config = SpacyConfig() ...
stack_v2_sparse_classes_36k_train_006692
3,356
permissive
[ { "docstring": "Returns spacy language model", "name": "nlp", "signature": "def nlp(self)" }, { "docstring": "Returns SQLAlchemy Session", "name": "sess", "signature": "def sess(self)" } ]
2
stack_v2_sparse_classes_30k_test_000076
Implement the Python class `MlTask` described below. Class description: Ml Base Task Method signatures and docstrings: - def nlp(self): Returns spacy language model - def sess(self): Returns SQLAlchemy Session
Implement the Python class `MlTask` described below. Class description: Ml Base Task Method signatures and docstrings: - def nlp(self): Returns spacy language model - def sess(self): Returns SQLAlchemy Session <|skeleton|> class MlTask: """Ml Base Task""" def nlp(self): """Returns spacy language mod...
4af213fe760516b1daac608758742862ed848d7f
<|skeleton|> class MlTask: """Ml Base Task""" def nlp(self): """Returns spacy language model""" <|body_0|> def sess(self): """Returns SQLAlchemy Session""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MlTask: """Ml Base Task""" def nlp(self): """Returns spacy language model""" if self._nlp is None: config = SpacyConfig() nlp = spacy.load(config.name) self._nlp = nlp return self._nlp def sess(self): """Returns SQLAlchemy Session""...
the_stack_v2_python_sparse
eyes/celery/ml/tasks.py
r05323028/eyes
train
74
71938574137ab9b0df5c1b16301b1795a23a8fea
[ "if self.master:\n if hasattr(self.master, 'notify_task'):\n self.master.notify_task(_task, _progress)\n else:\n print(self.__class__.__name__ + ': Internal deficiency, ' + self.master.__class__.__name__ + ' should have a notify_task function\\nTask:\\n' + _task + '\\n' + str(_progress))\nelse:\...
<|body_start_0|> if self.master: if hasattr(self.master, 'notify_task'): self.master.notify_task(_task, _progress) else: print(self.__class__.__name__ + ': Internal deficiency, ' + self.master.__class__.__name__ + ' should have a notify_task function\nTask...
This class introduces all properties that a frame in BPM tools should hold.
BPMFrame
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BPMFrame: """This class introduces all properties that a frame in BPM tools should hold.""" def notify_task(self, _task, _progress): """This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget stru...
stack_v2_sparse_classes_36k_train_006693
11,721
permissive
[ { "docstring": "This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget structure until someone has a notify_task that's different. See the main_tk_replicator.ReplicatorMain for an example, :param _task: Text that defines th...
2
stack_v2_sparse_classes_30k_train_010917
Implement the Python class `BPMFrame` described below. Class description: This class introduces all properties that a frame in BPM tools should hold. Method signatures and docstrings: - def notify_task(self, _task, _progress): This function checks if the master widget has a notify_task function, and if so, calls it. ...
Implement the Python class `BPMFrame` described below. Class description: This class introduces all properties that a frame in BPM tools should hold. Method signatures and docstrings: - def notify_task(self, _task, _progress): This function checks if the master widget has a notify_task function, and if so, calls it. ...
4d7a31c0d68042b4110e1fa3e733711e0fdd473e
<|skeleton|> class BPMFrame: """This class introduces all properties that a frame in BPM tools should hold.""" def notify_task(self, _task, _progress): """This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget stru...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BPMFrame: """This class introduces all properties that a frame in BPM tools should hold.""" def notify_task(self, _task, _progress): """This function checks if the master widget has a notify_task function, and if so, calls it. This way, notifications travel upwards in the widget structure until s...
the_stack_v2_python_sparse
qal/tools/gui/widgets_misc.py
OptimalBPM/qal
train
3
f8e8fc96c20017bdd9c6dd55aeb84705a3659cc0
[ "from cms.models import GlobalPagePermission, Page\nif user.is_superuser or GlobalPagePermission.objects.with_can_change_permissions(user):\n return self.all()\nfrom cms.utils.permissions import get_user_permission_level\ntry:\n user_level = get_user_permission_level(user)\nexcept NoPermissionsException:\n ...
<|body_start_0|> from cms.models import GlobalPagePermission, Page if user.is_superuser or GlobalPagePermission.objects.with_can_change_permissions(user): return self.all() from cms.utils.permissions import get_user_permission_level try: user_level = get_user_perm...
Page permission manager accessible under objects.
PagePermissionManager
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PagePermissionManager: """Page permission manager accessible under objects.""" def subordinate_to_user(self, user): """Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude obje...
stack_v2_sparse_classes_36k_train_006694
18,602
permissive
[ { "docstring": "Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude objects with given user, or any group containing this user - he can't be able to change his own permissions, because if he does, and re...
2
stack_v2_sparse_classes_30k_train_002567
Implement the Python class `PagePermissionManager` described below. Class description: Page permission manager accessible under objects. Method signatures and docstrings: - def subordinate_to_user(self, user): Get all page permission objects on which user/group is lover in hierarchy then given user and given user can...
Implement the Python class `PagePermissionManager` described below. Class description: Page permission manager accessible under objects. Method signatures and docstrings: - def subordinate_to_user(self, user): Get all page permission objects on which user/group is lover in hierarchy then given user and given user can...
d563d912c99f0c138a66d99829d8d0133226894e
<|skeleton|> class PagePermissionManager: """Page permission manager accessible under objects.""" def subordinate_to_user(self, user): """Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude obje...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PagePermissionManager: """Page permission manager accessible under objects.""" def subordinate_to_user(self, user): """Get all page permission objects on which user/group is lover in hierarchy then given user and given user can change permissions on them. !IMPORTANT, but exclude objects with give...
the_stack_v2_python_sparse
cms/models/managers.py
DrMeers/django-cms-2.0
train
4
6117b6be55b0572460a81b2633823993623b1741
[ "super(LevelTwo, self).__init__(screen)\nself.villain_one = None\nself.villain_two = None\nself._set_villain()", "self.villain_one = donkey.Donkey(100, constants.THREE_Y, 0, 500)\nself.active_sprite_list.add(self.villain_one)\nself.villain_two = donkey.Donkey(900, constants.TWO_Y, 700, 950)\nself.active_sprite_li...
<|body_start_0|> super(LevelTwo, self).__init__(screen) self.villain_one = None self.villain_two = None self._set_villain() <|end_body_0|> <|body_start_1|> self.villain_one = donkey.Donkey(100, constants.THREE_Y, 0, 500) self.active_sprite_list.add(self.villain_one) ...
Class which defines the second level of the game
LevelTwo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LevelTwo: """Class which defines the second level of the game""" def __init__(self, screen): """Constructor for the LevelTwo class""" <|body_0|> def _set_villain(self): """Sets the number of donkeys and their positions for the second level of the game.""" ...
stack_v2_sparse_classes_36k_train_006695
1,964
no_license
[ { "docstring": "Constructor for the LevelTwo class", "name": "__init__", "signature": "def __init__(self, screen)" }, { "docstring": "Sets the number of donkeys and their positions for the second level of the game.", "name": "_set_villain", "signature": "def _set_villain(self)" } ]
2
stack_v2_sparse_classes_30k_train_001143
Implement the Python class `LevelTwo` described below. Class description: Class which defines the second level of the game Method signatures and docstrings: - def __init__(self, screen): Constructor for the LevelTwo class - def _set_villain(self): Sets the number of donkeys and their positions for the second level of...
Implement the Python class `LevelTwo` described below. Class description: Class which defines the second level of the game Method signatures and docstrings: - def __init__(self, screen): Constructor for the LevelTwo class - def _set_villain(self): Sets the number of donkeys and their positions for the second level of...
26d629f8348f0110fa84b02009e787a238aff441
<|skeleton|> class LevelTwo: """Class which defines the second level of the game""" def __init__(self, screen): """Constructor for the LevelTwo class""" <|body_0|> def _set_villain(self): """Sets the number of donkeys and their positions for the second level of the game.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LevelTwo: """Class which defines the second level of the game""" def __init__(self, screen): """Constructor for the LevelTwo class""" super(LevelTwo, self).__init__(screen) self.villain_one = None self.villain_two = None self._set_villain() def _set_villain(se...
the_stack_v2_python_sparse
IIITSERC-ssad_2015_a3_group1-88a823ccd2d0/Akshat Tandon/201503001/levels.py
anirudhdahiya9/Open-data-projecy
train
1
42c8cacf1247d6146c1884916c8eb9d5d266a763
[ "path_of_preorder = []\n\ndef helper(node):\n if node:\n path_of_preorder.append(node.val)\n helper(node.left)\n helper(node.right)\nhelper(root)\nreturn '#'.join(map(str, path_of_preorder))", "if not data:\n return None\nnode_values = deque((int(value) for value in data.split('#')))\n\...
<|body_start_0|> path_of_preorder = [] def helper(node): if node: path_of_preorder.append(node.val) helper(node.left) helper(node.right) helper(root) return '#'.join(map(str, path_of_preorder)) <|end_body_0|> <|body_start_1|> ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|> <|body_start_0|> path_of_preord...
stack_v2_sparse_classes_36k_train_006696
2,343
no_license
[ { "docstring": "Encodes a tree to a single string.", "name": "serialize", "signature": "def serialize(self, root: TreeNode) -> str" }, { "docstring": "Decodes your encoded data to tree.", "name": "deserialize", "signature": "def deserialize(self, data: str) -> TreeNode" } ]
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. - def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. <|skeleton|> class Co...
5f71ba34f7198841fefaa68eee5b95f2f989296b
<|skeleton|> class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" <|body_0|> def deserialize(self, data: str) -> TreeNode: """Decodes your encoded data to tree.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string.""" path_of_preorder = [] def helper(node): if node: path_of_preorder.append(node.val) helper(node.left) helper(node.right) helpe...
the_stack_v2_python_sparse
LeetCode/medium/29_SerializeBST.py
Kohdz/Algorithms
train
5
7761259dab72aad87d471ba08bf6310965a2fbd9
[ "if self.success_url:\n return self.success_url\nreturn self.object.web_get_detail_url()", "obj = self.get_object()\ndata = {k: getattr(obj.db, k, '') for k in self.form_class.base_fields}\ndata.update({k: getattr(obj, k, '') for k in self.form_class.Meta.fields})\nreturn data", "data = {k: v for k, v in for...
<|body_start_0|> if self.success_url: return self.success_url return self.object.web_get_detail_url() <|end_body_0|> <|body_start_1|> obj = self.get_object() data = {k: getattr(obj.db, k, '') for k in self.form_class.base_fields} data.update({k: getattr(obj, k, '') f...
This is an important view. Any view you write that deals with updating a specific object will want to inherit from this. It provides the mechanisms by which to make sure the user requesting editing of an object is authenticated, and that they have permissions to edit the requested object. This functions slightly differ...
ObjectUpdateView
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectUpdateView: """This is an important view. Any view you write that deals with updating a specific object will want to inherit from this. It provides the mechanisms by which to make sure the user requesting editing of an object is authenticated, and that they have permissions to edit the requ...
stack_v2_sparse_classes_36k_train_006697
35,922
permissive
[ { "docstring": "Django hook. Can be overridden to return any URL you want to redirect the user to after the object is successfully updated, but by default it goes to the object detail page so the user can see their changes reflected.", "name": "get_success_url", "signature": "def get_success_url(self)" ...
3
null
Implement the Python class `ObjectUpdateView` described below. Class description: This is an important view. Any view you write that deals with updating a specific object will want to inherit from this. It provides the mechanisms by which to make sure the user requesting editing of an object is authenticated, and that...
Implement the Python class `ObjectUpdateView` described below. Class description: This is an important view. Any view you write that deals with updating a specific object will want to inherit from this. It provides the mechanisms by which to make sure the user requesting editing of an object is authenticated, and that...
5e97df013399e1a401d0a7ec184c4b9eb3100edd
<|skeleton|> class ObjectUpdateView: """This is an important view. Any view you write that deals with updating a specific object will want to inherit from this. It provides the mechanisms by which to make sure the user requesting editing of an object is authenticated, and that they have permissions to edit the requ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObjectUpdateView: """This is an important view. Any view you write that deals with updating a specific object will want to inherit from this. It provides the mechanisms by which to make sure the user requesting editing of an object is authenticated, and that they have permissions to edit the requested object....
the_stack_v2_python_sparse
evennia-engine/evennia/evennia/web/website/views.py
rajammanabrolu/WorldGeneration
train
69
dbc61411abf958bf9fcf1f49785c2ac5ac04d37c
[ "for state in connection_states:\n if state not in constants.TCPConnectionState.STATES:\n raise ValueError('Expected connection state not defined: %s' % state)\nip_address = ip_address or ''\nport = port or ''\ncmd = 'esxcli network ip connection list | grep %s:%s' % (ip_address, port)\nif keywords:\n ...
<|body_start_0|> for state in connection_states: if state not in constants.TCPConnectionState.STATES: raise ValueError('Expected connection state not defined: %s' % state) ip_address = ip_address or '' port = port or '' cmd = 'esxcli network ip connection list...
ESX55OSImpl
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ESX55OSImpl: def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): """Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connectio...
stack_v2_sparse_classes_36k_train_006698
3,893
no_license
[ { "docstring": "Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connection to this IP address. @type port: integer @param port: Check connection state to this port number. @type connection_states: list @param connection_stat...
3
stack_v2_sparse_classes_30k_test_000071
Implement the Python class `ESX55OSImpl` described below. Class description: Implement the ESX55OSImpl class. Method signatures and docstrings: - def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): Returns the tcp connection count using netsta...
Implement the Python class `ESX55OSImpl` described below. Class description: Implement the ESX55OSImpl class. Method signatures and docstrings: - def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): Returns the tcp connection count using netsta...
5b55817c050b637e2747084290f6206d2e622938
<|skeleton|> class ESX55OSImpl: def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): """Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connectio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ESX55OSImpl: def get_tcp_connection_count(cls, client_object, ip_address=None, port=None, connection_states=None, keywords=None, **kwargs): """Returns the tcp connection count using netstat command matching the given parameters. @type ip_address: string @param ip_address: Check connection to this IP a...
the_stack_v2_python_sparse
SystemTesting/pylib/vmware/vsphere/esx/cli/esx55_os_impl.py
Cloudxtreme/MyProject
train
0
053eddcf1177667ca644be58682e5b5265966dbb
[ "if data is not None:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n mean = float(sum(data) / len(data))\n new_data = [(x - mean) ** 2 for x in data]\n variance = sum(new_data) / len(dat...
<|body_start_0|> if data is not None: if type(data) is not list: raise TypeError('data must be a list') if len(data) < 2: raise ValueError('data must contain multiple values') mean = float(sum(data) / len(data)) new_data = [(x - mea...
Binomial distribution
Binomial
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Binomial: """Binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Instantiation method Args: data (list): data to be used to estimate the distribution. Defaults to None. n (int): number of Bernoulli trials. Defaults to 1. p (float): probability of a “success”. Defau...
stack_v2_sparse_classes_36k_train_006699
2,392
no_license
[ { "docstring": "Instantiation method Args: data (list): data to be used to estimate the distribution. Defaults to None. n (int): number of Bernoulli trials. Defaults to 1. p (float): probability of a “success”. Defaults to 0.5.", "name": "__init__", "signature": "def __init__(self, data=None, n=1, p=0.5...
3
stack_v2_sparse_classes_30k_train_003390
Implement the Python class `Binomial` described below. Class description: Binomial distribution Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Instantiation method Args: data (list): data to be used to estimate the distribution. Defaults to None. n (int): number of Bernoulli trials. De...
Implement the Python class `Binomial` described below. Class description: Binomial distribution Method signatures and docstrings: - def __init__(self, data=None, n=1, p=0.5): Instantiation method Args: data (list): data to be used to estimate the distribution. Defaults to None. n (int): number of Bernoulli trials. De...
bb980395b146c9f4e0d4e9766c4a36f67de70d2e
<|skeleton|> class Binomial: """Binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Instantiation method Args: data (list): data to be used to estimate the distribution. Defaults to None. n (int): number of Bernoulli trials. Defaults to 1. p (float): probability of a “success”. Defau...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Binomial: """Binomial distribution""" def __init__(self, data=None, n=1, p=0.5): """Instantiation method Args: data (list): data to be used to estimate the distribution. Defaults to None. n (int): number of Bernoulli trials. Defaults to 1. p (float): probability of a “success”. Defaults to 0.5.""...
the_stack_v2_python_sparse
math/0x03-probability/binomial.py
AndrewKalil/holbertonschool-machine_learning
train
0