blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
edf3f30c07f10dba8aff46dbff9ccfe43faef8d1
[ "self.users = [UserFactory.create() for i in range(10)]\nself.images = [ImageFactory.build() for i in range(10)]\nself.albums = [AlbumFactory.build() for i in range(10)]\nfor i in range(10):\n curr_image = self.images[i]\n curr_album = self.albums[i]\n curr_image.author = self.users[i]\n curr_album.owne...
<|body_start_0|> self.users = [UserFactory.create() for i in range(10)] self.images = [ImageFactory.build() for i in range(10)] self.albums = [AlbumFactory.build() for i in range(10)] for i in range(10): curr_image = self.images[i] curr_album = self.albums[i] ...
The test runner for the Photo model.
ImageTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageTestCase: """The test runner for the Photo model.""" def setUp(self): """The appropriate setup for the appropriate test.""" <|body_0|> def test_photo_can_be_assigned_to_user(self): """Test that a photo and user can be connected.""" <|body_1|> de...
stack_v2_sparse_classes_75kplus_train_000000
7,924
permissive
[ { "docstring": "The appropriate setup for the appropriate test.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test that a photo and user can be connected.", "name": "test_photo_can_be_assigned_to_user", "signature": "def test_photo_can_be_assigned_to_user(self)" ...
5
stack_v2_sparse_classes_30k_train_016432
Implement the Python class `ImageTestCase` described below. Class description: The test runner for the Photo model. Method signatures and docstrings: - def setUp(self): The appropriate setup for the appropriate test. - def test_photo_can_be_assigned_to_user(self): Test that a photo and user can be connected. - def te...
Implement the Python class `ImageTestCase` described below. Class description: The test runner for the Photo model. Method signatures and docstrings: - def setUp(self): The appropriate setup for the appropriate test. - def test_photo_can_be_assigned_to_user(self): Test that a photo and user can be connected. - def te...
9b33bdde34b325af3d54dcfbb9ff952ca90a26c1
<|skeleton|> class ImageTestCase: """The test runner for the Photo model.""" def setUp(self): """The appropriate setup for the appropriate test.""" <|body_0|> def test_photo_can_be_assigned_to_user(self): """Test that a photo and user can be connected.""" <|body_1|> de...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImageTestCase: """The test runner for the Photo model.""" def setUp(self): """The appropriate setup for the appropriate test.""" self.users = [UserFactory.create() for i in range(10)] self.images = [ImageFactory.build() for i in range(10)] self.albums = [AlbumFactory.build...
the_stack_v2_python_sparse
imagersite/imager_images/tests.py
CCallahanIV/django-imager
train
0
ab87269cb25a751db5b14e4c1fe2914a25778318
[ "self._clip_obs = clip_obs\nself._obs_shape = mdp_info.observation_space.shape\nself._obs_runstand = RunningStandardization(shape=self._obs_shape, alpha=alpha)\nself._add_save_attr(_clip_obs='primitive', _obs_shape='primitive', _obs_runstand='mushroom')", "assert obs.shape == self._obs_shape, 'Values given to run...
<|body_start_0|> self._clip_obs = clip_obs self._obs_shape = mdp_info.observation_space.shape self._obs_runstand = RunningStandardization(shape=self._obs_shape, alpha=alpha) self._add_save_attr(_clip_obs='primitive', _obs_shape='primitive', _obs_runstand='mushroom') <|end_body_0|> <|bod...
Preprocess observations from the environment using a running standardization.
StandardizationPreprocessor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StandardizationPreprocessor: """Preprocess observations from the environment using a running standardization.""" def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): """Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the norma...
stack_v2_sparse_classes_75kplus_train_000001
4,016
permissive
[ { "docstring": "Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the normalized observations; alpha (float, 1e-32): moving average catchup parameter for the normalization.", "name": "__init__", "signature": "def __init__(self, mdp_info, clip_obs=10.0, ...
2
stack_v2_sparse_classes_30k_train_018967
Implement the Python class `StandardizationPreprocessor` described below. Class description: Preprocess observations from the environment using a running standardization. Method signatures and docstrings: - def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): Constructor. Args: mdp_info (MDPInfo): information of...
Implement the Python class `StandardizationPreprocessor` described below. Class description: Preprocess observations from the environment using a running standardization. Method signatures and docstrings: - def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): Constructor. Args: mdp_info (MDPInfo): information of...
2decae31459a3481130afe1263bc0a5ba7954a99
<|skeleton|> class StandardizationPreprocessor: """Preprocess observations from the environment using a running standardization.""" def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): """Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the norma...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StandardizationPreprocessor: """Preprocess observations from the environment using a running standardization.""" def __init__(self, mdp_info, clip_obs=10.0, alpha=1e-32): """Constructor. Args: mdp_info (MDPInfo): information of the MDP; clip_obs (float, 10.): values to clip the normalized observa...
the_stack_v2_python_sparse
mushroom_rl/utils/preprocessors.py
MushroomRL/mushroom-rl
train
477
be145d69da147d8c0a117bd4ee974866ea1e8ea3
[ "N = len(nums)\nW = (sum(nums) + S) // 2\nif (sum(nums) + S) % 2 == 1:\n return 0\nif sum(nums) < S or sum(nums) < -S:\n return 0\ndp = [0] * (W + 1)\ndp[0] = 1\nfor i in range(1, N + 1):\n for j in range(W, nums[i - 1] - 1, -1):\n dp[j] = dp[j] + dp[j - nums[i - 1]]\nprint(dp)\nreturn dp[W]", "de...
<|body_start_0|> N = len(nums) W = (sum(nums) + S) // 2 if (sum(nums) + S) % 2 == 1: return 0 if sum(nums) < S or sum(nums) < -S: return 0 dp = [0] * (W + 1) dp[0] = 1 for i in range(1, N + 1): for j in range(W, nums[i - 1] - 1,...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: """状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2""" <|body_0|> def findTargetSumWays1(self, nums: List[int], S: in...
stack_v2_sparse_classes_75kplus_train_000002
3,913
permissive
[ { "docstring": "状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2", "name": "findTargetSumWays", "signature": "def findTargetSumWays(self, nums: List[int], S: int) -> int" }, { "docstring": "回溯算法:二进制递归枚举", ...
3
stack_v2_sparse_classes_30k_train_014214
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findTargetSumWays(self, nums: List[int], S: int) -> int: 状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findTargetSumWays(self, nums: List[int], S: int) -> int: 状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素...
e8a1c6cae6547cbcb6e8494be6df685f3e7c837c
<|skeleton|> class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: """状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2""" <|body_0|> def findTargetSumWays1(self, nums: List[int], S: in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: """状态转移方程:0-1背包 假设所有元素和为sum,所有添加正号的元素的和为A,所有添加负号的元素和为B, 则有sum = A + B 且 S = A - B,解方程得A = (sum + S)/2。 即题目转换成:从数组中选取一些元素使和恰好为(sum + S) / 2""" N = len(nums) W = (sum(nums) + S) // 2 if (sum(nums) + S) % 2 == ...
the_stack_v2_python_sparse
494-target-sum.py
yuenliou/leetcode
train
0
2ce78c7158dc1cc9446cc4ca6345778382c57f50
[ "super().__init__(name=name)\nself.fragments_storage = CloudFiles(fragments_path)\nself.output_storage = CloudFiles(output_path)", "print(f'aggregate skeletons with prefix of {prefix}')\nid2filenames = defaultdict(list)\nfor filename in self.fragments_storage.list_files(prefix=prefix):\n filename = os.path.bas...
<|body_start_0|> super().__init__(name=name) self.fragments_storage = CloudFiles(fragments_path) self.output_storage = CloudFiles(output_path) <|end_body_0|> <|body_start_1|> print(f'aggregate skeletons with prefix of {prefix}') id2filenames = defaultdict(list) for filen...
Merge skeleton fragments for Neuroglancer visualization.
AggregateSkeletonFragmentsOperator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AggregateSkeletonFragmentsOperator: """Merge skeleton fragments for Neuroglancer visualization.""" def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): """Parameters ------------ fragments_path: path to store fragment files output_path:...
stack_v2_sparse_classes_75kplus_train_000003
2,270
permissive
[ { "docstring": "Parameters ------------ fragments_path: path to store fragment files output_path: save the merged skeleton file here.", "name": "__init__", "signature": "def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments')" }, { "docstring": "To-do:...
2
stack_v2_sparse_classes_30k_train_033821
Implement the Python class `AggregateSkeletonFragmentsOperator` described below. Class description: Merge skeleton fragments for Neuroglancer visualization. Method signatures and docstrings: - def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): Parameters ------------ ...
Implement the Python class `AggregateSkeletonFragmentsOperator` described below. Class description: Merge skeleton fragments for Neuroglancer visualization. Method signatures and docstrings: - def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): Parameters ------------ ...
4b1b6cc7844f8bf453ae0ba3b618106163fa9bcf
<|skeleton|> class AggregateSkeletonFragmentsOperator: """Merge skeleton fragments for Neuroglancer visualization.""" def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): """Parameters ------------ fragments_path: path to store fragment files output_path:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AggregateSkeletonFragmentsOperator: """Merge skeleton fragments for Neuroglancer visualization.""" def __init__(self, fragments_path: str, output_path: str, name: str='aggregate-skeleton-fragments'): """Parameters ------------ fragments_path: path to store fragment files output_path: save the mer...
the_stack_v2_python_sparse
chunkflow/plugins/aggregate_skeleton_fragments.py
seung-lab/chunkflow
train
47
811a74e29519b7b7a5811d119bd4def2468c16d9
[ "parameters = models.CheckSkuAvailabilityParameter(skus=skus, kind=kind, type=type)\nurl = self.check_sku_availability.metadata['url']\npath_format_arguments = {'subscriptionId': self._serialize.url('self.config.subscription_id', self.config.subscription_id, 'str', min_length=1), 'location': self._serialize.url('lo...
<|body_start_0|> parameters = models.CheckSkuAvailabilityParameter(skus=skus, kind=kind, type=type) url = self.check_sku_availability.metadata['url'] path_format_arguments = {'subscriptionId': self._serialize.url('self.config.subscription_id', self.config.subscription_id, 'str', min_length=1), '...
CognitiveServicesManagementClientOperationsMixin
[ "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CognitiveServicesManagementClientOperationsMixin: def check_sku_availability(self, location, skus, kind, type, custom_headers=None, raw=False, **operation_config): """Check available SKUs. :param location: Resource location. :type location: str :param skus: The SKU of the resource. :type...
stack_v2_sparse_classes_75kplus_train_000004
7,119
permissive
[ { "docstring": "Check available SKUs. :param location: Resource location. :type location: str :param skus: The SKU of the resource. :type skus: list[str] :param kind: The Kind of the resource. :type kind: str :param type: The Type of the resource. :type type: str :param dict custom_headers: headers that will be...
2
stack_v2_sparse_classes_30k_val_001355
Implement the Python class `CognitiveServicesManagementClientOperationsMixin` described below. Class description: Implement the CognitiveServicesManagementClientOperationsMixin class. Method signatures and docstrings: - def check_sku_availability(self, location, skus, kind, type, custom_headers=None, raw=False, **ope...
Implement the Python class `CognitiveServicesManagementClientOperationsMixin` described below. Class description: Implement the CognitiveServicesManagementClientOperationsMixin class. Method signatures and docstrings: - def check_sku_availability(self, location, skus, kind, type, custom_headers=None, raw=False, **ope...
f779de8e53dbec033f98f976284e6d9491fd60b3
<|skeleton|> class CognitiveServicesManagementClientOperationsMixin: def check_sku_availability(self, location, skus, kind, type, custom_headers=None, raw=False, **operation_config): """Check available SKUs. :param location: Resource location. :type location: str :param skus: The SKU of the resource. :type...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CognitiveServicesManagementClientOperationsMixin: def check_sku_availability(self, location, skus, kind, type, custom_headers=None, raw=False, **operation_config): """Check available SKUs. :param location: Resource location. :type location: str :param skus: The SKU of the resource. :type skus: list[st...
the_stack_v2_python_sparse
sdk/cognitiveservices/azure-mgmt-cognitiveservices/azure/mgmt/cognitiveservices/operations/_cognitive_services_management_client_operations.py
YijunXieMS/azure-sdk-for-python
train
1
66fd1e94308a90fcc9030a979f26c054d3fe6061
[ "super().__init__(**kwargs)\nself.label = label\nself.did = did\nself.recipient_keys = list(recipient_keys) if recipient_keys else None\nself.endpoint = endpoint\nself.routing_keys = list(routing_keys) if routing_keys else None\nself.image_url = image_url", "c_json = self.to_json()\nc_i = bytes_to_b64(c_json.enco...
<|body_start_0|> super().__init__(**kwargs) self.label = label self.did = did self.recipient_keys = list(recipient_keys) if recipient_keys else None self.endpoint = endpoint self.routing_keys = list(routing_keys) if routing_keys else None self.image_url = image_ur...
Class representing a connection invitation.
ConnectionInvitation
[ "LicenseRef-scancode-dco-1.1", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConnectionInvitation: """Class representing a connection invitation.""" def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs): """Initialize connection invitation ...
stack_v2_sparse_classes_75kplus_train_000005
5,648
permissive
[ { "docstring": "Initialize connection invitation object. Args: label: Optional label for connection invitation did: DID for this connection invitation recipient_keys: List of recipient keys endpoint: Endpoint which this agent can be reached at routing_keys: List of routing keys image_url: Optional image URL for...
3
stack_v2_sparse_classes_30k_train_031714
Implement the Python class `ConnectionInvitation` described below. Class description: Class representing a connection invitation. Method signatures and docstrings: - def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_ur...
Implement the Python class `ConnectionInvitation` described below. Class description: Class representing a connection invitation. Method signatures and docstrings: - def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_ur...
39cac36d8937ce84a9307ce100aaefb8bc05ec04
<|skeleton|> class ConnectionInvitation: """Class representing a connection invitation.""" def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs): """Initialize connection invitation ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConnectionInvitation: """Class representing a connection invitation.""" def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs): """Initialize connection invitation object. Args:...
the_stack_v2_python_sparse
aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py
hyperledger/aries-cloudagent-python
train
370
e4ff882ac432ed2ee43f9e7487b700100fccbea4
[ "super(Morphological_Chan_Vese, self).__init__(paramlist)\nif not paramlist:\n self.params['algorithm'] = 'Morphological_Chan_Vese'\n self.params['alpha1'] = 1\n self.params['beta1'] = 1\n self.params['beta2'] = 1\n self.params['max_iter'] = 10\n self.params['n_segments'] = 0\nself.paramindexes = ...
<|body_start_0|> super(Morphological_Chan_Vese, self).__init__(paramlist) if not paramlist: self.params['algorithm'] = 'Morphological_Chan_Vese' self.params['alpha1'] = 1 self.params['beta1'] = 1 self.params['beta2'] = 1 self.params['max_iter']...
Peform Morphological Chan Vese segmentation algorithm. ONLY WORKS ON GRAYSCALE. Active contours without edges. Can be used to segment images/volumes without good borders. Required that the inside of the object looks different than outside (color, shade, darker). Parameters: image -- ndarray of grayscale image iteration...
Morphological_Chan_Vese
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Morphological_Chan_Vese: """Peform Morphological Chan Vese segmentation algorithm. ONLY WORKS ON GRAYSCALE. Active contours without edges. Can be used to segment images/volumes without good borders. Required that the inside of the object looks different than outside (color, shade, darker). Parame...
stack_v2_sparse_classes_75kplus_train_000006
29,598
permissive
[ { "docstring": "Get parameters from parameter list that are used in segmentation algorithm. Assign default values to these parameters.", "name": "__init__", "signature": "def __init__(self, paramlist=None)" }, { "docstring": "Evaluate segmentation algorithm on training image. Keyword arguments: ...
2
stack_v2_sparse_classes_30k_train_000742
Implement the Python class `Morphological_Chan_Vese` described below. Class description: Peform Morphological Chan Vese segmentation algorithm. ONLY WORKS ON GRAYSCALE. Active contours without edges. Can be used to segment images/volumes without good borders. Required that the inside of the object looks different than...
Implement the Python class `Morphological_Chan_Vese` described below. Class description: Peform Morphological Chan Vese segmentation algorithm. ONLY WORKS ON GRAYSCALE. Active contours without edges. Can be used to segment images/volumes without good borders. Required that the inside of the object looks different than...
9246b8b20510d4c89357a6764ed96b919eb92d5a
<|skeleton|> class Morphological_Chan_Vese: """Peform Morphological Chan Vese segmentation algorithm. ONLY WORKS ON GRAYSCALE. Active contours without edges. Can be used to segment images/volumes without good borders. Required that the inside of the object looks different than outside (color, shade, darker). Parame...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Morphological_Chan_Vese: """Peform Morphological Chan Vese segmentation algorithm. ONLY WORKS ON GRAYSCALE. Active contours without edges. Can be used to segment images/volumes without good borders. Required that the inside of the object looks different than outside (color, shade, darker). Parameters: image -...
the_stack_v2_python_sparse
see/Segmentors.py
Deepak768/see-segment
train
0
c8b2ca6de19c3c372573a4acf4791283971199ca
[ "self._host = host\nself._port = port\nif os.environ.get('TEST_MODE') != 'UNIT_TEST':\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._host, port=self._port))\nself.sender_lock = threading.Lock()", "while True:\n try:\n with self.sender_lock:\n with self.con...
<|body_start_0|> self._host = host self._port = port if os.environ.get('TEST_MODE') != 'UNIT_TEST': self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._host, port=self._port)) self.sender_lock = threading.Lock() <|end_body_0|> <|body_start_1|> ...
The singleton - is a core API object for API class.
RabbitApi
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RabbitApi: """The singleton - is a core API object for API class.""" def __init__(self, host: str, port: int): """Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service""" <|body_0|> def emit(self,...
stack_v2_sparse_classes_75kplus_train_000007
2,095
permissive
[ { "docstring": "Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service", "name": "__init__", "signature": "def __init__(self, host: str, port: int)" }, { "docstring": "Function for sending events used by API.send() :param ...
2
stack_v2_sparse_classes_30k_train_004037
Implement the Python class `RabbitApi` described below. Class description: The singleton - is a core API object for API class. Method signatures and docstrings: - def __init__(self, host: str, port: int): Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of R...
Implement the Python class `RabbitApi` described below. Class description: The singleton - is a core API object for API class. Method signatures and docstrings: - def __init__(self, host: str, port: int): Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of R...
647ad6d7cc5f91c188aa45e403d9c1a33a7fe947
<|skeleton|> class RabbitApi: """The singleton - is a core API object for API class.""" def __init__(self, host: str, port: int): """Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service""" <|body_0|> def emit(self,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RabbitApi: """The singleton - is a core API object for API class.""" def __init__(self, host: str, port: int): """Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service""" self._host = host self._port = port...
the_stack_v2_python_sparse
main_node/tools/rabbit_API_class.py
dpukhkaiev/BRISE2
train
6
c4fe4105eaa1555c6bb452e20b8d972c34fec537
[ "from anima.dcc.blackmagic import get_fusion\nfusion = get_fusion()\ncomp = fusion.GetCurrentComp()\nreturn comp.ActiveTool", "node_input_list = node.GetInputList()\nfor input_entry_key in node_input_list.keys():\n input_entry = node_input_list[input_entry_key]\n input_id = input_entry.GetAttrs()['INPS_ID']...
<|body_start_0|> from anima.dcc.blackmagic import get_fusion fusion = get_fusion() comp = fusion.GetCurrentComp() return comp.ActiveTool <|end_body_0|> <|body_start_1|> node_input_list = node.GetInputList() for input_entry_key in node_input_list.keys(): input...
Node related utils for Fusion
NodeUtils
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodeUtils: """Node related utils for Fusion""" def get_active_node(self): """returns the active node""" <|body_0|> def list_input_ids(cls, node): """List input ids of the given node :param node: :return:""" <|body_1|> def get_node_attr(cls, node, att...
stack_v2_sparse_classes_75kplus_train_000008
10,465
permissive
[ { "docstring": "returns the active node", "name": "get_active_node", "signature": "def get_active_node(self)" }, { "docstring": "List input ids of the given node :param node: :return:", "name": "list_input_ids", "signature": "def list_input_ids(cls, node)" }, { "docstring": "gets...
6
stack_v2_sparse_classes_30k_train_003586
Implement the Python class `NodeUtils` described below. Class description: Node related utils for Fusion Method signatures and docstrings: - def get_active_node(self): returns the active node - def list_input_ids(cls, node): List input ids of the given node :param node: :return: - def get_node_attr(cls, node, attr): ...
Implement the Python class `NodeUtils` described below. Class description: Node related utils for Fusion Method signatures and docstrings: - def get_active_node(self): returns the active node - def list_input_ids(cls, node): List input ids of the given node :param node: :return: - def get_node_attr(cls, node, attr): ...
7b4cf60cb17f00435ecc3e03d573a9e2d0b44fe0
<|skeleton|> class NodeUtils: """Node related utils for Fusion""" def get_active_node(self): """returns the active node""" <|body_0|> def list_input_ids(cls, node): """List input ids of the given node :param node: :return:""" <|body_1|> def get_node_attr(cls, node, att...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NodeUtils: """Node related utils for Fusion""" def get_active_node(self): """returns the active node""" from anima.dcc.blackmagic import get_fusion fusion = get_fusion() comp = fusion.GetCurrentComp() return comp.ActiveTool def list_input_ids(cls, node): ...
the_stack_v2_python_sparse
anima/dcc/fusion/utils.py
eoyilmaz/anima
train
113
f5d152942a426e5154f715a2c4f16e0228ac1ef9
[ "key_file = tempfile.NamedTemporaryFile()\nkey_file.write(test_crypto.TEST_PRIVATE_KEY_PEM)\nkey_file.flush()\ncrypto = util.read_private_key(key_file.name)\nself.assertEqual(test_crypto.TEST_PRIVATE_KEY_X, crypto.x)\nkey_file.close()", "key_file = tempfile.NamedTemporaryFile()\nkey_file.write(TEST_SECT163K1_PRIV...
<|body_start_0|> key_file = tempfile.NamedTemporaryFile() key_file.write(test_crypto.TEST_PRIVATE_KEY_PEM) key_file.flush() crypto = util.read_private_key(key_file.name) self.assertEqual(test_crypto.TEST_PRIVATE_KEY_X, crypto.x) key_file.close() <|end_body_0|> <|body_sta...
TestReadPrivateKey
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestReadPrivateKey: def test_read_private_key(self): """Test reading the signing key from a file.""" <|body_0|> def test_read_private_key_invalid_curve(self): """Test that we require NIST384p for the signing key.""" <|body_1|> def test_read_private_key_i...
stack_v2_sparse_classes_75kplus_train_000009
6,083
permissive
[ { "docstring": "Test reading the signing key from a file.", "name": "test_read_private_key", "signature": "def test_read_private_key(self)" }, { "docstring": "Test that we require NIST384p for the signing key.", "name": "test_read_private_key_invalid_curve", "signature": "def test_read_p...
3
stack_v2_sparse_classes_30k_train_023706
Implement the Python class `TestReadPrivateKey` described below. Class description: Implement the TestReadPrivateKey class. Method signatures and docstrings: - def test_read_private_key(self): Test reading the signing key from a file. - def test_read_private_key_invalid_curve(self): Test that we require NIST384p for ...
Implement the Python class `TestReadPrivateKey` described below. Class description: Implement the TestReadPrivateKey class. Method signatures and docstrings: - def test_read_private_key(self): Test reading the signing key from a file. - def test_read_private_key_invalid_curve(self): Test that we require NIST384p for ...
936355508212b55ba9d34aeec41a0aadb96ac645
<|skeleton|> class TestReadPrivateKey: def test_read_private_key(self): """Test reading the signing key from a file.""" <|body_0|> def test_read_private_key_invalid_curve(self): """Test that we require NIST384p for the signing key.""" <|body_1|> def test_read_private_key_i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestReadPrivateKey: def test_read_private_key(self): """Test reading the signing key from a file.""" key_file = tempfile.NamedTemporaryFile() key_file.write(test_crypto.TEST_PRIVATE_KEY_PEM) key_file.flush() crypto = util.read_private_key(key_file.name) self.ass...
the_stack_v2_python_sparse
brkt_cli/test_util.py
ramyabrkt/brkt-cli
train
0
3921ffc20c6e6fcb32261a5b42c703f6855121ff
[ "self.angle1 = angle1\nself.angle2 = angle2\nself.angle3 = angle3\nnumber_of_sides = 3", "if self.angle1 + self.angle2 + self.angle3 == 180:\n print('This is a triangle')\n return True\nelse:\n print('This is not a traingle')\n return False" ]
<|body_start_0|> self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 <|end_body_0|> <|body_start_1|> if self.angle1 + self.angle2 + self.angle3 == 180: print('This is a triangle') return True else: print(...
validateTriangle
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class validateTriangle: def __init__(self, angle1, angle2, angle3): """initializing""" <|body_0|> def checkValidity(self): """function to check if three sides form a triangle or not""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.angle1 = angle1 ...
stack_v2_sparse_classes_75kplus_train_000010
738
no_license
[ { "docstring": "initializing", "name": "__init__", "signature": "def __init__(self, angle1, angle2, angle3)" }, { "docstring": "function to check if three sides form a triangle or not", "name": "checkValidity", "signature": "def checkValidity(self)" } ]
2
stack_v2_sparse_classes_30k_train_041672
Implement the Python class `validateTriangle` described below. Class description: Implement the validateTriangle class. Method signatures and docstrings: - def __init__(self, angle1, angle2, angle3): initializing - def checkValidity(self): function to check if three sides form a triangle or not
Implement the Python class `validateTriangle` described below. Class description: Implement the validateTriangle class. Method signatures and docstrings: - def __init__(self, angle1, angle2, angle3): initializing - def checkValidity(self): function to check if three sides form a triangle or not <|skeleton|> class va...
646355ed2334cc28ab5ceedbd6d7036a5aa331ee
<|skeleton|> class validateTriangle: def __init__(self, angle1, angle2, angle3): """initializing""" <|body_0|> def checkValidity(self): """function to check if three sides form a triangle or not""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class validateTriangle: def __init__(self, angle1, angle2, angle3): """initializing""" self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def checkValidity(self): """function to check if three sides form a triangle or not""" ...
the_stack_v2_python_sparse
validate_triangle.py
vidzierlein/Internship-Sep2020-Code
train
0
72f8ba893736985521e157cf42d768137923168e
[ "super(DFTXC, self).__init__()\nself.xcstr = xcstr\nself.nnmodel = nnmodel", "hybridxc = HybridXC(self.xcstr, self.nnmodel, aweight0=0.0)\noutput = []\nfor entry in inputs:\n evl = XCNNSCF(hybridxc, entry)\n qcs = []\n for system in entry.get_systems():\n qcs.append(evl.run(system))\n if entry....
<|body_start_0|> super(DFTXC, self).__init__() self.xcstr = xcstr self.nnmodel = nnmodel <|end_body_0|> <|body_start_1|> hybridxc = HybridXC(self.xcstr, self.nnmodel, aweight0=0.0) output = [] for entry in inputs: evl = XCNNSCF(hybridxc, entry) qc...
This layer initializes the neural network exchange correlation functional and the hybrid functional. It is then used to run the Kohn Sham iterations. Examples -------- >>> import torch >>> from deepchem.feat.dft_data import DFTEntry >>> from deepchem.models.dft.dftxc import DFTXC >>> e_type = 'ie' >>> true_val= '0.5341...
DFTXC
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DFTXC: """This layer initializes the neural network exchange correlation functional and the hybrid functional. It is then used to run the Kohn Sham iterations. Examples -------- >>> import torch >>> from deepchem.feat.dft_data import DFTEntry >>> from deepchem.models.dft.dftxc import DFTXC >>> e_...
stack_v2_sparse_classes_75kplus_train_000011
9,553
permissive
[ { "docstring": "Parameters ---------- xcstr: str The choice of xc to use. Some of the commonly used ones are: lda_x, lda_c_pw, lda_c_ow, lda_c_pz, lda_xc_lp_a, lda_xc_lp_b. nnmodel: torch.nn.Module the PyTorch model implementing the calculation Notes ----- It is not necessary to use the default method(_construc...
2
stack_v2_sparse_classes_30k_train_004720
Implement the Python class `DFTXC` described below. Class description: This layer initializes the neural network exchange correlation functional and the hybrid functional. It is then used to run the Kohn Sham iterations. Examples -------- >>> import torch >>> from deepchem.feat.dft_data import DFTEntry >>> from deepch...
Implement the Python class `DFTXC` described below. Class description: This layer initializes the neural network exchange correlation functional and the hybrid functional. It is then used to run the Kohn Sham iterations. Examples -------- >>> import torch >>> from deepchem.feat.dft_data import DFTEntry >>> from deepch...
ee6e67ebcf7bf04259cf13aff6388e2b791fea3d
<|skeleton|> class DFTXC: """This layer initializes the neural network exchange correlation functional and the hybrid functional. It is then used to run the Kohn Sham iterations. Examples -------- >>> import torch >>> from deepchem.feat.dft_data import DFTEntry >>> from deepchem.models.dft.dftxc import DFTXC >>> e_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DFTXC: """This layer initializes the neural network exchange correlation functional and the hybrid functional. It is then used to run the Kohn Sham iterations. Examples -------- >>> import torch >>> from deepchem.feat.dft_data import DFTEntry >>> from deepchem.models.dft.dftxc import DFTXC >>> e_type = 'ie' >...
the_stack_v2_python_sparse
deepchem/models/dft/dftxc.py
deepchem/deepchem
train
4,876
3ca2f8b2dd0b84b9f9491d80ba02bcd19da80d24
[ "if not root:\n return ''\nreturn '{} '.format(root.val) + self.serialize(root.left) + self.serialize(root.right)", "if not data:\n return\nstack = []\ndata = [int(d) for d in data[:-1].split(' ')]\nroot = node = TreeNode(data[0])\nfor val in data[1:]:\n if val < node.val:\n node.left = TreeNode(v...
<|body_start_0|> if not root: return '' return '{} '.format(root.val) + self.serialize(root.left) + self.serialize(root.right) <|end_body_0|> <|body_start_1|> if not data: return stack = [] data = [int(d) for d in data[:-1].split(' ')] root = node...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_000012
1,716
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_025100
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:...
9126c2089e41d4d7fd3a204115eba2b5074076ad
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' return '{} '.format(root.val) + self.serialize(root.left) + self.serialize(root.right) def deserialize(self, data): """Decodes you...
the_stack_v2_python_sparse
449_Serialize and Deserialize BST.py
Shwan-Yu/Data_Structures_and_Algorithms
train
0
7cbf2015f363bdc69003436862a65a41531440ab
[ "super().__init__()\nself.tade1 = TADELayer(in_channels=in_channels, aux_channels=aux_channels, kernel_size=kernel_size, bias=bias, upsample_factor=1, upsample_mode=upsample_mode)\nself.gated_conv1 = torch.nn.Conv1d(in_channels, in_channels * 2, kernel_size, 1, bias=bias, padding=(kernel_size - 1) // 2)\nself.tade2...
<|body_start_0|> super().__init__() self.tade1 = TADELayer(in_channels=in_channels, aux_channels=aux_channels, kernel_size=kernel_size, bias=bias, upsample_factor=1, upsample_mode=upsample_mode) self.gated_conv1 = torch.nn.Conv1d(in_channels, in_channels * 2, kernel_size, 1, bias=bias, padding=(...
TADEResBlock module.
TADEResBlock
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TADEResBlock: """TADEResBlock module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'): """Initialize TADEResBlock module. Args: ...
stack_v2_sparse_classes_75kplus_train_000013
5,864
permissive
[ { "docstring": "Initialize TADEResBlock module. Args: in_channels (int): Number of input channles. aux_channels (int): Number of auxirialy channles. kernel_size (int): Kernel size. bias (bool): Whether to use bias parameter in conv. upsample_factor (int): Upsample factor. upsample_mode (str): Upsample mode. gat...
2
stack_v2_sparse_classes_30k_test_002999
Implement the Python class `TADEResBlock` described below. Class description: TADEResBlock module. Method signatures and docstrings: - def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_functio...
Implement the Python class `TADEResBlock` described below. Class description: TADEResBlock module. Method signatures and docstrings: - def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_functio...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class TADEResBlock: """TADEResBlock module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'): """Initialize TADEResBlock module. Args: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TADEResBlock: """TADEResBlock module.""" def __init__(self, in_channels: int=64, aux_channels: int=80, kernel_size: int=9, dilation: int=2, bias: bool=True, upsample_factor: int=2, upsample_mode: str='nearest', gated_function: str='softmax'): """Initialize TADEResBlock module. Args: in_channels (...
the_stack_v2_python_sparse
espnet2/gan_tts/style_melgan/tade_res_block.py
espnet/espnet
train
7,242
500bd1291abc2514a42f87040782b27f7e778456
[ "user_id = request.user.id\nadmin = request.user.is_superuser\nuser = api.keystone.user_get(request, user_id, admin)\ndata = user.to_dict()\nitems = []\nemail = data.get('email')\nmobile = data.get('mobile')\ninclude_myself = False\nif data.get('notify_list'):\n for item in data.get('notify_list'):\n name...
<|body_start_0|> user_id = request.user.id admin = request.user.is_superuser user = api.keystone.user_get(request, user_id, admin) data = user.to_dict() items = [] email = data.get('email') mobile = data.get('mobile') include_myself = False if data...
API for create and update notify list which belongs to current user. The notify list is used for alarms.
NotifyList
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotifyList: """API for create and update notify list which belongs to current user. The notify list is used for alarms.""" def get(self, request): """Get notify list of current user""" <|body_0|> def post(self, request): """Create notify list, update current user...
stack_v2_sparse_classes_75kplus_train_000014
34,106
permissive
[ { "docstring": "Get notify list of current user", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create notify list, update current user", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Update notify list of current user", "...
3
stack_v2_sparse_classes_30k_train_044603
Implement the Python class `NotifyList` described below. Class description: API for create and update notify list which belongs to current user. The notify list is used for alarms. Method signatures and docstrings: - def get(self, request): Get notify list of current user - def post(self, request): Create notify list...
Implement the Python class `NotifyList` described below. Class description: API for create and update notify list which belongs to current user. The notify list is used for alarms. Method signatures and docstrings: - def get(self, request): Get notify list of current user - def post(self, request): Create notify list...
9524f1952461c83db485d5d1702c350b158d7ce0
<|skeleton|> class NotifyList: """API for create and update notify list which belongs to current user. The notify list is used for alarms.""" def get(self, request): """Get notify list of current user""" <|body_0|> def post(self, request): """Create notify list, update current user...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NotifyList: """API for create and update notify list which belongs to current user. The notify list is used for alarms.""" def get(self, request): """Get notify list of current user""" user_id = request.user.id admin = request.user.is_superuser user = api.keystone.user_get...
the_stack_v2_python_sparse
easystack_dashboard/api/rest/keystone.py
oksbsb/horizon-acc
train
0
56f51b3403ad229105b492b082a63caafd4b4099
[ "left = 1\nright = len(nums)\nresult = 0\nwhile left <= right:\n mid = left + (right - left) // 2\n tmp = self.windowex(nums, mid, s)\n if tmp:\n right = mid - 1\n result = mid\n else:\n left = mid + 1\nreturn result", "sumnum = 0\nfor i in range(len(nums)):\n if i >= size:\n ...
<|body_start_0|> left = 1 right = len(nums) result = 0 while left <= right: mid = left + (right - left) // 2 tmp = self.windowex(nums, mid, s) if tmp: right = mid - 1 result = mid else: left =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minSubArrayLen(self, s: int, nums: [int]) -> int: """二分查找法 o(nlogn) 将原数组分为两部分,0~mid作为一个窗口大小,遍历整个数组, 如果一旦满足,窗口内的和>=s,则将mid-1作为右边界,形成新的mid窗口,进行遍历 如果窗口内 :param s: :param nums: :return:""" <|body_0|> def windowex(self, nums, size, s): """判断在窗口中,是否和>s :param...
stack_v2_sparse_classes_75kplus_train_000015
2,091
no_license
[ { "docstring": "二分查找法 o(nlogn) 将原数组分为两部分,0~mid作为一个窗口大小,遍历整个数组, 如果一旦满足,窗口内的和>=s,则将mid-1作为右边界,形成新的mid窗口,进行遍历 如果窗口内 :param s: :param nums: :return:", "name": "minSubArrayLen", "signature": "def minSubArrayLen(self, s: int, nums: [int]) -> int" }, { "docstring": "判断在窗口中,是否和>s :param nums: :param siz...
2
stack_v2_sparse_classes_30k_train_004051
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minSubArrayLen(self, s: int, nums: [int]) -> int: 二分查找法 o(nlogn) 将原数组分为两部分,0~mid作为一个窗口大小,遍历整个数组, 如果一旦满足,窗口内的和>=s,则将mid-1作为右边界,形成新的mid窗口,进行遍历 如果窗口内 :param s: :param nums: :ret...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minSubArrayLen(self, s: int, nums: [int]) -> int: 二分查找法 o(nlogn) 将原数组分为两部分,0~mid作为一个窗口大小,遍历整个数组, 如果一旦满足,窗口内的和>=s,则将mid-1作为右边界,形成新的mid窗口,进行遍历 如果窗口内 :param s: :param nums: :ret...
f68e60dd1d8bb010cdae88e6273b3fac4ea48776
<|skeleton|> class Solution: def minSubArrayLen(self, s: int, nums: [int]) -> int: """二分查找法 o(nlogn) 将原数组分为两部分,0~mid作为一个窗口大小,遍历整个数组, 如果一旦满足,窗口内的和>=s,则将mid-1作为右边界,形成新的mid窗口,进行遍历 如果窗口内 :param s: :param nums: :return:""" <|body_0|> def windowex(self, nums, size, s): """判断在窗口中,是否和>s :param...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minSubArrayLen(self, s: int, nums: [int]) -> int: """二分查找法 o(nlogn) 将原数组分为两部分,0~mid作为一个窗口大小,遍历整个数组, 如果一旦满足,窗口内的和>=s,则将mid-1作为右边界,形成新的mid窗口,进行遍历 如果窗口内 :param s: :param nums: :return:""" left = 1 right = len(nums) result = 0 while left <= right: ...
the_stack_v2_python_sparse
string/209_minSubArrayLen.py
liying123456/python_leetcode
train
0
6b3b7eed1a30982e3a59498fdb51a54af20a669d
[ "if n == 0:\n return []\ntotal_l = []\ntotal_l.append([None])\ntotal_l.append(['()'])\nfor i in range(2, n + 1):\n l = []\n for j in range(i):\n now_list1 = total_l[j]\n now_list2 = total_l[i - 1 - j]\n print(now_list1, now_list2)\n for k1 in now_list1:\n for k2 in no...
<|body_start_0|> if n == 0: return [] total_l = [] total_l.append([None]) total_l.append(['()']) for i in range(2, n + 1): l = [] for j in range(i): now_list1 = total_l[j] now_list2 = total_l[i - 1 - j] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def generateParenthesis(self, n): """:type n: int :rtype: List[str]""" <|body_0|> def _gen(self, left, right, n, result): """left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n == 0: ...
stack_v2_sparse_classes_75kplus_train_000016
3,718
no_license
[ { "docstring": ":type n: int :rtype: List[str]", "name": "generateParenthesis", "signature": "def generateParenthesis(self, n)" }, { "docstring": "left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列", "name": "_gen", "signature": "def _gen(self, left, right, n, result)" } ]
2
stack_v2_sparse_classes_30k_train_030156
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generateParenthesis(self, n): :type n: int :rtype: List[str] - def _gen(self, left, right, n, result): left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def generateParenthesis(self, n): :type n: int :rtype: List[str] - def _gen(self, left, right, n, result): left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列 <|skeleton|> cl...
a32c096e192a89a88457ccc1899be10352bf1edd
<|skeleton|> class Solution: def generateParenthesis(self, n): """:type n: int :rtype: List[str]""" <|body_0|> def _gen(self, left, right, n, result): """left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def generateParenthesis(self, n): """:type n: int :rtype: List[str]""" if n == 0: return [] total_l = [] total_l.append([None]) total_l.append(['()']) for i in range(2, n + 1): l = [] for j in range(i): ...
the_stack_v2_python_sparse
leetcode/022.括号生成.py
luhao2013/Algorithms
train
0
3685099924cb1869e32120a01b7c8a8819448837
[ "inshape = self.observation_space.shape[0]\nself.net = FeedForwardNet(inshape, [32, 32], activate_last=True)\nif hasattr(self.action_space, 'n'):\n self.dist = Categorical(32, self.action_space.n)\nelse:\n self.dist = DiagGaussian(32, self.action_space.shape[0])\nself.vf = torch.nn.Linear(32, 1)", "if isins...
<|body_start_0|> inshape = self.observation_space.shape[0] self.net = FeedForwardNet(inshape, [32, 32], activate_last=True) if hasattr(self.action_space, 'n'): self.dist = Categorical(32, self.action_space.n) else: self.dist = DiagGaussian(32, self.action_space.sh...
Test feed forward network.
FeedForwardBase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeedForwardBase: """Test feed forward network.""" def build(self): """Build network.""" <|body_0|> def forward(self, ob): """Forward.""" <|body_1|> <|end_skeleton|> <|body_start_0|> inshape = self.observation_space.shape[0] self.net = Fe...
stack_v2_sparse_classes_75kplus_train_000017
13,010
no_license
[ { "docstring": "Build network.", "name": "build", "signature": "def build(self)" }, { "docstring": "Forward.", "name": "forward", "signature": "def forward(self, ob)" } ]
2
stack_v2_sparse_classes_30k_train_048334
Implement the Python class `FeedForwardBase` described below. Class description: Test feed forward network. Method signatures and docstrings: - def build(self): Build network. - def forward(self, ob): Forward.
Implement the Python class `FeedForwardBase` described below. Class description: Test feed forward network. Method signatures and docstrings: - def build(self): Build network. - def forward(self, ob): Forward. <|skeleton|> class FeedForwardBase: """Test feed forward network.""" def build(self): """B...
e71c4b12955b01bfb907aa31c91ded6bcd8aaec8
<|skeleton|> class FeedForwardBase: """Test feed forward network.""" def build(self): """Build network.""" <|body_0|> def forward(self, ob): """Forward.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FeedForwardBase: """Test feed forward network.""" def build(self): """Build network.""" inshape = self.observation_space.shape[0] self.net = FeedForwardNet(inshape, [32, 32], activate_last=True) if hasattr(self.action_space, 'n'): self.dist = Categorical(32, se...
the_stack_v2_python_sparse
dl/rl/data_collection/rollout_data_collection.py
cbschaff/dl
train
1
d2761373fd20a8173ba1af2c29ee3f8d121fe007
[ "super(TimeDistributedDenseLayerSCP, self).__init__()\nassert isinstance(input_shape, tuple) and len(input_shape) == 1, '\"input_shape\" should be a tuple with single value.'\nassert isinstance(output_shape, tuple) and len(output_shape) == 1, '\"output_shape\" should be a tuple with single value.'\nassert isinstanc...
<|body_start_0|> super(TimeDistributedDenseLayerSCP, self).__init__() assert isinstance(input_shape, tuple) and len(input_shape) == 1, '"input_shape" should be a tuple with single value.' assert isinstance(output_shape, tuple) and len(output_shape) == 1, '"output_shape" should be a tuple with si...
This class implements time distributed dense layer connection.
TimeDistributedDenseLayerSCP
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TimeDistributedDenseLayerSCP: """This class implements time distributed dense layer connection.""" def __init__(self, input_shape, output_shape, use_bias=True, target_cpu=False): """This function initializes the class. Input is 3D tensor, output is 3D tensor. For efficient following ...
stack_v2_sparse_classes_75kplus_train_000018
8,571
permissive
[ { "docstring": "This function initializes the class. Input is 3D tensor, output is 3D tensor. For efficient following batch normalization, use_bias = False. Parameters ---------- input_shape: tuple a tuple of single value, i.e., (input dim,) output_shape: tupe a tuple of single value, i.e., (output dim,) use_bi...
4
null
Implement the Python class `TimeDistributedDenseLayerSCP` described below. Class description: This class implements time distributed dense layer connection. Method signatures and docstrings: - def __init__(self, input_shape, output_shape, use_bias=True, target_cpu=False): This function initializes the class. Input is...
Implement the Python class `TimeDistributedDenseLayerSCP` described below. Class description: This class implements time distributed dense layer connection. Method signatures and docstrings: - def __init__(self, input_shape, output_shape, use_bias=True, target_cpu=False): This function initializes the class. Input is...
7585261dd1b1c6c99dada5d2d1aabf482e89e880
<|skeleton|> class TimeDistributedDenseLayerSCP: """This class implements time distributed dense layer connection.""" def __init__(self, input_shape, output_shape, use_bias=True, target_cpu=False): """This function initializes the class. Input is 3D tensor, output is 3D tensor. For efficient following ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TimeDistributedDenseLayerSCP: """This class implements time distributed dense layer connection.""" def __init__(self, input_shape, output_shape, use_bias=True, target_cpu=False): """This function initializes the class. Input is 3D tensor, output is 3D tensor. For efficient following batch normali...
the_stack_v2_python_sparse
lemontree/experimentals/dense_scp.py
khshim/lemontree
train
3
8fb9673920f307f9923af87c72706bfd9d24a3a7
[ "obs = real_env.reset()\nR = 0\nstates = []\nfor i in range(H):\n if render:\n real_env.render()\n ac = policy @ obs\n new_obs, rew, done, info = real_env.step(ac)\n R += rew\n if done:\n break\n obs = new_obs\n states.append(obs)\nreturn (R, states)", "max_rewards = [max(reward...
<|body_start_0|> obs = real_env.reset() R = 0 states = [] for i in range(H): if render: real_env.render() ac = policy @ obs new_obs, rew, done, info = real_env.step(ac) R += rew if done: break ...
Basic ARS Agent for solving continuous control tasks. Without Safe Exploration.
Basic_ARS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Basic_ARS: """Basic ARS Agent for solving continuous control tasks. Without Safe Exploration.""" def rollout(self, real_env, policy, H, render=False): """:param real_env: :param policy: :param H: :param render: :return:""" <|body_0|> def sort_directions(self, deltas, rew...
stack_v2_sparse_classes_75kplus_train_000019
4,774
no_license
[ { "docstring": ":param real_env: :param policy: :param H: :param render: :return:", "name": "rollout", "signature": "def rollout(self, real_env, policy, H, render=False)" }, { "docstring": "Sort the directions deltas by max{r_k_+, r_k_-} :param deltas: array of matrices :param rewards: array of ...
4
stack_v2_sparse_classes_30k_train_024256
Implement the Python class `Basic_ARS` described below. Class description: Basic ARS Agent for solving continuous control tasks. Without Safe Exploration. Method signatures and docstrings: - def rollout(self, real_env, policy, H, render=False): :param real_env: :param policy: :param H: :param render: :return: - def s...
Implement the Python class `Basic_ARS` described below. Class description: Basic ARS Agent for solving continuous control tasks. Without Safe Exploration. Method signatures and docstrings: - def rollout(self, real_env, policy, H, render=False): :param real_env: :param policy: :param H: :param render: :return: - def s...
e10c1b6038f357ee5e9b67593a15a1d5f61c1e99
<|skeleton|> class Basic_ARS: """Basic ARS Agent for solving continuous control tasks. Without Safe Exploration.""" def rollout(self, real_env, policy, H, render=False): """:param real_env: :param policy: :param H: :param render: :return:""" <|body_0|> def sort_directions(self, deltas, rew...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Basic_ARS: """Basic ARS Agent for solving continuous control tasks. Without Safe Exploration.""" def rollout(self, real_env, policy, H, render=False): """:param real_env: :param policy: :param H: :param render: :return:""" obs = real_env.reset() R = 0 states = [] f...
the_stack_v2_python_sparse
safe_ars/ars.py
leonzheng2/Safe-Exploration-with-Simulator-in-RL-algorithms
train
0
f1595690445b58d8c24c8c40dc353829e05c7775
[ "res = set()\nif len(nums) < 4:\n return []\nnums.sort()\nfor i in range(len(nums) - 3):\n for j in range(i + 1, len(nums) - 2):\n l, r = (j + 1, len(nums) - 1)\n while l < r:\n s = nums[i] + nums[j] + nums[l] + nums[r]\n if s < target:\n l += 1\n ...
<|body_start_0|> res = set() if len(nums) < 4: return [] nums.sort() for i in range(len(nums) - 3): for j in range(i + 1, len(nums) - 2): l, r = (j + 1, len(nums) - 1) while l < r: s = nums[i] + nums[j] + nums[l]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def fourSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)""" <|body_0|> def fourSum1(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]] 方法二 O(n^3) 有点问题""" ...
stack_v2_sparse_classes_75kplus_train_000020
2,372
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)", "name": "fourSum", "signature": "def fourSum(self, nums, target)" }, { "docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]] 方法二 O(n^3) 有点问题", "name": "fourSum1", "si...
2
stack_v2_sparse_classes_30k_train_032612
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3) - def fourSum1(self, nums, target): :type nums: List[int] :type t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3) - def fourSum1(self, nums, target): :type nums: List[int] :type t...
069bb0b751ef7f469036b9897436eb5d138ffa24
<|skeleton|> class Solution: def fourSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)""" <|body_0|> def fourSum1(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]] 方法二 O(n^3) 有点问题""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def fourSum(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[List[int]] 向中间压缩的方式 O(n^3)""" res = set() if len(nums) < 4: return [] nums.sort() for i in range(len(nums) - 3): for j in range(i + 1, len(nums) - ...
the_stack_v2_python_sparse
算法/学习笔记/四数之和.py
RichieSong/algorithm
train
0
b8996bf48c29938c7c14e599decb94ae6c9945e0
[ "words_to_counts = {'cat': 1}\nexpected_result = {'cat': 1}\ntweets.common_words(words_to_counts, 1)\nself.assertEqual(words_to_counts, expected_result, 'none removed')", "dic = {'I': 10, 'you': 5, 'miss': 8, 'here': 6, 'how': 6}\ntweets.common_words(dic, 3)\nexpect_result = {'I': 10, 'miss': 8}\nself.assertEqual...
<|body_start_0|> words_to_counts = {'cat': 1} expected_result = {'cat': 1} tweets.common_words(words_to_counts, 1) self.assertEqual(words_to_counts, expected_result, 'none removed') <|end_body_0|> <|body_start_1|> dic = {'I': 10, 'you': 5, 'miss': 8, 'here': 6, 'how': 6} ...
TestCommonWords
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCommonWords: def test_none_removed(self): """Test common_words with N so that no words are removed.""" <|body_0|> def test_tie_removed(self): """Test common_words with N so that tied words are removed.""" <|body_1|> def test_tie_remained(self): ...
stack_v2_sparse_classes_75kplus_train_000021
1,649
permissive
[ { "docstring": "Test common_words with N so that no words are removed.", "name": "test_none_removed", "signature": "def test_none_removed(self)" }, { "docstring": "Test common_words with N so that tied words are removed.", "name": "test_tie_removed", "signature": "def test_tie_removed(se...
5
stack_v2_sparse_classes_30k_train_013761
Implement the Python class `TestCommonWords` described below. Class description: Implement the TestCommonWords class. Method signatures and docstrings: - def test_none_removed(self): Test common_words with N so that no words are removed. - def test_tie_removed(self): Test common_words with N so that tied words are re...
Implement the Python class `TestCommonWords` described below. Class description: Implement the TestCommonWords class. Method signatures and docstrings: - def test_none_removed(self): Test common_words with N so that no words are removed. - def test_tie_removed(self): Test common_words with N so that tied words are re...
214525afeeb2da2409f451bf269e792c6940a1ba
<|skeleton|> class TestCommonWords: def test_none_removed(self): """Test common_words with N so that no words are removed.""" <|body_0|> def test_tie_removed(self): """Test common_words with N so that tied words are removed.""" <|body_1|> def test_tie_remained(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestCommonWords: def test_none_removed(self): """Test common_words with N so that no words are removed.""" words_to_counts = {'cat': 1} expected_result = {'cat': 1} tweets.common_words(words_to_counts, 1) self.assertEqual(words_to_counts, expected_result, 'none removed'...
the_stack_v2_python_sparse
Python/Tweet/test_common_words.py
LilyYC/legendary-train
train
0
11773ae801e8daa41783c17bfc9bdf99e33ab012
[ "self.__window = window\nself.__back_color = BLUE\nself.__rect_color = RED\nself.__text_color = GREEN\nw, h = window.get_dimension()\nrect_w = 500\nrect_h = 300\nself.__rectangle = pygame.rect.Rect(int((w - rect_w) / 2), int((h - rect_h) / 2), rect_w, rect_h)\nself.__font = pygame.font.SysFont('comicsansms', 20)\ns...
<|body_start_0|> self.__window = window self.__back_color = BLUE self.__rect_color = RED self.__text_color = GREEN w, h = window.get_dimension() rect_w = 500 rect_h = 300 self.__rectangle = pygame.rect.Rect(int((w - rect_w) / 2), int((h - rect_h) / 2), rec...
This class represent the waiting screen where the players must wait the other is ready
DeconnectionScreen
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeconnectionScreen: """This class represent the waiting screen where the players must wait the other is ready""" def __init__(self, window): """Creates the connection screen""" <|body_0|> def launch(self): """Launches the connexion screen""" <|body_1|> <...
stack_v2_sparse_classes_75kplus_train_000022
2,404
no_license
[ { "docstring": "Creates the connection screen", "name": "__init__", "signature": "def __init__(self, window)" }, { "docstring": "Launches the connexion screen", "name": "launch", "signature": "def launch(self)" } ]
2
stack_v2_sparse_classes_30k_val_000956
Implement the Python class `DeconnectionScreen` described below. Class description: This class represent the waiting screen where the players must wait the other is ready Method signatures and docstrings: - def __init__(self, window): Creates the connection screen - def launch(self): Launches the connexion screen
Implement the Python class `DeconnectionScreen` described below. Class description: This class represent the waiting screen where the players must wait the other is ready Method signatures and docstrings: - def __init__(self, window): Creates the connection screen - def launch(self): Launches the connexion screen <|...
6e3734d38e111f455912474268cb7d0e8474fa40
<|skeleton|> class DeconnectionScreen: """This class represent the waiting screen where the players must wait the other is ready""" def __init__(self, window): """Creates the connection screen""" <|body_0|> def launch(self): """Launches the connexion screen""" <|body_1|> <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeconnectionScreen: """This class represent the waiting screen where the players must wait the other is ready""" def __init__(self, window): """Creates the connection screen""" self.__window = window self.__back_color = BLUE self.__rect_color = RED self.__text_colo...
the_stack_v2_python_sparse
client_side/graphical/deconnectionScreen.py
adam-hotait/3Dtictactoe
train
1
7105125f392f78dccaf5513b8de75c58a8f9a654
[ "self.sc_id = sc_id\nself.tleDir = tleDir\nself._loadTLEblacklist(blacklistFname)\nreturn", "if fname is None:\n sc_name_underscore = self.sc_id.upper().replace(' ', '_')\n fname = f'{sc_name_underscore}_tle_table.txt'\nwith open(fname, 'w') as f:\n print('Created TLE table file', fname)\n f.write('# ...
<|body_start_0|> self.sc_id = sc_id self.tleDir = tleDir self._loadTLEblacklist(blacklistFname) return <|end_body_0|> <|body_start_1|> if fname is None: sc_name_underscore = self.sc_id.upper().replace(' ', '_') fname = f'{sc_name_underscore}_tle_table.txt...
Make_TLE_table
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Make_TLE_table: def __init__(self, sc_id, tleDir='/home/mike/research/firebird/tle', blacklistFname=None): """NAME: Make_TLE_table(self, sc_id) USE: Makes a csv table of the TLEs for sc_id spacecraft. ARGS: REQUIRED: sc_id: Spacecraft id OPTIONAL: tleDir='/home/mike/research/firebird/tle...
stack_v2_sparse_classes_75kplus_train_000023
16,081
no_license
[ { "docstring": "NAME: Make_TLE_table(self, sc_id) USE: Makes a csv table of the TLEs for sc_id spacecraft. ARGS: REQUIRED: sc_id: Spacecraft id OPTIONAL: tleDir='/home/mike/research/firebird/tle': The directory containing the spacecraft TLEs. If propagating for FIREBIRD, download them off of Europa. blacklistFn...
3
null
Implement the Python class `Make_TLE_table` described below. Class description: Implement the Make_TLE_table class. Method signatures and docstrings: - def __init__(self, sc_id, tleDir='/home/mike/research/firebird/tle', blacklistFname=None): NAME: Make_TLE_table(self, sc_id) USE: Makes a csv table of the TLEs for sc...
Implement the Python class `Make_TLE_table` described below. Class description: Implement the Make_TLE_table class. Method signatures and docstrings: - def __init__(self, sc_id, tleDir='/home/mike/research/firebird/tle', blacklistFname=None): NAME: Make_TLE_table(self, sc_id) USE: Makes a csv table of the TLEs for sc...
196342fe358ff5e195541269646bb228941bed64
<|skeleton|> class Make_TLE_table: def __init__(self, sc_id, tleDir='/home/mike/research/firebird/tle', blacklistFname=None): """NAME: Make_TLE_table(self, sc_id) USE: Makes a csv table of the TLEs for sc_id spacecraft. ARGS: REQUIRED: sc_id: Spacecraft id OPTIONAL: tleDir='/home/mike/research/firebird/tle...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Make_TLE_table: def __init__(self, sc_id, tleDir='/home/mike/research/firebird/tle', blacklistFname=None): """NAME: Make_TLE_table(self, sc_id) USE: Makes a csv table of the TLEs for sc_id spacecraft. ARGS: REQUIRED: sc_id: Spacecraft id OPTIONAL: tleDir='/home/mike/research/firebird/tle': The directo...
the_stack_v2_python_sparse
mission_tools/orbit/make_ephem.py
mshumko/mission_tools
train
0
bc02a93b3db4a65d39291e73b15632f6bc1e7268
[ "result = input.sqrt()\nresult[input < 0] = 0\nctx.save_for_backward(result)\nreturn result", "result, = ctx.saved_tensors\ngrad_input = grad_output / (2 * result)\ngrad_input[result == 0] = 0\nreturn grad_input" ]
<|body_start_0|> result = input.sqrt() result[input < 0] = 0 ctx.save_for_backward(result) return result <|end_body_0|> <|body_start_1|> result, = ctx.saved_tensors grad_input = grad_output / (2 * result) grad_input[result == 0] = 0 return grad_input <|en...
Compute the square root and gradients class of a given tensor. Taken from the geomloss package.
Sqrt0
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sqrt0: """Compute the square root and gradients class of a given tensor. Taken from the geomloss package.""" def forward(ctx, input): """Compute the square root for a given Tensor.""" <|body_0|> def backward(ctx, grad_output): """Compute the square root gradients...
stack_v2_sparse_classes_75kplus_train_000024
8,555
permissive
[ { "docstring": "Compute the square root for a given Tensor.", "name": "forward", "signature": "def forward(ctx, input)" }, { "docstring": "Compute the square root gradients of a given Tensor.", "name": "backward", "signature": "def backward(ctx, grad_output)" } ]
2
stack_v2_sparse_classes_30k_train_046915
Implement the Python class `Sqrt0` described below. Class description: Compute the square root and gradients class of a given tensor. Taken from the geomloss package. Method signatures and docstrings: - def forward(ctx, input): Compute the square root for a given Tensor. - def backward(ctx, grad_output): Compute the ...
Implement the Python class `Sqrt0` described below. Class description: Compute the square root and gradients class of a given tensor. Taken from the geomloss package. Method signatures and docstrings: - def forward(ctx, input): Compute the square root for a given Tensor. - def backward(ctx, grad_output): Compute the ...
cd21033e5bbf974283fcb1b88e586270e5a6ba7e
<|skeleton|> class Sqrt0: """Compute the square root and gradients class of a given tensor. Taken from the geomloss package.""" def forward(ctx, input): """Compute the square root for a given Tensor.""" <|body_0|> def backward(ctx, grad_output): """Compute the square root gradients...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Sqrt0: """Compute the square root and gradients class of a given tensor. Taken from the geomloss package.""" def forward(ctx, input): """Compute the square root for a given Tensor.""" result = input.sqrt() result[input < 0] = 0 ctx.save_for_backward(result) return ...
the_stack_v2_python_sparse
GAN/utils.py
kilianFatras/unbiased_minibatch_sinkhorn_GAN
train
9
6ce02c0a5f04d9d2b7081a2725edd4b711c2f9e8
[ "super(SegnetConvLSTM, self).__init__()\nassert lstm_nlayers == len(lstm_hidden_dim)\nself.n_classes = decoder_out_channels\nself.v = verbose\nself.encoder = encoder.VGGencoder()\nself.decoder = decoder.VGGDecoder(decoder_out_channels, config=vgg_decoder_config)\nself.lstm = convlstm.ConvLSTM(input_size=(4, 8), inp...
<|body_start_0|> super(SegnetConvLSTM, self).__init__() assert lstm_nlayers == len(lstm_hidden_dim) self.n_classes = decoder_out_channels self.v = verbose self.encoder = encoder.VGGencoder() self.decoder = decoder.VGGDecoder(decoder_out_channels, config=vgg_decoder_config...
This class implements the whole end-to-end trainable model as described in the paper 'Robust Lane detection From Continuous Driving Scenes Using Deep Neural Networks'. The model comprises of a fully convolutional encoder-decoder (namely Segnet) and of a ConvLSTM, which 'fuses' information coming from multiple contiguou...
SegnetConvLSTM
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SegnetConvLSTM: """This class implements the whole end-to-end trainable model as described in the paper 'Robust Lane detection From Continuous Driving Scenes Using Deep Neural Networks'. The model comprises of a fully convolutional encoder-decoder (namely Segnet) and of a ConvLSTM, which 'fuses' ...
stack_v2_sparse_classes_75kplus_train_000025
4,953
no_license
[ { "docstring": ":param lstm_hidden_dim: list of hidden layers dimensions used to define the convlstm architecture (e.g [512, 512]). :param lstm_nlayers: number of hidden layers in lstm (== len(lstm_hidden_dim)) :param decoder_out_channels: number of channels the decoder output will have; it is generally the sam...
2
stack_v2_sparse_classes_30k_train_007050
Implement the Python class `SegnetConvLSTM` described below. Class description: This class implements the whole end-to-end trainable model as described in the paper 'Robust Lane detection From Continuous Driving Scenes Using Deep Neural Networks'. The model comprises of a fully convolutional encoder-decoder (namely Se...
Implement the Python class `SegnetConvLSTM` described below. Class description: This class implements the whole end-to-end trainable model as described in the paper 'Robust Lane detection From Continuous Driving Scenes Using Deep Neural Networks'. The model comprises of a fully convolutional encoder-decoder (namely Se...
b7fb520080c48a418d4d009ee35f4f92e01f50bd
<|skeleton|> class SegnetConvLSTM: """This class implements the whole end-to-end trainable model as described in the paper 'Robust Lane detection From Continuous Driving Scenes Using Deep Neural Networks'. The model comprises of a fully convolutional encoder-decoder (namely Segnet) and of a ConvLSTM, which 'fuses' ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SegnetConvLSTM: """This class implements the whole end-to-end trainable model as described in the paper 'Robust Lane detection From Continuous Driving Scenes Using Deep Neural Networks'. The model comprises of a fully convolutional encoder-decoder (namely Segnet) and of a ConvLSTM, which 'fuses' information c...
the_stack_v2_python_sparse
segnet_conv_lstm_model.py
arindam-modak/Robust-Lane-Detection-in-hazy-environment-using-Encoder-Decoder-CNN-LSTM-DCP
train
4
3d9ec6bbd1a3daf68331456a1faa0930e7a4d176
[ "n = len(s)\n\n@lru_cache(None)\ndef dfs(i):\n if i == n:\n return 1\n result = 0\n for j in range(i + 1, min(i + 3, n + 1)):\n if s[i] != '0' and 1 <= int(s[i:j]) <= 26:\n result += dfs(j)\n return result\nreturn dfs(0)", "n = len(s)\ndp = [0] * (n + 1)\ndp[0] = 1\nfor i in r...
<|body_start_0|> n = len(s) @lru_cache(None) def dfs(i): if i == n: return 1 result = 0 for j in range(i + 1, min(i + 3, n + 1)): if s[i] != '0' and 1 <= int(s[i:j]) <= 26: result += dfs(j) retur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numDecodings(self, s: str) -> int: """DFS+Memoization""" <|body_0|> def numDecodings(self, s: str) -> int: """DP, Time: O(n), Space: O(n)""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(s) @lru_cache(None) def ...
stack_v2_sparse_classes_75kplus_train_000026
1,213
no_license
[ { "docstring": "DFS+Memoization", "name": "numDecodings", "signature": "def numDecodings(self, s: str) -> int" }, { "docstring": "DP, Time: O(n), Space: O(n)", "name": "numDecodings", "signature": "def numDecodings(self, s: str) -> int" } ]
2
stack_v2_sparse_classes_30k_val_001425
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numDecodings(self, s: str) -> int: DFS+Memoization - def numDecodings(self, s: str) -> int: DP, Time: O(n), Space: O(n)
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numDecodings(self, s: str) -> int: DFS+Memoization - def numDecodings(self, s: str) -> int: DP, Time: O(n), Space: O(n) <|skeleton|> class Solution: def numDecodings(se...
72136e3487d239f5b37e2d6393e034262a6bf599
<|skeleton|> class Solution: def numDecodings(self, s: str) -> int: """DFS+Memoization""" <|body_0|> def numDecodings(self, s: str) -> int: """DP, Time: O(n), Space: O(n)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def numDecodings(self, s: str) -> int: """DFS+Memoization""" n = len(s) @lru_cache(None) def dfs(i): if i == n: return 1 result = 0 for j in range(i + 1, min(i + 3, n + 1)): if s[i] != '0' and 1 <= i...
the_stack_v2_python_sparse
python/91-Decode Ways.py
cwza/leetcode
train
0
be3246926d6a756cc4c67f7a826d87740007c1aa
[ "plt.figure(figsize=figsize)\nkey_list = []\nfor i in self.keys():\n key_list.append(i)\ntotal_time = len(self[key_list[0]])\nif legendlist == None:\n legendlist = ['variable {}'.format(i) for i in key_list]\nk = 0\nfor i in key_list:\n plt.plot(range(0, total_time), self[i], label=legendlist[k], linewidth...
<|body_start_0|> plt.figure(figsize=figsize) key_list = [] for i in self.keys(): key_list.append(i) total_time = len(self[key_list[0]]) if legendlist == None: legendlist = ['variable {}'.format(i) for i in key_list] k = 0 for i in key_list:...
Solution dictionary is an ordered dictionary that stores the optimization results Solution dictionary struture: D[name key]=time series data
SolutionDict
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SolutionDict: """Solution dictionary is an ordered dictionary that stores the optimization results Solution dictionary struture: D[name key]=time series data""" def plot_2d(self, x_str='Time', y_str='Value', title_str='Results', figsize=(15, 7), legendlist=None): """step plot""" ...
stack_v2_sparse_classes_75kplus_train_000027
6,642
no_license
[ { "docstring": "step plot", "name": "plot_2d", "signature": "def plot_2d(self, x_str='Time', y_str='Value', title_str='Results', figsize=(15, 7), legendlist=None)" }, { "docstring": "step plot", "name": "plot_step_2d", "signature": "def plot_step_2d(self, x_str='Time', y_str='Value', tit...
3
null
Implement the Python class `SolutionDict` described below. Class description: Solution dictionary is an ordered dictionary that stores the optimization results Solution dictionary struture: D[name key]=time series data Method signatures and docstrings: - def plot_2d(self, x_str='Time', y_str='Value', title_str='Resul...
Implement the Python class `SolutionDict` described below. Class description: Solution dictionary is an ordered dictionary that stores the optimization results Solution dictionary struture: D[name key]=time series data Method signatures and docstrings: - def plot_2d(self, x_str='Time', y_str='Value', title_str='Resul...
bdc3f39883aed5b2e85624525c662c00f60d35e3
<|skeleton|> class SolutionDict: """Solution dictionary is an ordered dictionary that stores the optimization results Solution dictionary struture: D[name key]=time series data""" def plot_2d(self, x_str='Time', y_str='Value', title_str='Results', figsize=(15, 7), legendlist=None): """step plot""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SolutionDict: """Solution dictionary is an ordered dictionary that stores the optimization results Solution dictionary struture: D[name key]=time series data""" def plot_2d(self, x_str='Time', y_str='Value', title_str='Results', figsize=(15, 7), legendlist=None): """step plot""" plt.figur...
the_stack_v2_python_sparse
Application/Application_DSOPT/formulation_general.py
whoiszyc/Repo_python
train
5
971bbe032c4be62aaa482df3a569b3e9d2ed665d
[ "self.maximum_requests = maximum_requests\nself.maximum_age = maximum_age\nself.birth = None\nself.kill_signal = None\nself.handled_tasks = 0\nself.task = task_handler(*handler_args, **handler_kwargs)", "self.birth = time.time()\nwhile self.handled_tasks < self.maximum_requests:\n if self.kill_signal:\n ...
<|body_start_0|> self.maximum_requests = maximum_requests self.maximum_age = maximum_age self.birth = None self.kill_signal = None self.handled_tasks = 0 self.task = task_handler(*handler_args, **handler_kwargs) <|end_body_0|> <|body_start_1|> self.birth = time.t...
Worker executing tasks
Worker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Worker: """Worker executing tasks""" def __init__(self, task_handler, maximum_requests, maximum_age, handler_args, handler_kwargs): """Create a new Worker to execute tasks. :param task_handler: Task handler to fetch and execute tasks. :param maximum_requests: Maximum number of tasks ...
stack_v2_sparse_classes_75kplus_train_000028
1,467
permissive
[ { "docstring": "Create a new Worker to execute tasks. :param task_handler: Task handler to fetch and execute tasks. :param maximum_requests: Maximum number of tasks this worker can execute. :param maximum_age: Maximum age of the worker.", "name": "__init__", "signature": "def __init__(self, task_handler...
2
stack_v2_sparse_classes_30k_train_053341
Implement the Python class `Worker` described below. Class description: Worker executing tasks Method signatures and docstrings: - def __init__(self, task_handler, maximum_requests, maximum_age, handler_args, handler_kwargs): Create a new Worker to execute tasks. :param task_handler: Task handler to fetch and execute...
Implement the Python class `Worker` described below. Class description: Worker executing tasks Method signatures and docstrings: - def __init__(self, task_handler, maximum_requests, maximum_age, handler_args, handler_kwargs): Create a new Worker to execute tasks. :param task_handler: Task handler to fetch and execute...
d8d3c9a86ab3235d4e36583fcee6f656e5209b7e
<|skeleton|> class Worker: """Worker executing tasks""" def __init__(self, task_handler, maximum_requests, maximum_age, handler_args, handler_kwargs): """Create a new Worker to execute tasks. :param task_handler: Task handler to fetch and execute tasks. :param maximum_requests: Maximum number of tasks ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Worker: """Worker executing tasks""" def __init__(self, task_handler, maximum_requests, maximum_age, handler_args, handler_kwargs): """Create a new Worker to execute tasks. :param task_handler: Task handler to fetch and execute tasks. :param maximum_requests: Maximum number of tasks this worker c...
the_stack_v2_python_sparse
src/mercury/common/task_managers/base/worker.py
jr0d/mercury
train
4
68edfb9888274b111beb4f45ebc052cbe9332fc0
[ "factor_dict = get_factor_dict()\n_factor_provider = HDFDataProvider(factor_dict[factor_name]['abs_path'], start_time, end_time)\n_rebcalculator = load_rebcalculator(reb_type, start_time, end_time)\n_quote_provider = HDFDataProvider(factor_dict['ADJ_CLOSE']['abs_path'], start_time, end_time)\nif universe is None:\n...
<|body_start_0|> factor_dict = get_factor_dict() _factor_provider = HDFDataProvider(factor_dict[factor_name]['abs_path'], start_time, end_time) _rebcalculator = load_rebcalculator(reb_type, start_time, end_time) _quote_provider = HDFDataProvider(factor_dict['ADJ_CLOSE']['abs_path'], star...
计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值
ICDecay
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ICDecay: """计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值""" def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): """Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_t...
stack_v2_sparse_classes_75kplus_train_000029
16,864
no_license
[ { "docstring": "Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_time: datetime like 测试的开始时间 end_time: datetime like 测试的结束时间 universe: str 使用的universe名称,要求能在fmanager.list_allfactor()中找到 period_num: int, default 10 IC衰减的最大期数 reb_type: str, default MONTHLY 换仓日计算的规则,目前只支持月度(MONTHLY)和...
2
stack_v2_sparse_classes_30k_test_000881
Implement the Python class `ICDecay` described below. Class description: 计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值 Method signatures and docstrings: - def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): Parameter --------- fact...
Implement the Python class `ICDecay` described below. Class description: 计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值 Method signatures and docstrings: - def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): Parameter --------- fact...
4080154dbf05781f3b48f551ee830d9f66687f87
<|skeleton|> class ICDecay: """计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值""" def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): """Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ICDecay: """计算因子(rank)IC的衰减情况 具体如下: 假设计算10期IC衰减情况,则分别计算每一个滞后期对应的IC的序列,然后求平均值,返回这10期的 所有的IC平均值""" def __init__(self, factor_name, start_time, end_time, universe=None, period_num=10, reb_type=MONTHLY): """Parameter --------- factor_name: str 因子名称,要求能在fmanager.get_factor_dict中找到 start_time: datetime...
the_stack_v2_python_sparse
factortest/correlation.py
rlcjj/GeneralLib
train
0
9150f2afa3a0045999b1dc3d991be81023990781
[ "midindex_0 = (len(A) + len(B) - 1) / 2\nmidindex_1 = (len(A) + len(B)) / 2\nif midindex_0 == midindex_1:\n return self._nthmin(midindex_0, A, B)\nelse:\n return (self._nthmin(midindex_0, A, B) + self._nthmin(midindex_1, A, B)) / 2.0", "if not A:\n return B[n]\nif not B:\n return A[n]\nif n == 0:\n ...
<|body_start_0|> midindex_0 = (len(A) + len(B) - 1) / 2 midindex_1 = (len(A) + len(B)) / 2 if midindex_0 == midindex_1: return self._nthmin(midindex_0, A, B) else: return (self._nthmin(midindex_0, A, B) + self._nthmin(midindex_1, A, B)) / 2.0 <|end_body_0|> <|bod...
Solver for https://oj.leetcode.com/problems/median-of-two-sorted-arrays/
Solution
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Solver for https://oj.leetcode.com/problems/median-of-two-sorted-arrays/""" def findMedianSortedArrays(self, A, B): """The main solver function.""" <|body_0|> def _nthmin(n, A, B): """Returns nth(0-indexed) minimum element of sorted arrays A and B.""...
stack_v2_sparse_classes_75kplus_train_000030
1,082
permissive
[ { "docstring": "The main solver function.", "name": "findMedianSortedArrays", "signature": "def findMedianSortedArrays(self, A, B)" }, { "docstring": "Returns nth(0-indexed) minimum element of sorted arrays A and B.", "name": "_nthmin", "signature": "def _nthmin(n, A, B)" } ]
2
stack_v2_sparse_classes_30k_train_044460
Implement the Python class `Solution` described below. Class description: Solver for https://oj.leetcode.com/problems/median-of-two-sorted-arrays/ Method signatures and docstrings: - def findMedianSortedArrays(self, A, B): The main solver function. - def _nthmin(n, A, B): Returns nth(0-indexed) minimum element of sor...
Implement the Python class `Solution` described below. Class description: Solver for https://oj.leetcode.com/problems/median-of-two-sorted-arrays/ Method signatures and docstrings: - def findMedianSortedArrays(self, A, B): The main solver function. - def _nthmin(n, A, B): Returns nth(0-indexed) minimum element of sor...
bdce2100d226f61e89cd7c6c21669756a2b6a30d
<|skeleton|> class Solution: """Solver for https://oj.leetcode.com/problems/median-of-two-sorted-arrays/""" def findMedianSortedArrays(self, A, B): """The main solver function.""" <|body_0|> def _nthmin(n, A, B): """Returns nth(0-indexed) minimum element of sorted arrays A and B.""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: """Solver for https://oj.leetcode.com/problems/median-of-two-sorted-arrays/""" def findMedianSortedArrays(self, A, B): """The main solver function.""" midindex_0 = (len(A) + len(B) - 1) / 2 midindex_1 = (len(A) + len(B)) / 2 if midindex_0 == midindex_1: ...
the_stack_v2_python_sparse
src/median-of-two-sorted-arrays.py
starrify/leetcode
train
0
1fb5c36c989205f77733c6677947d6c47ab6dc6d
[ "storage = get_messages(request)\nflash_message = {'error': [], 'success': [], 'warning': [], 'info': []}\nfor message in storage:\n flash_message[message.tags].append(message.__str__())\nreturn render(request, 'authentication/signup.html', {'error_message': flash_message['error'], 'success_message': flash_messa...
<|body_start_0|> storage = get_messages(request) flash_message = {'error': [], 'success': [], 'warning': [], 'info': []} for message in storage: flash_message[message.tags].append(message.__str__()) return render(request, 'authentication/signup.html', {'error_message': flash_...
RegistrationView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistrationView: def get(self, request): """GET""" <|body_0|> def post(self, request): """Handle post request""" <|body_1|> <|end_skeleton|> <|body_start_0|> storage = get_messages(request) flash_message = {'error': [], 'success': [], 'warn...
stack_v2_sparse_classes_75kplus_train_000031
10,104
no_license
[ { "docstring": "GET", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Handle post request", "name": "post", "signature": "def post(self, request)" } ]
2
null
Implement the Python class `RegistrationView` described below. Class description: Implement the RegistrationView class. Method signatures and docstrings: - def get(self, request): GET - def post(self, request): Handle post request
Implement the Python class `RegistrationView` described below. Class description: Implement the RegistrationView class. Method signatures and docstrings: - def get(self, request): GET - def post(self, request): Handle post request <|skeleton|> class RegistrationView: def get(self, request): """GET""" ...
992b0a23e4c22672d58af3a2ce3b48c5dbb8f748
<|skeleton|> class RegistrationView: def get(self, request): """GET""" <|body_0|> def post(self, request): """Handle post request""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegistrationView: def get(self, request): """GET""" storage = get_messages(request) flash_message = {'error': [], 'success': [], 'warning': [], 'info': []} for message in storage: flash_message[message.tags].append(message.__str__()) return render(request, '...
the_stack_v2_python_sparse
authentication/views.py
sadiachow15/platform
train
0
dc156979d8ed1c65d899a410e59272acabb493b5
[ "if 'id_token' in params:\n user = _get_user_from_google_token(params['id_token'])\nelse:\n user = User.find_by_email_or_username(params['email_or_username'])\n if not validate_user(user, params['password']):\n return ({'error': 'Bad username or password'}, 401)\nreturn _build_login_response(user, p...
<|body_start_0|> if 'id_token' in params: user = _get_user_from_google_token(params['id_token']) else: user = User.find_by_email_or_username(params['email_or_username']) if not validate_user(user, params['password']): return ({'error': 'Bad username or...
Controller for authentication
AuthenticationsView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthenticationsView: """Controller for authentication""" def post(self, **params): """Returns a cookie and a csrf token for double submit CSRF protection.""" <|body_0|> def delete(self): """Unsets the cookie in response""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_75kplus_train_000032
2,913
permissive
[ { "docstring": "Returns a cookie and a csrf token for double submit CSRF protection.", "name": "post", "signature": "def post(self, **params)" }, { "docstring": "Unsets the cookie in response", "name": "delete", "signature": "def delete(self)" } ]
2
null
Implement the Python class `AuthenticationsView` described below. Class description: Controller for authentication Method signatures and docstrings: - def post(self, **params): Returns a cookie and a csrf token for double submit CSRF protection. - def delete(self): Unsets the cookie in response
Implement the Python class `AuthenticationsView` described below. Class description: Controller for authentication Method signatures and docstrings: - def post(self, **params): Returns a cookie and a csrf token for double submit CSRF protection. - def delete(self): Unsets the cookie in response <|skeleton|> class Au...
98173eb380bd6add52b21dc9045893949a8a2d30
<|skeleton|> class AuthenticationsView: """Controller for authentication""" def post(self, **params): """Returns a cookie and a csrf token for double submit CSRF protection.""" <|body_0|> def delete(self): """Unsets the cookie in response""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AuthenticationsView: """Controller for authentication""" def post(self, **params): """Returns a cookie and a csrf token for double submit CSRF protection.""" if 'id_token' in params: user = _get_user_from_google_token(params['id_token']) else: user = User.f...
the_stack_v2_python_sparse
application/authentications/authentications_view.py
hpi-sam/ask-your-repository-api
train
4
dfe1f0e000450e3c3b62e1b59b231293c1b91e77
[ "super(TwoLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)", "h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred" ]
<|body_start_0|> super(TwoLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) <|end_body_0|> <|body_start_1|> h_relu = self.linear1(x).clamp(min=0) y_pred = self.linear2(h_relu) return y_pred <|end_body_1|>
TwoLayerNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TwoLayerNet: def __init__(self, D_in, H, D_out): """In the constructor we instantiate two nn.Linear modules and assign them as member variables.""" <|body_0|> def forward(self, x): """In the forward function we accept a Variable of input data and we must return a Var...
stack_v2_sparse_classes_75kplus_train_000033
3,631
no_license
[ { "docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.", "name": "__init__", "signature": "def __init__(self, D_in, H, D_out)" }, { "docstring": "In the forward function we accept a Variable of input data and we must return a Variable of outp...
2
stack_v2_sparse_classes_30k_train_032865
Implement the Python class `TwoLayerNet` described below. Class description: Implement the TwoLayerNet class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables. - def forward(self, x): In the forward func...
Implement the Python class `TwoLayerNet` described below. Class description: Implement the TwoLayerNet class. Method signatures and docstrings: - def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables. - def forward(self, x): In the forward func...
868d54b6094cb92240600418f2849d4b196374be
<|skeleton|> class TwoLayerNet: def __init__(self, D_in, H, D_out): """In the constructor we instantiate two nn.Linear modules and assign them as member variables.""" <|body_0|> def forward(self, x): """In the forward function we accept a Variable of input data and we must return a Var...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TwoLayerNet: def __init__(self, D_in, H, D_out): """In the constructor we instantiate two nn.Linear modules and assign them as member variables.""" super(TwoLayerNet, self).__init__() self.linear1 = torch.nn.Linear(D_in, H) self.linear2 = torch.nn.Linear(H, D_out) def forw...
the_stack_v2_python_sparse
pytorchtest/simpleMnist.py
metatron/pythontest
train
1
abc4e4ef09fd4da1cc6df66a3f00982d0f022ea4
[ "if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')\nself.independent_set = set()\nself.cardinality = 0\nself.source = None", "used = set()\nif source is no...
<|body_start_0|> if graph.is_directed(): raise ValueError('the graph is directed') self.graph = graph for edge in self.graph.iteredges(): if edge.source == edge.target: raise ValueError('a loop detected') self.independent_set = set() self.c...
Find a maximal independent set.
UnorderedSequentialIndependentSet1
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UnorderedSequentialIndependentSet1: """Find a maximal independent set.""" def __init__(self, graph): """The algorithm initialization.""" <|body_0|> def run(self, source=None): """Executable pseudocode.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_000034
3,887
permissive
[ { "docstring": "The algorithm initialization.", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Executable pseudocode.", "name": "run", "signature": "def run(self, source=None)" } ]
2
stack_v2_sparse_classes_30k_train_026723
Implement the Python class `UnorderedSequentialIndependentSet1` described below. Class description: Find a maximal independent set. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization. - def run(self, source=None): Executable pseudocode.
Implement the Python class `UnorderedSequentialIndependentSet1` described below. Class description: Find a maximal independent set. Method signatures and docstrings: - def __init__(self, graph): The algorithm initialization. - def run(self, source=None): Executable pseudocode. <|skeleton|> class UnorderedSequentialI...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class UnorderedSequentialIndependentSet1: """Find a maximal independent set.""" def __init__(self, graph): """The algorithm initialization.""" <|body_0|> def run(self, source=None): """Executable pseudocode.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UnorderedSequentialIndependentSet1: """Find a maximal independent set.""" def __init__(self, graph): """The algorithm initialization.""" if graph.is_directed(): raise ValueError('the graph is directed') self.graph = graph for edge in self.graph.iteredges(): ...
the_stack_v2_python_sparse
graphtheory/independentsets/isetus.py
kgashok/graphs-dict
train
0
d01e4f7e3b3ee39208237293aaf6869aefbce9e5
[ "node1 = None\nwords = ['']\nself.assertEqual(make_dafsa.to_words(node1), words)", "node1 = ('ab', [None])\nwords = ['ab']\nself.assertEqual(make_dafsa.to_words(node1), words)", "node2 = ('cd', [None])\nnode1 = ('ab', [node2])\nwords = ['abcd']\nself.assertEqual(make_dafsa.to_words(node1), words)", "node2 = (...
<|body_start_0|> node1 = None words = [''] self.assertEqual(make_dafsa.to_words(node1), words) <|end_body_0|> <|body_start_1|> node1 = ('ab', [None]) words = ['ab'] self.assertEqual(make_dafsa.to_words(node1), words) <|end_body_1|> <|body_start_2|> node2 = ('cd'...
ToWordsTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ToWordsTest: def testSink(self): """Tests the sink is exapnded to a list with an empty string.""" <|body_0|> def testSingleNode(self): """Tests a single node is expanded to a list with the label string.""" <|body_1|> def testChain(self): """Tests...
stack_v2_sparse_classes_75kplus_train_000035
20,781
permissive
[ { "docstring": "Tests the sink is exapnded to a list with an empty string.", "name": "testSink", "signature": "def testSink(self)" }, { "docstring": "Tests a single node is expanded to a list with the label string.", "name": "testSingleNode", "signature": "def testSingleNode(self)" }, ...
5
stack_v2_sparse_classes_30k_train_028702
Implement the Python class `ToWordsTest` described below. Class description: Implement the ToWordsTest class. Method signatures and docstrings: - def testSink(self): Tests the sink is exapnded to a list with an empty string. - def testSingleNode(self): Tests a single node is expanded to a list with the label string. ...
Implement the Python class `ToWordsTest` described below. Class description: Implement the ToWordsTest class. Method signatures and docstrings: - def testSink(self): Tests the sink is exapnded to a list with an empty string. - def testSingleNode(self): Tests a single node is expanded to a list with the label string. ...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class ToWordsTest: def testSink(self): """Tests the sink is exapnded to a list with an empty string.""" <|body_0|> def testSingleNode(self): """Tests a single node is expanded to a list with the label string.""" <|body_1|> def testChain(self): """Tests...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ToWordsTest: def testSink(self): """Tests the sink is exapnded to a list with an empty string.""" node1 = None words = [''] self.assertEqual(make_dafsa.to_words(node1), words) def testSingleNode(self): """Tests a single node is expanded to a list with the label str...
the_stack_v2_python_sparse
tools/media_engagement_preload/make_dafsa_unittest.py
chromium/chromium
train
17,408
76eea2440fe671983efef8d9ab4704e2a0b195a0
[ "username = self.cleaned_data.get('username')\nif User.objects.filter(username__iexact=username):\n raise ValidationError(self.error_messages['duplicate_username'])\nreturn username", "email = self.cleaned_data.get('email')\nif email and User.objects.filter(email__iexact=email):\n raise ValidationError(self...
<|body_start_0|> username = self.cleaned_data.get('username') if User.objects.filter(username__iexact=username): raise ValidationError(self.error_messages['duplicate_username']) return username <|end_body_0|> <|body_start_1|> email = self.cleaned_data.get('email') if...
Form for registering a new user account. Validates that the requested username and email is not already in use, and requires the password to be entered twice to catch typos.
RegistrationForm
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistrationForm: """Form for registering a new user account. Validates that the requested username and email is not already in use, and requires the password to be entered twice to catch typos.""" def clean_username(self): """Validate that the username is not already in use.""" ...
stack_v2_sparse_classes_75kplus_train_000036
3,293
permissive
[ { "docstring": "Validate that the username is not already in use.", "name": "clean_username", "signature": "def clean_username(self)" }, { "docstring": "Validate that the supplied email address is unique for the site.", "name": "clean_email", "signature": "def clean_email(self)" }, {...
4
stack_v2_sparse_classes_30k_train_026499
Implement the Python class `RegistrationForm` described below. Class description: Form for registering a new user account. Validates that the requested username and email is not already in use, and requires the password to be entered twice to catch typos. Method signatures and docstrings: - def clean_username(self): ...
Implement the Python class `RegistrationForm` described below. Class description: Form for registering a new user account. Validates that the requested username and email is not already in use, and requires the password to be entered twice to catch typos. Method signatures and docstrings: - def clean_username(self): ...
a05a5161c415b546084bbe98b00e0671860c9bc6
<|skeleton|> class RegistrationForm: """Form for registering a new user account. Validates that the requested username and email is not already in use, and requires the password to be entered twice to catch typos.""" def clean_username(self): """Validate that the username is not already in use.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegistrationForm: """Form for registering a new user account. Validates that the requested username and email is not already in use, and requires the password to be entered twice to catch typos.""" def clean_username(self): """Validate that the username is not already in use.""" username ...
the_stack_v2_python_sparse
DistributedSocialNetworking/Hindlebook/forms/auth_forms.py
Roshack/cmput410-project
train
0
041025a714706ad0a5beaa4f852d2f2f4cd0a4b6
[ "num1_len = len(nums1)\nnum2_len = len(nums2)\nif k > num1_len + num2_len:\n return -1\nret = [0] * k\nfor i in xrange(0, k + 1):\n j = k - i\n if i > num1_len or j > num2_len:\n continue\n left = self.maxsubstringNum(nums1, i)\n right = self.maxsubstringNum(nums2, k - i)\n num = self.merge...
<|body_start_0|> num1_len = len(nums1) num2_len = len(nums2) if k > num1_len + num2_len: return -1 ret = [0] * k for i in xrange(0, k + 1): j = k - i if i > num1_len or j > num2_len: continue left = self.maxsubstring...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxNumber(self, nums1, nums2, k): """:type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]""" <|body_0|> def merge(self, left, right): """:type left: List[int], the left part of maxinum :type right: List[int], the right part of th...
stack_v2_sparse_classes_75kplus_train_000037
2,089
permissive
[ { "docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]", "name": "maxNumber", "signature": "def maxNumber(self, nums1, nums2, k)" }, { "docstring": ":type left: List[int], the left part of maxinum :type right: List[int], the right part of the maxinum :rtype:...
3
stack_v2_sparse_classes_30k_train_005755
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxNumber(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] - def merge(self, left, right): :type left: List[int], the left...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxNumber(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] - def merge(self, left, right): :type left: List[int], the left...
86f1cb98de801f58c39d9a48ce9de12df7303d20
<|skeleton|> class Solution: def maxNumber(self, nums1, nums2, k): """:type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]""" <|body_0|> def merge(self, left, right): """:type left: List[int], the left part of maxinum :type right: List[int], the right part of th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxNumber(self, nums1, nums2, k): """:type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]""" num1_len = len(nums1) num2_len = len(nums2) if k > num1_len + num2_len: return -1 ret = [0] * k for i in xrange(0, k + ...
the_stack_v2_python_sparse
321-Create-Maximum-Number/solution.py
Tanych/CodeTracking
train
0
888f1fd253e04c41ad1badbf3034942cdaf23cb0
[ "if not asyncEstimate:\n error, estimation = self._coreEstimator.estimate(imageWithFaceDetection.image.coreImage, imageWithFaceDetection.boundingBox.coreEstimation)\n return POST_PROCESSING.postProcessing(error, estimation)\ntask = self._coreEstimator.asyncEstimate(imageWithFaceDetection.image.coreImage, imag...
<|body_start_0|> if not asyncEstimate: error, estimation = self._coreEstimator.estimate(imageWithFaceDetection.image.coreImage, imageWithFaceDetection.boundingBox.coreEstimation) return POST_PROCESSING.postProcessing(error, estimation) task = self._coreEstimator.asyncEstimate(ima...
Fisheye effect estimator. Work on face detections
FisheyeEstimator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FisheyeEstimator: """Fisheye effect estimator. Work on face detections""" def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False) -> Union[Fisheye, AsyncTask[Fisheye]]: """Estimate fisheye. Args: imageWithFaceDetection: image with face detection ...
stack_v2_sparse_classes_75kplus_train_000038
3,851
permissive
[ { "docstring": "Estimate fisheye. Args: imageWithFaceDetection: image with face detection asyncEstimate: estimate or run estimation in background Returns: fisheye estimation if asyncEstimate is false otherwise async task Raises: LunaSDKException: if estimation is failed", "name": "estimate", "signature"...
2
stack_v2_sparse_classes_30k_train_004715
Implement the Python class `FisheyeEstimator` described below. Class description: Fisheye effect estimator. Work on face detections Method signatures and docstrings: - def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False) -> Union[Fisheye, AsyncTask[Fisheye]]: Estimate fisheye....
Implement the Python class `FisheyeEstimator` described below. Class description: Fisheye effect estimator. Work on face detections Method signatures and docstrings: - def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False) -> Union[Fisheye, AsyncTask[Fisheye]]: Estimate fisheye....
7a4bebc92ae7a96d8d9c18a024208308942f90cd
<|skeleton|> class FisheyeEstimator: """Fisheye effect estimator. Work on face detections""" def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False) -> Union[Fisheye, AsyncTask[Fisheye]]: """Estimate fisheye. Args: imageWithFaceDetection: image with face detection ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FisheyeEstimator: """Fisheye effect estimator. Work on face detections""" def estimate(self, imageWithFaceDetection: ImageWithFaceDetection, asyncEstimate: bool=False) -> Union[Fisheye, AsyncTask[Fisheye]]: """Estimate fisheye. Args: imageWithFaceDetection: image with face detection asyncEstimate...
the_stack_v2_python_sparse
lunavl/sdk/estimators/face_estimators/fisheye.py
matemax/lunasdk
train
16
baaaf14016aefe59dbbb7b16964c11dd56f8af92
[ "self.ylim_down = ylim_down\nself.ylim_up = ylim_up\nself.xlim_down = xlim_down\nself.xlim_up = xlim_up\nself.background = background\nself.min_value = min_value\nself.max_value = max_value\nself.extend = extend\nself.legend_label = self._keyword_to_legend_label(background)", "if keyword == 'sig_vm':\n return ...
<|body_start_0|> self.ylim_down = ylim_down self.ylim_up = ylim_up self.xlim_down = xlim_down self.xlim_up = xlim_up self.background = background self.min_value = min_value self.max_value = max_value self.extend = extend self.legend_label = self._k...
PlotSettings
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlotSettings: def __init__(self, xlim_down: float=None, xlim_up: float=None, ylim_down: float=None, ylim_up: float=None, background: str='eps_vm', min_value: float=None, max_value: float=None, extend: str=None): """Define plot settings for Plotter class object. Args: xlim_down: lower lim...
stack_v2_sparse_classes_75kplus_train_000039
15,762
permissive
[ { "docstring": "Define plot settings for Plotter class object. Args: xlim_down: lower limit of x-axis xlim_up: upper limit of x-axis ylim_down: bottom of plot in [mm] (negative) ylim_up: top of plot in [mm] background: background plotted (e.g. 'sig_vm', 'eps_vm', 'disp_y', 'disp_x') min_value: minimum value of ...
2
null
Implement the Python class `PlotSettings` described below. Class description: Implement the PlotSettings class. Method signatures and docstrings: - def __init__(self, xlim_down: float=None, xlim_up: float=None, ylim_down: float=None, ylim_up: float=None, background: str='eps_vm', min_value: float=None, max_value: flo...
Implement the Python class `PlotSettings` described below. Class description: Implement the PlotSettings class. Method signatures and docstrings: - def __init__(self, xlim_down: float=None, xlim_up: float=None, ylim_down: float=None, ylim_up: float=None, background: str='eps_vm', min_value: float=None, max_value: flo...
7556651812bc1c0d38159d718a47847524fd1dd0
<|skeleton|> class PlotSettings: def __init__(self, xlim_down: float=None, xlim_up: float=None, ylim_down: float=None, ylim_up: float=None, background: str='eps_vm', min_value: float=None, max_value: float=None, extend: str=None): """Define plot settings for Plotter class object. Args: xlim_down: lower lim...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PlotSettings: def __init__(self, xlim_down: float=None, xlim_up: float=None, ylim_down: float=None, ylim_up: float=None, background: str='eps_vm', min_value: float=None, max_value: float=None, extend: str=None): """Define plot settings for Plotter class object. Args: xlim_down: lower limit of x-axis x...
the_stack_v2_python_sparse
crackpy/fracture_analysis/plot.py
dlr-wf/crackpy
train
40
0e3569fc19211dd8b1c16ac6b855860ddf8929e7
[ "if not root:\n return ''\nfrom collections import deque\ndeq = deque([root])\nres = [str(root.val), 'None']\nwhile deq:\n size = len(deq)\n for _ in range(size):\n node = deq.popleft()\n if node.children:\n res += [str(child.val) for child in node.children]\n deq += nod...
<|body_start_0|> if not root: return '' from collections import deque deq = deque([root]) res = [str(root.val), 'None'] while deq: size = len(deq) for _ in range(size): node = deq.popleft() if node.children: ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|e...
stack_v2_sparse_classes_75kplus_train_000040
2,282
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: Node :rtype: str", "name": "serialize", "signature": "def serialize(self, root: 'Node') -> str" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node", "name": "deserialize", "signature": "def des...
2
stack_v2_sparse_classes_30k_train_027380
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str - def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre...
4cf03307c5caeccaa87ccce249322bd02397f489
<|skeleton|> class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" <|body_0|> def deserialize(self, data: str) -> 'Node': """Decodes your encoded data to tree. :type data: str :rtype: Node""" <|body_1|> <|e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root: 'Node') -> str: """Encodes a tree to a single string. :type root: Node :rtype: str""" if not root: return '' from collections import deque deq = deque([root]) res = [str(root.val), 'None'] while deq: size ...
the_stack_v2_python_sparse
0428. Serialize and Deserialize N-ary Tree.py
aidardarmesh/leetcode2
train
0
488451854a3c0df8eaf4c34fbf79defc064719fc
[ "self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-fact' if model_name_or_path == '' else model_name_or_path, max_length=max_length, device=device, cache_dir=cache_dir)\nself.task = 'fact'\nself.dim = 'consistency'", "n_data = len(data)\neval_scores = [{} for _ in range(n_data)]\nsrc_list, output_l...
<|body_start_0|> self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-fact' if model_name_or_path == '' else model_name_or_path, max_length=max_length, device=device, cache_dir=cache_dir) self.task = 'fact' self.dim = 'consistency' <|end_body_0|> <|body_start_1|> n_data = le...
FactEvaluator
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FactEvaluator: def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): """Set up evaluator for factual consistency detection""" <|body_0|> def evaluate(self, data, category): """Get the factual consistency score (only 1 dimension for...
stack_v2_sparse_classes_75kplus_train_000041
14,573
permissive
[ { "docstring": "Set up evaluator for factual consistency detection", "name": "__init__", "signature": "def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None)" }, { "docstring": "Get the factual consistency score (only 1 dimension for this task) category: The cat...
2
stack_v2_sparse_classes_30k_train_007023
Implement the Python class `FactEvaluator` described below. Class description: Implement the FactEvaluator class. Method signatures and docstrings: - def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up evaluator for factual consistency detection - def evaluate(self, data, ...
Implement the Python class `FactEvaluator` described below. Class description: Implement the FactEvaluator class. Method signatures and docstrings: - def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): Set up evaluator for factual consistency detection - def evaluate(self, data, ...
c7b60f75470f067d1342705708810a660eabd684
<|skeleton|> class FactEvaluator: def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): """Set up evaluator for factual consistency detection""" <|body_0|> def evaluate(self, data, category): """Get the factual consistency score (only 1 dimension for...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FactEvaluator: def __init__(self, model_name_or_path, max_length=1024, device='cuda:0', cache_dir=None): """Set up evaluator for factual consistency detection""" self.scorer = UniEvaluator(model_name_or_path='MingZhong/unieval-fact' if model_name_or_path == '' else model_name_or_path, max_leng...
the_stack_v2_python_sparse
applications/Chat/evaluate/unieval/evaluator.py
hpcaitech/ColossalAI
train
32,044
98ff02c37875270d80470b39fb8aa52d86c0424f
[ "l = [5, 2, 8, 2, 6, 1, 454, 8, 23]\nfinal = [1, 2, 2, 5, 6, 8, 8, 23, 454]\nself.assertEqual(radix_sort(l), final)", "l = [5, 8, 2, 6, 3, 7, 3, 7, 1, 5, 789, 2344, 6, 1, 6, 7, 234, 8, 56, 4, 8, 234, 0, 12, 0]\nfinal = [0, 0, 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 12, 56, 234, 234, 789, 2344]\nself.as...
<|body_start_0|> l = [5, 2, 8, 2, 6, 1, 454, 8, 23] final = [1, 2, 2, 5, 6, 8, 8, 23, 454] self.assertEqual(radix_sort(l), final) <|end_body_0|> <|body_start_1|> l = [5, 8, 2, 6, 3, 7, 3, 7, 1, 5, 789, 2344, 6, 1, 6, 7, 234, 8, 56, 4, 8, 234, 0, 12, 0] final = [0, 0, 1, 1, 2, 3,...
TestRadixSort
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRadixSort: def test_short_list(self): """Tests if a short list of integers has been sorted""" <|body_0|> def test_long_list(self): """Tests if a long list of integers has been sorted""" <|body_1|> def test_float_list(self): """Tests if a list...
stack_v2_sparse_classes_75kplus_train_000042
1,656
permissive
[ { "docstring": "Tests if a short list of integers has been sorted", "name": "test_short_list", "signature": "def test_short_list(self)" }, { "docstring": "Tests if a long list of integers has been sorted", "name": "test_long_list", "signature": "def test_long_list(self)" }, { "do...
3
stack_v2_sparse_classes_30k_train_008499
Implement the Python class `TestRadixSort` described below. Class description: Implement the TestRadixSort class. Method signatures and docstrings: - def test_short_list(self): Tests if a short list of integers has been sorted - def test_long_list(self): Tests if a long list of integers has been sorted - def test_flo...
Implement the Python class `TestRadixSort` described below. Class description: Implement the TestRadixSort class. Method signatures and docstrings: - def test_short_list(self): Tests if a short list of integers has been sorted - def test_long_list(self): Tests if a long list of integers has been sorted - def test_flo...
189fe8bccb54a622d524ac813a8805a86f0a4a98
<|skeleton|> class TestRadixSort: def test_short_list(self): """Tests if a short list of integers has been sorted""" <|body_0|> def test_long_list(self): """Tests if a long list of integers has been sorted""" <|body_1|> def test_float_list(self): """Tests if a list...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestRadixSort: def test_short_list(self): """Tests if a short list of integers has been sorted""" l = [5, 2, 8, 2, 6, 1, 454, 8, 23] final = [1, 2, 2, 5, 6, 8, 8, 23, 454] self.assertEqual(radix_sort(l), final) def test_long_list(self): """Tests if a long list of i...
the_stack_v2_python_sparse
algorithms/sort_algorithms/radix_sort/test_radix_sort.py
nwthomas/data-structures-and-algorithms
train
13
27a55142a0835d99f741eafdf3e263040f7fae36
[ "actual = a1.stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.1, -0.01])\nexpected = (0.14, -0.17)\nself.assertEqual(actual, expected)", "actual = actual = a1.stock_price_summary([-0.01, -0.03, 0.02, 0.14, 0, 0, -0.1, 0.01])\nexpected = (0.17, -0.14)\nself.assertEqual(actual, expected)", "actual = a1.stoc...
<|body_start_0|> actual = a1.stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.1, -0.01]) expected = (0.14, -0.17) self.assertEqual(actual, expected) <|end_body_0|> <|body_start_1|> actual = actual = a1.stock_price_summary([-0.01, -0.03, 0.02, 0.14, 0, 0, -0.1, 0.01]) expec...
Test class for function a1.stock_price_summary.
TestStockPriceSummary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_random1(self): """Test the function with random numbers""" <|body_0|> def test_random2(self): """Test the function with inverted random numbers""" <|body_1|> def te...
stack_v2_sparse_classes_75kplus_train_000043
1,114
no_license
[ { "docstring": "Test the function with random numbers", "name": "test_random1", "signature": "def test_random1(self)" }, { "docstring": "Test the function with inverted random numbers", "name": "test_random2", "signature": "def test_random2(self)" }, { "docstring": "The the funct...
4
stack_v2_sparse_classes_30k_train_030987
Implement the Python class `TestStockPriceSummary` described below. Class description: Test class for function a1.stock_price_summary. Method signatures and docstrings: - def test_random1(self): Test the function with random numbers - def test_random2(self): Test the function with inverted random numbers - def test_z...
Implement the Python class `TestStockPriceSummary` described below. Class description: Test class for function a1.stock_price_summary. Method signatures and docstrings: - def test_random1(self): Test the function with random numbers - def test_random2(self): Test the function with inverted random numbers - def test_z...
ba0e48825e3f90f9da0e7506c89354622198c4a5
<|skeleton|> class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_random1(self): """Test the function with random numbers""" <|body_0|> def test_random2(self): """Test the function with inverted random numbers""" <|body_1|> def te...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestStockPriceSummary: """Test class for function a1.stock_price_summary.""" def test_random1(self): """Test the function with random numbers""" actual = a1.stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.1, -0.01]) expected = (0.14, -0.17) self.assertEqual(actual, ...
the_stack_v2_python_sparse
Coursera/Python3/Second Course Asignments/Assighment 1/test_stock_price_summary.py
Vutov/SideProjects
train
0
e7aa4170c27ff36a2796c8ca58ed9dd6da40739c
[ "if isinstance(cmd, Command):\n ret = cmd.run(arg_str, cwd=cwd, environ=environ, **kwargs)\nelif hasattr(cmd, 'run'):\n ret = cmd.run(arg_str, cwd=cwd, environ=environ, **kwargs)\nelse:\n cmd = Command(cmd, cwd=cwd, environ=environ)\n ret = cmd.run(arg_str, **kwargs)\nreturn ret", "if isinstance(cmd, ...
<|body_start_0|> if isinstance(cmd, Command): ret = cmd.run(arg_str, cwd=cwd, environ=environ, **kwargs) elif hasattr(cmd, 'run'): ret = cmd.run(arg_str, cwd=cwd, environ=environ, **kwargs) else: cmd = Command(cmd, cwd=cwd, environ=environ) ret = c...
ClientData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientData: def run_command(self, cmd, arg_str='', cwd='', environ=None, **kwargs): """Run a command on the command line :param cmd: mixed, the command you want to run :param arg_str: string, extra flags that will be appended to the cmd :param **kwargs: allows you to pass into underlying...
stack_v2_sparse_classes_75kplus_train_000044
3,565
permissive
[ { "docstring": "Run a command on the command line :param cmd: mixed, the command you want to run :param arg_str: string, extra flags that will be appended to the cmd :param **kwargs: allows you to pass into underlying Command.run() method :returns: string, the output from the command", "name": "run_command"...
3
null
Implement the Python class `ClientData` described below. Class description: Implement the ClientData class. Method signatures and docstrings: - def run_command(self, cmd, arg_str='', cwd='', environ=None, **kwargs): Run a command on the command line :param cmd: mixed, the command you want to run :param arg_str: strin...
Implement the Python class `ClientData` described below. Class description: Implement the ClientData class. Method signatures and docstrings: - def run_command(self, cmd, arg_str='', cwd='', environ=None, **kwargs): Run a command on the command line :param cmd: mixed, the command you want to run :param arg_str: strin...
41ca4bbbff595c2bb50403c5353f19670ec9e2ef
<|skeleton|> class ClientData: def run_command(self, cmd, arg_str='', cwd='', environ=None, **kwargs): """Run a command on the command line :param cmd: mixed, the command you want to run :param arg_str: string, extra flags that will be appended to the cmd :param **kwargs: allows you to pass into underlying...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ClientData: def run_command(self, cmd, arg_str='', cwd='', environ=None, **kwargs): """Run a command on the command line :param cmd: mixed, the command you want to run :param arg_str: string, extra flags that will be appended to the cmd :param **kwargs: allows you to pass into underlying Command.run()...
the_stack_v2_python_sparse
testdata/client.py
Jaymon/testdata
train
10
8a35cc0467f05bc6c013748ef70aa4c80b707008
[ "if head.next is None or head.next is None:\n return head\nnew_head = self.reverseList(head.next)\nhead.next.next = head\nhead.next = None\nreturn new_head", "if head is None:\n return head\npre = None\ncur = head\nwhile cur is not None:\n next_node = cur.next\n cur.next = pre\n pre = cur\n cur ...
<|body_start_0|> if head.next is None or head.next is None: return head new_head = self.reverseList(head.next) head.next.next = head head.next = None return new_head <|end_body_0|> <|body_start_1|> if head is None: return head pre = None ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head: ListNode) -> ListNode: """递归""" <|body_0|> def reverseList1(self, head: ListNode) -> ListNode: """迭代""" <|body_1|> <|end_skeleton|> <|body_start_0|> if head.next is None or head.next is None: return ...
stack_v2_sparse_classes_75kplus_train_000045
941
no_license
[ { "docstring": "递归", "name": "reverseList", "signature": "def reverseList(self, head: ListNode) -> ListNode" }, { "docstring": "迭代", "name": "reverseList1", "signature": "def reverseList1(self, head: ListNode) -> ListNode" } ]
2
stack_v2_sparse_classes_30k_train_021754
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head: ListNode) -> ListNode: 递归 - def reverseList1(self, head: ListNode) -> ListNode: 迭代
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head: ListNode) -> ListNode: 递归 - def reverseList1(self, head: ListNode) -> ListNode: 迭代 <|skeleton|> class Solution: def reverseList(self, head: List...
3fa96c81f92595cf076ad675ba332e2b0eb0e071
<|skeleton|> class Solution: def reverseList(self, head: ListNode) -> ListNode: """递归""" <|body_0|> def reverseList1(self, head: ListNode) -> ListNode: """迭代""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def reverseList(self, head: ListNode) -> ListNode: """递归""" if head.next is None or head.next is None: return head new_head = self.reverseList(head.next) head.next.next = head head.next = None return new_head def reverseList1(self, hea...
the_stack_v2_python_sparse
2020-03/3月每日一题复习/206反转链表.py
Annihilation7/Leetcode-Love
train
0
6ce4caed4560e626fd14e4b138382d5f3e8204b2
[ "super(FunctionComponent, self).__init__(opts)\nself.opts = opts\nself.options = opts.get(CONFIG_DATA_SECTION, {})", "self.opts = opts\nself.options = opts.get(CONFIG_DATA_SECTION, {})\nmaas360_utils = MaaS360Utils.get_the_maas360_utils()\nmaas360_utils.reload_options(opts)\nmaas360_utils.reconnect()", "try:\n ...
<|body_start_0|> super(FunctionComponent, self).__init__(opts) self.opts = opts self.options = opts.get(CONFIG_DATA_SECTION, {}) <|end_body_0|> <|body_start_1|> self.opts = opts self.options = opts.get(CONFIG_DATA_SECTION, {}) maas360_utils = MaaS360Utils.get_the_maas360...
Component that implements Resilient function 'maas360_delete_app
FunctionComponent
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FunctionComponent: """Component that implements Resilient function 'maas360_delete_app""" def __init__(self, opts): """constructor provides access to the configuration options""" <|body_0|> def _reload(self, event, opts): """Configuration options have changed, sa...
stack_v2_sparse_classes_75kplus_train_000046
3,056
permissive
[ { "docstring": "constructor provides access to the configuration options", "name": "__init__", "signature": "def __init__(self, opts)" }, { "docstring": "Configuration options have changed, save new values", "name": "_reload", "signature": "def _reload(self, event, opts)" }, { "d...
3
stack_v2_sparse_classes_30k_train_038912
Implement the Python class `FunctionComponent` described below. Class description: Component that implements Resilient function 'maas360_delete_app Method signatures and docstrings: - def __init__(self, opts): constructor provides access to the configuration options - def _reload(self, event, opts): Configuration opt...
Implement the Python class `FunctionComponent` described below. Class description: Component that implements Resilient function 'maas360_delete_app Method signatures and docstrings: - def __init__(self, opts): constructor provides access to the configuration options - def _reload(self, event, opts): Configuration opt...
6878c78b94eeca407998a41ce8db2cc00f2b6758
<|skeleton|> class FunctionComponent: """Component that implements Resilient function 'maas360_delete_app""" def __init__(self, opts): """constructor provides access to the configuration options""" <|body_0|> def _reload(self, event, opts): """Configuration options have changed, sa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FunctionComponent: """Component that implements Resilient function 'maas360_delete_app""" def __init__(self, opts): """constructor provides access to the configuration options""" super(FunctionComponent, self).__init__(opts) self.opts = opts self.options = opts.get(CONFIG_...
the_stack_v2_python_sparse
fn_maas360/fn_maas360/components/maas360_delete_app.py
ibmresilient/resilient-community-apps
train
81
455f4aaa167b657db10c13ddbc928827ea84f387
[ "self.config = config\nself.log = log\nself.reg_file = reg_file\nself.alignment = reg_file.alignment\nself.entry = []\nself.reset()\nself.num_read = 0\nself.num_write = 0\nreturn", "perf_metrics = {}\nperf_metrics['num_read'] = self.num_read\nperf_metrics['num_write'] = self.num_write\nreturn {'reg_track_table': ...
<|body_start_0|> self.config = config self.log = log self.reg_file = reg_file self.alignment = reg_file.alignment self.entry = [] self.reset() self.num_read = 0 self.num_write = 0 return <|end_body_0|> <|body_start_1|> perf_metrics = {} ...
RegTrackTable
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegTrackTable: def __init__(self, config, log, reg_file): """This table contains each entry per warp to track its regiser location validity information.""" <|body_0|> def get_perf_metrics(self): """Get a dictionary of performance metrics.""" <|body_1|> d...
stack_v2_sparse_classes_75kplus_train_000047
11,641
no_license
[ { "docstring": "This table contains each entry per warp to track its regiser location validity information.", "name": "__init__", "signature": "def __init__(self, config, log, reg_file)" }, { "docstring": "Get a dictionary of performance metrics.", "name": "get_perf_metrics", "signature"...
3
null
Implement the Python class `RegTrackTable` described below. Class description: Implement the RegTrackTable class. Method signatures and docstrings: - def __init__(self, config, log, reg_file): This table contains each entry per warp to track its regiser location validity information. - def get_perf_metrics(self): Get...
Implement the Python class `RegTrackTable` described below. Class description: Implement the RegTrackTable class. Method signatures and docstrings: - def __init__(self, config, log, reg_file): This table contains each entry per warp to track its regiser location validity information. - def get_perf_metrics(self): Get...
a357e73239a03384bae73d7006667cfeb07df635
<|skeleton|> class RegTrackTable: def __init__(self, config, log, reg_file): """This table contains each entry per warp to track its regiser location validity information.""" <|body_0|> def get_perf_metrics(self): """Get a dictionary of performance metrics.""" <|body_1|> d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegTrackTable: def __init__(self, config, log, reg_file): """This table contains each entry per warp to track its regiser location validity information.""" self.config = config self.log = log self.reg_file = reg_file self.alignment = reg_file.alignment self.entr...
the_stack_v2_python_sparse
simulator/subcore_table.py
GD06/MPU-ASPLOS-2021
train
3
206e94ef8f92fc4b0e778fd4a47822f5bb777b4e
[ "if not circuit.instructions:\n return ''\ncircuit_qubits = circuit.qubits\ncircuit_qubits.sort()\ny_axis_width = len(str(int(max(circuit_qubits))))\ny_axis_str = '{0:{width}} : |\\n'.format('T', width=y_axis_width + 1)\nfor qubit in circuit_qubits:\n y_axis_str += '{0:{width}}\\n'.format(' ', width=y_axis_wi...
<|body_start_0|> if not circuit.instructions: return '' circuit_qubits = circuit.qubits circuit_qubits.sort() y_axis_width = len(str(int(max(circuit_qubits)))) y_axis_str = '{0:{width}} : |\n'.format('T', width=y_axis_width + 1) for qubit in circuit_qubits: ...
Builds ASCII string circuit diagrams.
AsciiCircuitDiagram
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsciiCircuitDiagram: """Builds ASCII string circuit diagrams.""" def build_diagram(circuit) -> str: """Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit to build a diagram of. Returns: str: ASCII string circuit diagram.""" <|body_0|> def _ascii_diag...
stack_v2_sparse_classes_75kplus_train_000048
4,140
permissive
[ { "docstring": "Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit to build a diagram of. Returns: str: ASCII string circuit diagram.", "name": "build_diagram", "signature": "def build_diagram(circuit) -> str" }, { "docstring": "Return an ASCII string diagram of the circuit ...
2
null
Implement the Python class `AsciiCircuitDiagram` described below. Class description: Builds ASCII string circuit diagrams. Method signatures and docstrings: - def build_diagram(circuit) -> str: Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit to build a diagram of. Returns: str: ASCII string ci...
Implement the Python class `AsciiCircuitDiagram` described below. Class description: Builds ASCII string circuit diagrams. Method signatures and docstrings: - def build_diagram(circuit) -> str: Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit to build a diagram of. Returns: str: ASCII string ci...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class AsciiCircuitDiagram: """Builds ASCII string circuit diagrams.""" def build_diagram(circuit) -> str: """Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit to build a diagram of. Returns: str: ASCII string circuit diagram.""" <|body_0|> def _ascii_diag...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AsciiCircuitDiagram: """Builds ASCII string circuit diagrams.""" def build_diagram(circuit) -> str: """Build an ASCII string circuit diagram. Args: circuit (Circuit): Circuit to build a diagram of. Returns: str: ASCII string circuit diagram.""" if not circuit.instructions: ret...
the_stack_v2_python_sparse
artifacts/minimal_bugfixes/amazon-braket-sdk-python/amazon-braket-sdk-python#44/before/ascii_circuit_diagram.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
7ba2bd6877db278af819581d2a973aa771ccc809
[ "import sys\nn = len(nums)\nif n == 0:\n return 0\nnums.insert(0, -sys.maxsize)\nT = []\nfor i in range(n + 1):\n T.append([0] * (n + 2))\nfor j in range(n, 0, -1):\n for i in range(0, j):\n if nums[i] >= nums[j]:\n T[i][j] = T[i][j + 1]\n else:\n T[i][j] = max(T[i][j + ...
<|body_start_0|> import sys n = len(nums) if n == 0: return 0 nums.insert(0, -sys.maxsize) T = [] for i in range(n + 1): T.append([0] * (n + 2)) for j in range(n, 0, -1): for i in range(0, j): if nums[i] >= nums[...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """DP approach Time: O(n^2) Space: O(n^2) TLE :type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS2(self, nums): """DP approach 2: define dp[i] as LIS of nums[i...n] that starts with nums[i]. DP formula: dp[i] = 1 + m...
stack_v2_sparse_classes_75kplus_train_000049
1,733
no_license
[ { "docstring": "DP approach Time: O(n^2) Space: O(n^2) TLE :type nums: List[int] :rtype: int", "name": "lengthOfLIS", "signature": "def lengthOfLIS(self, nums)" }, { "docstring": "DP approach 2: define dp[i] as LIS of nums[i...n] that starts with nums[i]. DP formula: dp[i] = 1 + max{dp[j] | j > ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): DP approach Time: O(n^2) Space: O(n^2) TLE :type nums: List[int] :rtype: int - def lengthOfLIS2(self, nums): DP approach 2: define dp[i] as LIS of nu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLIS(self, nums): DP approach Time: O(n^2) Space: O(n^2) TLE :type nums: List[int] :rtype: int - def lengthOfLIS2(self, nums): DP approach 2: define dp[i] as LIS of nu...
143aa25f92f3827aa379f29c67a9b7ec3757fef9
<|skeleton|> class Solution: def lengthOfLIS(self, nums): """DP approach Time: O(n^2) Space: O(n^2) TLE :type nums: List[int] :rtype: int""" <|body_0|> def lengthOfLIS2(self, nums): """DP approach 2: define dp[i] as LIS of nums[i...n] that starts with nums[i]. DP formula: dp[i] = 1 + m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def lengthOfLIS(self, nums): """DP approach Time: O(n^2) Space: O(n^2) TLE :type nums: List[int] :rtype: int""" import sys n = len(nums) if n == 0: return 0 nums.insert(0, -sys.maxsize) T = [] for i in range(n + 1): T.ap...
the_stack_v2_python_sparse
py/leetcode_py/300.py
imsure/tech-interview-prep
train
0
553a266e4f3e0b4b7d513389b2cec2c0c792d75c
[ "message = Mock()\nmessage.has_label.return_value = False\nwith patch('eventstore.whatsapp_actions.update_rapidpro_preferred_channel') as update:\n message.fallback_channel = True\n handle_inbound(message)\n update.assert_not_called()\n message.fallback_channel = False\n handle_inbound(message)\n ...
<|body_start_0|> message = Mock() message.has_label.return_value = False with patch('eventstore.whatsapp_actions.update_rapidpro_preferred_channel') as update: message.fallback_channel = True handle_inbound(message) update.assert_not_called() messa...
HandleInboundTests
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HandleInboundTests: def test_contact_update(self): """If the message is not over the fallback channel then it should update the preferred channel""" <|body_0|> def test_alert_optout(self): """If the button text matches the optout phrase then it should update the cont...
stack_v2_sparse_classes_75kplus_train_000050
17,041
permissive
[ { "docstring": "If the message is not over the fallback channel then it should update the preferred channel", "name": "test_contact_update", "signature": "def test_contact_update(self)" }, { "docstring": "If the button text matches the optout phrase then it should update the contact in Rapidpro"...
4
stack_v2_sparse_classes_30k_train_025346
Implement the Python class `HandleInboundTests` described below. Class description: Implement the HandleInboundTests class. Method signatures and docstrings: - def test_contact_update(self): If the message is not over the fallback channel then it should update the preferred channel - def test_alert_optout(self): If t...
Implement the Python class `HandleInboundTests` described below. Class description: Implement the HandleInboundTests class. Method signatures and docstrings: - def test_contact_update(self): If the message is not over the fallback channel then it should update the preferred channel - def test_alert_optout(self): If t...
e1ea0beaf079f4f4d5f9562fb9d9a4f0670f459f
<|skeleton|> class HandleInboundTests: def test_contact_update(self): """If the message is not over the fallback channel then it should update the preferred channel""" <|body_0|> def test_alert_optout(self): """If the button text matches the optout phrase then it should update the cont...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HandleInboundTests: def test_contact_update(self): """If the message is not over the fallback channel then it should update the preferred channel""" message = Mock() message.has_label.return_value = False with patch('eventstore.whatsapp_actions.update_rapidpro_preferred_channel...
the_stack_v2_python_sparse
eventstore/test_whatsapp_actions.py
praekeltfoundation/ndoh-hub
train
0
6396d4fb00467611541cf92bb9b118ade7d42b08
[ "if not self.__timestamp:\n self.__timestamp = int(os.stat(str(self.value)).st_mtime)\nreturn self.__timestamp", "if not self.__size:\n self.__size = os.stat(str(self.value)).st_size\nreturn self.__size", "if not self.__hash:\n self.__hash = compute_file_hash(str(self.value))\nreturn self.__hash", "s...
<|body_start_0|> if not self.__timestamp: self.__timestamp = int(os.stat(str(self.value)).st_mtime) return self.__timestamp <|end_body_0|> <|body_start_1|> if not self.__size: self.__size = os.stat(str(self.value)).st_size return self.__size <|end_body_1|> <|bod...
Represent a cached Artifactory's artifact.
CachedArtifact
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CachedArtifact: """Represent a cached Artifactory's artifact.""" def timestamp(self): """Gets the Artifact's timestamp based on its value :return: Artifact's timestamp :rtype: int""" <|body_0|> def size(self): """Gets the Artifact's size (in bytes) based on its v...
stack_v2_sparse_classes_75kplus_train_000051
25,285
permissive
[ { "docstring": "Gets the Artifact's timestamp based on its value :return: Artifact's timestamp :rtype: int", "name": "timestamp", "signature": "def timestamp(self)" }, { "docstring": "Gets the Artifact's size (in bytes) based on its value :return: Artifact's size :rtype: int", "name": "size"...
5
stack_v2_sparse_classes_30k_train_027960
Implement the Python class `CachedArtifact` described below. Class description: Represent a cached Artifactory's artifact. Method signatures and docstrings: - def timestamp(self): Gets the Artifact's timestamp based on its value :return: Artifact's timestamp :rtype: int - def size(self): Gets the Artifact's size (in ...
Implement the Python class `CachedArtifact` described below. Class description: Represent a cached Artifactory's artifact. Method signatures and docstrings: - def timestamp(self): Gets the Artifact's timestamp based on its value :return: Artifact's timestamp :rtype: int - def size(self): Gets the Artifact's size (in ...
7bf09f20f117fc74d02b7635305ce664b65cdcba
<|skeleton|> class CachedArtifact: """Represent a cached Artifactory's artifact.""" def timestamp(self): """Gets the Artifact's timestamp based on its value :return: Artifact's timestamp :rtype: int""" <|body_0|> def size(self): """Gets the Artifact's size (in bytes) based on its v...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CachedArtifact: """Represent a cached Artifactory's artifact.""" def timestamp(self): """Gets the Artifact's timestamp based on its value :return: Artifact's timestamp :rtype: int""" if not self.__timestamp: self.__timestamp = int(os.stat(str(self.value)).st_mtime) ret...
the_stack_v2_python_sparse
acs/acs/UtilitiesFWK/Caching.py
intel/test-framework-and-suites-for-android
train
9
11db9682368c393662b60d25065f21eb15659e9f
[ "dists = []\nn = len(nums)\nfor i in range(n):\n for j in range(i + 1, n):\n dists.append(abs(nums[j] - nums[i]))\ndists.sort()\nreturn dists[k - 1]", "def countPairs2(nums: list, mid: int) -> int:\n n = len(nums)\n res = 0\n for i in range(n):\n res += upperBound(nums, i, n - 1, nums[i]...
<|body_start_0|> dists = [] n = len(nums) for i in range(n): for j in range(i + 1, n): dists.append(abs(nums[j] - nums[i])) dists.sort() return dists[k - 1] <|end_body_0|> <|body_start_1|> def countPairs2(nums: list, mid: int) -> int: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def smallestDistancePair0(self, nums, k): """:type nums: List[int] :type k: int :rtype: int Simple solution, but not effective in terms of time cost O(n^2)""" <|body_0|> def smallestDistancePair(self, nums, k): """:type nums: List[int] :type k: int :rtype: ...
stack_v2_sparse_classes_75kplus_train_000052
21,677
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: int Simple solution, but not effective in terms of time cost O(n^2)", "name": "smallestDistancePair0", "signature": "def smallestDistancePair0(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name"...
2
stack_v2_sparse_classes_30k_train_038398
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestDistancePair0(self, nums, k): :type nums: List[int] :type k: int :rtype: int Simple solution, but not effective in terms of time cost O(n^2) - def smallestDistancePai...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestDistancePair0(self, nums, k): :type nums: List[int] :type k: int :rtype: int Simple solution, but not effective in terms of time cost O(n^2) - def smallestDistancePai...
54d3d9530b25272d4a2e5dc33e7035c44f506dc5
<|skeleton|> class Solution: def smallestDistancePair0(self, nums, k): """:type nums: List[int] :type k: int :rtype: int Simple solution, but not effective in terms of time cost O(n^2)""" <|body_0|> def smallestDistancePair(self, nums, k): """:type nums: List[int] :type k: int :rtype: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def smallestDistancePair0(self, nums, k): """:type nums: List[int] :type k: int :rtype: int Simple solution, but not effective in terms of time cost O(n^2)""" dists = [] n = len(nums) for i in range(n): for j in range(i + 1, n): dists.appen...
the_stack_v2_python_sparse
old/Session002/Arrays/FindKthSmallestPairDistance.py
MaxIakovliev/algorithms
train
0
5c8bf7b8334da03f4bbc466cfe9538442c47deb2
[ "SparkReaderWriter.__init__(self, spark_session, None)\nDataFrameReader._jreader = HiveContext(sparkContext=spark_session.sparkContext)._ssql_ctx.read()\nDataFrameReader._spark = spark_session", "db_func = CommonDBFunc()\ndriver = db_func.get_db_driver(db_name)\ngp_config = ConfigInit().read_python_properties(f'{...
<|body_start_0|> SparkReaderWriter.__init__(self, spark_session, None) DataFrameReader._jreader = HiveContext(sparkContext=spark_session.sparkContext)._ssql_ctx.read() DataFrameReader._spark = spark_session <|end_body_0|> <|body_start_1|> db_func = CommonDBFunc() driver = db_fun...
兼容原始read函数
SparkReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SparkReader: """兼容原始read函数""" def __init__(self, spark_session): """初始化 :param spark_session: SparkSession""" <|body_0|> def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): """:param db_name: :param database_env: :param datab...
stack_v2_sparse_classes_75kplus_train_000053
1,366
no_license
[ { "docstring": "初始化 :param spark_session: SparkSession", "name": "__init__", "signature": "def __init__(self, spark_session)" }, { "docstring": ":param db_name: :param database_env: :param databases: :param query_sql_or_table: :param options: :return:", "name": "relational_db", "signatur...
2
stack_v2_sparse_classes_30k_train_025155
Implement the Python class `SparkReader` described below. Class description: 兼容原始read函数 Method signatures and docstrings: - def __init__(self, spark_session): 初始化 :param spark_session: SparkSession - def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): :param db_name: :param datab...
Implement the Python class `SparkReader` described below. Class description: 兼容原始read函数 Method signatures and docstrings: - def __init__(self, spark_session): 初始化 :param spark_session: SparkSession - def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): :param db_name: :param datab...
e883217e27a44699064c30e386379dea049af30d
<|skeleton|> class SparkReader: """兼容原始read函数""" def __init__(self, spark_session): """初始化 :param spark_session: SparkSession""" <|body_0|> def relational_db(self, db_name, database_env, databases, query_sql_or_table, **options): """:param db_name: :param database_env: :param datab...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SparkReader: """兼容原始read函数""" def __init__(self, spark_session): """初始化 :param spark_session: SparkSession""" SparkReaderWriter.__init__(self, spark_session, None) DataFrameReader._jreader = HiveContext(sparkContext=spark_session.sparkContext)._ssql_ctx.read() DataFrameRea...
the_stack_v2_python_sparse
mavenimportant/python/jobs/common/spark_reader.py
liProject/importantProject
train
0
4ef2f7dc0402b25a53e840687a7fc0b06db3961e
[ "super().__init__(prefix, language_id, shortcuts)\nself.command_data = command_data\nif self.command_data is None:\n self.command_data = custom_json.load(definitions.USER_COMMAND_DATA)", "if row is None:\n return None\nreturn UserData(prefix=row[0], language_id=row[1], command_data=custom_json.load(row[2]))...
<|body_start_0|> super().__init__(prefix, language_id, shortcuts) self.command_data = command_data if self.command_data is None: self.command_data = custom_json.load(definitions.USER_COMMAND_DATA) <|end_body_0|> <|body_start_1|> if row is None: return None ...
User data and configuration.
UserData
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserData: """User data and configuration.""" def __init__(self, prefix=None, language_id=None, shortcuts=None, command_data=None): """Object initialisation.""" <|body_0|> def create_object_from_database(row): """Create UserData object from a database row.""" ...
stack_v2_sparse_classes_75kplus_train_000054
5,426
no_license
[ { "docstring": "Object initialisation.", "name": "__init__", "signature": "def __init__(self, prefix=None, language_id=None, shortcuts=None, command_data=None)" }, { "docstring": "Create UserData object from a database row.", "name": "create_object_from_database", "signature": "def creat...
2
stack_v2_sparse_classes_30k_train_037126
Implement the Python class `UserData` described below. Class description: User data and configuration. Method signatures and docstrings: - def __init__(self, prefix=None, language_id=None, shortcuts=None, command_data=None): Object initialisation. - def create_object_from_database(row): Create UserData object from a ...
Implement the Python class `UserData` described below. Class description: User data and configuration. Method signatures and docstrings: - def __init__(self, prefix=None, language_id=None, shortcuts=None, command_data=None): Object initialisation. - def create_object_from_database(row): Create UserData object from a ...
521bb272388d111c69109afe336de656b52bc9b1
<|skeleton|> class UserData: """User data and configuration.""" def __init__(self, prefix=None, language_id=None, shortcuts=None, command_data=None): """Object initialisation.""" <|body_0|> def create_object_from_database(row): """Create UserData object from a database row.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserData: """User data and configuration.""" def __init__(self, prefix=None, language_id=None, shortcuts=None, command_data=None): """Object initialisation.""" super().__init__(prefix, language_id, shortcuts) self.command_data = command_data if self.command_data is None: ...
the_stack_v2_python_sparse
datatypes/config_data.py
saileille/mami
train
0
668caf3beee50d8e05323253dd442794bc8ac9e5
[ "url = '/api/itsystems/'\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\nself.assertNotContains(response, self.it2.name)\nself.assertNotContains(response, self.it_dec.name)", "url = '/api/itsystems/?all'\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\n...
<|body_start_0|> url = '/api/itsystems/' response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertNotContains(response, self.it2.name) self.assertNotContains(response, self.it_dec.name) <|end_body_0|> <|body_start_1|> url = '/api/itsystems/?...
ITSystemResourceTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ITSystemResourceTestCase: def test_list(self): """Test the ITSystemResource list response""" <|body_0|> def test_list_all(self): """Test the ITSystemResource list response with all param""" <|body_1|> def test_list_filter(self): """Test the ITSys...
stack_v2_sparse_classes_75kplus_train_000055
2,926
permissive
[ { "docstring": "Test the ITSystemResource list response", "name": "test_list", "signature": "def test_list(self)" }, { "docstring": "Test the ITSystemResource list response with all param", "name": "test_list_all", "signature": "def test_list_all(self)" }, { "docstring": "Test th...
3
stack_v2_sparse_classes_30k_train_038042
Implement the Python class `ITSystemResourceTestCase` described below. Class description: Implement the ITSystemResourceTestCase class. Method signatures and docstrings: - def test_list(self): Test the ITSystemResource list response - def test_list_all(self): Test the ITSystemResource list response with all param - d...
Implement the Python class `ITSystemResourceTestCase` described below. Class description: Implement the ITSystemResourceTestCase class. Method signatures and docstrings: - def test_list(self): Test the ITSystemResource list response - def test_list_all(self): Test the ITSystemResource list response with all param - d...
4d5caceba69cac7f59b63745a0f52322004df2eb
<|skeleton|> class ITSystemResourceTestCase: def test_list(self): """Test the ITSystemResource list response""" <|body_0|> def test_list_all(self): """Test the ITSystemResource list response with all param""" <|body_1|> def test_list_filter(self): """Test the ITSys...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ITSystemResourceTestCase: def test_list(self): """Test the ITSystemResource list response""" url = '/api/itsystems/' response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertNotContains(response, self.it2.name) self.assertNotContain...
the_stack_v2_python_sparse
registers/test_api.py
bryceprince0/it-assets
train
0
669ba5d3ddcb833f1e01465ccec198b7daee4b80
[ "super(Reader_Downstream, self).__init__()\nself.add = P.Add()\nself.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None)\nself.para_output_layer = SupportingOutputLayer(linear_1_weight_shape=(4096, 8192), linear_1_bias_shape=(8192,), bert_layer_norm_weight_shape=(8192,), bert_...
<|body_start_0|> super(Reader_Downstream, self).__init__() self.add = P.Add() self.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None) self.para_output_layer = SupportingOutputLayer(linear_1_weight_shape=(4096, 8192), linear_1_bias_shape=(8192,), be...
Downstream model for reader
Reader_Downstream
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Reader_Downstream: """Downstream model for reader""" def __init__(self): """init function""" <|body_0|> def construct(self, para_state, sent_state, state, context_mask): """construct function""" <|body_1|> <|end_skeleton|> <|body_start_0|> super...
stack_v2_sparse_classes_75kplus_train_000056
9,011
permissive
[ { "docstring": "init function", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "construct function", "name": "construct", "signature": "def construct(self, para_state, sent_state, state, context_mask)" } ]
2
stack_v2_sparse_classes_30k_train_002953
Implement the Python class `Reader_Downstream` described below. Class description: Downstream model for reader Method signatures and docstrings: - def __init__(self): init function - def construct(self, para_state, sent_state, state, context_mask): construct function
Implement the Python class `Reader_Downstream` described below. Class description: Downstream model for reader Method signatures and docstrings: - def __init__(self): init function - def construct(self, para_state, sent_state, state, context_mask): construct function <|skeleton|> class Reader_Downstream: """Down...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class Reader_Downstream: """Downstream model for reader""" def __init__(self): """init function""" <|body_0|> def construct(self, para_state, sent_state, state, context_mask): """construct function""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Reader_Downstream: """Downstream model for reader""" def __init__(self): """init function""" super(Reader_Downstream, self).__init__() self.add = P.Add() self.para_bias = Parameter(Tensor(np.random.uniform(0, 1, (1,)).astype(np.float32)), name=None) self.para_outpu...
the_stack_v2_python_sparse
research/nlp/tprr/src/reader_downstream.py
mindspore-ai/models
train
301
d8d82bff0f95ee16ca3f4001769161a5a3ddd319
[ "nums.sort()\nn = len(nums)\nreturn nums[n - k]", "import random\npivot = random.choice(nums)\nnums1, nums2 = ([], [])\nfor num in nums:\n if num > pivot:\n nums1.append(num)\n elif num < pivot:\n nums2.append(num)\nif k <= len(nums1):\n return self.findKthLargest(nums1, k)\nif k > len(nums...
<|body_start_0|> nums.sort() n = len(nums) return nums[n - k] <|end_body_0|> <|body_start_1|> import random pivot = random.choice(nums) nums1, nums2 = ([], []) for num in nums: if num > pivot: nums1.append(num) elif num < p...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findKthLargest(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def findKthLargest_1(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> def findKthLargest_2(self, nums, k): ...
stack_v2_sparse_classes_75kplus_train_000057
1,788
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "findKthLargest", "signature": "def findKthLargest(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "findKthLargest_1", "signature": "def findKthLargest_1(self, nums, k)" ...
3
stack_v2_sparse_classes_30k_train_026080
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def findKthLargest_1(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def find...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def findKthLargest_1(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def find...
ba58ac60b32e261e43482d7e71b32587700e3719
<|skeleton|> class Solution: def findKthLargest(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def findKthLargest_1(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> def findKthLargest_2(self, nums, k): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findKthLargest(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" nums.sort() n = len(nums) return nums[n - k] def findKthLargest_1(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" import random pi...
the_stack_v2_python_sparse
python/215_kth_largest_element_in_an_array.py
lingng/Leetcode
train
0
46b2934a2fde9c27678928d5b7492f1896be1501
[ "super().__init__(name='critic')\nself.model_size = model_size\nself.ema_decay = ema_decay\nself.mlp = MLP(model_size=self.model_size, output_layer_size=None)\nself.return_layer = RewardPredictorLayer(num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound)\nself.mlp_ema = MLP(model_size=self.mode...
<|body_start_0|> super().__init__(name='critic') self.model_size = model_size self.ema_decay = ema_decay self.mlp = MLP(model_size=self.model_size, output_layer_size=None) self.return_layer = RewardPredictorLayer(num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper...
The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual critic's weights). The EMA net is NOT used for target computations (we use the a...
CriticNetwork
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CriticNetwork: """The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual critic's weights). The EMA net is NOT u...
stack_v2_sparse_classes_75kplus_train_000058
7,414
permissive
[ { "docstring": "Initializes a CriticNetwork instance. Args: model_size: The \"Model Size\" used according to [1] Appendinx B. Use None for manually setting the different network sizes. num_buckets: The number of buckets to create. Note that the number of possible symlog'd outcomes from the used distribution is ...
4
stack_v2_sparse_classes_30k_val_000187
Implement the Python class `CriticNetwork` described below. Class description: The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual ...
Implement the Python class `CriticNetwork` described below. Class description: The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual ...
edba68c3e7cf255d1d6479329f305adb7fa4c3ed
<|skeleton|> class CriticNetwork: """The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual critic's weights). The EMA net is NOT u...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CriticNetwork: """The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual critic's weights). The EMA net is NOT used for targe...
the_stack_v2_python_sparse
rllib/algorithms/dreamerv3/tf/models/critic_network.py
ray-project/ray
train
29,482
a61867184b0743840a6010b67ef973857bdbf944
[ "del params\nself.num_players = num_players\nself.hand_length = hand_length\npieces = [('player', num_players, (num_players,))]\nif iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER:\n pieces.append(('private_hand', hand_length, (hand_length,)))\nif iig_obs_type.public_info:\n pieces.append((...
<|body_start_0|> del params self.num_players = num_players self.hand_length = hand_length pieces = [('player', num_players, (num_players,))] if iig_obs_type.private_info == pyspiel.PrivateInfoType.SINGLE_PLAYER: pieces.append(('private_hand', hand_length, (hand_length...
Observer, conforming to the PyObserver interface (see observation.py). An observation will consist of the following: - One hot encoding of the current player number: [0 0 0 1 0 0 0] - A vector of length hand_length containing the digits in a player's hand. - Two matrices each of size (hand_length * num_digits * num_pla...
LiarsPokerObserver
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LiarsPokerObserver: """Observer, conforming to the PyObserver interface (see observation.py). An observation will consist of the following: - One hot encoding of the current player number: [0 0 0 1 0 0 0] - A vector of length hand_length containing the digits in a player's hand. - Two matrices ea...
stack_v2_sparse_classes_75kplus_train_000059
16,165
permissive
[ { "docstring": "Initiliazes an empty observation tensor.", "name": "__init__", "signature": "def __init__(self, iig_obs_type, num_players, hand_length, num_digits, params=None)" }, { "docstring": "Updates `tensor` and `dict` to reflect `state` from PoV of `player`.", "name": "set_from", ...
3
null
Implement the Python class `LiarsPokerObserver` described below. Class description: Observer, conforming to the PyObserver interface (see observation.py). An observation will consist of the following: - One hot encoding of the current player number: [0 0 0 1 0 0 0] - A vector of length hand_length containing the digit...
Implement the Python class `LiarsPokerObserver` described below. Class description: Observer, conforming to the PyObserver interface (see observation.py). An observation will consist of the following: - One hot encoding of the current player number: [0 0 0 1 0 0 0] - A vector of length hand_length containing the digit...
ee149736f7d85e16c119a463eee338c6d4c2ceb0
<|skeleton|> class LiarsPokerObserver: """Observer, conforming to the PyObserver interface (see observation.py). An observation will consist of the following: - One hot encoding of the current player number: [0 0 0 1 0 0 0] - A vector of length hand_length containing the digits in a player's hand. - Two matrices ea...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LiarsPokerObserver: """Observer, conforming to the PyObserver interface (see observation.py). An observation will consist of the following: - One hot encoding of the current player number: [0 0 0 1 0 0 0] - A vector of length hand_length containing the digits in a player's hand. - Two matrices each of size (h...
the_stack_v2_python_sparse
open_spiel/python/games/liars_poker.py
lanctot/open_spiel
train
1
fa2af28e286bf670d1e12dd7e26469bcd7ebe88d
[ "self.dim = dim\nself.y_pos = y_pos\nself.bars = bars\nself.speed = speed\nself.palette = palette\nself.sin = sin\nself.surface = pygame.Surface((dim[0], dim[1]), flags=pygame.SRCALPHA)\nbar_height = 10\nself.bar_surface = pygame.Surface((dim[0], bar_height), flags=pygame.SRCALPHA)\nfor index, degree in enumerate(r...
<|body_start_0|> self.dim = dim self.y_pos = y_pos self.bars = bars self.speed = speed self.palette = palette self.sin = sin self.surface = pygame.Surface((dim[0], dim[1]), flags=pygame.SRCALPHA) bar_height = 10 self.bar_surface = pygame.Surface((d...
some simple horizontal raster bar
HorizontalRasterBar
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HorizontalRasterBar: """some simple horizontal raster bar""" def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): """:param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw ...
stack_v2_sparse_classes_75kplus_train_000060
5,116
no_license
[ { "docstring": ":param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw :param speed: speed per frame, 1 euqal one pixel per frame :param palette: palette to use 256 colors :param sin: pre calculated sins for 360 degrees", "name": "__init__", "signa...
2
stack_v2_sparse_classes_30k_train_031700
Implement the Python class `HorizontalRasterBar` described below. Class description: some simple horizontal raster bar Method signatures and docstrings: - def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): :param dim: dimensio of surface to draw on :param y_po...
Implement the Python class `HorizontalRasterBar` described below. Class description: some simple horizontal raster bar Method signatures and docstrings: - def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): :param dim: dimensio of surface to draw on :param y_po...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class HorizontalRasterBar: """some simple horizontal raster bar""" def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): """:param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class HorizontalRasterBar: """some simple horizontal raster bar""" def __init__(self, dim: tuple, y_pos: int, bars: int=5, speed: int=2, palette: list=PALETTE, sin: list=SIN): """:param dim: dimensio of surface to draw on :param y_pos: central y position :param bars: how many bars to draw :param speed:...
the_stack_v2_python_sparse
effects/RasterBar.py
gunny26/pygame
train
5
900edb290b37d25e3c1623848e985c8624705a02
[ "consumer_key = settings.TWITTER_CONSUMER_KEY\nconsumer_secret = settings.TWITTER_CONSUMER_SECRET\naccess_token = settings.TWITTER_ACCESS_TOKEN\naccess_token_secret = settings.TWITTER_ACCESS_TOKEN_SECRET\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_sec...
<|body_start_0|> consumer_key = settings.TWITTER_CONSUMER_KEY consumer_secret = settings.TWITTER_CONSUMER_SECRET access_token = settings.TWITTER_ACCESS_TOKEN access_token_secret = settings.TWITTER_ACCESS_TOKEN_SECRET auth = tweepy.OAuthHandler(consumer_key, consumer_secret) ...
Command
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: def setup_tweepy(self): """Returns a Tweepy API object, using credentials defined in settings.py""" <|body_0|> def tweet(self, message_body, api_handle): """Tweets the given message using a Tweepy API handle.""" <|body_1|> def construct_message(...
stack_v2_sparse_classes_75kplus_train_000061
2,110
permissive
[ { "docstring": "Returns a Tweepy API object, using credentials defined in settings.py", "name": "setup_tweepy", "signature": "def setup_tweepy(self)" }, { "docstring": "Tweets the given message using a Tweepy API handle.", "name": "tweet", "signature": "def tweet(self, message_body, api_...
4
stack_v2_sparse_classes_30k_train_036980
Implement the Python class `Command` described below. Class description: Implement the Command class. Method signatures and docstrings: - def setup_tweepy(self): Returns a Tweepy API object, using credentials defined in settings.py - def tweet(self, message_body, api_handle): Tweets the given message using a Tweepy A...
Implement the Python class `Command` described below. Class description: Implement the Command class. Method signatures and docstrings: - def setup_tweepy(self): Returns a Tweepy API object, using credentials defined in settings.py - def tweet(self, message_body, api_handle): Tweets the given message using a Tweepy A...
b1850ecfa5e2694961a34d450430a001a1a39a5e
<|skeleton|> class Command: def setup_tweepy(self): """Returns a Tweepy API object, using credentials defined in settings.py""" <|body_0|> def tweet(self, message_body, api_handle): """Tweets the given message using a Tweepy API handle.""" <|body_1|> def construct_message(...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Command: def setup_tweepy(self): """Returns a Tweepy API object, using credentials defined in settings.py""" consumer_key = settings.TWITTER_CONSUMER_KEY consumer_secret = settings.TWITTER_CONSUMER_SECRET access_token = settings.TWITTER_ACCESS_TOKEN access_token_secret ...
the_stack_v2_python_sparse
beer_search_v2/management/commands/announce.py
Ernir/bjorleitin
train
1
9f82ea2edfaa1f97df869b28a1868171460304ae
[ "if not Permission(UserNeed(profile_id)).can():\n if not VerifyEducationPermission.can():\n return abort(HTTPStatus.FORBIDDEN, 'User is not authorized to view this profile education')\neducation = Education.query.get(profile_id)\nif education is None:\n return abort(HTTPStatus.NOT_FOUND, 'Education is ...
<|body_start_0|> if not Permission(UserNeed(profile_id)).can(): if not VerifyEducationPermission.can(): return abort(HTTPStatus.FORBIDDEN, 'User is not authorized to view this profile education') education = Education.query.get(profile_id) if education is None: ...
ProfileEducationResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProfileEducationResource: def get(self, profile_id): """Get profile education info * User can view **their education** info * User with permission to **"verify education"** can view education info""" <|body_0|> def put(self, profile_id): """Update profile education i...
stack_v2_sparse_classes_75kplus_train_000062
2,764
permissive
[ { "docstring": "Get profile education info * User can view **their education** info * User with permission to **\"verify education\"** can view education info", "name": "get", "signature": "def get(self, profile_id)" }, { "docstring": "Update profile education info * User can edit **their educat...
2
stack_v2_sparse_classes_30k_test_001649
Implement the Python class `ProfileEducationResource` described below. Class description: Implement the ProfileEducationResource class. Method signatures and docstrings: - def get(self, profile_id): Get profile education info * User can view **their education** info * User with permission to **"verify education"** ca...
Implement the Python class `ProfileEducationResource` described below. Class description: Implement the ProfileEducationResource class. Method signatures and docstrings: - def get(self, profile_id): Get profile education info * User can view **their education** info * User with permission to **"verify education"** ca...
dce87ffe395ae4bd08b47f28e07594e1889da819
<|skeleton|> class ProfileEducationResource: def get(self, profile_id): """Get profile education info * User can view **their education** info * User with permission to **"verify education"** can view education info""" <|body_0|> def put(self, profile_id): """Update profile education i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ProfileEducationResource: def get(self, profile_id): """Get profile education info * User can view **their education** info * User with permission to **"verify education"** can view education info""" if not Permission(UserNeed(profile_id)).can(): if not VerifyEducationPermission.ca...
the_stack_v2_python_sparse
src/backend/app/api/public/profiles/profile/education/education.py
aimanow/sft
train
0
de652ebf388e3ced877abf6411340b5fab44e4fe
[ "shift_x = constants.all_shifts[direction_index]['x']\nshift_y = constants.all_shifts[direction_index]['y']\nreturn (shift_x, shift_y)", "shift_x, shift_y = Utilities.get_shift_by_direction(direction_index)\nnew_x, new_y = (shift_x + x, shift_y + y)\nreturn (new_x, new_y)" ]
<|body_start_0|> shift_x = constants.all_shifts[direction_index]['x'] shift_y = constants.all_shifts[direction_index]['y'] return (shift_x, shift_y) <|end_body_0|> <|body_start_1|> shift_x, shift_y = Utilities.get_shift_by_direction(direction_index) new_x, new_y = (shift_x + x, ...
Utilities
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Utilities: def get_shift_by_direction(direction_index): """Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows""" <|body_0|> def get_new_coordinates(direction_index, x, y): ...
stack_v2_sparse_classes_75kplus_train_000063
1,224
permissive
[ { "docstring": "Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows", "name": "get_shift_by_direction", "signature": "def get_shift_by_direction(direction_index)" }, { "docstring": "Function returns ne...
2
stack_v2_sparse_classes_30k_train_047821
Implement the Python class `Utilities` described below. Class description: Implement the Utilities class. Method signatures and docstrings: - def get_shift_by_direction(direction_index): Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by c...
Implement the Python class `Utilities` described below. Class description: Implement the Utilities class. Method signatures and docstrings: - def get_shift_by_direction(direction_index): Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by c...
291592e97b6d8fe9f9e6627dc0023875918d3463
<|skeleton|> class Utilities: def get_shift_by_direction(direction_index): """Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows""" <|body_0|> def get_new_coordinates(direction_index, x, y): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Utilities: def get_shift_by_direction(direction_index): """Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows""" shift_x = constants.all_shifts[direction_index]['x'] shift_y = constants.all_...
the_stack_v2_python_sparse
Dmytro_Skorobohatskyi/batch_10/dungeon_game_stereotype_pkg/build/lib/dungeon_game_stereotype_pkg/utilities.py
SmischenkoB/campus_2018_python
train
0
246312b70c575409e7e1cc458bda5ce450bb26a2
[ "self.first_idx = {}\nself.last_idx = {}\nself.key_map = {}\nself.arr = []", "if key not in self.key_map:\n self.arr.append([1, key])\n if 1 not in self.last_idx:\n self.first_idx[1] = len(self.arr) - 1\n self.last_idx[1] = len(self.arr) - 1\n self.key_map[key] = len(self.arr) - 1\nelse:\n j...
<|body_start_0|> self.first_idx = {} self.last_idx = {} self.key_map = {} self.arr = [] <|end_body_0|> <|body_start_1|> if key not in self.key_map: self.arr.append([1, key]) if 1 not in self.last_idx: self.first_idx[1] = len(self.arr) - 1 ...
AllOne
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void""" <|body_1|> def dec(self, key): """De...
stack_v2_sparse_classes_75kplus_train_000064
3,586
no_license
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void", "name": "inc", "signature": "def inc(self, key)" }, ...
5
stack_v2_sparse_classes_30k_train_032720
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void -...
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void -...
2722c0deafcd094ce64140a9a837b4027d29ed6f
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void""" <|body_1|> def dec(self, key): """De...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AllOne: def __init__(self): """Initialize your data structure here.""" self.first_idx = {} self.last_idx = {} self.key_map = {} self.arr = [] def inc(self, key): """Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rt...
the_stack_v2_python_sparse
432_all_one_ds_h/main.py
chao-shi/lclc
train
0
d7eaa930fa37968931d1c5a2eb838918ff9f7236
[ "epsilon = 0.25\nalpha = 2\nlamb = 2\n\ndef T(x):\n return func(xk) + epsilon * x * grad(xk).T @ dk\nwhile func(xk + lamb * dk) > T(lamb) or func(xk + alpha * lamb * dk) < T(alpha * lamb):\n if func(xk + lamb * dk) > T(lamb):\n lamb /= alpha\n else:\n lamb *= alpha\nreturn lamb", "a = 0\nb0...
<|body_start_0|> epsilon = 0.25 alpha = 2 lamb = 2 def T(x): return func(xk) + epsilon * x * grad(xk).T @ dk while func(xk + lamb * dk) > T(lamb) or func(xk + alpha * lamb * dk) < T(alpha * lamb): if func(xk + lamb * dk) > T(lamb): lamb /=...
Linesearch
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Linesearch: def inexactLinesearch(xk, dk, func, grad): """Armijo's rule""" <|body_0|> def exactLinesearch(xk, dk, func, grad): """The bisection method""" <|body_1|> <|end_skeleton|> <|body_start_0|> epsilon = 0.25 alpha = 2 lamb = 2 ...
stack_v2_sparse_classes_75kplus_train_000065
1,444
no_license
[ { "docstring": "Armijo's rule", "name": "inexactLinesearch", "signature": "def inexactLinesearch(xk, dk, func, grad)" }, { "docstring": "The bisection method", "name": "exactLinesearch", "signature": "def exactLinesearch(xk, dk, func, grad)" } ]
2
null
Implement the Python class `Linesearch` described below. Class description: Implement the Linesearch class. Method signatures and docstrings: - def inexactLinesearch(xk, dk, func, grad): Armijo's rule - def exactLinesearch(xk, dk, func, grad): The bisection method
Implement the Python class `Linesearch` described below. Class description: Implement the Linesearch class. Method signatures and docstrings: - def inexactLinesearch(xk, dk, func, grad): Armijo's rule - def exactLinesearch(xk, dk, func, grad): The bisection method <|skeleton|> class Linesearch: def inexactLines...
dc5dc96348248ce480ad3bdb6299dc4b28fb867c
<|skeleton|> class Linesearch: def inexactLinesearch(xk, dk, func, grad): """Armijo's rule""" <|body_0|> def exactLinesearch(xk, dk, func, grad): """The bisection method""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Linesearch: def inexactLinesearch(xk, dk, func, grad): """Armijo's rule""" epsilon = 0.25 alpha = 2 lamb = 2 def T(x): return func(xk) + epsilon * x * grad(xk).T @ dk while func(xk + lamb * dk) > T(lamb) or func(xk + alpha * lamb * dk) < T(alpha * l...
the_stack_v2_python_sparse
Newton/Linesearch.py
AugustBergoo/NumAlgPython
train
0
fe3d5f98df4a311f16bf7df30be598b0b17bbdfd
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
* Allow to communicate with the vehicle's system shell.
ShellServiceServicer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShellServiceServicer: """* Allow to communicate with the vehicle's system shell.""" def Send(self, request, context): """Send a command line.""" <|body_0|> def SubscribeReceive(self, request, context): """Receive feedback from a sent command line. This subscripti...
stack_v2_sparse_classes_75kplus_train_000066
2,389
permissive
[ { "docstring": "Send a command line.", "name": "Send", "signature": "def Send(self, request, context)" }, { "docstring": "Receive feedback from a sent command line. This subscription needs to be made before a command line is sent, otherwise, no response will be sent.", "name": "SubscribeRece...
2
stack_v2_sparse_classes_30k_train_041623
Implement the Python class `ShellServiceServicer` described below. Class description: * Allow to communicate with the vehicle's system shell. Method signatures and docstrings: - def Send(self, request, context): Send a command line. - def SubscribeReceive(self, request, context): Receive feedback from a sent command ...
Implement the Python class `ShellServiceServicer` described below. Class description: * Allow to communicate with the vehicle's system shell. Method signatures and docstrings: - def Send(self, request, context): Send a command line. - def SubscribeReceive(self, request, context): Receive feedback from a sent command ...
a328834518621842f530804572ecb3baeec31805
<|skeleton|> class ShellServiceServicer: """* Allow to communicate with the vehicle's system shell.""" def Send(self, request, context): """Send a command line.""" <|body_0|> def SubscribeReceive(self, request, context): """Receive feedback from a sent command line. This subscripti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ShellServiceServicer: """* Allow to communicate with the vehicle's system shell.""" def Send(self, request, context): """Send a command line.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method...
the_stack_v2_python_sparse
mavsdk/shell_pb2_grpc.py
PML-UCF/MAVSDK-Python
train
0
701f142fc3f245ea291ebd663f9e903bee70eaa5
[ "if user.id:\n try:\n provider_auth = pyramid_basemodel.Session.query(AuthenticationProvider).filter(AuthenticationProvider.user_id == user.id, AuthenticationProvider.provider == provider_name).one()\n if provider_auth.provider_id != user_provider_id:\n return False\n return True\...
<|body_start_0|> if user.id: try: provider_auth = pyramid_basemodel.Session.query(AuthenticationProvider).filter(AuthenticationProvider.user_id == user.id, AuthenticationProvider.provider == provider_name).one() if provider_auth.provider_id != user_provider_id: ...
Social login views definition.
SocialLoginViews
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SocialLoginViews: """Social login views definition.""" def set_provider(self, user, provider_name, user_provider_id): """Set authentication provider on user. This method will connect given provider with given user, unless provider_id has already been used on another user. :param pyra...
stack_v2_sparse_classes_75kplus_train_000067
8,669
permissive
[ { "docstring": "Set authentication provider on user. This method will connect given provider with given user, unless provider_id has already been used on another user. :param pyramid_fullauth.user.User user: user object :param str provider_name: provider name :param str user_provider_id: user id delivered by gi...
5
null
Implement the Python class `SocialLoginViews` described below. Class description: Social login views definition. Method signatures and docstrings: - def set_provider(self, user, provider_name, user_provider_id): Set authentication provider on user. This method will connect given provider with given user, unless provi...
Implement the Python class `SocialLoginViews` described below. Class description: Social login views definition. Method signatures and docstrings: - def set_provider(self, user, provider_name, user_provider_id): Set authentication provider on user. This method will connect given provider with given user, unless provi...
0088fceeeb100497afc88a291ccc9b1ee9bfaa49
<|skeleton|> class SocialLoginViews: """Social login views definition.""" def set_provider(self, user, provider_name, user_provider_id): """Set authentication provider on user. This method will connect given provider with given user, unless provider_id has already been used on another user. :param pyra...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SocialLoginViews: """Social login views definition.""" def set_provider(self, user, provider_name, user_provider_id): """Set authentication provider on user. This method will connect given provider with given user, unless provider_id has already been used on another user. :param pyramid_fullauth....
the_stack_v2_python_sparse
pyramid_fullauth/views/social.py
fizyk/pyramid_fullauth
train
22
e0a26975717a4560f4f184dfd94261cb0577016c
[ "if len(names) == 0:\n self.leader = None\nelse:\n self.leader = Person(names[0])\n current_person = self.leader\n for name in names[1:]:\n current_person.next = Person(name)\n current_person = current_person.next", "if not self.leader:\n raise ShortChainError\nelse:\n return self....
<|body_start_0|> if len(names) == 0: self.leader = None else: self.leader = Person(names[0]) current_person = self.leader for name in names[1:]: current_person.next = Person(name) current_person = current_person.next <|end_b...
A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty.
PeopleChain
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PeopleChain: """A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty.""" def __init__(self, names: List[str]) -> None: """Create people linked together in the order provided in <names>. The leader of the chain is the...
stack_v2_sparse_classes_75kplus_train_000068
4,481
no_license
[ { "docstring": "Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>.", "name": "__init__", "signature": "def __init__(self, names: List[str]) -> None" }, { "docstring": "Return the name of the leader of the chain. Raise ShortChai...
5
stack_v2_sparse_classes_30k_train_044807
Implement the Python class `PeopleChain` described below. Class description: A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty. Method signatures and docstrings: - def __init__(self, names: List[str]) -> None: Create people linked together in the ...
Implement the Python class `PeopleChain` described below. Class description: A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty. Method signatures and docstrings: - def __init__(self, names: List[str]) -> None: Create people linked together in the ...
b876b816ae2610ef18812371cd3ba7e92392b4f0
<|skeleton|> class PeopleChain: """A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty.""" def __init__(self, names: List[str]) -> None: """Create people linked together in the order provided in <names>. The leader of the chain is the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PeopleChain: """A chain of people. === Attributes === leader: Person | None The first person in the chain, or None if the chain is empty.""" def __init__(self, names: List[str]) -> None: """Create people linked together in the order provided in <names>. The leader of the chain is the first person...
the_stack_v2_python_sparse
mini-exercises/mini exercise 2/chain.py
ColeRichardson/CSC148
train
0
9f6612c20775ec9469ae89dd92f50276327e5a22
[ "super(PCC_Layer, self).__init__()\nself.alpha = alpha\nself.centroid = centroid", "z = emb.unsqueeze(1)\nu = self.centroid\nqij = (1.0 + torch.sum((z - u) ** 2, dim=2) / self.alpha) ** (-1)\nqij_normalize = qij.T / torch.sum(qij, dim=1)\nqij_normalize = qij_normalize.T\nreturn qij_normalize" ]
<|body_start_0|> super(PCC_Layer, self).__init__() self.alpha = alpha self.centroid = centroid <|end_body_0|> <|body_start_1|> z = emb.unsqueeze(1) u = self.centroid qij = (1.0 + torch.sum((z - u) ** 2, dim=2) / self.alpha) ** (-1) qij_normalize = qij.T / torch.s...
PCC_Layer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PCC_Layer: def __init__(self, centroid, alpha=1.0): """:param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)""" <|body_0|> def forward(self, emb): """see paper `Unsupervised Deep Embedding for Clustering Analysis` qij = 1/(1+dist(zi, uj)^2), then no...
stack_v2_sparse_classes_75kplus_train_000069
2,727
no_license
[ { "docstring": ":param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)", "name": "__init__", "signature": "def __init__(self, centroid, alpha=1.0)" }, { "docstring": "see paper `Unsupervised Deep Embedding for Clustering Analysis` qij = 1/(1+dist(zi, uj)^2), then normalize it. q...
2
stack_v2_sparse_classes_30k_train_053223
Implement the Python class `PCC_Layer` described below. Class description: Implement the PCC_Layer class. Method signatures and docstrings: - def __init__(self, centroid, alpha=1.0): :param centroid: tensor, predefined centroid, shape: (n_class, emb_dim) - def forward(self, emb): see paper `Unsupervised Deep Embeddin...
Implement the Python class `PCC_Layer` described below. Class description: Implement the PCC_Layer class. Method signatures and docstrings: - def __init__(self, centroid, alpha=1.0): :param centroid: tensor, predefined centroid, shape: (n_class, emb_dim) - def forward(self, emb): see paper `Unsupervised Deep Embeddin...
4e5908eb4c230e80e7d49bdbd77e7ec73de327c6
<|skeleton|> class PCC_Layer: def __init__(self, centroid, alpha=1.0): """:param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)""" <|body_0|> def forward(self, emb): """see paper `Unsupervised Deep Embedding for Clustering Analysis` qij = 1/(1+dist(zi, uj)^2), then no...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PCC_Layer: def __init__(self, centroid, alpha=1.0): """:param centroid: tensor, predefined centroid, shape: (n_class, emb_dim)""" super(PCC_Layer, self).__init__() self.alpha = alpha self.centroid = centroid def forward(self, emb): """see paper `Unsupervised Deep E...
the_stack_v2_python_sparse
network_torch/Dual_CSA.py
lusccc/Trajectory-Classification-using-Dual-CSA
train
10
d747529797c266d0199220879c7cdd9392d532d6
[ "super().__init__(embed_dim, num_heads, dropout=dropout, bias=True, add_bias_kv=False, add_zero_attn=add_zero_attn, kdim=None, vdim=None)\nself.id_out_weight = torch.eye(self.head_dim)\nself.id_out_bias = torch.zeros(self.head_dim)", "query = query.transpose(1, 0)\nkey = key.transpose(1, 0)\nvalue = value.transpo...
<|body_start_0|> super().__init__(embed_dim, num_heads, dropout=dropout, bias=True, add_bias_kv=False, add_zero_attn=add_zero_attn, kdim=None, vdim=None) self.id_out_weight = torch.eye(self.head_dim) self.id_out_bias = torch.zeros(self.head_dim) <|end_body_0|> <|body_start_1|> query = q...
MultiheadAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiheadAttention: def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): """Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim.""" ...
stack_v2_sparse_classes_75kplus_train_000070
20,414
no_license
[ { "docstring": "Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim.", "name": "__init__", "signature": "def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=Fa...
2
stack_v2_sparse_classes_30k_train_028088
Implement the Python class `MultiheadAttention` described below. Class description: Implement the MultiheadAttention class. Method signatures and docstrings: - def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): Same as `torch.nn.MultiheadAttention`, but with option to return attention weights...
Implement the Python class `MultiheadAttention` described below. Class description: Implement the MultiheadAttention class. Method signatures and docstrings: - def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): Same as `torch.nn.MultiheadAttention`, but with option to return attention weights...
793543ebd3e526bdd8931a269fdf17808762d9bc
<|skeleton|> class MultiheadAttention: def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): """Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiheadAttention: def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): """Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim.""" super().__...
the_stack_v2_python_sparse
seqmodel/model/transformer.py
devinkwok/seqmodelv2
train
0
bb199b1e282a9949748c56fcefd6739e6d05e6de
[ "self.feature_of_interest_id = BNode()\nself.label = Literal(label)\nself.comment = Literal(comment)", "return self.feature_of_interest_id\nobsgraph.add((self.feature_of_interest_id, RDF.type, sosa.FeatureOfInterest))\nobsgraph.add((self.feature_of_interest_id, RDFS.comment, self.comment))\nobsgraph.add((self.fea...
<|body_start_0|> self.feature_of_interest_id = BNode() self.label = Literal(label) self.comment = Literal(comment) <|end_body_0|> <|body_start_1|> return self.feature_of_interest_id obsgraph.add((self.feature_of_interest_id, RDF.type, sosa.FeatureOfInterest)) obsgraph.ad...
Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an act of Sampling.
FeatureOfInterest
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureOfInterest: """Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an a...
stack_v2_sparse_classes_75kplus_train_000071
1,302
permissive
[ { "docstring": "constructor for Feature of Interest Args: label, comment (literal): label and comment for the feature of interest Returns: FOI object: instantiated with feature_of_interest_id, label and comment", "name": "__init__", "signature": "def __init__(self, label, comment)" }, { "docstri...
2
stack_v2_sparse_classes_30k_train_004893
Implement the Python class `FeatureOfInterest` described below. Class description: Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which ...
Implement the Python class `FeatureOfInterest` described below. Class description: Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which ...
1993668bd75bc882286da818955a40dd01d2f7c6
<|skeleton|> class FeatureOfInterest: """Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FeatureOfInterest: """Creates a feature of interest object representing SOSA FOI The thing whose property is being estimated or calculated in the course of an Observation to arrive at a Result, or whose property is being manipulated by an Actuator, or which is being sampled or transformed in an act of Samplin...
the_stack_v2_python_sparse
PySOSA/FeatureOfInterest.py
landrs-toolkit/PySOSA
train
1
7bb0d73167a60aa90d9d8ddaae89802b3571ad85
[ "TestCommand.finalize_options(self)\nself.test_args = []\nself.test_suite = True", "import tox\nerrcode = tox.cmdline(self.test_args)\nsys.exit(errcode)" ]
<|body_start_0|> TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True <|end_body_0|> <|body_start_1|> import tox errcode = tox.cmdline(self.test_args) sys.exit(errcode) <|end_body_1|>
Runs Tox comands
Tox
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tox: """Runs Tox comands""" def finalize_options(self): """preps test suite""" <|body_0|> def run_tests(self): """runs test suite""" <|body_1|> <|end_skeleton|> <|body_start_0|> TestCommand.finalize_options(self) self.test_args = [] ...
stack_v2_sparse_classes_75kplus_train_000072
752
permissive
[ { "docstring": "preps test suite", "name": "finalize_options", "signature": "def finalize_options(self)" }, { "docstring": "runs test suite", "name": "run_tests", "signature": "def run_tests(self)" } ]
2
stack_v2_sparse_classes_30k_train_024056
Implement the Python class `Tox` described below. Class description: Runs Tox comands Method signatures and docstrings: - def finalize_options(self): preps test suite - def run_tests(self): runs test suite
Implement the Python class `Tox` described below. Class description: Runs Tox comands Method signatures and docstrings: - def finalize_options(self): preps test suite - def run_tests(self): runs test suite <|skeleton|> class Tox: """Runs Tox comands""" def finalize_options(self): """preps test suite...
3abf8b93c6d1c162cba3e7cb2a1777dadbaffebe
<|skeleton|> class Tox: """Runs Tox comands""" def finalize_options(self): """preps test suite""" <|body_0|> def run_tests(self): """runs test suite""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Tox: """Runs Tox comands""" def finalize_options(self): """preps test suite""" TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): """runs test suite""" import tox errcode = tox.cmdline(self.test_a...
the_stack_v2_python_sparse
setup.py
pcaruana/armada
train
0
13a2825e1dba546a69beb6a2cda328345ef71920
[ "n = len(nums)\nif n * k == 0:\n return []\nreturn [max(nums[i:i + k]) for i in range(n - k + 1)]", "size = len(nums)\nif size * k == 0:\n return []\nif size == 1:\n return nums\nqueue, output, max_idx = (deque(), [], 0)\n\ndef clean_up(index: int):\n if queue and queue[0] == index - k:\n queue...
<|body_start_0|> n = len(nums) if n * k == 0: return [] return [max(nums[i:i + k]) for i in range(n - k + 1)] <|end_body_0|> <|body_start_1|> size = len(nums) if size * k == 0: return [] if size == 1: return nums queue, output,...
SlidingWindow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SlidingWindow: def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: """Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:""" <|body_0|> def get_max_in_window_(self, nums: List[int], k: int) -> List[int]: ...
stack_v2_sparse_classes_75kplus_train_000073
2,981
no_license
[ { "docstring": "Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:", "name": "get_max_in_window__", "signature": "def get_max_in_window__(self, nums: List[int], k: int) -> List[int]" }, { "docstring": "Approach: Using Deque Time Complexity: O(N) Spa...
3
stack_v2_sparse_classes_30k_train_037481
Implement the Python class `SlidingWindow` described below. Class description: Implement the SlidingWindow class. Method signatures and docstrings: - def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return: -...
Implement the Python class `SlidingWindow` described below. Class description: Implement the SlidingWindow class. Method signatures and docstrings: - def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return: -...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class SlidingWindow: def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: """Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:""" <|body_0|> def get_max_in_window_(self, nums: List[int], k: int) -> List[int]: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SlidingWindow: def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: """Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:""" n = len(nums) if n * k == 0: return [] return [max(nums[i:i + k]) for i in ran...
the_stack_v2_python_sparse
revisited/arrays/sliding_window.py
Shiv2157k/leet_code
train
1
3077b4a38ab4845fb78851c919da24877c0f68af
[ "super().__init__(*args, **kwargs)\nself.token = config.get('api-token', None)\nself.chatid = config.get('chat-id', None)\nif self.token is not None and self.chatid is not None:\n self.useable = True\nelse:\n self.useable = False", "if self.useable:\n message = self.format(record)\n thread = threading...
<|body_start_0|> super().__init__(*args, **kwargs) self.token = config.get('api-token', None) self.chatid = config.get('chat-id', None) if self.token is not None and self.chatid is not None: self.useable = True else: self.useable = False <|end_body_0|> <|...
A logging.StreamHandler which handles log dispatching to a Telegram-Bot.
TelegramHandler
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TelegramHandler: """A logging.StreamHandler which handles log dispatching to a Telegram-Bot.""" def __init__(self, *args, **kwargs): """Construct a logging.StreamHandler which sends messages to a bot. This StreamHandler relies on the contents of api-token and chat-id in src/utils/tel...
stack_v2_sparse_classes_75kplus_train_000074
3,270
permissive
[ { "docstring": "Construct a logging.StreamHandler which sends messages to a bot. This StreamHandler relies on the contents of api-token and chat-id in src/utils/telegram.py. They get generated by either environment variables or a telegram.json file in src/utils. For more details look at the source code! The com...
2
null
Implement the Python class `TelegramHandler` described below. Class description: A logging.StreamHandler which handles log dispatching to a Telegram-Bot. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Construct a logging.StreamHandler which sends messages to a bot. This StreamHandler relies ...
Implement the Python class `TelegramHandler` described below. Class description: A logging.StreamHandler which handles log dispatching to a Telegram-Bot. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Construct a logging.StreamHandler which sends messages to a bot. This StreamHandler relies ...
7f0086d2cdec23b49958c5afc0e6d12a08598465
<|skeleton|> class TelegramHandler: """A logging.StreamHandler which handles log dispatching to a Telegram-Bot.""" def __init__(self, *args, **kwargs): """Construct a logging.StreamHandler which sends messages to a bot. This StreamHandler relies on the contents of api-token and chat-id in src/utils/tel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TelegramHandler: """A logging.StreamHandler which handles log dispatching to a Telegram-Bot.""" def __init__(self, *args, **kwargs): """Construct a logging.StreamHandler which sends messages to a bot. This StreamHandler relies on the contents of api-token and chat-id in src/utils/telegram.py. The...
the_stack_v2_python_sparse
src/utils/telegram.py
image357/conex-generator
train
0
122b0681a25c45b66b89c7f99c1b562d6e44ffbd
[ "if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=MyUserManager.normalize_email(email), date_of_birth=date_of_birth or timezone.now(), first_name=first_name or '', last_name=last_name or '')\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "if ...
<|body_start_0|> if not email: raise ValueError('Users must have an email address') user = self.model(email=MyUserManager.normalize_email(email), date_of_birth=date_of_birth or timezone.now(), first_name=first_name or '', last_name=last_name or '') user.set_password(password) ...
MyUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyUserManager: def create_user(self, email, first_name=None, last_name=None, date_of_birth=None, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, email, date_of_birth, first_name, last_name...
stack_v2_sparse_classes_75kplus_train_000075
1,411
no_license
[ { "docstring": "Creates and saves a User with the given email, date of birth and password.", "name": "create_user", "signature": "def create_user(self, email, first_name=None, last_name=None, date_of_birth=None, password=None)" }, { "docstring": "Creates and saves a superuser with the given emai...
2
stack_v2_sparse_classes_30k_train_051026
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, email, first_name=None, last_name=None, date_of_birth=None, password=None): Creates and saves a User with the given email, date of birth and passw...
Implement the Python class `MyUserManager` described below. Class description: Implement the MyUserManager class. Method signatures and docstrings: - def create_user(self, email, first_name=None, last_name=None, date_of_birth=None, password=None): Creates and saves a User with the given email, date of birth and passw...
42654f6c058de095ac6ff540bdd89854b7f864f9
<|skeleton|> class MyUserManager: def create_user(self, email, first_name=None, last_name=None, date_of_birth=None, password=None): """Creates and saves a User with the given email, date of birth and password.""" <|body_0|> def create_superuser(self, email, date_of_birth, first_name, last_name...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MyUserManager: def create_user(self, email, first_name=None, last_name=None, date_of_birth=None, password=None): """Creates and saves a User with the given email, date of birth and password.""" if not email: raise ValueError('Users must have an email address') user = self.m...
the_stack_v2_python_sparse
thesis/DavideCrestini/tesi-crestini/Piattaforma/services/managers.py
lbedogni/iot
train
0
c25f12f104c9433903baa15292696b05b0171894
[ "super(CustomEdit, self).__init__(None, parent)\nself.w = size[2]\nself.h = size[3]\nself.setGeometry(*size)\nself.setObjectName(name)\nself.drag_flag = False\nif drag:\n self.setAcceptDrops(True)\n self.setDragEnabled(True)\nelse:\n self.setAcceptDrops(False)\n self.setDragEnabled(False)\nself.click_fl...
<|body_start_0|> super(CustomEdit, self).__init__(None, parent) self.w = size[2] self.h = size[3] self.setGeometry(*size) self.setObjectName(name) self.drag_flag = False if drag: self.setAcceptDrops(True) self.setDragEnabled(True) e...
带下拉框的文本输入框类(文本下拉输入框),输入文字可以搜索内容
CustomEdit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomEdit: """带下拉框的文本输入框类(文本下拉输入框),输入文字可以搜索内容""" def __init__(self, parent, size=(50, 50, 100, 20), name='edit', drag=False, text_list=True, search=True, qss_file=''): """初始化控件 :param parent: 控件显示的父对象 :param size: 输入框控件尺寸 :param name: 输入框控件名称 :param drag: 拖放标识位 :param text_list: 是否开...
stack_v2_sparse_classes_75kplus_train_000076
5,622
no_license
[ { "docstring": "初始化控件 :param parent: 控件显示的父对象 :param size: 输入框控件尺寸 :param name: 输入框控件名称 :param drag: 拖放标识位 :param text_list: 是否开启下拉框功能标识位", "name": "__init__", "signature": "def __init__(self, parent, size=(50, 50, 100, 20), name='edit', drag=False, text_list=True, search=True, qss_file='')" }, { ...
4
stack_v2_sparse_classes_30k_train_033255
Implement the Python class `CustomEdit` described below. Class description: 带下拉框的文本输入框类(文本下拉输入框),输入文字可以搜索内容 Method signatures and docstrings: - def __init__(self, parent, size=(50, 50, 100, 20), name='edit', drag=False, text_list=True, search=True, qss_file=''): 初始化控件 :param parent: 控件显示的父对象 :param size: 输入框控件尺寸 :par...
Implement the Python class `CustomEdit` described below. Class description: 带下拉框的文本输入框类(文本下拉输入框),输入文字可以搜索内容 Method signatures and docstrings: - def __init__(self, parent, size=(50, 50, 100, 20), name='edit', drag=False, text_list=True, search=True, qss_file=''): 初始化控件 :param parent: 控件显示的父对象 :param size: 输入框控件尺寸 :par...
925612139b6ac62dfb0c1a5d143485f1fd36645a
<|skeleton|> class CustomEdit: """带下拉框的文本输入框类(文本下拉输入框),输入文字可以搜索内容""" def __init__(self, parent, size=(50, 50, 100, 20), name='edit', drag=False, text_list=True, search=True, qss_file=''): """初始化控件 :param parent: 控件显示的父对象 :param size: 输入框控件尺寸 :param name: 输入框控件名称 :param drag: 拖放标识位 :param text_list: 是否开...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomEdit: """带下拉框的文本输入框类(文本下拉输入框),输入文字可以搜索内容""" def __init__(self, parent, size=(50, 50, 100, 20), name='edit', drag=False, text_list=True, search=True, qss_file=''): """初始化控件 :param parent: 控件显示的父对象 :param size: 输入框控件尺寸 :param name: 输入框控件名称 :param drag: 拖放标识位 :param text_list: 是否开启下拉框功能标识位""" ...
the_stack_v2_python_sparse
Custom_Edit.py
harry2002731/Stock-programe
train
2
4db32db61e02696d8c3ccb2bd54c42a3e6579a0d
[ "self.__dict__.update(dict_data)\nself.comparable_service = comparable_name(self.service)\nself.formatted_date = formatted_github_day_and_time(self.date)", "config_dict = service.config.copy()\nconfig_dict['service'] = service.name\nconfig_dict['site'] = service.site_name\nif service.config.get('sha', False):\n ...
<|body_start_0|> self.__dict__.update(dict_data) self.comparable_service = comparable_name(self.service) self.formatted_date = formatted_github_day_and_time(self.date) <|end_body_0|> <|body_start_1|> config_dict = service.config.copy() config_dict['service'] = service.name ...
ServiceConfig
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServiceConfig: def __init__(self, **dict_data): """The dict_data contains all the service config's attributes: Ex. { "service": "billweb", "author": "chrisg@surveymonkey.com", "site": "mt1", "sha": "3a2df77fbcf804165c8e79e3d22d05fa3798e405", "date": "2012-03-06T15:17:44-08:00", "message"...
stack_v2_sparse_classes_75kplus_train_000077
1,283
permissive
[ { "docstring": "The dict_data contains all the service config's attributes: Ex. { \"service\": \"billweb\", \"author\": \"chrisg@surveymonkey.com\", \"site\": \"mt1\", \"sha\": \"3a2df77fbcf804165c8e79e3d22d05fa3798e405\", \"date\": \"2012-03-06T15:17:44-08:00\", \"message\": \"Add ho-DOR\" }", "name": "__i...
2
null
Implement the Python class `ServiceConfig` described below. Class description: Implement the ServiceConfig class. Method signatures and docstrings: - def __init__(self, **dict_data): The dict_data contains all the service config's attributes: Ex. { "service": "billweb", "author": "chrisg@surveymonkey.com", "site": "m...
Implement the Python class `ServiceConfig` described below. Class description: Implement the ServiceConfig class. Method signatures and docstrings: - def __init__(self, **dict_data): The dict_data contains all the service config's attributes: Ex. { "service": "billweb", "author": "chrisg@surveymonkey.com", "site": "m...
239a8c522c9d3488920581f802f7a1ef1f5f6355
<|skeleton|> class ServiceConfig: def __init__(self, **dict_data): """The dict_data contains all the service config's attributes: Ex. { "service": "billweb", "author": "chrisg@surveymonkey.com", "site": "mt1", "sha": "3a2df77fbcf804165c8e79e3d22d05fa3798e405", "date": "2012-03-06T15:17:44-08:00", "message"...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServiceConfig: def __init__(self, **dict_data): """The dict_data contains all the service config's attributes: Ex. { "service": "billweb", "author": "chrisg@surveymonkey.com", "site": "mt1", "sha": "3a2df77fbcf804165c8e79e3d22d05fa3798e405", "date": "2012-03-06T15:17:44-08:00", "message": "Add ho-DOR"...
the_stack_v2_python_sparse
doula/models/service_config.py
msabramo/Doula
train
0
3b953875149dd9710aca7dac868373a618172a95
[ "xx = np.vstack([x for i in range(N)]).T\nyy = np.vstack([y + np.random.normal(loc=0, scale=yerr) for i in range(N)]).T\nself._splines = [spline(x, yy[:, i], *args, **kwargs) for i in range(N)]", "x = np.atleast_1d(x)\ns = np.vstack([curve(x, *args, **kwargs) for curve in self._splines])\nreturn (np.mean(s, axis=...
<|body_start_0|> xx = np.vstack([x for i in range(N)]).T yy = np.vstack([y + np.random.normal(loc=0, scale=yerr) for i in range(N)]).T self._splines = [spline(x, yy[:, i], *args, **kwargs) for i in range(N)] <|end_body_0|> <|body_start_1|> x = np.atleast_1d(x) s = np.vstack([cur...
Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slower than a normal spline!
ErrorPropagationSpline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ErrorPropagationSpline: """Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slowe...
stack_v2_sparse_classes_75kplus_train_000078
47,749
permissive
[ { "docstring": "See docstring for InterpolatedUnivariateSpline The parameter `N` gives the number of splines to generate for error propagation.", "name": "__init__", "signature": "def __init__(self, x, y, yerr, N=1000, *args, **kwargs)" }, { "docstring": "Get the spline value and uncertainty at ...
2
stack_v2_sparse_classes_30k_train_031960
Implement the Python class `ErrorPropagationSpline` described below. Class description: Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates...
Implement the Python class `ErrorPropagationSpline` described below. Class description: Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates...
8a9f00a6977dad8d4477eef1d664fd62e9ecab75
<|skeleton|> class ErrorPropagationSpline: """Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slowe...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ErrorPropagationSpline: """Does a spline fit, but returns both the spline value and associated uncertainty. This accomplishes the task by generating lots of splines, and return the mean and standard deviation of the spline values at the requested coordinates. It is therefore roughly N times slower than a norm...
the_stack_v2_python_sparse
kglib/utils/HelperFunctions.py
kgullikson88/gullikson-scripts
train
4
ebde779893a9261774b027f7e556b200470fcffe
[ "n = len(piles)\n'\\n Greedy approach does not work. One can try a few cases to see this.\\n DP is the way. What are the states? Playing this game requires one to choose\\n from either left end or right end. This should give a hint for (l,r) or (i,j)\\n Then the game is played by two pla...
<|body_start_0|> n = len(piles) '\n Greedy approach does not work. One can try a few cases to see this.\n DP is the way. What are the states? Playing this game requires one to choose\n from either left end or right end. This should give a hint for (l,r) or (i,j)\n Then the ga...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" <|body_0|> def stoneGameDPfast(self, piles): """:type piles: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(piles) '\n Gre...
stack_v2_sparse_classes_75kplus_train_000079
5,113
no_license
[ { "docstring": ":type piles: List[int] :rtype: bool", "name": "stoneGame", "signature": "def stoneGame(self, piles)" }, { "docstring": ":type piles: List[int] :rtype: bool", "name": "stoneGameDPfast", "signature": "def stoneGameDPfast(self, piles)" } ]
2
stack_v2_sparse_classes_30k_train_024087
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def stoneGame(self, piles): :type piles: List[int] :rtype: bool - def stoneGameDPfast(self, piles): :type piles: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def stoneGame(self, piles): :type piles: List[int] :rtype: bool - def stoneGameDPfast(self, piles): :type piles: List[int] :rtype: bool <|skeleton|> class Solution: def sto...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" <|body_0|> def stoneGameDPfast(self, piles): """:type piles: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def stoneGame(self, piles): """:type piles: List[int] :rtype: bool""" n = len(piles) '\n Greedy approach does not work. One can try a few cases to see this.\n DP is the way. What are the states? Playing this game requires one to choose\n from either left ...
the_stack_v2_python_sparse
S/StoneGame.py
bssrdf/pyleet
train
2
5533738cfe772ea3bb4f6f84500b97841a7e4725
[ "if self.field:\n return 'Summary aggregations for \"{0:s}\"'.format(self.field)\nreturn 'Summary aggregations for an unknown field.'", "self.field = field\nself.field_query_string = field_query_string\nformatted_field_name = self.format_field_by_type(field)\nif field_query_string == '*':\n formatted_field_...
<|body_start_0|> if self.field: return 'Summary aggregations for "{0:s}"'.format(self.field) return 'Summary aggregations for an unknown field.' <|end_body_0|> <|body_start_1|> self.field = field self.field_query_string = field_query_string formatted_field_name = sel...
Summary Aggregations.
SummaryAggregation
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SummaryAggregation: """Summary Aggregations.""" def chart_title(self): """Returns a title for the chart.""" <|body_0|> def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit=5): """Runs the Summary...
stack_v2_sparse_classes_75kplus_train_000080
13,136
permissive
[ { "docstring": "Returns a title for the chart.", "name": "chart_title", "signature": "def chart_title(self)" }, { "docstring": "Runs the SummaryAggregation aggregator. Args: field: What field to aggregate on. field_query_string: The field value(s) to aggregate on. supported_charts: The chart typ...
2
stack_v2_sparse_classes_30k_train_026043
Implement the Python class `SummaryAggregation` described below. Class description: Summary Aggregations. Method signatures and docstrings: - def chart_title(self): Returns a title for the chart. - def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit...
Implement the Python class `SummaryAggregation` described below. Class description: Summary Aggregations. Method signatures and docstrings: - def chart_title(self): Returns a title for the chart. - def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit...
24f471b58ca4a87cb053961b5f05c07a544ca7b8
<|skeleton|> class SummaryAggregation: """Summary Aggregations.""" def chart_title(self): """Returns a title for the chart.""" <|body_0|> def run(self, field, field_query_string='*', start_time='', end_time='', most_common_limit=10, rare_value_document_limit=5): """Runs the Summary...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SummaryAggregation: """Summary Aggregations.""" def chart_title(self): """Returns a title for the chart.""" if self.field: return 'Summary aggregations for "{0:s}"'.format(self.field) return 'Summary aggregations for an unknown field.' def run(self, field, field_q...
the_stack_v2_python_sparse
timesketch/lib/aggregators/summary.py
google/timesketch
train
2,263
b6b789d8ac801d10a3d0eedcf367452c3210483e
[ "len_a = 0\nlen_b = 0\na = headA\nwhile a:\n len_a += 1\n a = a.next\nb = headB\nwhile b:\n len_b += 1\n b = b.next\nif len_a < len_b:\n headA, headB = (headB, headA)\n len_a, len_b = (len_b, len_a)\nfor _ in range(len_a - len_b):\n headA = headA.next\nwhile headA:\n if headA == headB:\n ...
<|body_start_0|> len_a = 0 len_b = 0 a = headA while a: len_a += 1 a = a.next b = headB while b: len_b += 1 b = b.next if len_a < len_b: headA, headB = (headB, headA) len_a, len_b = (len_b, le...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getIntersectionNode1(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def getIntersectionNode2(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_1|> def getIntersectionNode3(s...
stack_v2_sparse_classes_75kplus_train_000081
2,598
no_license
[ { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode1", "signature": "def getIntersectionNode1(self, headA, headB)" }, { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode2", "signature": "def getIntersection...
4
stack_v2_sparse_classes_30k_train_007013
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode1(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def getIntersectionNode2(self, headA, headB): :type head1, head1: ListNode :rtype: L...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode1(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def getIntersectionNode2(self, headA, headB): :type head1, head1: ListNode :rtype: L...
8fb6c1d947046dabd58ff8482b2c0b41f39aa988
<|skeleton|> class Solution: def getIntersectionNode1(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def getIntersectionNode2(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_1|> def getIntersectionNode3(s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def getIntersectionNode1(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" len_a = 0 len_b = 0 a = headA while a: len_a += 1 a = a.next b = headB while b: len_b += 1 b = b.n...
the_stack_v2_python_sparse
Python/LeetCode/160.py
czx94/Algorithms-Collection
train
2
973a1b2eceea1137486521b730f9110f3ff40762
[ "\"\"\" Threading Data \"\"\"\nself.GRID_LOCK = GRID_LOCK\n' Surface Display Data '\nself.subsurface = subsurface\nself.clean_subsurface = subsurface.copy()\nself.x = coordinates[0]\nself.y = coordinates[1]\n' Surface Design Data'\nself.clock_font = pygame.font.SysFont('arial', 28, True, False) if font is None els...
<|body_start_0|> """ Threading Data """ self.GRID_LOCK = GRID_LOCK ' Surface Display Data ' self.subsurface = subsurface self.clean_subsurface = subsurface.copy() self.x = coordinates[0] self.y = coordinates[1] ' Surface Design Data' self.clock_fo...
GameClock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameClock: def __init__(self, GRID_LOCK, subsurface, coordinates, font=None): """:param GRID_LOCK: :param subsurface: :param coordinates:""" <|body_0|> def run(self): """Runs the game clock""" <|body_1|> def display(self): """Displays the time st...
stack_v2_sparse_classes_75kplus_train_000082
2,449
no_license
[ { "docstring": ":param GRID_LOCK: :param subsurface: :param coordinates:", "name": "__init__", "signature": "def __init__(self, GRID_LOCK, subsurface, coordinates, font=None)" }, { "docstring": "Runs the game clock", "name": "run", "signature": "def run(self)" }, { "docstring": "...
3
null
Implement the Python class `GameClock` described below. Class description: Implement the GameClock class. Method signatures and docstrings: - def __init__(self, GRID_LOCK, subsurface, coordinates, font=None): :param GRID_LOCK: :param subsurface: :param coordinates: - def run(self): Runs the game clock - def display(s...
Implement the Python class `GameClock` described below. Class description: Implement the GameClock class. Method signatures and docstrings: - def __init__(self, GRID_LOCK, subsurface, coordinates, font=None): :param GRID_LOCK: :param subsurface: :param coordinates: - def run(self): Runs the game clock - def display(s...
8995bd57ae0faaf7420c74e1a7b2c091c64d6942
<|skeleton|> class GameClock: def __init__(self, GRID_LOCK, subsurface, coordinates, font=None): """:param GRID_LOCK: :param subsurface: :param coordinates:""" <|body_0|> def run(self): """Runs the game clock""" <|body_1|> def display(self): """Displays the time st...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GameClock: def __init__(self, GRID_LOCK, subsurface, coordinates, font=None): """:param GRID_LOCK: :param subsurface: :param coordinates:""" """ Threading Data """ self.GRID_LOCK = GRID_LOCK ' Surface Display Data ' self.subsurface = subsurface self.clean_subsu...
the_stack_v2_python_sparse
widgets/widget___game_clock.py
EcoSimulator/EcoSim2.0
train
0
9e334ff611cc040556c187b536407a49560c945d
[ "serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nserializer.preview()\nreturn Response(serializer.data, status=status.HTTP_200_OK)", "self.get_object()\nserializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nserializer.cancel...
<|body_start_0|> serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.preview() return Response(serializer.data, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> self.get_object() serializer = self.get_seriali...
Quote ViewSet.
QuoteViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuoteViewSet: """Quote ViewSet.""" def preview(self, request, *args, **kwargs): """Same as `create` but without actually saving the changes.""" <|body_0|> def cancel(self, request, *args, **kwargs): """Cancel a quote.""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_75kplus_train_000083
2,551
permissive
[ { "docstring": "Same as `create` but without actually saving the changes.", "name": "preview", "signature": "def preview(self, request, *args, **kwargs)" }, { "docstring": "Cancel a quote.", "name": "cancel", "signature": "def cancel(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_027828
Implement the Python class `QuoteViewSet` described below. Class description: Quote ViewSet. Method signatures and docstrings: - def preview(self, request, *args, **kwargs): Same as `create` but without actually saving the changes. - def cancel(self, request, *args, **kwargs): Cancel a quote.
Implement the Python class `QuoteViewSet` described below. Class description: Quote ViewSet. Method signatures and docstrings: - def preview(self, request, *args, **kwargs): Same as `create` but without actually saving the changes. - def cancel(self, request, *args, **kwargs): Cancel a quote. <|skeleton|> class Quot...
a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e
<|skeleton|> class QuoteViewSet: """Quote ViewSet.""" def preview(self, request, *args, **kwargs): """Same as `create` but without actually saving the changes.""" <|body_0|> def cancel(self, request, *args, **kwargs): """Cancel a quote.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QuoteViewSet: """Quote ViewSet.""" def preview(self, request, *args, **kwargs): """Same as `create` but without actually saving the changes.""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.preview() return...
the_stack_v2_python_sparse
datahub/omis/quote/views.py
cgsunkel/data-hub-api
train
0
3f0852cff7c49d86edf3535a79447785075f4ccb
[ "if not root:\n return -1\nret = 1 + max((self.find_leaves_helper(child, results) for child in (root.left, root.right)))\nif ret >= len(results):\n results.append([])\nresults[ret].append(root.val)\nreturn ret", "ret = []\nself.find_leaves_helper(root, ret)\nreturn ret" ]
<|body_start_0|> if not root: return -1 ret = 1 + max((self.find_leaves_helper(child, results) for child in (root.left, root.right))) if ret >= len(results): results.append([]) results[ret].append(root.val) return ret <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def find_leaves_helper(self, root, results): """push root and all descendants to results return the distance from root to farthest leaf""" <|body_0|> def find_leaves(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_s...
stack_v2_sparse_classes_75kplus_train_000084
1,688
no_license
[ { "docstring": "push root and all descendants to results return the distance from root to farthest leaf", "name": "find_leaves_helper", "signature": "def find_leaves_helper(self, root, results)" }, { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "find_leaves", "sig...
2
stack_v2_sparse_classes_30k_train_044384
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_leaves_helper(self, root, results): push root and all descendants to results return the distance from root to farthest leaf - def find_leaves(self, root): :type root: Tr...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def find_leaves_helper(self, root, results): push root and all descendants to results return the distance from root to farthest leaf - def find_leaves(self, root): :type root: Tr...
e3637e293c5e4e8b4e5cc2e24dcd638ef796c560
<|skeleton|> class Solution: def find_leaves_helper(self, root, results): """push root and all descendants to results return the distance from root to farthest leaf""" <|body_0|> def find_leaves(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def find_leaves_helper(self, root, results): """push root and all descendants to results return the distance from root to farthest leaf""" if not root: return -1 ret = 1 + max((self.find_leaves_helper(child, results) for child in (root.left, root.right))) ...
the_stack_v2_python_sparse
tree/findLeavesOfBinaryTree.py
ay701/Coding_Challenges
train
1
35d7968871449a894c7cb9f762d230d7daff2f86
[ "max_profit = 0\n_len = len(prices)\nfor i in range(_len):\n for j in range(i + 1, _len):\n max_profit = max(prices[j] - prices[i], max_profit)\nreturn max_profit", "profit = 0\nmin_price = float('inf')\nfor price in prices:\n min_price = min(price, min_price)\n profit = max(profit, price - min_pr...
<|body_start_0|> max_profit = 0 _len = len(prices) for i in range(_len): for j in range(i + 1, _len): max_profit = max(prices[j] - prices[i], max_profit) return max_profit <|end_body_0|> <|body_start_1|> profit = 0 min_price = float('inf') ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit1(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit2(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> max_profit = 0 _len = len(price...
stack_v2_sparse_classes_75kplus_train_000085
696
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit1", "signature": "def maxProfit1(self, prices)" }, { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit2", "signature": "def maxProfit2(self, prices)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices): :type prices: List[int] :rtype: int - def maxProfit2(self, prices): :type prices: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit1(self, prices): :type prices: List[int] :rtype: int - def maxProfit2(self, prices): :type prices: List[int] :rtype: int <|skeleton|> class Solution: def maxPr...
c338b66db9f8f09db9115e7ffe75925c455b17b8
<|skeleton|> class Solution: def maxProfit1(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit2(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxProfit1(self, prices): """:type prices: List[int] :rtype: int""" max_profit = 0 _len = len(prices) for i in range(_len): for j in range(i + 1, _len): max_profit = max(prices[j] - prices[i], max_profit) return max_profit ...
the_stack_v2_python_sparse
Array/Best Time to Buy and Sell Stock.py
mikolaje/leetcode_practice
train
0
22137a9f593b615b474b0755edcb3e7c4786999d
[ "self.device = device\nself.ip = ip\nself.netapp_user = user\nself.netapp_password = password\nself.path_prefix = prefix\nself.publish_metric = pm\nself._netapp_login()\nfilers_xml = self.get_netapp_data()\nfor volume in filers_xml:\n max_inodes = volume.find('files-total').text\n used_inodes = volume.find('f...
<|body_start_0|> self.device = device self.ip = ip self.netapp_user = user self.netapp_password = password self.path_prefix = prefix self.publish_metric = pm self._netapp_login() filers_xml = self.get_netapp_data() for volume in filers_xml: ...
Our netapp_inode Collector
netapp_inodeCol
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class netapp_inodeCol: """Our netapp_inode Collector""" def __init__(self, device, ip, user, password, prefix, pm): """Instantiate _our_ stuff""" <|body_0|> def push(self, metric_name=None, metric_value=None, volume=None): """Ship that shit off to graphite broski""" ...
stack_v2_sparse_classes_75kplus_train_000086
3,492
permissive
[ { "docstring": "Instantiate _our_ stuff", "name": "__init__", "signature": "def __init__(self, device, ip, user, password, prefix, pm)" }, { "docstring": "Ship that shit off to graphite broski", "name": "push", "signature": "def push(self, metric_name=None, metric_value=None, volume=None...
4
stack_v2_sparse_classes_30k_train_000283
Implement the Python class `netapp_inodeCol` described below. Class description: Our netapp_inode Collector Method signatures and docstrings: - def __init__(self, device, ip, user, password, prefix, pm): Instantiate _our_ stuff - def push(self, metric_name=None, metric_value=None, volume=None): Ship that shit off to ...
Implement the Python class `netapp_inodeCol` described below. Class description: Our netapp_inode Collector Method signatures and docstrings: - def __init__(self, device, ip, user, password, prefix, pm): Instantiate _our_ stuff - def push(self, metric_name=None, metric_value=None, volume=None): Ship that shit off to ...
461caf29e84db8cbf46f9fc4c895f56353e10c61
<|skeleton|> class netapp_inodeCol: """Our netapp_inode Collector""" def __init__(self, device, ip, user, password, prefix, pm): """Instantiate _our_ stuff""" <|body_0|> def push(self, metric_name=None, metric_value=None, volume=None): """Ship that shit off to graphite broski""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class netapp_inodeCol: """Our netapp_inode Collector""" def __init__(self, device, ip, user, password, prefix, pm): """Instantiate _our_ stuff""" self.device = device self.ip = ip self.netapp_user = user self.netapp_password = password self.path_prefix = prefix ...
the_stack_v2_python_sparse
src/collectors/netapp/netapp_inode.py
python-diamond/Diamond
train
1,874
81d22e75721c89511ef8dc2afedcabb678d6a98b
[ "EasyFrame.__init__(self, title='Square Rooting Numbers')\nself.addLabel(text='An integer', row=0, column=0)\nself.inputField = self.addIntegerField(value=0, row=0, column=1, width=10)\nself.addLabel(text='Square root', row=1, column=0)\nself.outputField = self.addFloatField(value=0.0, row=1, column=1, width=8, pre...
<|body_start_0|> EasyFrame.__init__(self, title='Square Rooting Numbers') self.addLabel(text='An integer', row=0, column=0) self.inputField = self.addIntegerField(value=0, row=0, column=1, width=10) self.addLabel(text='Square root', row=1, column=0) self.outputField = self.addFlo...
Computes and displays the square root of an input number.
NumberFieldApplication
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumberFieldApplication: """Computes and displays the square root of an input number.""" def __init__(self): """Sets up the window and widgets.""" <|body_0|> def compute_square_root(self): """Inputs the integer, computes the square root, and outputs the result. Ne...
stack_v2_sparse_classes_75kplus_train_000087
2,402
no_license
[ { "docstring": "Sets up the window and widgets.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inputs the integer, computes the square root, and outputs the result. Negative and non integer numbers will have an error message displayed.", "name": "compute_square_ro...
2
stack_v2_sparse_classes_30k_train_051019
Implement the Python class `NumberFieldApplication` described below. Class description: Computes and displays the square root of an input number. Method signatures and docstrings: - def __init__(self): Sets up the window and widgets. - def compute_square_root(self): Inputs the integer, computes the square root, and o...
Implement the Python class `NumberFieldApplication` described below. Class description: Computes and displays the square root of an input number. Method signatures and docstrings: - def __init__(self): Sets up the window and widgets. - def compute_square_root(self): Inputs the integer, computes the square root, and o...
86f50c0094dbbf43ad033b1153e57ad5c258700e
<|skeleton|> class NumberFieldApplication: """Computes and displays the square root of an input number.""" def __init__(self): """Sets up the window and widgets.""" <|body_0|> def compute_square_root(self): """Inputs the integer, computes the square root, and outputs the result. Ne...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NumberFieldApplication: """Computes and displays the square root of an input number.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title='Square Rooting Numbers') self.addLabel(text='An integer', row=0, column=0) self.inputField = se...
the_stack_v2_python_sparse
Week-13-1/gui-8.py
AdyGCode/Python-Basics-2021S1
train
0
5290ff69768a9011af417546c3e2ee3cc0917e8e
[ "self.error_status = 0\nself.username = None\nself.password = None\nself.client = None", "test_status = False\nif self.error_status == 0 and self.username is not None:\n try:\n mail_server = smtplib.SMTP(self.client)\n mail_server.starttls()\n mail_server.login(self.username, self.password...
<|body_start_0|> self.error_status = 0 self.username = None self.password = None self.client = None <|end_body_0|> <|body_start_1|> test_status = False if self.error_status == 0 and self.username is not None: try: mail_server = smtplib.SMTP(se...
Objects to send messages through a gmail account
MailSender
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MailSender: """Objects to send messages through a gmail account""" def __init__(self): """Creates an empty MailSender instance""" <|body_0|> def test_credentials(self): """Tests validity of credentials loaded in system by trying to log-in to gmail. OUTPUT (bool) ...
stack_v2_sparse_classes_75kplus_train_000088
9,487
no_license
[ { "docstring": "Creates an empty MailSender instance", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Tests validity of credentials loaded in system by trying to log-in to gmail. OUTPUT (bool) Whether or not credentials managed to be used to log into account", "name...
4
stack_v2_sparse_classes_30k_train_015267
Implement the Python class `MailSender` described below. Class description: Objects to send messages through a gmail account Method signatures and docstrings: - def __init__(self): Creates an empty MailSender instance - def test_credentials(self): Tests validity of credentials loaded in system by trying to log-in to ...
Implement the Python class `MailSender` described below. Class description: Objects to send messages through a gmail account Method signatures and docstrings: - def __init__(self): Creates an empty MailSender instance - def test_credentials(self): Tests validity of credentials loaded in system by trying to log-in to ...
550a82b74a4422b5952c8618262755f9822f7c22
<|skeleton|> class MailSender: """Objects to send messages through a gmail account""" def __init__(self): """Creates an empty MailSender instance""" <|body_0|> def test_credentials(self): """Tests validity of credentials loaded in system by trying to log-in to gmail. OUTPUT (bool) ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MailSender: """Objects to send messages through a gmail account""" def __init__(self): """Creates an empty MailSender instance""" self.error_status = 0 self.username = None self.password = None self.client = None def test_credentials(self): """Tests va...
the_stack_v2_python_sparse
python/global_libraries/mail_sender.py
bopopescu/Home_Code
train
0
a5f18d9776b4d2f5ad4db84ef0f98200d8305024
[ "ulist = struct.unpack(pktt.header_rec, data)\nself.frame = pktt.frame\nself.index = pktt.index\nself.seconds = ulist[0]\nself.usecs = ulist[1]\nself.length_inc = ulist[2]\nself.length_orig = ulist[3]\npktt.pkt.record = self\nself.secs = float(self.seconds) + float(self.usecs) / 1000000.0\nif pktt.tstart is None:\n...
<|body_start_0|> ulist = struct.unpack(pktt.header_rec, data) self.frame = pktt.frame self.index = pktt.index self.seconds = ulist[0] self.usecs = ulist[1] self.length_inc = ulist[2] self.length_orig = ulist[3] pktt.pkt.record = self self.secs = fl...
Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int, # Number of bytes in packet secs ...
Record
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Record: """Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int,...
stack_v2_sparse_classes_75kplus_train_000089
4,513
no_license
[ { "docstring": "Constructor Initialize object's private data. pktt: Packet trace object (packet.pktt.Pktt) so this layer has access to the parent layers. data: Raw packet data for this layer.", "name": "__init__", "signature": "def __init__(self, pktt, data)" }, { "docstring": "String representa...
2
stack_v2_sparse_classes_30k_train_049233
Implement the Python class `Record` described below. Class description: Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of byt...
Implement the Python class `Record` described below. Class description: Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of byt...
1f06ae8c73d253141a3434fb9d2c36be3fe768ea
<|skeleton|> class Record: """Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Record: """Record object Usage: from packet.record import Record x = Record(pktt, data) Object definition: Record( frame = int, # Frame number index = int, # Packet number seconds = int, # Seconds usecs = int, # Microseconds length_inc = int, # Number of bytes included in trace length_orig = int, # Number of ...
the_stack_v2_python_sparse
packet/record.py
MihailRusetskiy/nfs
train
0
66239f52d2d85e8c8ea54fc1a2230bb85642f22c
[ "try:\n return cls.byName(campaignName)\nexcept SQLObjectNotFound:\n return cls(name=campaignName, searchQuery=query)", "try:\n return cls.byName(campaignName)\nexcept SQLObjectNotFound as e:\n raise type(e)('Use the campaign manager to create the Campaign as name and search query. Name not found: {!r...
<|body_start_0|> try: return cls.byName(campaignName) except SQLObjectNotFound: return cls(name=campaignName, searchQuery=query) <|end_body_0|> <|body_start_1|> try: return cls.byName(campaignName) except SQLObjectNotFound as e: raise type...
Model a Campaign, which can be assigned to a Tweet as a label. Used to group Tweets which are added to the DB because they matched the same campaign, such as a search topic. See docs/models.md document.
Campaign
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Campaign: """Model a Campaign, which can be assigned to a Tweet as a label. Used to group Tweets which are added to the DB because they matched the same campaign, such as a search topic. See docs/models.md document.""" def getOrCreate(cls, campaignName, query=None): """Get a campaign...
stack_v2_sparse_classes_75kplus_train_000090
15,734
permissive
[ { "docstring": "Get a campaign otherwise create and return one. Query may be empty as in some cases like a utility's campaign label the campaign is a label for grouping rather than searching.", "name": "getOrCreate", "signature": "def getOrCreate(cls, campaignName, query=None)" }, { "docstring":...
2
null
Implement the Python class `Campaign` described below. Class description: Model a Campaign, which can be assigned to a Tweet as a label. Used to group Tweets which are added to the DB because they matched the same campaign, such as a search topic. See docs/models.md document. Method signatures and docstrings: - def g...
Implement the Python class `Campaign` described below. Class description: Model a Campaign, which can be assigned to a Tweet as a label. Used to group Tweets which are added to the DB because they matched the same campaign, such as a search topic. See docs/models.md document. Method signatures and docstrings: - def g...
e7c36efcd16dcd8141a5e198af53ab1a41010610
<|skeleton|> class Campaign: """Model a Campaign, which can be assigned to a Tweet as a label. Used to group Tweets which are added to the DB because they matched the same campaign, such as a search topic. See docs/models.md document.""" def getOrCreate(cls, campaignName, query=None): """Get a campaign...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Campaign: """Model a Campaign, which can be assigned to a Tweet as a label. Used to group Tweets which are added to the DB because they matched the same campaign, such as a search topic. See docs/models.md document.""" def getOrCreate(cls, campaignName, query=None): """Get a campaign otherwise cr...
the_stack_v2_python_sparse
app/models/tweets.py
MichaelCurrin/twitterverse
train
12
daf79bd8d7e9f93793bd267bb36d7d790eeca8a6
[ "def helper(remain, combi, idx):\n if remain < 0:\n return\n if remain == 0:\n res.append(combi)\n return\n if idx >= len(candidates):\n return\n helper(remain, combi, idx + 1)\n helper(remain - candidates[idx], combi + [candidates[idx]], idx)\nres = []\nhelper(target, [],...
<|body_start_0|> def helper(remain, combi, idx): if remain < 0: return if remain == 0: res.append(combi) return if idx >= len(candidates): return helper(remain, combi, idx + 1) helper(rema...
Solution_
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum_hash(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]...
stack_v2_sparse_classes_75kplus_train_000091
3,701
no_license
[ { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum", "signature": "def combinationSum(self, candidates, target)" }, { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum_has...
2
stack_v2_sparse_classes_30k_train_041784
Implement the Python class `Solution_` described below. Class description: Implement the Solution_ class. Method signatures and docstrings: - def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum_hash(self, candidates, target): :type c...
Implement the Python class `Solution_` described below. Class description: Implement the Solution_ class. Method signatures and docstrings: - def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum_hash(self, candidates, target): :type c...
fab4c341486e872fb2926d1b6d50499d55e76a4a
<|skeleton|> class Solution_: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum_hash(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution_: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" def helper(remain, combi, idx): if remain < 0: return if remain == 0: res.append(combi) r...
the_stack_v2_python_sparse
leetcode/39. Combination Sum.py
lunar-r/sword-to-offer-python
train
0
23345a776cf8013a11a56718ea6e5a526e25653e
[ "dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]\ndp[-1][-1] = True\nfor i in range(len(text), -1, -1):\n for j in range(len(pattern) - 1, -1, -1):\n first_match = i < len(text) and pattern[j] in {text[i], '.'}\n if j + 1 < len(pattern) and pattern[j + 1] == '*':\n dp[i...
<|body_start_0|> dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)] dp[-1][-1] = True for i in range(len(text), -1, -1): for j in range(len(pattern) - 1, -1, -1): first_match = i < len(text) and pattern[j] in {text[i], '.'} if j + 1 < le...
PatternMatching
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PatternMatching: def is_match(self, text: str, pattern: str) -> bool: """Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:""" <|body_0|> def is_match_(self, text: str, pattern: str) -> bool: "...
stack_v2_sparse_classes_75kplus_train_000092
1,884
no_license
[ { "docstring": "Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:", "name": "is_match", "signature": "def is_match(self, text: str, pattern: str) -> bool" }, { "docstring": "Approach: Recursion :param text: :param pattern...
2
stack_v2_sparse_classes_30k_train_021163
Implement the Python class `PatternMatching` described below. Class description: Implement the PatternMatching class. Method signatures and docstrings: - def is_match(self, text: str, pattern: str) -> bool: Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param patt...
Implement the Python class `PatternMatching` described below. Class description: Implement the PatternMatching class. Method signatures and docstrings: - def is_match(self, text: str, pattern: str) -> bool: Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param patt...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class PatternMatching: def is_match(self, text: str, pattern: str) -> bool: """Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:""" <|body_0|> def is_match_(self, text: str, pattern: str) -> bool: "...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PatternMatching: def is_match(self, text: str, pattern: str) -> bool: """Approach: Dynamic Programming Bottom-Up Time Complexity: O(TP) Space Complexity: O(TP) :param text: :param pattern: :return:""" dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)] dp[-1][-1] = True ...
the_stack_v2_python_sparse
math_and_srings/regular_expression_matching.py
Shiv2157k/leet_code
train
1
5b35020d867bf112d6fca90d753216f8bbb72769
[ "super().__init__(trainloader, valloader, model, num_classes, linear_layer, loss, device, logger)\nself.eta = eta\nself.device = device\nself.init_out = list()\nself.init_l1 = list()\nself.selection_type = selection_type\nself.valid = valid\nself.ss_indices = ss_indices", "omp_start_time = time.time()\nself.updat...
<|body_start_0|> super().__init__(trainloader, valloader, model, num_classes, linear_layer, loss, device, logger) self.eta = eta self.device = device self.init_out = list() self.init_l1 = list() self.selection_type = selection_type self.valid = valid self....
Implementation of GradMatch Strategy from the paper :footcite:`sivasubramanian2020gradmatch` for supervised learning frameworks. GradMatch strategy tries to solve the optimization problem given below: .. math:: \\min_{\\mathbf{w}, S: |S| \\leq k} \\Vert \\sum_{i \\in S} w_i \\nabla_{\\theta}L_T^i(\\theta) - \\nabla_{\\...
AdapWeightsStrategy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdapWeightsStrategy: """Implementation of GradMatch Strategy from the paper :footcite:`sivasubramanian2020gradmatch` for supervised learning frameworks. GradMatch strategy tries to solve the optimization problem given below: .. math:: \\min_{\\mathbf{w}, S: |S| \\leq k} \\Vert \\sum_{i \\in S} w_...
stack_v2_sparse_classes_75kplus_train_000093
5,115
permissive
[ { "docstring": "Constructor method", "name": "__init__", "signature": "def __init__(self, trainloader, valloader, model, loss, eta, device, num_classes, linear_layer, selection_type, logger, ss_indices, valid=False)" }, { "docstring": "Apply OMP Algorithm for data selection Parameters ----------...
2
stack_v2_sparse_classes_30k_train_044649
Implement the Python class `AdapWeightsStrategy` described below. Class description: Implementation of GradMatch Strategy from the paper :footcite:`sivasubramanian2020gradmatch` for supervised learning frameworks. GradMatch strategy tries to solve the optimization problem given below: .. math:: \\min_{\\mathbf{w}, S: ...
Implement the Python class `AdapWeightsStrategy` described below. Class description: Implementation of GradMatch Strategy from the paper :footcite:`sivasubramanian2020gradmatch` for supervised learning frameworks. GradMatch strategy tries to solve the optimization problem given below: .. math:: \\min_{\\mathbf{w}, S: ...
8d10c7f5d96e071f98c20e4e9ff4c41c2c4ea2af
<|skeleton|> class AdapWeightsStrategy: """Implementation of GradMatch Strategy from the paper :footcite:`sivasubramanian2020gradmatch` for supervised learning frameworks. GradMatch strategy tries to solve the optimization problem given below: .. math:: \\min_{\\mathbf{w}, S: |S| \\leq k} \\Vert \\sum_{i \\in S} w_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdapWeightsStrategy: """Implementation of GradMatch Strategy from the paper :footcite:`sivasubramanian2020gradmatch` for supervised learning frameworks. GradMatch strategy tries to solve the optimization problem given below: .. math:: \\min_{\\mathbf{w}, S: |S| \\leq k} \\Vert \\sum_{i \\in S} w_i \\nabla_{\\...
the_stack_v2_python_sparse
cords/selectionstrategies/SL/adapweightsstrategy.py
decile-team/cords
train
289
e3224eec60d4161ee553dc6a6a8d5e4399bd5740
[ "testfile = ('lib/l10n_utils/tests/test_files/templates/even_more_lang_files.html',)\nwith capture_stdio() as out:\n extracted = next(extract_from_files(testfile, method_map=METHODS))\nself.assertTupleEqual(extracted, (testfile[0], 9, 'Mark it 8 Dude.', []))\nself.assertEqual(out[0], ' %s' % testfile)", "base...
<|body_start_0|> testfile = ('lib/l10n_utils/tests/test_files/templates/even_more_lang_files.html',) with capture_stdio() as out: extracted = next(extract_from_files(testfile, method_map=METHODS)) self.assertTupleEqual(extracted, (testfile[0], 9, 'Mark it 8 Dude.', [])) self....
TestL10nExtract
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestL10nExtract: def test_extract_from_files(self): """Should be able to extract strings from a specific file.""" <|body_0|> def test_extract_from_multiple_files(self): """Should be able to extract strings from specific files.""" <|body_1|> def test_extr...
stack_v2_sparse_classes_75kplus_train_000094
14,956
no_license
[ { "docstring": "Should be able to extract strings from a specific file.", "name": "test_extract_from_files", "signature": "def test_extract_from_files(self)" }, { "docstring": "Should be able to extract strings from specific files.", "name": "test_extract_from_multiple_files", "signature...
6
stack_v2_sparse_classes_30k_train_020817
Implement the Python class `TestL10nExtract` described below. Class description: Implement the TestL10nExtract class. Method signatures and docstrings: - def test_extract_from_files(self): Should be able to extract strings from a specific file. - def test_extract_from_multiple_files(self): Should be able to extract s...
Implement the Python class `TestL10nExtract` described below. Class description: Implement the TestL10nExtract class. Method signatures and docstrings: - def test_extract_from_files(self): Should be able to extract strings from a specific file. - def test_extract_from_multiple_files(self): Should be able to extract s...
5fa3a818c3d41bd9c3eb25122e1d376c8910269c
<|skeleton|> class TestL10nExtract: def test_extract_from_files(self): """Should be able to extract strings from a specific file.""" <|body_0|> def test_extract_from_multiple_files(self): """Should be able to extract strings from specific files.""" <|body_1|> def test_extr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestL10nExtract: def test_extract_from_files(self): """Should be able to extract strings from a specific file.""" testfile = ('lib/l10n_utils/tests/test_files/templates/even_more_lang_files.html',) with capture_stdio() as out: extracted = next(extract_from_files(testfile, m...
the_stack_v2_python_sparse
ExtractFeatures/Data/thesantosh/test_commands.py
vivekaxl/LexisNexis
train
9
d443527bada8adc6a4169dab68e87850448217a0
[ "super(RMSModel, self).__init__()\nself.el = np.array(model_spec.keys())\nself.rms = np.array(model_spec.values())\nself.alpha, self.beta = fit_power_law(self.el, self.rms)", "if el < 0:\n raise RuntimeError('el = {} < 0'.format(el))\nelif el > 90:\n raise RuntimeError('el = {} > 90'.format(el))\nif 0 <= el...
<|body_start_0|> super(RMSModel, self).__init__() self.el = np.array(model_spec.keys()) self.rms = np.array(model_spec.values()) self.alpha, self.beta = fit_power_law(self.el, self.rms) <|end_body_0|> <|body_start_1|> if el < 0: raise RuntimeError('el = {} < 0'.forma...
RMSModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RMSModel: def __init__(self, model_spec=SNR_8): """???""" <|body_0|> def __call__(self, el): """??? note that el is in [deg]""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(RMSModel, self).__init__() self.el = np.array(model_spec.keys(...
stack_v2_sparse_classes_75kplus_train_000095
2,471
permissive
[ { "docstring": "???", "name": "__init__", "signature": "def __init__(self, model_spec=SNR_8)" }, { "docstring": "??? note that el is in [deg]", "name": "__call__", "signature": "def __call__(self, el)" } ]
2
stack_v2_sparse_classes_30k_train_020227
Implement the Python class `RMSModel` described below. Class description: Implement the RMSModel class. Method signatures and docstrings: - def __init__(self, model_spec=SNR_8): ??? - def __call__(self, el): ??? note that el is in [deg]
Implement the Python class `RMSModel` described below. Class description: Implement the RMSModel class. Method signatures and docstrings: - def __init__(self, model_spec=SNR_8): ??? - def __call__(self, el): ??? note that el is in [deg] <|skeleton|> class RMSModel: def __init__(self, model_spec=SNR_8): ...
e364be68cb0cadbeea10ca569963b8f99aa7b05b
<|skeleton|> class RMSModel: def __init__(self, model_spec=SNR_8): """???""" <|body_0|> def __call__(self, el): """??? note that el is in [deg]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RMSModel: def __init__(self, model_spec=SNR_8): """???""" super(RMSModel, self).__init__() self.el = np.array(model_spec.keys()) self.rms = np.array(model_spec.values()) self.alpha, self.beta = fit_power_law(self.el, self.rms) def __call__(self, el): """???...
the_stack_v2_python_sparse
pyrsss/gnss/rms_model.py
butala/pyrsss
train
7
77825902e31b4bfc1f4ac1898d638db067123821
[ "c = ircdb.channels.getChannel(channel)\nc.addIgnore(banmask, expires)\nircdb.channels.setChannel(channel, c)\nirc.replySuccess()", "c = ircdb.channels.getChannel(channel)\ntry:\n c.removeIgnore(banmask)\n ircdb.channels.setChannel(channel, c)\n irc.replySuccess()\nexcept KeyError:\n irc.error('There ...
<|body_start_0|> c = ircdb.channels.getChannel(channel) c.addIgnore(banmask, expires) ircdb.channels.setChannel(channel, c) irc.replySuccess() <|end_body_0|> <|body_start_1|> c = ircdb.channels.getChannel(channel) try: c.removeIgnore(banmask) ircd...
ignore
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ignore: def add(self, irc, msg, args, channel, banmask, expires): """[<channel>] <nick|hostmask> [<expires>] If you have the #channel,op capability, this will set a persistent ignore on <hostmask> or the hostmask currently associated with <nick>. <expires> is an optional argument specify...
stack_v2_sparse_classes_75kplus_train_000096
35,475
permissive
[ { "docstring": "[<channel>] <nick|hostmask> [<expires>] If you have the #channel,op capability, this will set a persistent ignore on <hostmask> or the hostmask currently associated with <nick>. <expires> is an optional argument specifying when (in \"seconds from now\") the ignore will expire; if it isn't given,...
3
stack_v2_sparse_classes_30k_train_029846
Implement the Python class `ignore` described below. Class description: Implement the ignore class. Method signatures and docstrings: - def add(self, irc, msg, args, channel, banmask, expires): [<channel>] <nick|hostmask> [<expires>] If you have the #channel,op capability, this will set a persistent ignore on <hostma...
Implement the Python class `ignore` described below. Class description: Implement the ignore class. Method signatures and docstrings: - def add(self, irc, msg, args, channel, banmask, expires): [<channel>] <nick|hostmask> [<expires>] If you have the #channel,op capability, this will set a persistent ignore on <hostma...
656f42f8d6b3fe4544a5270e0dab816fd3603118
<|skeleton|> class ignore: def add(self, irc, msg, args, channel, banmask, expires): """[<channel>] <nick|hostmask> [<expires>] If you have the #channel,op capability, this will set a persistent ignore on <hostmask> or the hostmask currently associated with <nick>. <expires> is an optional argument specify...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ignore: def add(self, irc, msg, args, channel, banmask, expires): """[<channel>] <nick|hostmask> [<expires>] If you have the #channel,op capability, this will set a persistent ignore on <hostmask> or the hostmask currently associated with <nick>. <expires> is an optional argument specifying when (in "...
the_stack_v2_python_sparse
plugins/Channel/plugin.py
kblin/supybot-gsoc
train
2
fd870f007d03036bafb3d1d54f73e97f37d00fa2
[ "if obj is None:\n return super(UseCaseAdminInLine, self).has_delete_permission(request, obj=None)\nelif (request.user == obj.created_by or request.user.has_perm('muo.can_edit_all')) and obj.status in ('draft', 'rejected'):\n return super(UseCaseAdminInLine, self).has_delete_permission(request, obj=None)\nels...
<|body_start_0|> if obj is None: return super(UseCaseAdminInLine, self).has_delete_permission(request, obj=None) elif (request.user == obj.created_by or request.user.has_perm('muo.can_edit_all')) and obj.status in ('draft', 'rejected'): return super(UseCaseAdminInLine, self).has_...
UseCaseAdminInLine
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UseCaseAdminInLine: def has_delete_permission(self, request, obj=None): """Overriding the method such that the delete option on the UseCaseAdminInline form on change form is not available for the users except the original author or users with 'can_edit_all' permission. The delete option ...
stack_v2_sparse_classes_75kplus_train_000097
18,243
no_license
[ { "docstring": "Overriding the method such that the delete option on the UseCaseAdminInline form on change form is not available for the users except the original author or users with 'can_edit_all' permission. The delete option is only available to the original author or users with 'can_edit_all' permission if...
3
stack_v2_sparse_classes_30k_train_048086
Implement the Python class `UseCaseAdminInLine` described below. Class description: Implement the UseCaseAdminInLine class. Method signatures and docstrings: - def has_delete_permission(self, request, obj=None): Overriding the method such that the delete option on the UseCaseAdminInline form on change form is not ava...
Implement the Python class `UseCaseAdminInLine` described below. Class description: Implement the UseCaseAdminInLine class. Method signatures and docstrings: - def has_delete_permission(self, request, obj=None): Overriding the method such that the delete option on the UseCaseAdminInline form on change form is not ava...
d9b330ef70b0d0985bfc8248612ba57ee46ff0f4
<|skeleton|> class UseCaseAdminInLine: def has_delete_permission(self, request, obj=None): """Overriding the method such that the delete option on the UseCaseAdminInline form on change form is not available for the users except the original author or users with 'can_edit_all' permission. The delete option ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UseCaseAdminInLine: def has_delete_permission(self, request, obj=None): """Overriding the method such that the delete option on the UseCaseAdminInline form on change form is not available for the users except the original author or users with 'can_edit_all' permission. The delete option is only availa...
the_stack_v2_python_sparse
Code/EnhanceCWE-master/muo/admin.py
happinesstaker/more-website
train
0
da7e6db8d5b7bf251bd415e236ec1f155f4215c9
[ "if not email:\n raise ValueError('The given email must be set')\nemail = normalize_email(email)\nuser = self.model(email=email, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False)\nre...
<|body_start_0|> if not email: raise ValueError('The given email must be set') email = normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> ...
Define a model manager for User model with no username field.
CustomUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserManager: """Define a model manager for User model with no username field.""" def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" <|body_0|> def create_user(self, email, password=None, **extra_...
stack_v2_sparse_classes_75kplus_train_000098
3,359
no_license
[ { "docstring": "Create and save a User with the given email and password.", "name": "_create_user", "signature": "def _create_user(self, email, password, **extra_fields)" }, { "docstring": "Create and save a regular User with the given email and password.", "name": "create_user", "signat...
3
stack_v2_sparse_classes_30k_train_038287
Implement the Python class `CustomUserManager` described below. Class description: Define a model manager for User model with no username field. Method signatures and docstrings: - def _create_user(self, email, password, **extra_fields): Create and save a User with the given email and password. - def create_user(self...
Implement the Python class `CustomUserManager` described below. Class description: Define a model manager for User model with no username field. Method signatures and docstrings: - def _create_user(self, email, password, **extra_fields): Create and save a User with the given email and password. - def create_user(self...
97c29690929693b172ab88a52c3b426b17461011
<|skeleton|> class CustomUserManager: """Define a model manager for User model with no username field.""" def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" <|body_0|> def create_user(self, email, password=None, **extra_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomUserManager: """Define a model manager for User model with no username field.""" def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') ...
the_stack_v2_python_sparse
stationery/apps/accounts/models.py
minidron/stationery
train
0
0ac6044b2c4c86291768f2c820e5037f47242f2f
[ "if inputFile.sample != None:\n outDir = inputFile.sample.outputDir\nelse:\n outDir = inputFile.pool.outputDir\nif inputFile.fileName.endswith('.tar.gz'):\n return self._extractTarGz(inputFile, outDir)\nelif inputFile.fileName.endswith('.gz'):\n return self._extractGz(inputFile, outDir)\nelse:\n rais...
<|body_start_0|> if inputFile.sample != None: outDir = inputFile.sample.outputDir else: outDir = inputFile.pool.outputDir if inputFile.fileName.endswith('.tar.gz'): return self._extractTarGz(inputFile, outDir) elif inputFile.fileName.endswith('.gz'): ...
The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi
Decompressor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decompressor: """The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi""" def extract(self, inputFile): """This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is ...
stack_v2_sparse_classes_75kplus_train_000099
2,548
no_license
[ { "docstring": "This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is called :param inputFile: The compressed .gz or . tar.gz file which has to be extracted :type inputFile: instance of a child object of the :py:class:`File.File` object :returns...
3
stack_v2_sparse_classes_30k_train_047506
Implement the Python class `Decompressor` described below. Class description: The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi Method signatures and docstrings: - def extract(self, inputFile): This function calls extractGz if the file .gz compressed, if thi...
Implement the Python class `Decompressor` described below. Class description: The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi Method signatures and docstrings: - def extract(self, inputFile): This function calls extractGz if the file .gz compressed, if thi...
53315eca821785aa02218e903b60921ecf18246b
<|skeleton|> class Decompressor: """The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi""" def extract(self, inputFile): """This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Decompressor: """The Decompressor class regulates all Decompress functions .. module:: programs .. moduleauthor:: Jetse Jacobi""" def extract(self, inputFile): """This function calls extractGz if the file .gz compressed, if this file is .tar.gz compressed, the method extractTarGz is called :param...
the_stack_v2_python_sparse
pythonCodebase/src/programs/Decompressor.py
JJacobi13/VLPB
train
0