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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ff8030efdd399085c27a372308e5480d2f6d5fc | [
"if _cfg.server_backend == 'cassandra':\n clear_graph()\nelse:\n Gremlin().gremlin_post('graph.truncateBackend();')\nInsertData(gremlin='gremlin_alg_03.txt').gremlin_graph()",
"body = {}\ncode, res = Algorithm().post_weak_connected_component(body, auth=auth)\nid = res['task_id']\nif id > 0:\n result = ge... | <|body_start_0|>
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_alg_03.txt').gremlin_graph()
<|end_body_0|>
<|body_start_1|>
body = {}
code, res = Algorithm().post_... | weak_connected_component 接口 | TestWeakConnectedComponent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestWeakConnectedComponent:
"""weak_connected_component 接口"""
def setup(self):
"""case 开始"""
<|body_0|>
def test_weakConnectedComponent_01(self):
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if _cfg.server_backend == 'cassandra':
... | stack_v2_sparse_classes_75kplus_train_005400 | 1,447 | no_license | [
{
"docstring": "case 开始",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": ":return:",
"name": "test_weakConnectedComponent_01",
"signature": "def test_weakConnectedComponent_01(self)"
}
] | 2 | null | Implement the Python class `TestWeakConnectedComponent` described below.
Class description:
weak_connected_component 接口
Method signatures and docstrings:
- def setup(self): case 开始
- def test_weakConnectedComponent_01(self): :return: | Implement the Python class `TestWeakConnectedComponent` described below.
Class description:
weak_connected_component 接口
Method signatures and docstrings:
- def setup(self): case 开始
- def test_weakConnectedComponent_01(self): :return:
<|skeleton|>
class TestWeakConnectedComponent:
"""weak_connected_component 接口""... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class TestWeakConnectedComponent:
"""weak_connected_component 接口"""
def setup(self):
"""case 开始"""
<|body_0|>
def test_weakConnectedComponent_01(self):
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestWeakConnectedComponent:
"""weak_connected_component 接口"""
def setup(self):
"""case 开始"""
if _cfg.server_backend == 'cassandra':
clear_graph()
else:
Gremlin().gremlin_post('graph.truncateBackend();')
InsertData(gremlin='gremlin_alg_03.txt').greml... | the_stack_v2_python_sparse | src/graph_function_test/server/algorithm_olap/test_weakConnectedComponent.py | hugegraph/hugegraph-test | train | 1 |
f2acc81bdafcb72dbc9753477a78cbbdaf72742f | [
"s = pandas.HDFStore(path_or_buf)\ngroups = s.groups()\nif len(groups) == 0:\n raise ValueError('No dataset in HDF5 file.')\ncandidate_only_group = groups[0]\nformat = getattr(candidate_only_group._v_attrs, 'table_type', None)\ns.close()\nreturn format",
"if cls._validate_hdf_format(path_or_buf=path_or_buf) is... | <|body_start_0|>
s = pandas.HDFStore(path_or_buf)
groups = s.groups()
if len(groups) == 0:
raise ValueError('No dataset in HDF5 file.')
candidate_only_group = groups[0]
format = getattr(candidate_only_group._v_attrs, 'table_type', None)
s.close()
retur... | Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class. | HDFDispatcher | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDFDispatcher:
"""Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class."""
def _validate_hdf_format(cls, path_or_buf):
"""Validate `path_or_buf` and then return `table_type` parameter of store group ... | stack_v2_sparse_classes_75kplus_train_005401 | 3,478 | permissive | [
{
"docstring": "Validate `path_or_buf` and then return `table_type` parameter of store group attribute. Parameters ---------- path_or_buf : str, buffer or path object Path to the file to open, or an open :class:`pandas.HDFStore` object. Returns ------- str `table_type` parameter of store group attribute.",
... | 2 | stack_v2_sparse_classes_30k_train_029677 | Implement the Python class `HDFDispatcher` described below.
Class description:
Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class.
Method signatures and docstrings:
- def _validate_hdf_format(cls, path_or_buf): Validate `path_or_bu... | Implement the Python class `HDFDispatcher` described below.
Class description:
Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class.
Method signatures and docstrings:
- def _validate_hdf_format(cls, path_or_buf): Validate `path_or_bu... | 8f6e00378e095817deccd25f4140406c5ee6c992 | <|skeleton|>
class HDFDispatcher:
"""Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class."""
def _validate_hdf_format(cls, path_or_buf):
"""Validate `path_or_buf` and then return `table_type` parameter of store group ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HDFDispatcher:
"""Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class."""
def _validate_hdf_format(cls, path_or_buf):
"""Validate `path_or_buf` and then return `table_type` parameter of store group attribute. Pa... | the_stack_v2_python_sparse | modin/core/io/column_stores/hdf_dispatcher.py | modin-project/modin | train | 9,241 |
43cccbce5d9fb7a31cfb7f142253a564ebbd7505 | [
"user = User.objects.filter(email__iexact=attrs.get('email')).first()\nif user is None:\n msg = _('Sorry, email not found.')\n raise ValidationError(msg)\nattrs['user'] = user\nreturn attrs",
"forget_password = ForgetPassword(user=validated_data['user'])\nforget_password.save()\nreturn forget_password"
] | <|body_start_0|>
user = User.objects.filter(email__iexact=attrs.get('email')).first()
if user is None:
msg = _('Sorry, email not found.')
raise ValidationError(msg)
attrs['user'] = user
return attrs
<|end_body_0|>
<|body_start_1|>
forget_password = Forget... | The serializer for ForgetPassword Objects | ForgetPasswordSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForgetPasswordSerializer:
"""The serializer for ForgetPassword Objects"""
def validate(self, attrs):
"""Check if the email is found and it is verified :param attrs: :return:"""
<|body_0|>
def create(self, validated_data):
"""create a ForgetPassword that contains ... | stack_v2_sparse_classes_75kplus_train_005402 | 1,480 | permissive | [
{
"docstring": "Check if the email is found and it is verified :param attrs: :return:",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "create a ForgetPassword that contains a key to send to the user in order to enter a new password :param validated_data: :return:... | 2 | stack_v2_sparse_classes_30k_train_038448 | Implement the Python class `ForgetPasswordSerializer` described below.
Class description:
The serializer for ForgetPassword Objects
Method signatures and docstrings:
- def validate(self, attrs): Check if the email is found and it is verified :param attrs: :return:
- def create(self, validated_data): create a ForgetPa... | Implement the Python class `ForgetPasswordSerializer` described below.
Class description:
The serializer for ForgetPassword Objects
Method signatures and docstrings:
- def validate(self, attrs): Check if the email is found and it is verified :param attrs: :return:
- def create(self, validated_data): create a ForgetPa... | 73d3c40aa449eec5acc59d4493ee94059bddabbd | <|skeleton|>
class ForgetPasswordSerializer:
"""The serializer for ForgetPassword Objects"""
def validate(self, attrs):
"""Check if the email is found and it is verified :param attrs: :return:"""
<|body_0|>
def create(self, validated_data):
"""create a ForgetPassword that contains ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ForgetPasswordSerializer:
"""The serializer for ForgetPassword Objects"""
def validate(self, attrs):
"""Check if the email is found and it is verified :param attrs: :return:"""
user = User.objects.filter(email__iexact=attrs.get('email')).first()
if user is None:
msg = ... | the_stack_v2_python_sparse | libs/core/users/api/serializers/ForgetPasswordSerializer.py | nileshkorpad1/WebDjangular | train | 0 |
4e17aa8262896e3213f5fd73711b86d8bd5dc07f | [
"self.m = abs(int(num_row))\nself.n = abs(int(num_col))\nself.dis = str(distribution)\nif self.dis == 'gaussian':\n self.mu = np.zeros((self.m, self.n))\n self.sigma = np.ones((self.m, self.n))",
"times = abs(int(times))\nself.bootstrap_matrix = []\nif self.dis == 'gaussian':\n for _ in range(times):\n ... | <|body_start_0|>
self.m = abs(int(num_row))
self.n = abs(int(num_col))
self.dis = str(distribution)
if self.dis == 'gaussian':
self.mu = np.zeros((self.m, self.n))
self.sigma = np.ones((self.m, self.n))
<|end_body_0|>
<|body_start_1|>
times = abs(int(time... | Weight | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Weight:
def __init__(self, num_row, num_col, distribution='gaussian'):
"""Creates a Weight class and saves it in the variable "weight_matrix" in class Network. @param num_row: The number of rows there will be in the weight matrix. @param num_col: The number of columns there will be in th... | stack_v2_sparse_classes_75kplus_train_005403 | 4,650 | permissive | [
{
"docstring": "Creates a Weight class and saves it in the variable \"weight_matrix\" in class Network. @param num_row: The number of rows there will be in the weight matrix. @param num_col: The number of columns there will be in the weight matrix. @param distribution: The distribution class Bias follows. Defau... | 5 | stack_v2_sparse_classes_30k_train_009541 | Implement the Python class `Weight` described below.
Class description:
Implement the Weight class.
Method signatures and docstrings:
- def __init__(self, num_row, num_col, distribution='gaussian'): Creates a Weight class and saves it in the variable "weight_matrix" in class Network. @param num_row: The number of row... | Implement the Python class `Weight` described below.
Class description:
Implement the Weight class.
Method signatures and docstrings:
- def __init__(self, num_row, num_col, distribution='gaussian'): Creates a Weight class and saves it in the variable "weight_matrix" in class Network. @param num_row: The number of row... | 439d3b3778903c4ccfea9285d18d400bf498036f | <|skeleton|>
class Weight:
def __init__(self, num_row, num_col, distribution='gaussian'):
"""Creates a Weight class and saves it in the variable "weight_matrix" in class Network. @param num_row: The number of rows there will be in the weight matrix. @param num_col: The number of columns there will be in th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Weight:
def __init__(self, num_row, num_col, distribution='gaussian'):
"""Creates a Weight class and saves it in the variable "weight_matrix" in class Network. @param num_row: The number of rows there will be in the weight matrix. @param num_col: The number of columns there will be in the weight matri... | the_stack_v2_python_sparse | residual-sample-nn/Weight.py | vinceLuong/residual-sample-nn | train | 2 | |
b9f5d9813e43dd7de3606aeac778cdfa6395723c | [
"event_id = request.GET.get('event_id')\ntry:\n event = Event.objects.get(id=event_id)\nexcept:\n logger.log_error(f'Invalid event id {event_id} entered for getting presigned url')\n return api_error_response(message='Event is not valid', status=400)\nimage_name = event.images\nbucket = BUCKET\nobject_name... | <|body_start_0|>
event_id = request.GET.get('event_id')
try:
event = Event.objects.get(id=event_id)
except:
logger.log_error(f'Invalid event id {event_id} entered for getting presigned url')
return api_error_response(message='Event is not valid', status=400)
... | Api for presigned url created here | PresignedUrl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PresignedUrl:
"""Api for presigned url created here"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
event_id = request.GET.... | stack_v2_sparse_classes_75kplus_train_005404 | 2,040 | no_license | [
{
"docstring": ":param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": ":param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021313 | Implement the Python class `PresignedUrl` described below.
Class description:
Api for presigned url created here
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return: | Implement the Python class `PresignedUrl` described below.
Class description:
Api for presigned url created here
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return:
<|skeleton|>
class PresignedUrl:
"""Api for presigned url creat... | b76de21b3318ab24e1add18a9aa4f437ed02e10e | <|skeleton|>
class PresignedUrl:
"""Api for presigned url created here"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PresignedUrl:
"""Api for presigned url created here"""
def get(self, request):
""":param request: :return:"""
event_id = request.GET.get('event_id')
try:
event = Event.objects.get(id=event_id)
except:
logger.log_error(f'Invalid event id {event_id} e... | the_stack_v2_python_sparse | core/presigned_url.py | ameyk20/eon-backend | train | 0 |
a93985f62cb809f5cfa8b50b693db9caef6b93e9 | [
"super().set_params(params)\nparams = dict_to_namespace(params)\nself.params.name = getattr(params, 'name', 'MesAcqFunction')\nself.params.opt_mode = getattr(params, 'opt_mode', 'max')",
"with Timer(f'Compute acquisition function for a batch of {len(x_list)} points'):\n mu, std = self.model.get_post_mu_cov(x_l... | <|body_start_0|>
super().set_params(params)
params = dict_to_namespace(params)
self.params.name = getattr(params, 'name', 'MesAcqFunction')
self.params.opt_mode = getattr(params, 'opt_mode', 'max')
<|end_body_0|>
<|body_start_1|>
with Timer(f'Compute acquisition function for a b... | Class for max-value entropy search acquisition functions. | MesAcqFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MesAcqFunction:
"""Class for max-value entropy search acquisition functions."""
def set_params(self, params):
"""Set self.params, the parameters for the AcqFunction."""
<|body_0|>
def get_acq_list_batch(self, x_list):
"""Return acquisition function for a batch of... | stack_v2_sparse_classes_75kplus_train_005405 | 26,407 | no_license | [
{
"docstring": "Set self.params, the parameters for the AcqFunction.",
"name": "set_params",
"signature": "def set_params(self, params)"
},
{
"docstring": "Return acquisition function for a batch of inputs x_list.",
"name": "get_acq_list_batch",
"signature": "def get_acq_list_batch(self,... | 2 | stack_v2_sparse_classes_30k_train_045695 | Implement the Python class `MesAcqFunction` described below.
Class description:
Class for max-value entropy search acquisition functions.
Method signatures and docstrings:
- def set_params(self, params): Set self.params, the parameters for the AcqFunction.
- def get_acq_list_batch(self, x_list): Return acquisition fu... | Implement the Python class `MesAcqFunction` described below.
Class description:
Class for max-value entropy search acquisition functions.
Method signatures and docstrings:
- def set_params(self, params): Set self.params, the parameters for the AcqFunction.
- def get_acq_list_batch(self, x_list): Return acquisition fu... | d75d1a89bb566e62662e4d010d91893bfe1ee9f4 | <|skeleton|>
class MesAcqFunction:
"""Class for max-value entropy search acquisition functions."""
def set_params(self, params):
"""Set self.params, the parameters for the AcqFunction."""
<|body_0|>
def get_acq_list_batch(self, x_list):
"""Return acquisition function for a batch of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MesAcqFunction:
"""Class for max-value entropy search acquisition functions."""
def set_params(self, params):
"""Set self.params, the parameters for the AcqFunction."""
super().set_params(params)
params = dict_to_namespace(params)
self.params.name = getattr(params, 'name',... | the_stack_v2_python_sparse | bax/acq/acquisition.py | willieneis/bayesian-algorithm-execution | train | 45 |
739c3b2989434fdac35edf6948c601c59db85d42 | [
"if not PIL:\n raise ImportError('ImageHash pipeline is not available - install \"pipeline\" extra to enable')\nself.algorithm = algorithm\nself.size = size\nself.strings = strings",
"values = [images] if not isinstance(images, list) else images\nvalues = [Image.open(image) if isinstance(image, str) else image... | <|body_start_0|>
if not PIL:
raise ImportError('ImageHash pipeline is not available - install "pipeline" extra to enable')
self.algorithm = algorithm
self.size = size
self.strings = strings
<|end_body_0|>
<|body_start_1|>
values = [images] if not isinstance(images, l... | Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images. | ImageHash | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageHash:
"""Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images."""
def __init__(self, algorithm='average', size=8, strings=True):
"""C... | stack_v2_sparse_classes_75kplus_train_005406 | 2,546 | permissive | [
{
"docstring": "Creates an ImageHash pipeline. Args: algorithm: image hashing algorithm (average, perceptual, difference, wavelet, color) size: hash size strings: outputs hex strings if True (default), otherwise the pipeline returns numpy arrays",
"name": "__init__",
"signature": "def __init__(self, alg... | 3 | stack_v2_sparse_classes_30k_train_010918 | Implement the Python class `ImageHash` described below.
Class description:
Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images.
Method signatures and docstrings:
- def __i... | Implement the Python class `ImageHash` described below.
Class description:
Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images.
Method signatures and docstrings:
- def __i... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class ImageHash:
"""Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images."""
def __init__(self, algorithm='average', size=8, strings=True):
"""C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageHash:
"""Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images."""
def __init__(self, algorithm='average', size=8, strings=True):
"""Creates an Ima... | the_stack_v2_python_sparse | src/python/txtai/pipeline/image/imagehash.py | neuml/txtai | train | 4,804 |
3f590307c4e50d1541efba93db3325a8e347bd33 | [
"keypair_name = 'instancekey_{0}'.format(randint(100, 1000))\nself.instance_keypair = self.os_conn.create_key(key_name=keypair_name)\nlogger.info('New keypair \"{0}\" was created'.format(keypair_name))\nzone = self.os_conn.nova.availability_zones.find(zoneName='nova')\nhosts = zone.hosts.keys()[:2]\nlogger.info('Ad... | <|body_start_0|>
keypair_name = 'instancekey_{0}'.format(randint(100, 1000))
self.instance_keypair = self.os_conn.create_key(key_name=keypair_name)
logger.info('New keypair "{0}" was created'.format(keypair_name))
zone = self.os_conn.nova.availability_zones.find(zoneName='nova')
... | Check restarts of openvswitch-agents. | TestOVSRestartTwoSeparateVms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOVSRestartTwoSeparateVms:
"""Check restarts of openvswitch-agents."""
def _prepare_openstack(self):
"""Prepare OpenStack for scenarios run Steps: 1. Update default security group if needed 2. Create CONFIG 1: Network: test_net_05 SubNetw: test_net_05__subnet, 192.168.5.0/24 Route... | stack_v2_sparse_classes_75kplus_train_005407 | 41,546 | no_license | [
{
"docstring": "Prepare OpenStack for scenarios run Steps: 1. Update default security group if needed 2. Create CONFIG 1: Network: test_net_05 SubNetw: test_net_05__subnet, 192.168.5.0/24 Router: test_router_05 3. Create CONFIG 2: Network: test_net_06 SubNetw: test_net_06__subnet, 192.168.6.0/24 Router: test_ro... | 2 | stack_v2_sparse_classes_30k_train_004688 | Implement the Python class `TestOVSRestartTwoSeparateVms` described below.
Class description:
Check restarts of openvswitch-agents.
Method signatures and docstrings:
- def _prepare_openstack(self): Prepare OpenStack for scenarios run Steps: 1. Update default security group if needed 2. Create CONFIG 1: Network: test_... | Implement the Python class `TestOVSRestartTwoSeparateVms` described below.
Class description:
Check restarts of openvswitch-agents.
Method signatures and docstrings:
- def _prepare_openstack(self): Prepare OpenStack for scenarios run Steps: 1. Update default security group if needed 2. Create CONFIG 1: Network: test_... | 8aced2855b78b5f123195d188c80e27b43888a2e | <|skeleton|>
class TestOVSRestartTwoSeparateVms:
"""Check restarts of openvswitch-agents."""
def _prepare_openstack(self):
"""Prepare OpenStack for scenarios run Steps: 1. Update default security group if needed 2. Create CONFIG 1: Network: test_net_05 SubNetw: test_net_05__subnet, 192.168.5.0/24 Route... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestOVSRestartTwoSeparateVms:
"""Check restarts of openvswitch-agents."""
def _prepare_openstack(self):
"""Prepare OpenStack for scenarios run Steps: 1. Update default security group if needed 2. Create CONFIG 1: Network: test_net_05 SubNetw: test_net_05__subnet, 192.168.5.0/24 Router: test_route... | the_stack_v2_python_sparse | mos_tests/neutron/python_tests/test_ovs_restart.py | Mirantis/mos-integration-tests | train | 16 |
a23cd4d90338cf67c3466c238547fd7b09d858c1 | [
"self.fig = Figure(figsize=(width / dpi, height / dpi), dpi=dpi)\nself.fcqt = FigureCanvasQT(self.fig)\nself.ax = self.fcqt.figure.subplots()\nFigureCanvasQTAgg.__init__(self, self.fcqt.figure)\nFigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)\nFigureCanvasQTAgg.updateGeometry(sel... | <|body_start_0|>
self.fig = Figure(figsize=(width / dpi, height / dpi), dpi=dpi)
self.fcqt = FigureCanvasQT(self.fig)
self.ax = self.fcqt.figure.subplots()
FigureCanvasQTAgg.__init__(self, self.fcqt.figure)
FigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.... | The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax (matplotlib.axes.Axes): Axes of th... | BCanvas | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCanvas:
"""The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax... | stack_v2_sparse_classes_75kplus_train_005408 | 22,292 | permissive | [
{
"docstring": "Initialization of the Bathymetry canvas. It makes a bridge between Matplotlib and the window, creates the figure to display and then show statically or dynamically the figure. Args: parent (QWidget): Parent of the canvas (default: None). width (int): Width of the canvas (default: 800). height (i... | 4 | stack_v2_sparse_classes_30k_train_030517 | Implement the Python class `BCanvas` described below.
Class description:
The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvas... | Implement the Python class `BCanvas` described below.
Class description:
The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvas... | 0b39cd5e499f6168f10906d29ef826ab9aaa45c4 | <|skeleton|>
class BCanvas:
"""The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BCanvas:
"""The Bathymetry canvas (static and dynamic). The canvas can be either static of dynamic, depending on the Start/Stop button's state Attributes: fig (matplotlib.figure.Figure): TimeStack figure. fcqt (matplotlib.backends.backend_qt5agg.FigureCanvasQT): the PyQT canvas for Matplotlib. ax (matplotlib.... | the_stack_v2_python_sparse | src/graphics/ApplicationWindow.py | GregoireThoumyre/Bathymetry-Inversion | train | 1 |
37bb3fb27b22760d6bac1c34dbb456389756d54c | [
"i = len(nums) - 2\nwhile i >= 0:\n if nums[i] < nums[i + 1]:\n break\n i -= 1\nif i < 0:\n nums.reverse()\n return\nl = -1\nfor j in reversed(range(i, len(nums))):\n if nums[j] > nums[i]:\n l = j\n break\nnums[i], nums[l] = (nums[l], nums[i])\nnums[i + 1:] = sorted(nums[i + 1:])... | <|body_start_0|>
i = len(nums) - 2
while i >= 0:
if nums[i] < nums[i + 1]:
break
i -= 1
if i < 0:
nums.reverse()
return
l = -1
for j in reversed(range(i, len(nums))):
if nums[j] > nums[i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def prevPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place in... | stack_v2_sparse_classes_75kplus_train_005409 | 2,250 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermutation(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def prevPermutation(self, nums): :type nums: List[int]... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
- def prevPermutation(self, nums): :type nums: List[int]... | 7de5f69e6e44ca4e74d75fed2af390b3d2cbd2b9 | <|skeleton|>
class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def prevPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextPermutation(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
i = len(nums) - 2
while i >= 0:
if nums[i] < nums[i + 1]:
break
i -= 1
if i < 0:
nums.re... | the_stack_v2_python_sparse | interview/facebook/mid/LC31. Next Permutation.py | zhangshv123/superjump | train | 1 | |
c24a333d4228d3898e8d0ab20b12c8120265dd08 | [
"result = 1\nfor a in args:\n result = result * a\nreturn result",
"if name == 'product':\n return cls(cls.product).get\nelse:\n raise NotImplementedError"
] | <|body_start_0|>
result = 1
for a in args:
result = result * a
return result
<|end_body_0|>
<|body_start_1|>
if name == 'product':
return cls(cls.product).get
else:
raise NotImplementedError
<|end_body_1|>
| Fuzzy norms (conjunctions). | SNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SNorm:
"""Fuzzy norms (conjunctions)."""
def product(*args):
"""Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands."""
<|body_0|>
def method(cls, name):
"""Returns callable operator of chosen name. Arguments: name Name of the operator: {'prod... | stack_v2_sparse_classes_75kplus_train_005410 | 7,372 | no_license | [
{
"docstring": "Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands.",
"name": "product",
"signature": "def product(*args)"
},
{
"docstring": "Returns callable operator of chosen name. Arguments: name Name of the operator: {'product'}",
"name": "method",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_024106 | Implement the Python class `SNorm` described below.
Class description:
Fuzzy norms (conjunctions).
Method signatures and docstrings:
- def product(*args): Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands.
- def method(cls, name): Returns callable operator of chosen name. Arguments: name Name of... | Implement the Python class `SNorm` described below.
Class description:
Fuzzy norms (conjunctions).
Method signatures and docstrings:
- def product(*args): Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands.
- def method(cls, name): Returns callable operator of chosen name. Arguments: name Name of... | 1c2c3abe50bd9125b105ffd13eef513839f3f9d8 | <|skeleton|>
class SNorm:
"""Fuzzy norms (conjunctions)."""
def product(*args):
"""Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands."""
<|body_0|>
def method(cls, name):
"""Returns callable operator of chosen name. Arguments: name Name of the operator: {'prod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SNorm:
"""Fuzzy norms (conjunctions)."""
def product(*args):
"""Product fuzzy s-norm (conjunction) Arguments: args Sequence of operands."""
result = 1
for a in args:
result = result * a
return result
def method(cls, name):
"""Returns callable opera... | the_stack_v2_python_sparse | monitor/fuzzy.py | martinbenes1996/bc | train | 0 |
ea5eac98686f4395729fa3158cebdda0e467c4d0 | [
"self.cmd_base = cmd_base\nself.env_vars = env_vars.copy() if env_vars is not None else dict()\nself.ros_args = ros_args",
"cmd = self.cmd_base\nfor name, val in self.ros_args.items():\n cmd += f' {name}:={val}'\nreturn cmd",
"for var, val in self.env_vars.items():\n os.environ[var] = str(val)\nprocess = ... | <|body_start_0|>
self.cmd_base = cmd_base
self.env_vars = env_vars.copy() if env_vars is not None else dict()
self.ros_args = ros_args
<|end_body_0|>
<|body_start_1|>
cmd = self.cmd_base
for name, val in self.ros_args.items():
cmd += f' {name}:={val}'
return ... | Holds data for a ROS command and makes it executable. | ROSCmd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROSCmd:
"""Holds data for a ROS command and makes it executable."""
def __init__(self, cmd_base: str, *, env_vars: Dict[str, Any], **ros_args):
"""Initialize ROSCmd. Args: cmd_base: Command string without arguments. env_vars: Environment variables set prior to running the command. ro... | stack_v2_sparse_classes_75kplus_train_005411 | 1,808 | permissive | [
{
"docstring": "Initialize ROSCmd. Args: cmd_base: Command string without arguments. env_vars: Environment variables set prior to running the command. ros_args: ROS arguments passed when running the command.",
"name": "__init__",
"signature": "def __init__(self, cmd_base: str, *, env_vars: Dict[str, Any... | 3 | stack_v2_sparse_classes_30k_train_033492 | Implement the Python class `ROSCmd` described below.
Class description:
Holds data for a ROS command and makes it executable.
Method signatures and docstrings:
- def __init__(self, cmd_base: str, *, env_vars: Dict[str, Any], **ros_args): Initialize ROSCmd. Args: cmd_base: Command string without arguments. env_vars: E... | Implement the Python class `ROSCmd` described below.
Class description:
Holds data for a ROS command and makes it executable.
Method signatures and docstrings:
- def __init__(self, cmd_base: str, *, env_vars: Dict[str, Any], **ros_args): Initialize ROSCmd. Args: cmd_base: Command string without arguments. env_vars: E... | 8a9438b5a24c288721ae0302889fe55e26046310 | <|skeleton|>
class ROSCmd:
"""Holds data for a ROS command and makes it executable."""
def __init__(self, cmd_base: str, *, env_vars: Dict[str, Any], **ros_args):
"""Initialize ROSCmd. Args: cmd_base: Command string without arguments. env_vars: Environment variables set prior to running the command. ro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ROSCmd:
"""Holds data for a ROS command and makes it executable."""
def __init__(self, cmd_base: str, *, env_vars: Dict[str, Any], **ros_args):
"""Initialize ROSCmd. Args: cmd_base: Command string without arguments. env_vars: Environment variables set prior to running the command. ros_args: ROS a... | the_stack_v2_python_sparse | simulation/utils/basics/ros_cmd.py | KITcar-Team/kitcar-gazebo-simulation | train | 19 |
d3b7949bf307de3672b29b9cb80c1d064ecddc87 | [
"super().__init__()\nself.embed = get_embeddings(embed)\nself.embed_scale = math.sqrt(d_model)\nself.pos_embed = pos_embed\nself.num_layers = num_layers\nself.d_model = d_model\nself.n_head = n_head\nself.dim_ff = dim_ff\nself.dropout = dropout\nself.input_fc = nn.Linear(self.embed.embedding_dim, d_model)\nself.lay... | <|body_start_0|>
super().__init__()
self.embed = get_embeddings(embed)
self.embed_scale = math.sqrt(d_model)
self.pos_embed = pos_embed
self.num_layers = num_layers
self.d_model = d_model
self.n_head = n_head
self.dim_ff = dim_ff
self.dropout = dro... | LinearTransformerEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearTransformerEncoder:
def __init__(self, embed: Union[nn.Module, StaticEmbedding, Tuple[int, int]], pos_embed=None, num_layers=6, d_model=512, n_head=8, dim_ff=2048, dropout=0.1):
"""基于Transformer的Encoder :param embed: encoder输入token的embedding :param nn.Module pos_embed: position emb... | stack_v2_sparse_classes_75kplus_train_005412 | 4,348 | no_license | [
{
"docstring": "基于Transformer的Encoder :param embed: encoder输入token的embedding :param nn.Module pos_embed: position embedding :param int num_layers: 多少层的encoder :param int d_model: 输入输出的维度 :param int n_head: 多少个head :param int dim_ff: FFN中间的维度大小 :param float dropout: Attention和FFN的dropout大小",
"name": "__init_... | 2 | stack_v2_sparse_classes_30k_train_009014 | Implement the Python class `LinearTransformerEncoder` described below.
Class description:
Implement the LinearTransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, embed: Union[nn.Module, StaticEmbedding, Tuple[int, int]], pos_embed=None, num_layers=6, d_model=512, n_head=8, dim_ff=2048, dr... | Implement the Python class `LinearTransformerEncoder` described below.
Class description:
Implement the LinearTransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, embed: Union[nn.Module, StaticEmbedding, Tuple[int, int]], pos_embed=None, num_layers=6, d_model=512, n_head=8, dim_ff=2048, dr... | 5410533becf267a655d4a37b380e330d55df1de0 | <|skeleton|>
class LinearTransformerEncoder:
def __init__(self, embed: Union[nn.Module, StaticEmbedding, Tuple[int, int]], pos_embed=None, num_layers=6, d_model=512, n_head=8, dim_ff=2048, dropout=0.1):
"""基于Transformer的Encoder :param embed: encoder输入token的embedding :param nn.Module pos_embed: position emb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearTransformerEncoder:
def __init__(self, embed: Union[nn.Module, StaticEmbedding, Tuple[int, int]], pos_embed=None, num_layers=6, d_model=512, n_head=8, dim_ff=2048, dropout=0.1):
"""基于Transformer的Encoder :param embed: encoder输入token的embedding :param nn.Module pos_embed: position embedding :param ... | the_stack_v2_python_sparse | modules/encoder.py | xyltt/Linear-Transformer | train | 10 | |
0d0359bd81af146d883dd4119fa71dc2fe4897f9 | [
"n = len(nums)\nif n == 0:\n return 0\ndp = [1] * n\nfor i in range(n):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"def binary_search(a, num):\n l, r = (0, len(a) - 1)\n while l <= r:\n m = l + (r - l) // 2\n if a[m - ... | <|body_start_0|>
n = len(nums)
if n == 0:
return 0
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1|>
def binary... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Running Time: O(n^2) where n is the length of nums."""
<|body_0|>
def lengthOfLIS_2(self, nums: List[int]) -> int:
"""Binary search Running Time: O(n log n) where n is the length of nums."""
<|bod... | stack_v2_sparse_classes_75kplus_train_005413 | 1,260 | permissive | [
{
"docstring": "DP Running Time: O(n^2) where n is the length of nums.",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums: List[int]) -> int"
},
{
"docstring": "Binary search Running Time: O(n log n) where n is the length of nums.",
"name": "lengthOfLIS_2",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_009708 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: DP Running Time: O(n^2) where n is the length of nums.
- def lengthOfLIS_2(self, nums: List[int]) -> int: Binary search Running Tim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: DP Running Time: O(n^2) where n is the length of nums.
- def lengthOfLIS_2(self, nums: List[int]) -> int: Binary search Running Tim... | 4a508a982b125a3a90ea893ae70863df7c99cc70 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Running Time: O(n^2) where n is the length of nums."""
<|body_0|>
def lengthOfLIS_2(self, nums: List[int]) -> int:
"""Binary search Running Time: O(n log n) where n is the length of nums."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Running Time: O(n^2) where n is the length of nums."""
n = len(nums)
if n == 0:
return 0
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
... | the_stack_v2_python_sparse | solutions/300_longest_increasing_subsequence.py | YiqunPeng/leetcode_pro | train | 0 | |
77fbbdf098a92185e8e5c86e99ee6f65aa1404c9 | [
"pygame.sprite.Sprite.__init__(self)\nself.image, self.rect = utils.load_image('sprites/key.png', colorkey=(255, 255, 255))\nself.mask = pygame.mask.from_surface(self.image)\nself.offset = (500, 400)",
"mx, my = game.maze.rect.topleft\nself.rect.center = (mx + self.offset[0], my + self.offset[1])\nif self.mask:\n... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = utils.load_image('sprites/key.png', colorkey=(255, 255, 255))
self.mask = pygame.mask.from_surface(self.image)
self.offset = (500, 400)
<|end_body_0|>
<|body_start_1|>
mx, my = game.maze.rect.topleft
... | Key | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Key:
def __init__(self):
"""Key object. A key used to unlock the end of the maze"""
<|body_0|>
def update(self):
"""Sprite update method. Executed every loop of the mainloop."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pygame.sprite.Sprite.__ini... | stack_v2_sparse_classes_75kplus_train_005414 | 1,163 | no_license | [
{
"docstring": "Key object. A key used to unlock the end of the maze",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Sprite update method. Executed every loop of the mainloop.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014994 | Implement the Python class `Key` described below.
Class description:
Implement the Key class.
Method signatures and docstrings:
- def __init__(self): Key object. A key used to unlock the end of the maze
- def update(self): Sprite update method. Executed every loop of the mainloop. | Implement the Python class `Key` described below.
Class description:
Implement the Key class.
Method signatures and docstrings:
- def __init__(self): Key object. A key used to unlock the end of the maze
- def update(self): Sprite update method. Executed every loop of the mainloop.
<|skeleton|>
class Key:
def __... | 6cd858c0e3f9a75c4e48398fbcf8e3fe820e3df7 | <|skeleton|>
class Key:
def __init__(self):
"""Key object. A key used to unlock the end of the maze"""
<|body_0|>
def update(self):
"""Sprite update method. Executed every loop of the mainloop."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Key:
def __init__(self):
"""Key object. A key used to unlock the end of the maze"""
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = utils.load_image('sprites/key.png', colorkey=(255, 255, 255))
self.mask = pygame.mask.from_surface(self.image)
self.offset = (... | the_stack_v2_python_sparse | game/sprites/Key.py | AM2i9/apcs-final-project | train | 0 | |
7c294c98568c18ef93b773a5b5236442d0469a1a | [
"points = sorted(points, key=lambda x: x[1])\nres, end = (0, -float('inf'))\nfor interval in points:\n if interval[0] > end:\n res += 1\n end = interval[1]\nreturn res",
"if not points:\n return 0\npoints.sort()\nresult = 0\ni = 0\nwhile i < len(points):\n j = i + 1\n right_bound = point... | <|body_start_0|>
points = sorted(points, key=lambda x: x[1])
res, end = (0, -float('inf'))
for interval in points:
if interval[0] > end:
res += 1
end = interval[1]
return res
<|end_body_0|>
<|body_start_1|>
if not points:
r... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def findMinArrowShots2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
points = sor... | stack_v2_sparse_classes_75kplus_train_005415 | 4,349 | permissive | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "findMinArrowShots2",
"signature": "def findMinArrowShots2(self, points)"
}... | 2 | stack_v2_sparse_classes_30k_train_025753 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def findMinArrowShots2(self, points): :type points: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def findMinArrowShots2(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|>
cla... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def findMinArrowShots2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
points = sorted(points, key=lambda x: x[1])
res, end = (0, -float('inf'))
for interval in points:
if interval[0] > end:
res += 1
end = inte... | the_stack_v2_python_sparse | cs15211/MinimumNumberOfArrowsToBurstBalloons.py | JulyKikuAkita/PythonPrac | train | 1 | |
b5f44a7547891aaae2178655686e3767d7d3b285 | [
"super(ClassificationLoss, self).__init__()\nself.loss_type = loss_type\nself.focal_loss_fn = FocalLoss()\nself.loss_fn = torch.nn.BCEWithLogitsLoss()\nself.recursive_relation = get_hierarchy_relations(taxonomic_hierarchy, label_map)\nself.recursive_penalty = recursive_penalty\nself.recursive_constraint = recursive... | <|body_start_0|>
super(ClassificationLoss, self).__init__()
self.loss_type = loss_type
self.focal_loss_fn = FocalLoss()
self.loss_fn = torch.nn.BCEWithLogitsLoss()
self.recursive_relation = get_hierarchy_relations(taxonomic_hierarchy, label_map)
self.recursive_penalty = r... | ClassificationLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationLoss:
def __init__(self, taxonomic_hierarchy, label_map, recursive_penalty, recursive_constraint=True, loss_type='bce'):
"""Criterion class, classfication loss & recursive regularization :param taxonomic_hierarchy: Str, file path of hierarchy taxonomy :param label_map: Dict... | stack_v2_sparse_classes_75kplus_train_005416 | 6,278 | permissive | [
{
"docstring": "Criterion class, classfication loss & recursive regularization :param taxonomic_hierarchy: Str, file path of hierarchy taxonomy :param label_map: Dict, label to id :param recursive_penalty: Float, lambda value <- config.train.loss.recursive_regularization.penalty :param recursive_constraint: Boo... | 3 | null | Implement the Python class `ClassificationLoss` described below.
Class description:
Implement the ClassificationLoss class.
Method signatures and docstrings:
- def __init__(self, taxonomic_hierarchy, label_map, recursive_penalty, recursive_constraint=True, loss_type='bce'): Criterion class, classfication loss & recur... | Implement the Python class `ClassificationLoss` described below.
Class description:
Implement the ClassificationLoss class.
Method signatures and docstrings:
- def __init__(self, taxonomic_hierarchy, label_map, recursive_penalty, recursive_constraint=True, loss_type='bce'): Criterion class, classfication loss & recur... | 199ebc6b06b3cce2b3f2298cb9e20f81c01dc7a6 | <|skeleton|>
class ClassificationLoss:
def __init__(self, taxonomic_hierarchy, label_map, recursive_penalty, recursive_constraint=True, loss_type='bce'):
"""Criterion class, classfication loss & recursive regularization :param taxonomic_hierarchy: Str, file path of hierarchy taxonomy :param label_map: Dict... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassificationLoss:
def __init__(self, taxonomic_hierarchy, label_map, recursive_penalty, recursive_constraint=True, loss_type='bce'):
"""Criterion class, classfication loss & recursive regularization :param taxonomic_hierarchy: Str, file path of hierarchy taxonomy :param label_map: Dict, label to id ... | the_stack_v2_python_sparse | train_modules/criterions.py | RuiBai1999/HiMatch | train | 7 | |
63ead2b56773beeb8e9760388e7afb09f99b3130 | [
"filters = ()\nresult = model_admin.get_queryset(request)[:5]\nfor res in result:\n filters = filters + ((res.title, res.title),)\nreturn filters",
"title = self.value()\nprint('query set ... %s' % title)\nif title:\n return queryset.filter(title__contains=title)\nelse:\n return queryset.all()"
] | <|body_start_0|>
filters = ()
result = model_admin.get_queryset(request)[:5]
for res in result:
filters = filters + ((res.title, res.title),)
return filters
<|end_body_0|>
<|body_start_1|>
title = self.value()
print('query set ... %s' % title)
if titl... | 标题过滤器 | TitleFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
"""只显示前5个title作为过滤词"""
<|body_0|>
def queryset(self, request, queryset):
"""过滤方式"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
filters = ()
result = model_admin.get_quer... | stack_v2_sparse_classes_75kplus_train_005417 | 1,665 | no_license | [
{
"docstring": "只显示前5个title作为过滤词",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "过滤方式",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001303 | Implement the Python class `TitleFilter` described below.
Class description:
标题过滤器
Method signatures and docstrings:
- def lookups(self, request, model_admin): 只显示前5个title作为过滤词
- def queryset(self, request, queryset): 过滤方式 | Implement the Python class `TitleFilter` described below.
Class description:
标题过滤器
Method signatures and docstrings:
- def lookups(self, request, model_admin): 只显示前5个title作为过滤词
- def queryset(self, request, queryset): 过滤方式
<|skeleton|>
class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
... | a12ad8144938e96ea33881d29eee7f5ecfe2bd08 | <|skeleton|>
class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
"""只显示前5个title作为过滤词"""
<|body_0|>
def queryset(self, request, queryset):
"""过滤方式"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TitleFilter:
"""标题过滤器"""
def lookups(self, request, model_admin):
"""只显示前5个title作为过滤词"""
filters = ()
result = model_admin.get_queryset(request)[:5]
for res in result:
filters = filters + ((res.title, res.title),)
return filters
def queryset(self, ... | the_stack_v2_python_sparse | wiki/admin.py | ting723/viking | train | 0 |
e03854bf167e891cdae2111754fbedc9f8bea900 | [
"super(UserModelForm, self).__init__(*args, **kwargs)\nfor name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'",
"password = self.cleaned_data['password']\nr_password = self.cleaned_data['r_password']\nif password != r_password:\n raise ValidationError('两次密码输入不一致')\nreturn r_p... | <|body_start_0|>
super(UserModelForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data['password']
r_password = self.cleaned_data['r_password']
... | UserModelForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserModelForm:
def __init__(self, *args, **kwargs):
"""统一给ModelForm字段构建样式 :param args: :param kwargs:"""
<|body_0|>
def clean_r_password(self):
"""钩子函数 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(UserModelForm, self).__init__(*arg... | stack_v2_sparse_classes_75kplus_train_005418 | 2,889 | no_license | [
{
"docstring": "统一给ModelForm字段构建样式 :param args: :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "钩子函数 :return:",
"name": "clean_r_password",
"signature": "def clean_r_password(self)"
}
] | 2 | null | Implement the Python class `UserModelForm` described below.
Class description:
Implement the UserModelForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 统一给ModelForm字段构建样式 :param args: :param kwargs:
- def clean_r_password(self): 钩子函数 :return: | Implement the Python class `UserModelForm` described below.
Class description:
Implement the UserModelForm class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 统一给ModelForm字段构建样式 :param args: :param kwargs:
- def clean_r_password(self): 钩子函数 :return:
<|skeleton|>
class UserModelForm:
... | 49a95679f028e60e758cf25eaa2469d569a472b2 | <|skeleton|>
class UserModelForm:
def __init__(self, *args, **kwargs):
"""统一给ModelForm字段构建样式 :param args: :param kwargs:"""
<|body_0|>
def clean_r_password(self):
"""钩子函数 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserModelForm:
def __init__(self, *args, **kwargs):
"""统一给ModelForm字段构建样式 :param args: :param kwargs:"""
super(UserModelForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
def clean_r_password(self)... | the_stack_v2_python_sparse | rbac/forms/user.py | WuAlin0327/Rbac | train | 1 | |
b0f13d3b13be7bc768d3b8ce635c4c8a5a187102 | [
"assert isinstance(base, (str, pathlib.Path))\nassert isinstance(unique, bool)\nself._base_path = pathlib.Path(base) if isinstance(base, str) else base\nself._unique = unique",
"count_str: str = '' if count == 0 else f' ({count})'\next_str: str = '' if ext is None else f'.{ext}'\nfile_name: pathlib.Path = self._b... | <|body_start_0|>
assert isinstance(base, (str, pathlib.Path))
assert isinstance(unique, bool)
self._base_path = pathlib.Path(base) if isinstance(base, str) else base
self._unique = unique
<|end_body_0|>
<|body_start_1|>
count_str: str = '' if count == 0 else f' ({count})'
... | A file name generator that generates file names in a base path. | BaseFileNameGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFileNameGenerator:
"""A file name generator that generates file names in a base path."""
def __init__(self, base: typing.Union[str, pathlib.Path]='', *, unique: bool=False):
"""Create a new base file name generator. :param base: The base path, current working directory by default... | stack_v2_sparse_classes_75kplus_train_005419 | 5,061 | permissive | [
{
"docstring": "Create a new base file name generator. :param base: The base path, current working directory by default :param unique: Force unique file names",
"name": "__init__",
"signature": "def __init__(self, base: typing.Union[str, pathlib.Path]='', *, unique: bool=False)"
},
{
"docstring"... | 3 | stack_v2_sparse_classes_30k_val_001631 | Implement the Python class `BaseFileNameGenerator` described below.
Class description:
A file name generator that generates file names in a base path.
Method signatures and docstrings:
- def __init__(self, base: typing.Union[str, pathlib.Path]='', *, unique: bool=False): Create a new base file name generator. :param ... | Implement the Python class `BaseFileNameGenerator` described below.
Class description:
A file name generator that generates file names in a base path.
Method signatures and docstrings:
- def __init__(self, base: typing.Union[str, pathlib.Path]='', *, unique: bool=False): Create a new base file name generator. :param ... | bb4e18743dcab017765d09b6ce1c3bba88be073e | <|skeleton|>
class BaseFileNameGenerator:
"""A file name generator that generates file names in a base path."""
def __init__(self, base: typing.Union[str, pathlib.Path]='', *, unique: bool=False):
"""Create a new base file name generator. :param base: The base path, current working directory by default... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseFileNameGenerator:
"""A file name generator that generates file names in a base path."""
def __init__(self, base: typing.Union[str, pathlib.Path]='', *, unique: bool=False):
"""Create a new base file name generator. :param base: The base path, current working directory by default :param uniqu... | the_stack_v2_python_sparse | dax/util/output.py | Ginobilium/dax | train | 0 |
4b653de11fba1d6aa8bfc0f0e14ea998358939b0 | [
"super(NormalizeImage, self).__init__()\nself.mean = mean\nself.std = std\nself.is_scale = is_scale\nself.is_channel_first = is_channel_first\nif not (isinstance(self.mean, list) and isinstance(self.std, list) and isinstance(self.is_scale, bool)):\n raise TypeError('{}: input type is invalid.'.format(self))\nfro... | <|body_start_0|>
super(NormalizeImage, self).__init__()
self.mean = mean
self.std = std
self.is_scale = is_scale
self.is_channel_first = is_channel_first
if not (isinstance(self.mean, list) and isinstance(self.std, list) and isinstance(self.is_scale, bool)):
r... | NormalizeImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], is_scale=True, is_channel_first=False):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
<|body_0|>
def __call__(self, sample, context=None):
"""Normalize ... | stack_v2_sparse_classes_75kplus_train_005420 | 19,057 | permissive | [
{
"docstring": "Args: mean (list): the pixel mean std (list): the pixel variance",
"name": "__init__",
"signature": "def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], is_scale=True, is_channel_first=False)"
},
{
"docstring": "Normalize the image. Operators: 1.(optional) S... | 2 | stack_v2_sparse_classes_30k_train_028309 | Implement the Python class `NormalizeImage` described below.
Class description:
Implement the NormalizeImage class.
Method signatures and docstrings:
- def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], is_scale=True, is_channel_first=False): Args: mean (list): the pixel mean std (list): the pi... | Implement the Python class `NormalizeImage` described below.
Class description:
Implement the NormalizeImage class.
Method signatures and docstrings:
- def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], is_scale=True, is_channel_first=False): Args: mean (list): the pixel mean std (list): the pi... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], is_scale=True, is_channel_first=False):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
<|body_0|>
def __call__(self, sample, context=None):
"""Normalize ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NormalizeImage:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], is_scale=True, is_channel_first=False):
"""Args: mean (list): the pixel mean std (list): the pixel variance"""
super(NormalizeImage, self).__init__()
self.mean = mean
self.std = std
... | the_stack_v2_python_sparse | CV/PaddleReid/reid/data/transform/operators.py | sserdoubleh/Research | train | 10 | |
c0dea813b5b6d49d470983212b489534044b4e23 | [
"try:\n from gensim.models import word2vec\nexcept ModuleNotFoundError:\n raise ImportError('This class requires mol2vec to be installed.')\nself.radius = radius\nself.unseen = unseen\nself.mol2alt_sentence = _mol2alt_sentence\nif pretrain_model_path is None:\n data_dir = get_data_dir()\n pretrain_model... | <|body_start_0|>
try:
from gensim.models import word2vec
except ModuleNotFoundError:
raise ImportError('This class requires mol2vec to be installed.')
self.radius = radius
self.unseen = unseen
self.mol2alt_sentence = _mol2alt_sentence
if pretrain_m... | Mol2Vec fingerprints. This class convert molecules to vector representations by using Mol2Vec. Mol2Vec is an unsupervised machine learning approach to learn vector representations of molecular substructures and the algorithm is based on Word2Vec, which is one of the most popular technique to learn word embeddings using... | Mol2VecFingerprint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mol2VecFingerprint:
"""Mol2Vec fingerprints. This class convert molecules to vector representations by using Mol2Vec. Mol2Vec is an unsupervised machine learning approach to learn vector representations of molecular substructures and the algorithm is based on Word2Vec, which is one of the most po... | stack_v2_sparse_classes_75kplus_train_005421 | 7,587 | permissive | [
{
"docstring": "Parameters ---------- pretrain_file: str, optional The path for pretrained model. If this value is None, we use the model which is put on github repository (https://github.com/samoturk/mol2vec/tree/master/examples/models). The model is trained on 20 million compounds downloaded from ZINC. radius... | 3 | null | Implement the Python class `Mol2VecFingerprint` described below.
Class description:
Mol2Vec fingerprints. This class convert molecules to vector representations by using Mol2Vec. Mol2Vec is an unsupervised machine learning approach to learn vector representations of molecular substructures and the algorithm is based o... | Implement the Python class `Mol2VecFingerprint` described below.
Class description:
Mol2Vec fingerprints. This class convert molecules to vector representations by using Mol2Vec. Mol2Vec is an unsupervised machine learning approach to learn vector representations of molecular substructures and the algorithm is based o... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class Mol2VecFingerprint:
"""Mol2Vec fingerprints. This class convert molecules to vector representations by using Mol2Vec. Mol2Vec is an unsupervised machine learning approach to learn vector representations of molecular substructures and the algorithm is based on Word2Vec, which is one of the most po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mol2VecFingerprint:
"""Mol2Vec fingerprints. This class convert molecules to vector representations by using Mol2Vec. Mol2Vec is an unsupervised machine learning approach to learn vector representations of molecular substructures and the algorithm is based on Word2Vec, which is one of the most popular techniq... | the_stack_v2_python_sparse | deepchem/feat/molecule_featurizers/mol2vec_fingerprint.py | deepchem/deepchem | train | 4,876 |
74f9eafdea97ac8b9552b795b3af81549c804fc5 | [
"current_user = request.user\nhighlight_data = request.data.get('highlight_data', {})\ntry:\n article = Articles.objects.get(slug=slug)\nexcept Articles.DoesNotExist:\n return Response({'errors': HIGHLIGHT_MSGS['ARTICLE_NOT_FOUND']}, status=status.HTTP_404_NOT_FOUND)\nhighlights = Highlights.objects.filter(ar... | <|body_start_0|>
current_user = request.user
highlight_data = request.data.get('highlight_data', {})
try:
article = Articles.objects.get(slug=slug)
except Articles.DoesNotExist:
return Response({'errors': HIGHLIGHT_MSGS['ARTICLE_NOT_FOUND']}, status=status.HTTP_40... | Provide methods for creating a highlight | CreateGetDeleteMyHighlightsAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateGetDeleteMyHighlightsAPIView:
"""Provide methods for creating a highlight"""
def get(self, request, slug):
"""Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { "message": "message body", "hig... | stack_v2_sparse_classes_75kplus_train_005422 | 12,153 | permissive | [
{
"docstring": "Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { \"message\": \"message body\", \"highlights\": list of highlights and their details } OR { \"errors\": \"error details body\" }",
"name": "get",
"signa... | 2 | stack_v2_sparse_classes_30k_train_003472 | Implement the Python class `CreateGetDeleteMyHighlightsAPIView` described below.
Class description:
Provide methods for creating a highlight
Method signatures and docstrings:
- def get(self, request, slug): Get all my highlights for an article Params ------- request: Object with request data and functions. Returns --... | Implement the Python class `CreateGetDeleteMyHighlightsAPIView` described below.
Class description:
Provide methods for creating a highlight
Method signatures and docstrings:
- def get(self, request, slug): Get all my highlights for an article Params ------- request: Object with request data and functions. Returns --... | 5a31840856de4b361fe2594dfa7a33d7774d3fe2 | <|skeleton|>
class CreateGetDeleteMyHighlightsAPIView:
"""Provide methods for creating a highlight"""
def get(self, request, slug):
"""Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { "message": "message body", "hig... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateGetDeleteMyHighlightsAPIView:
"""Provide methods for creating a highlight"""
def get(self, request, slug):
"""Get all my highlights for an article Params ------- request: Object with request data and functions. Returns -------- Response object: { "message": "message body", "highlights": lis... | the_stack_v2_python_sparse | authors/apps/highlights/views.py | bl4ck4ndbr0wn/ah-centauri-backend | train | 0 |
0bee4bd66a68b8aa475a80c7287be4560c178818 | [
"\"\"\"通过前序遍历链接节点\n \"\"\"\npreOrder_list = []\n\ndef pre_order(root):\n if not root:\n return\n preOrder_list.append(root)\n pre_order(root.left)\n pre_order(root.right)\npre_order(root)\nfor i in range(1, len(preOrder_list)):\n prev_node, cur_node = (preOrder_list[i - 1], preOrder_lis... | <|body_start_0|>
"""通过前序遍历链接节点
"""
preOrder_list = []
def pre_order(root):
if not root:
return
preOrder_list.append(root)
pre_order(root.left)
pre_order(root.right)
pre_order(root)
for i in range(1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten_1(self, root: TreeNode) -> None:
"""在遍历途中,记录prev的节点"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""通过前序遍历链接节点... | stack_v2_sparse_classes_75kplus_train_005423 | 1,327 | no_license | [
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "在遍历途中,记录prev的节点",
"name": "flatten_1",
"signature": "def flatten_1(self, root: TreeNode) -> None"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def flatten_1(self, root: TreeNode) -> None: 在遍历途中,记录prev的节点 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def flatten_1(self, root: TreeNode) -> None: 在遍历途中,记录prev的节点
<|skeleton|>
clas... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten_1(self, root: TreeNode) -> None:
"""在遍历途中,记录prev的节点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def flatten(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
"""通过前序遍历链接节点
"""
preOrder_list = []
def pre_order(root):
if not root:
return
preOrder_list.append(root)
... | the_stack_v2_python_sparse | algorithm/leetcode/backtracking/15-二叉树展开为链表.py | lxconfig/UbuntuCode_bak | train | 0 | |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\nserializer = TableSerializer(username=username, repo_base=repo_base, request=request)\ntables = serializer.list_tables(repo_name)\nreturn Response(tables, status=status.HTTP_200_OK)",
"username = request.user.get_username()\nserializer = TableSerializer(username=username, ... | <|body_start_0|>
username = request.user.get_username()
serializer = TableSerializer(username=username, repo_base=repo_base, request=request)
tables = serializer.list_tables(repo_name)
return Response(tables, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
username = ... | Tables | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tables:
def get(self, request, repo_base, repo_name, format=None):
"""Tables in a repo"""
<|body_0|>
def post(self, request, repo_base, repo_name, format=None):
"""Create a table in a repo note: Using execute_query to create tables gives more control over table creat... | stack_v2_sparse_classes_75kplus_train_005424 | 31,465 | permissive | [
{
"docstring": "Tables in a repo",
"name": "get",
"signature": "def get(self, request, repo_base, repo_name, format=None)"
},
{
"docstring": "Create a table in a repo note: Using execute_query to create tables gives more control over table creation e.g. { \"table_name\": \"mytablename\", \"param... | 2 | stack_v2_sparse_classes_30k_train_038122 | Implement the Python class `Tables` described below.
Class description:
Implement the Tables class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, format=None): Tables in a repo
- def post(self, request, repo_base, repo_name, format=None): Create a table in a repo note: Using execute... | Implement the Python class `Tables` described below.
Class description:
Implement the Tables class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, format=None): Tables in a repo
- def post(self, request, repo_base, repo_name, format=None): Create a table in a repo note: Using execute... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class Tables:
def get(self, request, repo_base, repo_name, format=None):
"""Tables in a repo"""
<|body_0|>
def post(self, request, repo_base, repo_name, format=None):
"""Create a table in a repo note: Using execute_query to create tables gives more control over table creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tables:
def get(self, request, repo_base, repo_name, format=None):
"""Tables in a repo"""
username = request.user.get_username()
serializer = TableSerializer(username=username, repo_base=repo_base, request=request)
tables = serializer.list_tables(repo_name)
return Respo... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 | |
e94417b36416adbfe227ab0f03b7116556e310e3 | [
"self.common_acl = common_acl\nself.grant_vec = grant_vec\nself.keystone_acl = keystone_acl\nself.swift_read_acl = swift_read_acl\nself.swift_write_acl = swift_write_acl",
"if dictionary is None:\n return None\ncommon_acl = cohesity_management_sdk.models.common_acl_proto.CommonACLProto.from_dictionary(dictiona... | <|body_start_0|>
self.common_acl = common_acl
self.grant_vec = grant_vec
self.keystone_acl = keystone_acl
self.swift_read_acl = swift_read_acl
self.swift_write_acl = swift_write_acl
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
co... | Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keystone_acl (KeystoneACLProto): KeystoneAC... | ACLProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACLProto:
"""Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keyston... | stack_v2_sparse_classes_75kplus_train_005425 | 3,081 | permissive | [
{
"docstring": "Constructor for the ACLProto class",
"name": "__init__",
"signature": "def __init__(self, common_acl=None, grant_vec=None, keystone_acl=None, swift_read_acl=None, swift_write_acl=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dicti... | 2 | stack_v2_sparse_classes_30k_train_034804 | Implement the Python class `ACLProto` described below.
Class description:
Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant... | Implement the Python class `ACLProto` described below.
Class description:
Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ACLProto:
"""Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keyston... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ACLProto:
"""Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keystone_acl (Keysto... | the_stack_v2_python_sparse | cohesity_management_sdk/models/acl_proto.py | cohesity/management-sdk-python | train | 24 |
2600bba18f39e4e9a14ae4ecb69ded51c385c635 | [
"context = super().get_context_data(**kwargs)\nrights_statement = RightsStatement.objects.get(pk=self.kwargs.get('pk'))\norganization = rights_statement.organization\napplies_to_type_choices = self.get_applies_to_type_choices(organization)\nformset_data = self.get_formset(rights_statement.rights_basis)\nformset = f... | <|body_start_0|>
context = super().get_context_data(**kwargs)
rights_statement = RightsStatement.objects.get(pk=self.kwargs.get('pk'))
organization = rights_statement.organization
applies_to_type_choices = self.get_applies_to_type_choices(organization)
formset_data = self.get_for... | Update Rights Statements. | RightsUpdateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RightsUpdateView:
"""Update Rights Statements."""
def get_context_data(self, **kwargs):
"""Adds formsets to context data."""
<|body_0|>
def form_valid(self, form):
"""Sets variables needed in formsets."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005426 | 6,959 | permissive | [
{
"docstring": "Adds formsets to context data.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Sets variables needed in formsets.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048312 | Implement the Python class `RightsUpdateView` described below.
Class description:
Update Rights Statements.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds formsets to context data.
- def form_valid(self, form): Sets variables needed in formsets. | Implement the Python class `RightsUpdateView` described below.
Class description:
Update Rights Statements.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Adds formsets to context data.
- def form_valid(self, form): Sets variables needed in formsets.
<|skeleton|>
class RightsUpdateView:
... | 896cff3566746001dd594baa2e85bf3256016efb | <|skeleton|>
class RightsUpdateView:
"""Update Rights Statements."""
def get_context_data(self, **kwargs):
"""Adds formsets to context data."""
<|body_0|>
def form_valid(self, form):
"""Sets variables needed in formsets."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RightsUpdateView:
"""Update Rights Statements."""
def get_context_data(self, **kwargs):
"""Adds formsets to context data."""
context = super().get_context_data(**kwargs)
rights_statement = RightsStatement.objects.get(pk=self.kwargs.get('pk'))
organization = rights_statemen... | the_stack_v2_python_sparse | bag_transfer/rights/views.py | RockefellerArchiveCenter/aurora | train | 24 |
10d9804c5917fd199178a70ac57620d6ee80cd46 | [
"if m == n:\n return head\ndummy = mylist.ListNode(0)\ndummy.next = head\nbefore_reverve = dummy\nfor i in range(m - 1):\n before_reverve = before_reverve.next\nreverse_head = before_reverve.next\nfor i in range(n - m):\n tmp = before_reverve.next\n before_reverve.next = reverse_head.next\n reverse_h... | <|body_start_0|>
if m == n:
return head
dummy = mylist.ListNode(0)
dummy.next = head
before_reverve = dummy
for i in range(m - 1):
before_reverve = before_reverve.next
reverse_head = before_reverve.next
for i in range(n - m):
tm... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseBetween(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverseBetween2(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_005427 | 2,154 | no_license | [
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head, m, n)"
},
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverseBetween2",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_025089 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverseBetween2(self, head, m, n): :type head: ListNode :type m: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverseBetween2(self, head, m, n): :type head: ListNode :type m: int :... | 41365b549f1e6b04aac9f1632a66e71c1e05b322 | <|skeleton|>
class Solution:
def reverseBetween(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverseBetween2(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseBetween(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
if m == n:
return head
dummy = mylist.ListNode(0)
dummy.next = head
before_reverve = dummy
for i in range(m - 1):
before... | the_stack_v2_python_sparse | python practice/LinkedList/reverseListii.py | SuzyWu2014/coding-practice | train | 1 | |
b622207880edde1bd21cc4df826718565a5dde89 | [
"posts = PostService.get_all_post()\npost_schema = PostSchema(exclude=['comments'])\nreturn render_template('posts.html', title='Articles', posts=post_schema.dump(posts, many=True), current_connected_user=connected_user(get_jwt_identity()))",
"user_id = get_jwt_identity()\npost = PostService.create_post(request.f... | <|body_start_0|>
posts = PostService.get_all_post()
post_schema = PostSchema(exclude=['comments'])
return render_template('posts.html', title='Articles', posts=post_schema.dump(posts, many=True), current_connected_user=connected_user(get_jwt_identity()))
<|end_body_0|>
<|body_start_1|>
... | PostList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostList:
def get(self):
"""Obtenir tous les posts"""
<|body_0|>
def post(self):
"""Creer un nouveau post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
posts = PostService.get_all_post()
post_schema = PostSchema(exclude=['comments'])
... | stack_v2_sparse_classes_75kplus_train_005428 | 3,927 | no_license | [
{
"docstring": "Obtenir tous les posts",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creer un nouveau post",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009247 | Implement the Python class `PostList` described below.
Class description:
Implement the PostList class.
Method signatures and docstrings:
- def get(self): Obtenir tous les posts
- def post(self): Creer un nouveau post | Implement the Python class `PostList` described below.
Class description:
Implement the PostList class.
Method signatures and docstrings:
- def get(self): Obtenir tous les posts
- def post(self): Creer un nouveau post
<|skeleton|>
class PostList:
def get(self):
"""Obtenir tous les posts"""
<|bod... | dbeb9e603f8c24583dd6fd8b4e69ae488bc62591 | <|skeleton|>
class PostList:
def get(self):
"""Obtenir tous les posts"""
<|body_0|>
def post(self):
"""Creer un nouveau post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostList:
def get(self):
"""Obtenir tous les posts"""
posts = PostService.get_all_post()
post_schema = PostSchema(exclude=['comments'])
return render_template('posts.html', title='Articles', posts=post_schema.dump(posts, many=True), current_connected_user=connected_user(get_jwt... | the_stack_v2_python_sparse | blog/controllers/post.py | buzzromain/projet-web-serveur | train | 0 | |
ef4751c9c39df4e1a19b5aaae8fc10a0113ad9b1 | [
"self.api = api\nself.config_entry = config_entry\nsuper().__init__(hass=hass, logger=_LOGGER, name=name, update_interval=timedelta(seconds=polling_interval))",
"try:\n data = await self.api.get_telemetry_data()\nexcept OmniLogicException as error:\n raise UpdateFailed(f'Error updating from OmniLogic: {erro... | <|body_start_0|>
self.api = api
self.config_entry = config_entry
super().__init__(hass=hass, logger=_LOGGER, name=name, update_interval=timedelta(seconds=polling_interval))
<|end_body_0|>
<|body_start_1|>
try:
data = await self.api.get_telemetry_data()
except OmniLog... | Class to manage fetching update data from single endpoint. | OmniLogicUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OmniLogicUpdateCoordinator:
"""Class to manage fetching update data from single endpoint."""
def __init__(self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int) -> None:
"""Initialize the global Omnilogic data updater."""
<|bod... | stack_v2_sparse_classes_75kplus_train_005429 | 5,339 | permissive | [
{
"docstring": "Initialize the global Omnilogic data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int) -> None"
},
{
"docstring": "Fetch data from OmniLogic.",
"name": "_async_upda... | 2 | stack_v2_sparse_classes_30k_train_011556 | Implement the Python class `OmniLogicUpdateCoordinator` described below.
Class description:
Class to manage fetching update data from single endpoint.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int) -> None: Initi... | Implement the Python class `OmniLogicUpdateCoordinator` described below.
Class description:
Class to manage fetching update data from single endpoint.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int) -> None: Initi... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OmniLogicUpdateCoordinator:
"""Class to manage fetching update data from single endpoint."""
def __init__(self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int) -> None:
"""Initialize the global Omnilogic data updater."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OmniLogicUpdateCoordinator:
"""Class to manage fetching update data from single endpoint."""
def __init__(self, hass: HomeAssistant, api: OmniLogic, name: str, config_entry: ConfigEntry, polling_interval: int) -> None:
"""Initialize the global Omnilogic data updater."""
self.api = api
... | the_stack_v2_python_sparse | homeassistant/components/omnilogic/common.py | home-assistant/core | train | 35,501 |
ced2d9b715e2c0f1d0c57e331383cda2eaa99552 | [
"logger.debug('Start clean data in UpdateUserForm.')\nname = self.cleaned_data.get('name')\nphone = self.cleaned_data.get('phone')\ndate_of_birth = self.cleaned_data.get('date_of_birth')\nself.validator_all(name, phone, date_of_birth)\nlogger.debug('Exit clean data in UpdateUserForm.')",
"logger.debug('Start vali... | <|body_start_0|>
logger.debug('Start clean data in UpdateUserForm.')
name = self.cleaned_data.get('name')
phone = self.cleaned_data.get('phone')
date_of_birth = self.cleaned_data.get('date_of_birth')
self.validator_all(name, phone, date_of_birth)
logger.debug('Exit clean ... | Form to update the users. | UpdateUserForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateUserForm:
"""Form to update the users."""
def clean(self):
"""Get user fields."""
<|body_0|>
def validator_all(self, name, phone, date_of_birth):
"""Checks validator in all fields."""
<|body_1|>
def verify_password(self, password):
"""V... | stack_v2_sparse_classes_75kplus_train_005430 | 2,539 | permissive | [
{
"docstring": "Get user fields.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Checks validator in all fields.",
"name": "validator_all",
"signature": "def validator_all(self, name, phone, date_of_birth)"
},
{
"docstring": "Verifies if the given password ma... | 3 | stack_v2_sparse_classes_30k_train_004034 | Implement the Python class `UpdateUserForm` described below.
Class description:
Form to update the users.
Method signatures and docstrings:
- def clean(self): Get user fields.
- def validator_all(self, name, phone, date_of_birth): Checks validator in all fields.
- def verify_password(self, password): Verifies if the ... | Implement the Python class `UpdateUserForm` described below.
Class description:
Form to update the users.
Method signatures and docstrings:
- def clean(self): Get user fields.
- def validator_all(self, name, phone, date_of_birth): Checks validator in all fields.
- def verify_password(self, password): Verifies if the ... | 5387eb80dfb354e948abe64f7d8bbe087fc4f136 | <|skeleton|>
class UpdateUserForm:
"""Form to update the users."""
def clean(self):
"""Get user fields."""
<|body_0|>
def validator_all(self, name, phone, date_of_birth):
"""Checks validator in all fields."""
<|body_1|>
def verify_password(self, password):
"""V... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateUserForm:
"""Form to update the users."""
def clean(self):
"""Get user fields."""
logger.debug('Start clean data in UpdateUserForm.')
name = self.cleaned_data.get('name')
phone = self.cleaned_data.get('phone')
date_of_birth = self.cleaned_data.get('date_of_bi... | the_stack_v2_python_sparse | medical_prescription/user/forms/updateuserform.py | ristovao/2017.2-Receituario-Medico | train | 0 |
6216f4c0a918125385bd73e784d9149e235d13e4 | [
"self.f_min = root.val\n\ndef findSecondMinimumValueAct(root):\n if not root:\n return []\n cand = [root.val] if root.val > self.f_min else []\n return cand + findSecondMinimumValueAct(root.left) + findSecondMinimumValueAct(root.right)\ncand = findSecondMinimumValueAct(root)\nreturn min(cand) if can... | <|body_start_0|>
self.f_min = root.val
def findSecondMinimumValueAct(root):
if not root:
return []
cand = [root.val] if root.val > self.f_min else []
return cand + findSecondMinimumValueAct(root.left) + findSecondMinimumValueAct(root.right)
ca... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSecondMinimumValue(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findSecondMinimumValueIterative(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.f_min = roo... | stack_v2_sparse_classes_75kplus_train_005431 | 1,405 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findSecondMinimumValue",
"signature": "def findSecondMinimumValue(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findSecondMinimumValueIterative",
"signature": "def findSecondMinimumValueIterative(se... | 2 | stack_v2_sparse_classes_30k_train_004584 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSecondMinimumValue(self, root): :type root: TreeNode :rtype: int
- def findSecondMinimumValueIterative(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSecondMinimumValue(self, root): :type root: TreeNode :rtype: int
- def findSecondMinimumValueIterative(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class S... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def findSecondMinimumValue(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findSecondMinimumValueIterative(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findSecondMinimumValue(self, root):
""":type root: TreeNode :rtype: int"""
self.f_min = root.val
def findSecondMinimumValueAct(root):
if not root:
return []
cand = [root.val] if root.val > self.f_min else []
return cand... | the_stack_v2_python_sparse | cs_notes/tree/recursive/second_minimum_node_in_a_binary_tree.py | hwc1824/LeetCodeSolution | train | 0 | |
7e662022c92054646d06f0baebf72054df5502c4 | [
"self.X, self.Y = (tar_tr_X, tar_tr_Y)\nself.score = score\nif cv == True:\n self.folder = LeaveOneOut()\nelif isinstance(cv, int):\n self.folder = KFold(cv)",
"scores = []\nfor _, (train, test) in enumerate(self.folder.split(self.X, self.Y)):\n scores.append(self.score(augmenter, self.X[train], self.Y[t... | <|body_start_0|>
self.X, self.Y = (tar_tr_X, tar_tr_Y)
self.score = score
if cv == True:
self.folder = LeaveOneOut()
elif isinstance(cv, int):
self.folder = KFold(cv)
<|end_body_0|>
<|body_start_1|>
scores = []
for _, (train, test) in enumerate(se... | The scorer class to evaluate the performance by cross-validating on a single target domain. | SingleTargetDomainCVPerformanceValidationScorer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleTargetDomainCVPerformanceValidationScorer:
"""The scorer class to evaluate the performance by cross-validating on a single target domain."""
def __init__(self, tar_tr_X: np.ndarray, tar_tr_Y: np.ndarray, score: AugScoreBase, cv: Union[bool, int]=True):
"""Parameters: tar_tr_X: ... | stack_v2_sparse_classes_75kplus_train_005432 | 1,748 | permissive | [
{
"docstring": "Parameters: tar_tr_X: target domain training data predictor variables. tar_tr_Y: target domain training data predicted variables. score: a scorer to measure the quality of the prediction. cv: the type of the cross-validation (``True``: leave-one-out cross validation. ``k: int``: ``k``-fold cross... | 2 | stack_v2_sparse_classes_30k_train_049564 | Implement the Python class `SingleTargetDomainCVPerformanceValidationScorer` described below.
Class description:
The scorer class to evaluate the performance by cross-validating on a single target domain.
Method signatures and docstrings:
- def __init__(self, tar_tr_X: np.ndarray, tar_tr_Y: np.ndarray, score: AugScor... | Implement the Python class `SingleTargetDomainCVPerformanceValidationScorer` described below.
Class description:
The scorer class to evaluate the performance by cross-validating on a single target domain.
Method signatures and docstrings:
- def __init__(self, tar_tr_X: np.ndarray, tar_tr_Y: np.ndarray, score: AugScor... | 2878ced51cfe473aad8fbc1886e2b65dfc9fc060 | <|skeleton|>
class SingleTargetDomainCVPerformanceValidationScorer:
"""The scorer class to evaluate the performance by cross-validating on a single target domain."""
def __init__(self, tar_tr_X: np.ndarray, tar_tr_Y: np.ndarray, score: AugScoreBase, cv: Union[bool, int]=True):
"""Parameters: tar_tr_X: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleTargetDomainCVPerformanceValidationScorer:
"""The scorer class to evaluate the performance by cross-validating on a single target domain."""
def __init__(self, tar_tr_X: np.ndarray, tar_tr_Y: np.ndarray, score: AugScoreBase, cv: Union[bool, int]=True):
"""Parameters: tar_tr_X: target domain... | the_stack_v2_python_sparse | causal_da/api_support/validator/performance.py | SoldierY/few-shot-domain-adaptation-by-causal-mechanism-transfer | train | 0 |
2f977ffdbc7769fce449961bf01bdc38de3c583c | [
"length = 0\nstack = 0\nnextpoint = 0\nrightpareCount = 0\nfor i in range(len(s)):\n if s[i] == '(':\n stack += 1\n if s[i] == ')':\n if stack > 0:\n stack -= 1\n rightpareCount += 1\n if stack == 0:\n length += 2 * rightpareCount\n ... | <|body_start_0|>
length = 0
stack = 0
nextpoint = 0
rightpareCount = 0
for i in range(len(s)):
if s[i] == '(':
stack += 1
if s[i] == ')':
if stack > 0:
stack -= 1
rightpareCount += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses2(self, s: str) -> int:
"""brute force"""
<|body_0|>
def longestValidParentheses(self, s: str) -> int:
"""dynamic programming"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = 0
stack = 0
n... | stack_v2_sparse_classes_75kplus_train_005433 | 2,072 | no_license | [
{
"docstring": "brute force",
"name": "longestValidParentheses2",
"signature": "def longestValidParentheses2(self, s: str) -> int"
},
{
"docstring": "dynamic programming",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_039292 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses2(self, s: str) -> int: brute force
- def longestValidParentheses(self, s: str) -> int: dynamic programming | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses2(self, s: str) -> int: brute force
- def longestValidParentheses(self, s: str) -> int: dynamic programming
<|skeleton|>
class Solution:
def long... | 9ae273595b506d4d7114b9fb4cc8663e779ef7ee | <|skeleton|>
class Solution:
def longestValidParentheses2(self, s: str) -> int:
"""brute force"""
<|body_0|>
def longestValidParentheses(self, s: str) -> int:
"""dynamic programming"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestValidParentheses2(self, s: str) -> int:
"""brute force"""
length = 0
stack = 0
nextpoint = 0
rightpareCount = 0
for i in range(len(s)):
if s[i] == '(':
stack += 1
if s[i] == ')':
if sta... | the_stack_v2_python_sparse | longest_valid_parentheses.py | sqlxx/algo-python | train | 1 | |
50b31da39114c5e2c1f3dd2111b7ffd849f8769b | [
"extra = self.extra_parameters.copy()\nextra['parent_node_id'] = node['id']\nextra['catalog_id'] = catalog_id\nexpand_model = CatalogStructureModel(self.catalog_name, extra)\nnode['expand_url'] = request.link(expand_model)\nselection_id = node.get('selection_id')\nif selection_id:\n extra['selection_id'] = selec... | <|body_start_0|>
extra = self.extra_parameters.copy()
extra['parent_node_id'] = node['id']
extra['catalog_id'] = catalog_id
expand_model = CatalogStructureModel(self.catalog_name, extra)
node['expand_url'] = request.link(expand_model)
selection_id = node.get('selection_id... | Specialization to retrieve values for structure catalogs | CatalogStructureModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatalogStructureModel:
"""Specialization to retrieve values for structure catalogs"""
def _adjust_node(self, node, catalog_id, request):
"""Prepares the node for REST. Remove the fields we do not need and add further fields if necessary."""
<|body_0|>
def get_nodes(self,... | stack_v2_sparse_classes_75kplus_train_005434 | 20,917 | no_license | [
{
"docstring": "Prepares the node for REST. Remove the fields we do not need and add further fields if necessary.",
"name": "_adjust_node",
"signature": "def _adjust_node(self, node, catalog_id, request)"
},
{
"docstring": "Returns a list of dictionaries where every dictionary represents a node.... | 2 | stack_v2_sparse_classes_30k_train_019153 | Implement the Python class `CatalogStructureModel` described below.
Class description:
Specialization to retrieve values for structure catalogs
Method signatures and docstrings:
- def _adjust_node(self, node, catalog_id, request): Prepares the node for REST. Remove the fields we do not need and add further fields if ... | Implement the Python class `CatalogStructureModel` described below.
Class description:
Specialization to retrieve values for structure catalogs
Method signatures and docstrings:
- def _adjust_node(self, node, catalog_id, request): Prepares the node for REST. Remove the fields we do not need and add further fields if ... | 6bc932c67bc8d93b873838ae6d9fb8d33c72234d | <|skeleton|>
class CatalogStructureModel:
"""Specialization to retrieve values for structure catalogs"""
def _adjust_node(self, node, catalog_id, request):
"""Prepares the node for REST. Remove the fields we do not need and add further fields if necessary."""
<|body_0|>
def get_nodes(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CatalogStructureModel:
"""Specialization to retrieve values for structure catalogs"""
def _adjust_node(self, node, catalog_id, request):
"""Prepares the node for REST. Remove the fields we do not need and add further fields if necessary."""
extra = self.extra_parameters.copy()
ext... | the_stack_v2_python_sparse | site-packages/cs.web-15.3.0.6-py2.7.egg/cs/web/components/ui_support/catalogs.py | prachipainuly-rbei/devops-poc | train | 0 |
a0bb364f699895722d5ab88777a41059245036bd | [
"dummy_node = ListNode(-1)\ndummy_node.next = head\npre_node = dummy_node\ncur_node = dummy_node.next\nwhile cur_node:\n if cur_node.val == val:\n pre_node.next = cur_node.next\n break\n pre_node = cur_node\n cur_node = cur_node.next\nreturn dummy_node.next",
"if head.val == val:\n retur... | <|body_start_0|>
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node.next
while cur_node:
if cur_node.val == val:
pre_node.next = cur_node.next
break
pre_node = cur_node
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
<|body_0|>
def deleteNode(self, head: ListNode, val: int) -> ListNode:
"""如果匹配的值是第一个直接返回即可."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy_nod... | stack_v2_sparse_classes_75kplus_train_005435 | 1,496 | no_license | [
{
"docstring": "使用了虚拟头节点,因为匹配的值可能是第一个。",
"name": "deleteNode2",
"signature": "def deleteNode2(self, head: ListNode, val: int) -> ListNode"
},
{
"docstring": "如果匹配的值是第一个直接返回即可.",
"name": "deleteNode",
"signature": "def deleteNode(self, head: ListNode, val: int) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_val_001803 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode2(self, head: ListNode, val: int) -> ListNode: 使用了虚拟头节点,因为匹配的值可能是第一个。
- def deleteNode(self, head: ListNode, val: int) -> ListNode: 如果匹配的值是第一个直接返回即可. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteNode2(self, head: ListNode, val: int) -> ListNode: 使用了虚拟头节点,因为匹配的值可能是第一个。
- def deleteNode(self, head: ListNode, val: int) -> ListNode: 如果匹配的值是第一个直接返回即可.
<|skeleton|>
... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
<|body_0|>
def deleteNode(self, head: ListNode, val: int) -> ListNode:
"""如果匹配的值是第一个直接返回即可."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def deleteNode2(self, head: ListNode, val: int) -> ListNode:
"""使用了虚拟头节点,因为匹配的值可能是第一个。"""
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node.next
while cur_node:
if cur_node.val == val:
... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 18. 删除链表的节点.py | tenqaz/crazy_arithmetic | train | 0 | |
addf43752923312296fd6737f40f518c72260c56 | [
"super(MultitaskLoss, self).__init__()\nself.losses = nn.ModuleList()\nfor loss_dict in losses:\n self.losses.append(initialize(loss_dict))\nif weights is None:\n weights = [1 for _ in range(len(losses))]\nassert isinstance(weights, list) and len(weights) == len(losses)\nself.weights = weights\nself.weight_de... | <|body_start_0|>
super(MultitaskLoss, self).__init__()
self.losses = nn.ModuleList()
for loss_dict in losses:
self.losses.append(initialize(loss_dict))
if weights is None:
weights = [1 for _ in range(len(losses))]
assert isinstance(weights, list) and len(w... | MultitaskLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultitaskLoss:
def __init__(self, losses, weights=None, weight_decay=0.0, model=None):
"""Defines a wrapper loss around an ordered list of individual losses for a multitask model. Parameters ---------- losses : List[Dict[str, Union[str, Dict[str, Any]]]] Contains dictionaries that define... | stack_v2_sparse_classes_75kplus_train_005436 | 20,295 | no_license | [
{
"docstring": "Defines a wrapper loss around an ordered list of individual losses for a multitask model. Parameters ---------- losses : List[Dict[str, Union[str, Dict[str, Any]]]] Contains dictionaries that define the construction of the individual loss functions. Each dictionary should have a \"classname\" ke... | 2 | stack_v2_sparse_classes_30k_train_052897 | Implement the Python class `MultitaskLoss` described below.
Class description:
Implement the MultitaskLoss class.
Method signatures and docstrings:
- def __init__(self, losses, weights=None, weight_decay=0.0, model=None): Defines a wrapper loss around an ordered list of individual losses for a multitask model. Parame... | Implement the Python class `MultitaskLoss` described below.
Class description:
Implement the MultitaskLoss class.
Method signatures and docstrings:
- def __init__(self, losses, weights=None, weight_decay=0.0, model=None): Defines a wrapper loss around an ordered list of individual losses for a multitask model. Parame... | 1f1ea0ea4355275ac0566299fe7059ba336a6f02 | <|skeleton|>
class MultitaskLoss:
def __init__(self, losses, weights=None, weight_decay=0.0, model=None):
"""Defines a wrapper loss around an ordered list of individual losses for a multitask model. Parameters ---------- losses : List[Dict[str, Union[str, Dict[str, Any]]]] Contains dictionaries that define... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultitaskLoss:
def __init__(self, losses, weights=None, weight_decay=0.0, model=None):
"""Defines a wrapper loss around an ordered list of individual losses for a multitask model. Parameters ---------- losses : List[Dict[str, Union[str, Dict[str, Any]]]] Contains dictionaries that define the construct... | the_stack_v2_python_sparse | innout/losses.py | p-lambda/in-n-out | train | 14 | |
457892631cd8804366663db4c350ca395b81253f | [
"LDC_Info.__init__(self)\nself.setTitle(self.name)\nself.status = compat_res[0]\nui = Ui_soundFrame()\nui.setupUi(self.frame)\nself.__fill_frame(ui, info_res, compat_res, diag_res)",
"ui.productLineEdit.setText(QtGui.QApplication.translate('soundFrame', self._check_invalid_values(info_res.product[1]), None, QtGui... | <|body_start_0|>
LDC_Info.__init__(self)
self.setTitle(self.name)
self.status = compat_res[0]
ui = Ui_soundFrame()
ui.setupUi(self.frame)
self.__fill_frame(ui, info_res, compat_res, diag_res)
<|end_body_0|>
<|body_start_1|>
ui.productLineEdit.setText(QtGui.QAppli... | Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som. | GUISound | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUISound:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som."""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res... | stack_v2_sparse_classes_75kplus_train_005437 | 3,403 | no_license | [
{
"docstring": "Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista com as tuples de resultados de compatibilidade [(True, msg)] diag_res -- Lista com os resultados do diagnóstico (lista de 'DaigResSound')",
"name": "__init__",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_052161 | Implement the Python class `GUISound` described below.
Class description:
Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som.
Method signatures and docstrings:
- def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os re... | Implement the Python class `GUISound` described below.
Class description:
Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som.
Method signatures and docstrings:
- def __init__(self, info_res, compat_res, diag_res): Construtor Parâmetros: info_res -- lista com os re... | bda0c2c8977dd1246339f1f0f4718d29e8795f21 | <|skeleton|>
class GUISound:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som."""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GUISound:
"""Estende a classe 'LDC_Info'. Classe que define a interface gráfica com os resultados para o teste de som."""
def __init__(self, info_res, compat_res, diag_res):
"""Construtor Parâmetros: info_res -- lista com os resultados informativos (lista de 'InfoResSound) compat_res -- Lista com... | the_stack_v2_python_sparse | src/libs/sound/gui_sound.py | adrianomelo/ldc-desktop | train | 1 |
6f2082242b9ef8a1c22e1eb9609c1218a61ba995 | [
"self.commandTemplateString = commandString\nself.argumentLists = Formatter.FlattenArgsList(argLists)\nif self.argumentLists is not None:\n self.argumentLists = [[Formatter.ListAsString(arg) for arg in lst] for lst in self.argumentLists]\nelse:\n SimpleLogger.outputVerbose('No arguments were provided')\nself.... | <|body_start_0|>
self.commandTemplateString = commandString
self.argumentLists = Formatter.FlattenArgsList(argLists)
if self.argumentLists is not None:
self.argumentLists = [[Formatter.ListAsString(arg) for arg in lst] for lst in self.argumentLists]
else:
SimpleLo... | This class represents a templated command to be ran multiple times using different arguments | BashForEachCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BashForEachCommand:
"""This class represents a templated command to be ran multiple times using different arguments"""
def __init__(self, commandString, argLists, runAllArgumentCombinations=False):
"""Initialize the command with the provided options parameters: commandString (string)... | stack_v2_sparse_classes_75kplus_train_005438 | 2,213 | permissive | [
{
"docstring": "Initialize the command with the provided options parameters: commandString (string): Template for the command to be executed argLists (list(list(string, string...))): A list containing sub-lists with options for each argument in the command template runAllArgumentCombinations (boolean): This opt... | 2 | stack_v2_sparse_classes_30k_train_001462 | Implement the Python class `BashForEachCommand` described below.
Class description:
This class represents a templated command to be ran multiple times using different arguments
Method signatures and docstrings:
- def __init__(self, commandString, argLists, runAllArgumentCombinations=False): Initialize the command wit... | Implement the Python class `BashForEachCommand` described below.
Class description:
This class represents a templated command to be ran multiple times using different arguments
Method signatures and docstrings:
- def __init__(self, commandString, argLists, runAllArgumentCombinations=False): Initialize the command wit... | d27fe49e15c79101cb76d72ff4805a09ffc248b3 | <|skeleton|>
class BashForEachCommand:
"""This class represents a templated command to be ran multiple times using different arguments"""
def __init__(self, commandString, argLists, runAllArgumentCombinations=False):
"""Initialize the command with the provided options parameters: commandString (string)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BashForEachCommand:
"""This class represents a templated command to be ran multiple times using different arguments"""
def __init__(self, commandString, argLists, runAllArgumentCombinations=False):
"""Initialize the command with the provided options parameters: commandString (string): Template fo... | the_stack_v2_python_sparse | bashForEachCommand.py | kieselai/bashForEach.py | train | 1 |
5099e8ed38dda145d7a7cd83b0c60c88e6b0388c | [
"unpack = pktt.unpack\nulist = unpack.unpack(14, '!6s6sH')\nself.dst = MacAddr(ulist[0].encode('hex'))\nself.src = MacAddr(ulist[1].encode('hex'))\nself.type = ulist[2]\npktt.pkt.ethernet = self\nif self.type == 2048:\n IPv4(pktt)\nelif self.type == 34525:\n IPv6(pktt)\nelse:\n self.data = unpack.getbytes(... | <|body_start_0|>
unpack = pktt.unpack
ulist = unpack.unpack(14, '!6s6sH')
self.dst = MacAddr(ulist[0].encode('hex'))
self.src = MacAddr(ulist[1].encode('hex'))
self.type = ulist[2]
pktt.pkt.ethernet = self
if self.type == 2048:
IPv4(pktt)
elif ... | Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported ) | ETHERNET | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ETHERNET:
"""Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported )... | stack_v2_sparse_classes_75kplus_train_005439 | 3,367 | 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.",
"name": "__init__",
"signature": "def __init__(self, pktt)"
},
{
"docstring": "String representation of object The representation depends on... | 2 | stack_v2_sparse_classes_30k_train_041520 | Implement the Python class `ETHERNET` described below.
Class description:
Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw dat... | Implement the Python class `ETHERNET` described below.
Class description:
Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw dat... | 1f06ae8c73d253141a3434fb9d2c36be3fe768ea | <|skeleton|>
class ETHERNET:
"""Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported )... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ETHERNET:
"""Ethernet object Usage: from packet.link.ethernet import ETHERNET x = ETHERNET(pktt) Object definition: ETHERNET( dst = MacAddr(), # destination MAC address src = MacAddr(), # source MAC address type = int, # payload type data = string, # raw data of payload if type is not supported )"""
def ... | the_stack_v2_python_sparse | packet/link/ethernet.py | MihailRusetskiy/nfs | train | 0 |
ecbdeb3819b62baac7ff9a1d6264ad15e1dbe52d | [
"super(MergeLayer1, self).__init__()\nself.list_k = list_k\ntrans, up, score = ([], [], [])\nfor ik in list_k:\n if ik[1] > 0:\n trans.append(nn.SequentialCell([nn.Conv2d(ik[1], ik[0], 1, 1, has_bias=False), nn.ReLU()]))\n up.append(nn.SequentialCell([nn.Conv2d(ik[0], ik[2], ik[3], 1, has_bias=True, pa... | <|body_start_0|>
super(MergeLayer1, self).__init__()
self.list_k = list_k
trans, up, score = ([], [], [])
for ik in list_k:
if ik[1] > 0:
trans.append(nn.SequentialCell([nn.Conv2d(ik[1], ik[0], 1, 1, has_bias=False), nn.ReLU()]))
up.append(nn.Seque... | merge layer 1 | MergeLayer1 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeLayer1:
"""merge layer 1"""
def __init__(self, list_k):
"""initialize merge layer 1 @param list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]"""
<|body_0|>
def construct(self, list_x, x_size):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_005440 | 12,164 | permissive | [
{
"docstring": "initialize merge layer 1 @param list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]",
"name": "__init__",
"signature": "def __init__(self, list_k)"
},
{
"docstring": "forward",
"name": "construct",
"signature": "def construct(self, list_x, x_size)"
}
] | 2 | null | Implement the Python class `MergeLayer1` described below.
Class description:
merge layer 1
Method signatures and docstrings:
- def __init__(self, list_k): initialize merge layer 1 @param list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]
- def construct(self, list_x, x_size): forward | Implement the Python class `MergeLayer1` described below.
Class description:
merge layer 1
Method signatures and docstrings:
- def __init__(self, list_k): initialize merge layer 1 @param list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]
- def construct(self, list_x, x_size): forward
<|skeleton|>
class Mer... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class MergeLayer1:
"""merge layer 1"""
def __init__(self, list_k):
"""initialize merge layer 1 @param list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]"""
<|body_0|>
def construct(self, list_x, x_size):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MergeLayer1:
"""merge layer 1"""
def __init__(self, list_k):
"""initialize merge layer 1 @param list_k: [[64, 512, 64], [128, 512, 128], [256, 0, 256] ... ]"""
super(MergeLayer1, self).__init__()
self.list_k = list_k
trans, up, score = ([], [], [])
for ik in list_k... | the_stack_v2_python_sparse | research/cv/EGnet/src/egnet.py | mindspore-ai/models | train | 301 |
efb701013d70263cf7f2a42272c05b5f72f24e9c | [
"l_serial = None\np_controller_obj._Data = bytearray()\nl_baud = p_controller_obj.Interface.Baud\nl_host = p_controller_obj.Interface.Host.lower()\nl_port = p_controller_obj.Interface.Port\nl_computer = p_pyhouse_obj.Computer.Name.lower()\nl_name = p_controller_obj.Name\nif l_host != l_computer:\n LOG.warning('D... | <|body_start_0|>
l_serial = None
p_controller_obj._Data = bytearray()
l_baud = p_controller_obj.Interface.Baud
l_host = p_controller_obj.Interface.Host.lower()
l_port = p_controller_obj.Interface.Port
l_computer = p_pyhouse_obj.Computer.Name.lower()
l_name = p_con... | This is a statefull factory for the serial protocol. | SerialApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerialApi:
"""This is a statefull factory for the serial protocol."""
def open_serial_driver(self, p_pyhouse_obj, p_controller_obj):
"""@param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller information for the serial controller we are opening. @r... | stack_v2_sparse_classes_75kplus_train_005441 | 11,736 | permissive | [
{
"docstring": "@param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller information for the serial controller we are opening. @return: the serial driver pointer",
"name": "open_serial_driver",
"signature": "def open_serial_driver(self, p_pyhouse_obj, p_controller_obj)... | 5 | stack_v2_sparse_classes_30k_train_041313 | Implement the Python class `SerialApi` described below.
Class description:
This is a statefull factory for the serial protocol.
Method signatures and docstrings:
- def open_serial_driver(self, p_pyhouse_obj, p_controller_obj): @param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller... | Implement the Python class `SerialApi` described below.
Class description:
This is a statefull factory for the serial protocol.
Method signatures and docstrings:
- def open_serial_driver(self, p_pyhouse_obj, p_controller_obj): @param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller... | a100fc67761a22ae47ed6f21f3c9464e2de5d54f | <|skeleton|>
class SerialApi:
"""This is a statefull factory for the serial protocol."""
def open_serial_driver(self, p_pyhouse_obj, p_controller_obj):
"""@param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller information for the serial controller we are opening. @r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SerialApi:
"""This is a statefull factory for the serial protocol."""
def open_serial_driver(self, p_pyhouse_obj, p_controller_obj):
"""@param p_pyhouse_obj: is the entire PyHouse Data @param p_controller_obj: is the controller information for the serial controller we are opening. @return: the se... | the_stack_v2_python_sparse | Project/src/Modules/Core/Drivers/Serial/Serial_driver.py | DBrianKimmel/PyHouse | train | 3 |
8e2828d8b44921476b5ac8f523d1ca777d70a368 | [
"DE = 0.001\nCHI = 10\nN = 108\nLAM = 306.3\nBETA = 16\nTHC_DIM = 350\noutput = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)\nstps1 = output[0]\noutput = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps1)\nassert output == (10912, 5250145120, 2142)",
"DE = 0.001\nCHI = 10\nN = 152\nLAM = 1201... | <|body_start_0|>
DE = 0.001
CHI = 10
N = 108
LAM = 306.3
BETA = 16
THC_DIM = 350
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)
stps1 = output[0]
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps1)
assert... | THCCostTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
<|body_0|>
def test_li_thc(self):
"""Reproduce Li et al orbital THC FT costs from paper"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
DE = 0.001
... | stack_v2_sparse_classes_75kplus_train_005442 | 1,527 | permissive | [
{
"docstring": "Reproduce Reiher et al orbital THC FT costs from paper",
"name": "test_reiher_thc",
"signature": "def test_reiher_thc(self)"
},
{
"docstring": "Reproduce Li et al orbital THC FT costs from paper",
"name": "test_li_thc",
"signature": "def test_li_thc(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006034 | Implement the Python class `THCCostTest` described below.
Class description:
Implement the THCCostTest class.
Method signatures and docstrings:
- def test_reiher_thc(self): Reproduce Reiher et al orbital THC FT costs from paper
- def test_li_thc(self): Reproduce Li et al orbital THC FT costs from paper | Implement the Python class `THCCostTest` described below.
Class description:
Implement the THCCostTest class.
Method signatures and docstrings:
- def test_reiher_thc(self): Reproduce Reiher et al orbital THC FT costs from paper
- def test_li_thc(self): Reproduce Li et al orbital THC FT costs from paper
<|skeleton|>
... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
<|body_0|>
def test_li_thc(self):
"""Reproduce Li et al orbital THC FT costs from paper"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class THCCostTest:
def test_reiher_thc(self):
"""Reproduce Reiher et al orbital THC FT costs from paper"""
DE = 0.001
CHI = 10
N = 108
LAM = 306.3
BETA = 16
THC_DIM = 350
output = thc.compute_cost(N, LAM, DE, CHI, BETA, THC_DIM, stps=20000)
stp... | the_stack_v2_python_sparse | src/openfermion/resource_estimates/thc/compute_cost_thc_test.py | quantumlib/OpenFermion | train | 1,481 | |
e64ea47db918c33122276d220898cba3c658cfa2 | [
"user = request.user\nbook_id = request.GET['book_id']\nif EmailDeliveryModel.objects.filter(user=user, book_id=book_id, send_email=False).exists():\n return Response(status=status.HTTP_200_OK, data={'data': True})\nreturn Response(status=status.HTTP_204_NO_CONTENT, data={'data': False})",
"user = request.user... | <|body_start_0|>
user = request.user
book_id = request.GET['book_id']
if EmailDeliveryModel.objects.filter(user=user, book_id=book_id, send_email=False).exists():
return Response(status=status.HTTP_200_OK, data={'data': True})
return Response(status=status.HTTP_204_NO_CONTENT... | EmailDelivery | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailDelivery:
def get(self, request):
"""이전에 알림예약을 했는지 확인 :param request: :return: boolean"""
<|body_0|>
def post(self, request):
"""알림 예약 등록 {"book_title":"한입에 쏙 파이썬", "book_id":1127719808} :param request: :return:"""
<|body_1|>
def delete(self, reques... | stack_v2_sparse_classes_75kplus_train_005443 | 1,828 | permissive | [
{
"docstring": "이전에 알림예약을 했는지 확인 :param request: :return: boolean",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "알림 예약 등록 {\"book_title\":\"한입에 쏙 파이썬\", \"book_id\":1127719808} :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
... | 3 | stack_v2_sparse_classes_30k_train_026118 | Implement the Python class `EmailDelivery` described below.
Class description:
Implement the EmailDelivery class.
Method signatures and docstrings:
- def get(self, request): 이전에 알림예약을 했는지 확인 :param request: :return: boolean
- def post(self, request): 알림 예약 등록 {"book_title":"한입에 쏙 파이썬", "book_id":1127719808} :param re... | Implement the Python class `EmailDelivery` described below.
Class description:
Implement the EmailDelivery class.
Method signatures and docstrings:
- def get(self, request): 이전에 알림예약을 했는지 확인 :param request: :return: boolean
- def post(self, request): 알림 예약 등록 {"book_title":"한입에 쏙 파이썬", "book_id":1127719808} :param re... | d2050a455ca4d8acaf5e4d18a6e5cc4e99eaf85c | <|skeleton|>
class EmailDelivery:
def get(self, request):
"""이전에 알림예약을 했는지 확인 :param request: :return: boolean"""
<|body_0|>
def post(self, request):
"""알림 예약 등록 {"book_title":"한입에 쏙 파이썬", "book_id":1127719808} :param request: :return:"""
<|body_1|>
def delete(self, reques... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailDelivery:
def get(self, request):
"""이전에 알림예약을 했는지 확인 :param request: :return: boolean"""
user = request.user
book_id = request.GET['book_id']
if EmailDeliveryModel.objects.filter(user=user, book_id=book_id, send_email=False).exists():
return Response(status=st... | the_stack_v2_python_sparse | app/email_delivery/views.py | bear-engineer/Search-all-library-books-in-Ansan | train | 0 | |
63e36106197155f3777fd5212ee11a06a539ce20 | [
"super().__init__(**kwargs)\nself._name = 'auc'\nself._type = 'max'",
"y_true, y_pred = self.get_true_pred_data()\nif len(y_pred.shape) != 1:\n y_pred = y_pred[:, 1]\nif any(np.isnan(y_pred)):\n logger.warn('There is nan in prediction values for auc. Replace nan with zero')\n np.nan_to_num(y_pred, copy=F... | <|body_start_0|>
super().__init__(**kwargs)
self._name = 'auc'
self._type = 'max'
<|end_body_0|>
<|body_start_1|>
y_true, y_pred = self.get_true_pred_data()
if len(y_pred.shape) != 1:
y_pred = y_pred[:, 1]
if any(np.isnan(y_pred)):
logger.warn('Th... | A metric class to return AUC. | AUCMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AUCMetric:
"""A metric class to return AUC."""
def __init__(self, **kwargs):
"""Initialize AUCMetric."""
<|body_0|>
def calculate(self):
"""Calculate AUC."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(**kwargs)
self._n... | stack_v2_sparse_classes_75kplus_train_005444 | 7,080 | permissive | [
{
"docstring": "Initialize AUCMetric.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Calculate AUC.",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028664 | Implement the Python class `AUCMetric` described below.
Class description:
A metric class to return AUC.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize AUCMetric.
- def calculate(self): Calculate AUC. | Implement the Python class `AUCMetric` described below.
Class description:
A metric class to return AUC.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize AUCMetric.
- def calculate(self): Calculate AUC.
<|skeleton|>
class AUCMetric:
"""A metric class to return AUC."""
def __init_... | cbf468f030ab6b337d549ca77c5158eac6429f2a | <|skeleton|>
class AUCMetric:
"""A metric class to return AUC."""
def __init__(self, **kwargs):
"""Initialize AUCMetric."""
<|body_0|>
def calculate(self):
"""Calculate AUC."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AUCMetric:
"""A metric class to return AUC."""
def __init__(self, **kwargs):
"""Initialize AUCMetric."""
super().__init__(**kwargs)
self._name = 'auc'
self._type = 'max'
def calculate(self):
"""Calculate AUC."""
y_true, y_pred = self.get_true_pred_data... | the_stack_v2_python_sparse | multiml/agent/metric.py | camellia26/multiml | train | 0 |
e5b52a15afb6a90b02115a2567485fe602292fc2 | [
"bert = cls()\nif 'farm_lm_name' in kwargs:\n bert.name = kwargs['farm_lm_name']\nelse:\n bert.name = pretrained_model_name_or_path\nfarm_lm_config = Path(pretrained_model_name_or_path) / 'language_model_config.json'\nif os.path.exists(farm_lm_config):\n bert_config = BertConfig.from_pretrained(farm_lm_con... | <|body_start_0|>
bert = cls()
if 'farm_lm_name' in kwargs:
bert.name = kwargs['farm_lm_name']
else:
bert.name = pretrained_model_name_or_path
farm_lm_config = Path(pretrained_model_name_or_path) / 'language_model_config.json'
if os.path.exists(farm_lm_conf... | BertLongLanguageModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertLongLanguageModel:
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""Load a pretrained model by supplying * the name of a remote model on s3 ("bert-base-cased" ...) * OR a local path of a model trained via transformers ("some_dir/huggingface_model") * OR a loc... | stack_v2_sparse_classes_75kplus_train_005445 | 4,031 | no_license | [
{
"docstring": "Load a pretrained model by supplying * the name of a remote model on s3 (\"bert-base-cased\" ...) * OR a local path of a model trained via transformers (\"some_dir/huggingface_model\") * OR a local path of a model trained via FARM (\"some_dir/farm_model\") :param pretrained_model_name_or_path: T... | 2 | stack_v2_sparse_classes_30k_train_002053 | Implement the Python class `BertLongLanguageModel` described below.
Class description:
Implement the BertLongLanguageModel class.
Method signatures and docstrings:
- def load(cls, pretrained_model_name_or_path, language=None, **kwargs): Load a pretrained model by supplying * the name of a remote model on s3 ("bert-ba... | Implement the Python class `BertLongLanguageModel` described below.
Class description:
Implement the BertLongLanguageModel class.
Method signatures and docstrings:
- def load(cls, pretrained_model_name_or_path, language=None, **kwargs): Load a pretrained model by supplying * the name of a remote model on s3 ("bert-ba... | 79aa582d0f17f1e8dace19d4b893daf15fb1b793 | <|skeleton|>
class BertLongLanguageModel:
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""Load a pretrained model by supplying * the name of a remote model on s3 ("bert-base-cased" ...) * OR a local path of a model trained via transformers ("some_dir/huggingface_model") * OR a loc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BertLongLanguageModel:
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""Load a pretrained model by supplying * the name of a remote model on s3 ("bert-base-cased" ...) * OR a local path of a model trained via transformers ("some_dir/huggingface_model") * OR a local path of a m... | the_stack_v2_python_sparse | experiments/custom_models/Longformer.py | agrov/MTL_clinical_outcome | train | 0 | |
d2984848ce0d9e83b070f82a4ba3febe86940e5f | [
"super(RunningNorm, self).__init__(name=name)\nself.history_length = history_length\nself.max_divisor = max_divisor\nself.upper_idx = int((self.history_length - 1) * upper_percentile)\nself.lower_idx = int((self.history_length - 1) * lower_percentile)\nself.clip = clip\nself.return_sample = None\nself.norm_lists = ... | <|body_start_0|>
super(RunningNorm, self).__init__(name=name)
self.history_length = history_length
self.max_divisor = max_divisor
self.upper_idx = int((self.history_length - 1) * upper_percentile)
self.lower_idx = int((self.history_length - 1) * lower_percentile)
self.cli... | Takes a stream of frames and normalize them (per dimension) using a running percentile approach | RunningNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunningNorm:
"""Takes a stream of frames and normalize them (per dimension) using a running percentile approach"""
def __init__(self, channels=None, history_length=550, max_divisor=0.01, upper_percentile=0.99, lower_percentile=0.9, clip=True, update_every=1, name='RunningNorm'):
"""S... | stack_v2_sparse_classes_75kplus_train_005446 | 2,941 | no_license | [
{
"docstring": "Stores parameters for the normalizing.",
"name": "__init__",
"signature": "def __init__(self, channels=None, history_length=550, max_divisor=0.01, upper_percentile=0.99, lower_percentile=0.9, clip=True, update_every=1, name='RunningNorm')"
},
{
"docstring": "Running normalization... | 2 | stack_v2_sparse_classes_30k_train_044343 | Implement the Python class `RunningNorm` described below.
Class description:
Takes a stream of frames and normalize them (per dimension) using a running percentile approach
Method signatures and docstrings:
- def __init__(self, channels=None, history_length=550, max_divisor=0.01, upper_percentile=0.99, lower_percenti... | Implement the Python class `RunningNorm` described below.
Class description:
Takes a stream of frames and normalize them (per dimension) using a running percentile approach
Method signatures and docstrings:
- def __init__(self, channels=None, history_length=550, max_divisor=0.01, upper_percentile=0.99, lower_percenti... | 8766168c07f1fe8ab9743034a7512bc1861388a7 | <|skeleton|>
class RunningNorm:
"""Takes a stream of frames and normalize them (per dimension) using a running percentile approach"""
def __init__(self, channels=None, history_length=550, max_divisor=0.01, upper_percentile=0.99, lower_percentile=0.9, clip=True, update_every=1, name='RunningNorm'):
"""S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunningNorm:
"""Takes a stream of frames and normalize them (per dimension) using a running percentile approach"""
def __init__(self, channels=None, history_length=550, max_divisor=0.01, upper_percentile=0.99, lower_percentile=0.9, clip=True, update_every=1, name='RunningNorm'):
"""Stores paramet... | the_stack_v2_python_sparse | Nodes/RunningNorm.py | cognitive-systems-lab/EMG-GUI | train | 0 |
3236b0b970465c83630651fb37628868a253f3e2 | [
"node = self._getObjectNode('object')\nnode.appendChild(self._extractProperties())\nnode.appendChild(self._extractObjects())\nself._logger.info('Types tool exported.')\nreturn node",
"if self.environ.shouldPurge():\n self._purgeProperties()\n self._purgeObjects()\nself._initProperties(node)\nself._initObjec... | <|body_start_0|>
node = self._getObjectNode('object')
node.appendChild(self._extractProperties())
node.appendChild(self._extractObjects())
self._logger.info('Types tool exported.')
return node
<|end_body_0|>
<|body_start_1|>
if self.environ.shouldPurge():
sel... | XML im- and exporter for TypesTool. | TypesToolXMLAdapter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypesToolXMLAdapter:
"""XML im- and exporter for TypesTool."""
def _exportNode(self):
"""Export the object as a DOM node."""
<|body_0|>
def _importNode(self, node):
"""Import the object from the DOM node."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005447 | 8,767 | permissive | [
{
"docstring": "Export the object as a DOM node.",
"name": "_exportNode",
"signature": "def _exportNode(self)"
},
{
"docstring": "Import the object from the DOM node.",
"name": "_importNode",
"signature": "def _importNode(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053601 | Implement the Python class `TypesToolXMLAdapter` described below.
Class description:
XML im- and exporter for TypesTool.
Method signatures and docstrings:
- def _exportNode(self): Export the object as a DOM node.
- def _importNode(self, node): Import the object from the DOM node. | Implement the Python class `TypesToolXMLAdapter` described below.
Class description:
XML im- and exporter for TypesTool.
Method signatures and docstrings:
- def _exportNode(self): Export the object as a DOM node.
- def _importNode(self, node): Import the object from the DOM node.
<|skeleton|>
class TypesToolXMLAdapt... | 8c32b5ec521536c1a2c3752426f6ed209b11190c | <|skeleton|>
class TypesToolXMLAdapter:
"""XML im- and exporter for TypesTool."""
def _exportNode(self):
"""Export the object as a DOM node."""
<|body_0|>
def _importNode(self, node):
"""Import the object from the DOM node."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TypesToolXMLAdapter:
"""XML im- and exporter for TypesTool."""
def _exportNode(self):
"""Export the object as a DOM node."""
node = self._getObjectNode('object')
node.appendChild(self._extractProperties())
node.appendChild(self._extractObjects())
self._logger.info(... | the_stack_v2_python_sparse | src/Products/CMFCore/exportimport/typeinfo.py | zopefoundation/Products.CMFCore | train | 4 |
3df723a63680e66cc032c999335f1638a515b872 | [
"self.event_connections = []\n' List of event connections b/w components. The from and to\\n attributes are described as component:port\\n @type: list((string, string)) '\nself.single_child_defs = []\n' List of single-child instantiation definitions.\\n @type: list(string) '\nself.multi_child_d... | <|body_start_0|>
self.event_connections = []
' List of event connections b/w components. The from and to\n attributes are described as component:port\n @type: list((string, string)) '
self.single_child_defs = []
' List of single-child instantiation definitions.\n @ty... | Stores the structural characteristics for a component type. | Structure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Structure:
"""Stores the structural characteristics for a component type."""
def __init__(self):
"""Constructor."""
<|body_0|>
def add_event_connection(self, from_, to):
"""Adds an event connection to the list of event connections in this component. @param from_:... | stack_v2_sparse_classes_75kplus_train_005448 | 4,147 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds an event connection to the list of event connections in this component. @param from_: The component:port from where the event originates. @type from_: string @param to: The component:port... | 5 | stack_v2_sparse_classes_30k_train_042117 | Implement the Python class `Structure` described below.
Class description:
Stores the structural characteristics for a component type.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def add_event_connection(self, from_, to): Adds an event connection to the list of event connections in this com... | Implement the Python class `Structure` described below.
Class description:
Stores the structural characteristics for a component type.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def add_event_connection(self, from_, to): Adds an event connection to the list of event connections in this com... | 7fc8ff79fbf2cd0c28cad1e4ab3e7b65b0c2bda3 | <|skeleton|>
class Structure:
"""Stores the structural characteristics for a component type."""
def __init__(self):
"""Constructor."""
<|body_0|>
def add_event_connection(self, from_, to):
"""Adds an event connection to the list of event connections in this component. @param from_:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Structure:
"""Stores the structural characteristics for a component type."""
def __init__(self):
"""Constructor."""
self.event_connections = []
' List of event connections b/w components. The from and to\n attributes are described as component:port\n @type: list((str... | the_stack_v2_python_sparse | lems/model/structure.py | stevemarsh/pylems | train | 0 |
34298ffd8e29cf2ea15b1a8b6fb9c5ddb8024603 | [
"self.res = []\nself._reverse_print(head)\nreturn self.res",
"if not head:\n return\nself._reverse_print(head.next)\nself.res.append(head.val)"
] | <|body_start_0|>
self.res = []
self._reverse_print(head)
return self.res
<|end_body_0|>
<|body_start_1|>
if not head:
return
self._reverse_print(head.next)
self.res.append(head.val)
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reversePrint(self, head):
"""time: O(N) space: O(N) Args: head: ListNode Return: List[int]"""
<|body_0|>
def _reverse_print(self, head):
"""Args: head: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.res = []
self... | stack_v2_sparse_classes_75kplus_train_005449 | 983 | no_license | [
{
"docstring": "time: O(N) space: O(N) Args: head: ListNode Return: List[int]",
"name": "reversePrint",
"signature": "def reversePrint(self, head)"
},
{
"docstring": "Args: head: ListNode",
"name": "_reverse_print",
"signature": "def _reverse_print(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reversePrint(self, head): time: O(N) space: O(N) Args: head: ListNode Return: List[int]
- def _reverse_print(self, head): Args: head: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reversePrint(self, head): time: O(N) space: O(N) Args: head: ListNode Return: List[int]
- def _reverse_print(self, head): Args: head: ListNode
<|skeleton|>
class Solution:
... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def reversePrint(self, head):
"""time: O(N) space: O(N) Args: head: ListNode Return: List[int]"""
<|body_0|>
def _reverse_print(self, head):
"""Args: head: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reversePrint(self, head):
"""time: O(N) space: O(N) Args: head: ListNode Return: List[int]"""
self.res = []
self._reverse_print(head)
return self.res
def _reverse_print(self, head):
"""Args: head: ListNode"""
if not head:
return
... | the_stack_v2_python_sparse | code/面试题06. 从尾到头打印链表.py | AiZhanghan/Leetcode | train | 0 | |
9a0e9aae6fe2d7883105feebc28ed50090160bc3 | [
"self.trees_num = trees_num\nself.depth = depth\nself.output_logits_dim = output_logits_dim\nself.smooth_step_param = smooth_step_param\nself.parallelize_over_samples = parallelize_over_samples\nself.sum_outputs = sum_outputs\nself.split_initializer = keras.initializers.get(split_initializer)\nself.leaf_initializer... | <|body_start_0|>
self.trees_num = trees_num
self.depth = depth
self.output_logits_dim = output_logits_dim
self.smooth_step_param = smooth_step_param
self.parallelize_over_samples = parallelize_over_samples
self.sum_outputs = sum_outputs
self.split_initializer = ke... | A custom layer containing additive decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only one child) or in a soft way. The decision whe... | NeuralTrees | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralTrees:
"""A custom layer containing additive decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only one ch... | stack_v2_sparse_classes_75kplus_train_005450 | 7,707 | permissive | [
{
"docstring": "Initializes neural trees layer.",
"name": "__init__",
"signature": "def __init__(self, output_logits_dim, trees_num=1, depth=3, smooth_step_param=0.3, sum_outputs=True, parallelize_over_samples=False, split_initializer=RandomUniform(-0.01, 0.01), leaf_initializer=RandomUniform(-0.01, 0.0... | 5 | null | Implement the Python class `NeuralTrees` described below.
Class description:
A custom layer containing additive decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed i... | Implement the Python class `NeuralTrees` described below.
Class description:
A custom layer containing additive decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed i... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class NeuralTrees:
"""A custom layer containing additive decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only one ch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralTrees:
"""A custom layer containing additive decision trees. Each tree in the layer is composed of splitting (internal) nodes and leaves. A splitting node "routes" the samples left or right based on the corresponding activation. Samples can be routed in a hard way (i.e., sent to only one child) or in a ... | the_stack_v2_python_sparse | tf_trees/neural_trees_layer.py | Tarkiyah/googleResearch | train | 11 |
46cbd726862a2c1d26e2813f68439fa48c908e69 | [
"instance = TriggerInstance(action, trigger_info, self)\nself.trigger_instances.append(instance)\nif self.topic is not None:\n await instance.async_attach_trigger()\n\n@callback\ndef async_remove() -> None:\n \"\"\"Remove trigger.\"\"\"\n if instance not in self.trigger_instances:\n raise HomeAssist... | <|body_start_0|>
instance = TriggerInstance(action, trigger_info, self)
self.trigger_instances.append(instance)
if self.topic is not None:
await instance.async_attach_trigger()
@callback
def async_remove() -> None:
"""Remove trigger."""
if ins... | Device trigger settings. | Trigger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trigger:
"""Device trigger settings."""
async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]:
"""Add MQTT trigger."""
<|body_0|>
async def update_trigger(self, config: ConfigType) -> None:
"""Update MQTT device t... | stack_v2_sparse_classes_75kplus_train_005451 | 11,475 | permissive | [
{
"docstring": "Add MQTT trigger.",
"name": "add_trigger",
"signature": "async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]"
},
{
"docstring": "Update MQTT device trigger.",
"name": "update_trigger",
"signature": "async def update_trig... | 3 | stack_v2_sparse_classes_30k_train_011126 | Implement the Python class `Trigger` described below.
Class description:
Device trigger settings.
Method signatures and docstrings:
- async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: Add MQTT trigger.
- async def update_trigger(self, config: ConfigType) -> None:... | Implement the Python class `Trigger` described below.
Class description:
Device trigger settings.
Method signatures and docstrings:
- async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: Add MQTT trigger.
- async def update_trigger(self, config: ConfigType) -> None:... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Trigger:
"""Device trigger settings."""
async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]:
"""Add MQTT trigger."""
<|body_0|>
async def update_trigger(self, config: ConfigType) -> None:
"""Update MQTT device t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trigger:
"""Device trigger settings."""
async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]:
"""Add MQTT trigger."""
instance = TriggerInstance(action, trigger_info, self)
self.trigger_instances.append(instance)
if self.t... | the_stack_v2_python_sparse | homeassistant/components/mqtt/device_trigger.py | home-assistant/core | train | 35,501 |
5b62c474c7a3113c037069c9b2ceb49a5fd9eca5 | [
"if type(data) is not np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nd, n = data.shape\nif n < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1).reshape(d, 1)\nX = data - self.mean\nself.cov = np.matmul(X, X.T) / (n - ... | <|body_start_0|>
if type(data) is not np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = data.shape
if n < 2:
raise ValueError('data must contain multiple data points')
self.mean = np.mean(data, axis=1).reshape(d, 1)
... | Class multinormal | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Class multinormal"""
def __init__(self, data):
"""Class constructor"""
<|body_0|>
def pdf(self, x):
"""Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing the data point whose P... | stack_v2_sparse_classes_75kplus_train_005452 | 1,495 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing the data point whose PDF should be calculated. Returns:",
... | 2 | stack_v2_sparse_classes_30k_train_019378 | Implement the Python class `MultiNormal` described below.
Class description:
Class multinormal
Method signatures and docstrings:
- def __init__(self, data): Class constructor
- def pdf(self, x): Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing t... | Implement the Python class `MultiNormal` described below.
Class description:
Class multinormal
Method signatures and docstrings:
- def __init__(self, data): Class constructor
- def pdf(self, x): Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing t... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class MultiNormal:
"""Class multinormal"""
def __init__(self, data):
"""Class constructor"""
<|body_0|>
def pdf(self, x):
"""Calculates the Probability distribution function at a data point. Args: x (np.ndarray): matrix of shape (d, 1) containing the data point whose P... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""Class multinormal"""
def __init__(self, data):
"""Class constructor"""
if type(data) is not np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = data.shape
if n < 2:
raise ValueError('data mus... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
017005a9942002b1c99bd927dee08f8d76159a8d | [
"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... | Proto file describing the Campaign Criterion service. Service to manage campaign criteria. | CampaignCriterionServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignCriterionServiceServicer:
"""Proto file describing the Campaign Criterion service. Service to manage campaign criteria."""
def GetCampaignCriterion(self, request, context):
"""Returns the requested criterion in full detail."""
<|body_0|>
def MutateCampaignCriteri... | stack_v2_sparse_classes_75kplus_train_005453 | 5,776 | permissive | [
{
"docstring": "Returns the requested criterion in full detail.",
"name": "GetCampaignCriterion",
"signature": "def GetCampaignCriterion(self, request, context)"
},
{
"docstring": "Creates, updates, or removes criteria. Operation statuses are returned.",
"name": "MutateCampaignCriteria",
... | 2 | stack_v2_sparse_classes_30k_train_052478 | Implement the Python class `CampaignCriterionServiceServicer` described below.
Class description:
Proto file describing the Campaign Criterion service. Service to manage campaign criteria.
Method signatures and docstrings:
- def GetCampaignCriterion(self, request, context): Returns the requested criterion in full det... | Implement the Python class `CampaignCriterionServiceServicer` described below.
Class description:
Proto file describing the Campaign Criterion service. Service to manage campaign criteria.
Method signatures and docstrings:
- def GetCampaignCriterion(self, request, context): Returns the requested criterion in full det... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class CampaignCriterionServiceServicer:
"""Proto file describing the Campaign Criterion service. Service to manage campaign criteria."""
def GetCampaignCriterion(self, request, context):
"""Returns the requested criterion in full detail."""
<|body_0|>
def MutateCampaignCriteri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CampaignCriterionServiceServicer:
"""Proto file describing the Campaign Criterion service. Service to manage campaign criteria."""
def GetCampaignCriterion(self, request, context):
"""Returns the requested criterion in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/campaign_criterion_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
a49c8da3f2f0ddba68181e58cd708323a9ab6ff7 | [
"super(GLU, self).__init__()\nassert input_type in ['fc', 'conv2d']\nif input_type == 'fc':\n self.layer1 = nn.Linear(context_dim, input_dim)\n self.layer2 = nn.Linear(input_dim, output_dim)\nelif input_type == 'conv2d':\n self.layer1 = nn.Conv2d(context_dim, input_dim, 1, 1, 0)\n self.layer2 = nn.Conv2... | <|body_start_0|>
super(GLU, self).__init__()
assert input_type in ['fc', 'conv2d']
if input_type == 'fc':
self.layer1 = nn.Linear(context_dim, input_dim)
self.layer2 = nn.Linear(input_dim, output_dim)
elif input_type == 'conv2d':
self.layer1 = nn.Conv2... | Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the input. gate = sigmoid(linear(input.size)(context)) # Gate the input and return an output of desired size. gated_input = gate * input output = linear(output_... | GLU | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GLU:
"""Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the input. gate = sigmoid(linear(input.size)(context)) # Gate the input and return an output of desired size. gated_input = gate ... | stack_v2_sparse_classes_75kplus_train_005454 | 2,968 | permissive | [
{
"docstring": "Overview: Init GLU Arguments: - input_dim (:obj:`int`): the input dimension - output_dim (:obj:`int`): the output dimension - context_dim (:obj:`int`): the context dimension - input_type (:obj:`str`): the type of input, now support ['fc', 'conv2d']",
"name": "__init__",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_val_001573 | Implement the Python class `GLU` described below.
Class description:
Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the input. gate = sigmoid(linear(input.size)(context)) # Gate the input and return an outp... | Implement the Python class `GLU` described below.
Class description:
Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the input. gate = sigmoid(linear(input.size)(context)) # Gate the input and return an outp... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class GLU:
"""Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the input. gate = sigmoid(linear(input.size)(context)) # Gate the input and return an output of desired size. gated_input = gate ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GLU:
"""Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the input. gate = sigmoid(linear(input.size)(context)) # Gate the input and return an output of desired size. gated_input = gate * input outpu... | the_stack_v2_python_sparse | ding/torch_utils/network/activation.py | shengxuesun/DI-engine | train | 1 |
c8ea358fae71a32ffac9f03c116940ddf9369630 | [
"response = requests.get(end_point[2] + brew_get_brewery)\nactual = response.json()\nexpected = brew_get_brewery_response\nassert actual == expected\nassert response.status_code == 200",
"response = requests.get(end_point[2] + brew_filter_by_state)\nfor data in response.json():\n assert data['state'] == brewer... | <|body_start_0|>
response = requests.get(end_point[2] + brew_get_brewery)
actual = response.json()
expected = brew_get_brewery_response
assert actual == expected
assert response.status_code == 200
<|end_body_0|>
<|body_start_1|>
response = requests.get(end_point[2] + bre... | Testsuite of tests for JSON API https://api.openbrewerydb.org | TestSuiteOpenbrewerydb | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSuiteOpenbrewerydb:
"""Testsuite of tests for JSON API https://api.openbrewerydb.org"""
def test_brew_get_brewery(self, end_point, brew_get_brewery, brew_get_brewery_response):
"""Get breweries list test"""
<|body_0|>
def test_brew_filter_by_state(self, end_point, br... | stack_v2_sparse_classes_75kplus_train_005455 | 10,869 | permissive | [
{
"docstring": "Get breweries list test",
"name": "test_brew_get_brewery",
"signature": "def test_brew_get_brewery(self, end_point, brew_get_brewery, brew_get_brewery_response)"
},
{
"docstring": "Filter breweries list by state test",
"name": "test_brew_filter_by_state",
"signature": "de... | 6 | null | Implement the Python class `TestSuiteOpenbrewerydb` described below.
Class description:
Testsuite of tests for JSON API https://api.openbrewerydb.org
Method signatures and docstrings:
- def test_brew_get_brewery(self, end_point, brew_get_brewery, brew_get_brewery_response): Get breweries list test
- def test_brew_fil... | Implement the Python class `TestSuiteOpenbrewerydb` described below.
Class description:
Testsuite of tests for JSON API https://api.openbrewerydb.org
Method signatures and docstrings:
- def test_brew_get_brewery(self, end_point, brew_get_brewery, brew_get_brewery_response): Get breweries list test
- def test_brew_fil... | 9d7e31317857801735bad8c05e2c15757dab0ab1 | <|skeleton|>
class TestSuiteOpenbrewerydb:
"""Testsuite of tests for JSON API https://api.openbrewerydb.org"""
def test_brew_get_brewery(self, end_point, brew_get_brewery, brew_get_brewery_response):
"""Get breweries list test"""
<|body_0|>
def test_brew_filter_by_state(self, end_point, br... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSuiteOpenbrewerydb:
"""Testsuite of tests for JSON API https://api.openbrewerydb.org"""
def test_brew_get_brewery(self, end_point, brew_get_brewery, brew_get_brewery_response):
"""Get breweries list test"""
response = requests.get(end_point[2] + brew_get_brewery)
actual = resp... | the_stack_v2_python_sparse | lesson_3/test_lesson_3.py | Sokolov85/otus-qa-course | train | 0 |
2293f316453ab980e638c99c1500df574c7d0581 | [
"super(MGCN, self).__init__()\nself.raw = [FullyConnectNN(i, n_hids, h_size, act, layer_norm_on) for i in n_feats]\nself.msg = MultiMessagePassing([h_size for _ in range(len(n_feats))], n_hids, h_size, n_steps, act, layer_norm_on)\nself.transform = FullyConnectNN(h_size, n_hids, n_output, act, layer_norm_on)",
"i... | <|body_start_0|>
super(MGCN, self).__init__()
self.raw = [FullyConnectNN(i, n_hids, h_size, act, layer_norm_on) for i in n_feats]
self.msg = MultiMessagePassing([h_size for _ in range(len(n_feats))], n_hids, h_size, n_steps, act, layer_norm_on)
self.transform = FullyConnectNN(h_size, n_h... | MGCN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MGCN:
def __init__(self, n_feats, n_output, n_hids, h_size, n_steps, act=nn.LeakyReLU, layer_norm_on=False):
"""n_feats: number of node features (a list) n_output: output size of node n_hids: number of hidden neurons (a list) n_steps: number of message passing steps The list in the input... | stack_v2_sparse_classes_75kplus_train_005456 | 1,914 | no_license | [
{
"docstring": "n_feats: number of node features (a list) n_output: output size of node n_hids: number of hidden neurons (a list) n_steps: number of message passing steps The list in the input features correspond to different type of the intput. For each type, there are 3 processing units: 1. map all raw featur... | 2 | stack_v2_sparse_classes_30k_train_046603 | Implement the Python class `MGCN` described below.
Class description:
Implement the MGCN class.
Method signatures and docstrings:
- def __init__(self, n_feats, n_output, n_hids, h_size, n_steps, act=nn.LeakyReLU, layer_norm_on=False): n_feats: number of node features (a list) n_output: output size of node n_hids: num... | Implement the Python class `MGCN` described below.
Class description:
Implement the MGCN class.
Method signatures and docstrings:
- def __init__(self, n_feats, n_output, n_hids, h_size, n_steps, act=nn.LeakyReLU, layer_norm_on=False): n_feats: number of node features (a list) n_output: output size of node n_hids: num... | 4bda823ef99a34a9a3250192897d2a0faedca500 | <|skeleton|>
class MGCN:
def __init__(self, n_feats, n_output, n_hids, h_size, n_steps, act=nn.LeakyReLU, layer_norm_on=False):
"""n_feats: number of node features (a list) n_output: output size of node n_hids: number of hidden neurons (a list) n_steps: number of message passing steps The list in the input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MGCN:
def __init__(self, n_feats, n_output, n_hids, h_size, n_steps, act=nn.LeakyReLU, layer_norm_on=False):
"""n_feats: number of node features (a list) n_output: output size of node n_hids: number of hidden neurons (a list) n_steps: number of message passing steps The list in the input features corr... | the_stack_v2_python_sparse | gcn/mgcn.py | kshiteejm/net-update-code | train | 0 | |
ec67b2d467221d14944dfcf25831faf75adae755 | [
"payload = {'layers': 'heat_tot_curr_density_ha', 'year': '2012', 'areas': [{'points': [{'lat': 48.25759852914997, 'lng': 16.351432800292972}, {'lat': 48.267426453675895, 'lng': 16.351432800292972}, {'lat': 48.267426453675895, 'lng': 16.369628906250004}, {'lat': 48.25759852914997, 'lng': 16.369628906250004}]}]}\nex... | <|body_start_0|>
payload = {'layers': 'heat_tot_curr_density_ha', 'year': '2012', 'areas': [{'points': [{'lat': 48.25759852914997, 'lng': 16.351432800292972}, {'lat': 48.267426453675895, 'lng': 16.351432800292972}, {'lat': 48.267426453675895, 'lng': 16.369628906250004}, {'lat': 48.25759852914997, 'lng': 16.3696... | TestExportRasterHectare | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExportRasterHectare:
def test_post(self):
"""this test will pass the upload/export/raster/hectare method"""
<|body_0|>
def test_port_wrong_parameters(self):
"""this test will fail because the wrong parameters are given"""
<|body_1|>
def test_post_wro... | stack_v2_sparse_classes_75kplus_train_005457 | 2,494 | permissive | [
{
"docstring": "this test will pass the upload/export/raster/hectare method",
"name": "test_post",
"signature": "def test_post(self)"
},
{
"docstring": "this test will fail because the wrong parameters are given",
"name": "test_port_wrong_parameters",
"signature": "def test_port_wrong_pa... | 3 | stack_v2_sparse_classes_30k_train_045880 | Implement the Python class `TestExportRasterHectare` described below.
Class description:
Implement the TestExportRasterHectare class.
Method signatures and docstrings:
- def test_post(self): this test will pass the upload/export/raster/hectare method
- def test_port_wrong_parameters(self): this test will fail because... | Implement the Python class `TestExportRasterHectare` described below.
Class description:
Implement the TestExportRasterHectare class.
Method signatures and docstrings:
- def test_post(self): this test will pass the upload/export/raster/hectare method
- def test_port_wrong_parameters(self): this test will fail because... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestExportRasterHectare:
def test_post(self):
"""this test will pass the upload/export/raster/hectare method"""
<|body_0|>
def test_port_wrong_parameters(self):
"""this test will fail because the wrong parameters are given"""
<|body_1|>
def test_post_wro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestExportRasterHectare:
def test_post(self):
"""this test will pass the upload/export/raster/hectare method"""
payload = {'layers': 'heat_tot_curr_density_ha', 'year': '2012', 'areas': [{'points': [{'lat': 48.25759852914997, 'lng': 16.351432800292972}, {'lat': 48.267426453675895, 'lng': 16.35... | the_stack_v2_python_sparse | pytest_suit/routes/uploads/test_exportRasterHectare.py | HotMaps/Hotmaps-toolbox-service | train | 4 | |
68e947a37066d7651e46c12d790c90490a96c602 | [
"if self.action in ['list']:\n permission_classes = [IsAuthenticated]\nelse:\n try:\n permission_classes = getattr(self, self.action).kwargs.get('permission_classes')\n except AttributeError:\n permission_classes = self.permission_classes\nreturn [permission() for permission in permission_cla... | <|body_start_0|>
if self.action in ['list']:
permission_classes = [IsAuthenticated]
else:
try:
permission_classes = getattr(self, self.action).kwargs.get('permission_classes')
except AttributeError:
permission_classes = self.permission_... | API endpoints for users. | UserViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
"""API endpoints for users."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
def list(self, request, *args, *... | stack_v2_sparse_classes_75kplus_train_005458 | 6,127 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "This endpoint is intended to allow searc... | 4 | stack_v2_sparse_classes_30k_train_026323 | Implement the Python class `UserViewSet` described below.
Class description:
API endpoints for users.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.
- ... | Implement the Python class `UserViewSet` described below.
Class description:
API endpoints for users.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions.
- ... | 22e4afa728a851bb4c2479fbb6f5944a75984b9b | <|skeleton|>
class UserViewSet:
"""API endpoints for users."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
def list(self, request, *args, *... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserViewSet:
"""API endpoints for users."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods, defaulting to the actions self defined permissions if applicable or to the ViewSet's default permissions."""
if self.action in ['list']:
permission_classes = ... | the_stack_v2_python_sparse | src/backend/partaj/core/api/user.py | MTES-MCT/partaj | train | 4 |
7e967f9dee523d2cfea0f0eb6ec019c763ca8106 | [
"self.current_frame_index = None\nself.packets_data = []\nself.remaining_packets = None",
"full_frame = b''\nis_first_packet = self.current_frame_index is None\nif is_first_packet or p.frame_index > self.current_frame_index:\n if not is_first_packet and self.remaining_packets != 0:\n full_frame = b''\n ... | <|body_start_0|>
self.current_frame_index = None
self.packets_data = []
self.remaining_packets = None
<|end_body_0|>
<|body_start_1|>
full_frame = b''
is_first_packet = self.current_frame_index is None
if is_first_packet or p.frame_index > self.current_frame_index:
... | Definition of the class UdpPacketsHandler. | UdpPacketsHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UdpPacketsHandler:
"""Definition of the class UdpPacketsHandler."""
def __init__(self):
"""Constructor."""
<|body_0|>
def process_packet(self, p: UdpPacket) -> Union[bytes, None]:
"""Processes a given packet. If all the packets were collected, returns the full fr... | stack_v2_sparse_classes_75kplus_train_005459 | 3,250 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Processes a given packet. If all the packets were collected, returns the full frame. Otherwise, returns None.",
"name": "process_packet",
"signature": "def process_packet(self, p: UdpP... | 3 | stack_v2_sparse_classes_30k_train_015916 | Implement the Python class `UdpPacketsHandler` described below.
Class description:
Definition of the class UdpPacketsHandler.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def process_packet(self, p: UdpPacket) -> Union[bytes, None]: Processes a given packet. If all the packets were collected... | Implement the Python class `UdpPacketsHandler` described below.
Class description:
Definition of the class UdpPacketsHandler.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def process_packet(self, p: UdpPacket) -> Union[bytes, None]: Processes a given packet. If all the packets were collected... | d88933620286e655c39776e0a4e99de9d9067172 | <|skeleton|>
class UdpPacketsHandler:
"""Definition of the class UdpPacketsHandler."""
def __init__(self):
"""Constructor."""
<|body_0|>
def process_packet(self, p: UdpPacket) -> Union[bytes, None]:
"""Processes a given packet. If all the packets were collected, returns the full fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UdpPacketsHandler:
"""Definition of the class UdpPacketsHandler."""
def __init__(self):
"""Constructor."""
self.current_frame_index = None
self.packets_data = []
self.remaining_packets = None
def process_packet(self, p: UdpPacket) -> Union[bytes, None]:
"""Pro... | the_stack_v2_python_sparse | client/video/udp_packets_handler.py | HadarShahar/zoom | train | 0 |
c7dd6d09117cc8686eddbd1a7ea10d88a5909a25 | [
"transactions = get_transactions_by_gifts(None)\nresult = TransactionSchema(many=True).dump(transactions).data\nreturn (result, 200)",
"transactions = get_transactions_by_gifts(request.json['searchable_ids'])\nresult = TransactionSchema(many=True).dump(transactions).data\nreturn (result, 200)"
] | <|body_start_0|>
transactions = get_transactions_by_gifts(None)
result = TransactionSchema(many=True).dump(transactions).data
return (result, 200)
<|end_body_0|>
<|body_start_1|>
transactions = get_transactions_by_gifts(request.json['searchable_ids'])
result = TransactionSchema(... | Flask-RESTful resource endpoints for TransactionModel by gift searchable ID's. | TransactionsByGifts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionsByGifts:
"""Flask-RESTful resource endpoints for TransactionModel by gift searchable ID's."""
def get(self):
"""Simple endpoint to retrieve all rows from table."""
<|body_0|>
def post(self):
"""Simple endpoint to return several rows from table given a... | stack_v2_sparse_classes_75kplus_train_005460 | 4,727 | no_license | [
{
"docstring": "Simple endpoint to retrieve all rows from table.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Simple endpoint to return several rows from table given a list of gift searchable ID's.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040105 | Implement the Python class `TransactionsByGifts` described below.
Class description:
Flask-RESTful resource endpoints for TransactionModel by gift searchable ID's.
Method signatures and docstrings:
- def get(self): Simple endpoint to retrieve all rows from table.
- def post(self): Simple endpoint to return several ro... | Implement the Python class `TransactionsByGifts` described below.
Class description:
Flask-RESTful resource endpoints for TransactionModel by gift searchable ID's.
Method signatures and docstrings:
- def get(self): Simple endpoint to retrieve all rows from table.
- def post(self): Simple endpoint to return several ro... | d5ffcc5d276692d1578cea704125b1b3952beb1c | <|skeleton|>
class TransactionsByGifts:
"""Flask-RESTful resource endpoints for TransactionModel by gift searchable ID's."""
def get(self):
"""Simple endpoint to retrieve all rows from table."""
<|body_0|>
def post(self):
"""Simple endpoint to return several rows from table given a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransactionsByGifts:
"""Flask-RESTful resource endpoints for TransactionModel by gift searchable ID's."""
def get(self):
"""Simple endpoint to retrieve all rows from table."""
transactions = get_transactions_by_gifts(None)
result = TransactionSchema(many=True).dump(transactions).d... | the_stack_v2_python_sparse | application/resources/transaction.py | transreductionist/API-Project-1 | train | 0 |
1f4780688b393b4658f4e0f3523ba672931c1a8a | [
"self.model = model\nself.data = data\nself.checkpoint_dir = checkpoint_dir\nif log_dir:\n self._summary_writer = summary_ops_v2.create_file_writer_v2(logdir=log_dir)\nelse:\n self._summary_writer = None\nself._iterations = variables.Variable(name='iterations', initial_value=_ITERATIONS_UNINITIALIZED, dtype=d... | <|body_start_0|>
self.model = model
self.data = data
self.checkpoint_dir = checkpoint_dir
if log_dir:
self._summary_writer = summary_ops_v2.create_file_writer_v2(logdir=log_dir)
else:
self._summary_writer = None
self._iterations = variables.Variabl... | A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (with compiled metrics) provided at `__init__... | SidecarEvaluator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SidecarEvaluator:
"""A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (... | stack_v2_sparse_classes_75kplus_train_005461 | 8,189 | permissive | [
{
"docstring": "Initializes an `SidecarEvaluator` object. Args: model: Model to use for evaluation. The model object used here should be a `tf.keras.Model`, and should be the same as the one that is used in training, where `tf.keras.Model`s are checkpointed. The model should have one or more metrics compiled be... | 2 | stack_v2_sparse_classes_30k_train_047054 | Implement the Python class `SidecarEvaluator` described below.
Class description:
A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, an... | Implement the Python class `SidecarEvaluator` described below.
Class description:
A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, an... | 1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206 | <|skeleton|>
class SidecarEvaluator:
"""A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SidecarEvaluator:
"""A class designed for a dedicated evaluator task. `SidecarEvaluator` is expected to be run on a process in a separate machine from the training cluster. It continuously loads checkpoints saved periodically by that training counterpart, and performs evaluation using the model (with compiled... | the_stack_v2_python_sparse | tensorflow/python/keras/distribute/sidecar_evaluator.py | galeone/tensorflow | train | 21 |
ca1ec382ef5b4d9b5d14cece87aa3612a3e39ab9 | [
"m = defaultdict(list)\nfor i, v in enumerate(nums):\n m[v].append(i)\nfor v in nums:\n try:\n x = m[v].pop()\n y = m[target - v].pop()\n return sorted([x, y])\n except:\n pass",
"lookup = {}\nfor i, num in enumerate(nums):\n if target - num in lookup:\n return [look... | <|body_start_0|>
m = defaultdict(list)
for i, v in enumerate(nums):
m[v].append(i)
for v in nums:
try:
x = m[v].pop()
y = m[target - v].pop()
return sorted([x, y])
except:
pass
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_005462 | 806 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
... | 2 | stack_v2_sparse_classes_30k_train_039060 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
m = defaultdict(list)
for i, v in enumerate(nums):
m[v].append(i)
for v in nums:
try:
x = m[v].pop()
y = m[target ... | the_stack_v2_python_sparse | two-sum/solution.py | uxlsl/leetcode_practice | train | 0 | |
20fefe8cf543fee8525213e4cfc0a527aa7beb3c | [
"decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)\npaginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request))\ntry:\n\n def outputFunction(itemObj):\n return itemObj.ge... | <|body_start_0|>
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)
paginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPaginatedParamValues(request))
try:
def outputFunct... | APIKeysInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIKeysInfo:
def get(self, tenant):
"""Get list of ticket types"""
<|body_0|>
def post(self, tenant):
"""Create APIKey"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWT... | stack_v2_sparse_classes_75kplus_train_005463 | 9,554 | permissive | [
{
"docstring": "Get list of ticket types",
"name": "get",
"signature": "def get(self, tenant)"
},
{
"docstring": "Create APIKey",
"name": "post",
"signature": "def post(self, tenant)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050883 | Implement the Python class `APIKeysInfo` described below.
Class description:
Implement the APIKeysInfo class.
Method signatures and docstrings:
- def get(self, tenant): Get list of ticket types
- def post(self, tenant): Create APIKey | Implement the Python class `APIKeysInfo` described below.
Class description:
Implement the APIKeysInfo class.
Method signatures and docstrings:
- def get(self, tenant): Get list of ticket types
- def post(self, tenant): Create APIKey
<|skeleton|>
class APIKeysInfo:
def get(self, tenant):
"""Get list of ... | d3908c46614fb1b638553282cd72ba3634277495 | <|skeleton|>
class APIKeysInfo:
def get(self, tenant):
"""Get list of ticket types"""
<|body_0|>
def post(self, tenant):
"""Create APIKey"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIKeysInfo:
def get(self, tenant):
"""Get list of ticket types"""
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)
paginatedParamValues = object_store_abstraction.sanatizePaginatedParamValues(getPagi... | the_stack_v2_python_sparse | services/src/APIlogin_APIKeys.py | rmetcalf9/saas_user_management_system | train | 1 | |
838907f1040524b245a42fa0707a97468d517995 | [
"members = Member.objects.all()\nserializer = MemberSerializer(members, many=True)\nreturn Response(serializer.data)",
"hash = request.query_params.get('h', None)\ninfo = request.query_params.get('d', None)\ncheck = decode_data(hash, info)\nif isinstance(check, Exception):\n print(check.message.__str__())\n ... | <|body_start_0|>
members = Member.objects.all()
serializer = MemberSerializer(members, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
hash = request.query_params.get('h', None)
info = request.query_params.get('d', None)
check = decode_data(ha... | MemberList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberList:
def get(self, request, format=None):
"""List all members"""
<|body_0|>
def post(self, request, format=None):
"""Add a new member"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
members = Member.objects.all()
serializer = MemberSe... | stack_v2_sparse_classes_75kplus_train_005464 | 6,806 | no_license | [
{
"docstring": "List all members",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Add a new member",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014537 | Implement the Python class `MemberList` described below.
Class description:
Implement the MemberList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all members
- def post(self, request, format=None): Add a new member | Implement the Python class `MemberList` described below.
Class description:
Implement the MemberList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all members
- def post(self, request, format=None): Add a new member
<|skeleton|>
class MemberList:
def get(self, request, for... | c5ac11e40a628c93c3865363e97b4f255a104ca8 | <|skeleton|>
class MemberList:
def get(self, request, format=None):
"""List all members"""
<|body_0|>
def post(self, request, format=None):
"""Add a new member"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemberList:
def get(self, request, format=None):
"""List all members"""
members = Member.objects.all()
serializer = MemberSerializer(members, many=True)
return Response(serializer.data)
def post(self, request, format=None):
"""Add a new member"""
hash = req... | the_stack_v2_python_sparse | members/views.py | lubegamark/gosacco | train | 2 | |
37c585c0ed5e4ce24230ca74ecffef3c117ab1f2 | [
"requires = field.requires\nif not hasattr(requires, 'options'):\n return TAG['input'](self.label(), **attr)\nitems = [self.label(), self.hint()] + self.items(requires.options())\nreturn TAG['select1'](items, **attr)",
"items = []\nsetstr = self.setstr\ngetstr = self.getstr\nfor index, option in enumerate(opti... | <|body_start_0|>
requires = field.requires
if not hasattr(requires, 'options'):
return TAG['input'](self.label(), **attr)
items = [self.label(), self.hint()] + self.items(requires.options())
return TAG['select1'](items, **attr)
<|end_body_0|>
<|body_start_1|>
items =... | Options Widget for XForms | S3XFormsOptionsWidget | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3XFormsOptionsWidget:
"""Options Widget for XForms"""
def widget(self, field, attr):
"""Widget renderer (parameter description see base class)"""
<|body_0|>
def items(self, options):
"""Render the items for the selector Args: options: the options, list of tuples... | stack_v2_sparse_classes_75kplus_train_005465 | 29,818 | permissive | [
{
"docstring": "Widget renderer (parameter description see base class)",
"name": "widget",
"signature": "def widget(self, field, attr)"
},
{
"docstring": "Render the items for the selector Args: options: the options, list of tuples (value, text)",
"name": "items",
"signature": "def items... | 2 | stack_v2_sparse_classes_30k_train_020082 | Implement the Python class `S3XFormsOptionsWidget` described below.
Class description:
Options Widget for XForms
Method signatures and docstrings:
- def widget(self, field, attr): Widget renderer (parameter description see base class)
- def items(self, options): Render the items for the selector Args: options: the op... | Implement the Python class `S3XFormsOptionsWidget` described below.
Class description:
Options Widget for XForms
Method signatures and docstrings:
- def widget(self, field, attr): Widget renderer (parameter description see base class)
- def items(self, options): Render the items for the selector Args: options: the op... | 7ec4b959d009daf26d5ca6ce91dd9c3c0bd978d6 | <|skeleton|>
class S3XFormsOptionsWidget:
"""Options Widget for XForms"""
def widget(self, field, attr):
"""Widget renderer (parameter description see base class)"""
<|body_0|>
def items(self, options):
"""Render the items for the selector Args: options: the options, list of tuples... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class S3XFormsOptionsWidget:
"""Options Widget for XForms"""
def widget(self, field, attr):
"""Widget renderer (parameter description see base class)"""
requires = field.requires
if not hasattr(requires, 'options'):
return TAG['input'](self.label(), **attr)
items = [... | the_stack_v2_python_sparse | modules/core/methods/xforms.py | nursix/drkcm | train | 3 |
10ff3efab79c8e7290680587c754d4c7b0f087f9 | [
"def generate(sequence: List[str]) -> None:\n \"\"\"递归生成所有序列,并将有效序列加入结果。\"\"\"\n if len(sequence) == 2 * n:\n if valid(sequence):\n ans.append(''.join(sequence))\n else:\n sequence.append('(')\n generate(sequence)\n sequence.pop()\n sequence.append(')')\n ... | <|body_start_0|>
def generate(sequence: List[str]) -> None:
"""递归生成所有序列,并将有效序列加入结果。"""
if len(sequence) == 2 * n:
if valid(sequence):
ans.append(''.join(sequence))
else:
sequence.append('(')
generate(sequence... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
"""暴力。"""
<|body_0|>
def generate_parenthesis_2(self, n: int) -> List[str]:
"""回溯法。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def generate(sequence: List[str]) -> None:
... | stack_v2_sparse_classes_75kplus_train_005466 | 3,775 | no_license | [
{
"docstring": "暴力。",
"name": "generate_parenthesis",
"signature": "def generate_parenthesis(self, n: int) -> List[str]"
},
{
"docstring": "回溯法。",
"name": "generate_parenthesis_2",
"signature": "def generate_parenthesis_2(self, n: int) -> List[str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_038726 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate_parenthesis(self, n: int) -> List[str]: 暴力。
- def generate_parenthesis_2(self, n: int) -> List[str]: 回溯法。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generate_parenthesis(self, n: int) -> List[str]: 暴力。
- def generate_parenthesis_2(self, n: int) -> List[str]: 回溯法。
<|skeleton|>
class Solution:
def generate_parenthesis... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
"""暴力。"""
<|body_0|>
def generate_parenthesis_2(self, n: int) -> List[str]:
"""回溯法。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
"""暴力。"""
def generate(sequence: List[str]) -> None:
"""递归生成所有序列,并将有效序列加入结果。"""
if len(sequence) == 2 * n:
if valid(sequence):
ans.append(''.join(sequence))
el... | the_stack_v2_python_sparse | 0022_generate-parentheses.py | Nigirimeshi/leetcode | train | 0 | |
840e7b9ec9da1bfb6e1ea03702b21c13e531bb2e | [
"layout = self.layout\ncolumn = layout.column()\ncolumn.label(text=self.target + ':')\nif self.bone == '':\n ConstraintButtons.main(ConstraintButtons, context, layout, bpy.data.objects[self.object].constraints[self.target])\nelif context.mode == 'POSE':\n ConstraintButtons.main(ConstraintButtons, context, lay... | <|body_start_0|>
layout = self.layout
column = layout.column()
column.label(text=self.target + ':')
if self.bone == '':
ConstraintButtons.main(ConstraintButtons, context, layout, bpy.data.objects[self.object].constraints[self.target])
elif context.mode == 'POSE':
... | This is operator is used to create the required pop-up panel. | constraint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class constraint:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the constraint options."""
<|body_0|>
def execute(self, context):
"""Execute the operator."""
<|body_1|>
def invoke(self, context, event)... | stack_v2_sparse_classes_75kplus_train_005467 | 17,024 | no_license | [
{
"docstring": "Draw the constraint options.",
"name": "draw",
"signature": "def draw(self, context)"
},
{
"docstring": "Execute the operator.",
"name": "execute",
"signature": "def execute(self, context)"
},
{
"docstring": "Invoke the operator panel/menu, control its width.",
... | 3 | stack_v2_sparse_classes_30k_train_047695 | Implement the Python class `constraint` described below.
Class description:
This is operator is used to create the required pop-up panel.
Method signatures and docstrings:
- def draw(self, context): Draw the constraint options.
- def execute(self, context): Execute the operator.
- def invoke(self, context, event): In... | Implement the Python class `constraint` described below.
Class description:
This is operator is used to create the required pop-up panel.
Method signatures and docstrings:
- def draw(self, context): Draw the constraint options.
- def execute(self, context): Execute the operator.
- def invoke(self, context, event): In... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class constraint:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the constraint options."""
<|body_0|>
def execute(self, context):
"""Execute the operator."""
<|body_1|>
def invoke(self, context, event)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class constraint:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the constraint options."""
layout = self.layout
column = layout.column()
column.label(text=self.target + ':')
if self.bone == '':
Constraint... | the_stack_v2_python_sparse | All_In_One/addons/name_panel/scripts/operator/icon.py | 2434325680/Learnbgame | train | 0 |
96913276d483996a4c499e7aa1c4c45970014abc | [
"logger.info('BWA Indexer')\nTool.__init__(self)\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)",
"au_handler = alignerUtils()\namb_loc, ann_loc, bwt_loc, pac_loc, sa_loc = au_handler.bwa_index_genome(file_loc)\ntry:\n logger.info('BWA - idx_out', idx_out, idx_out.... | <|body_start_0|>
logger.info('BWA Indexer')
Tool.__init__(self)
if configuration is None:
configuration = {}
self.configuration.update(configuration)
<|end_body_0|>
<|body_start_1|>
au_handler = alignerUtils()
amb_loc, ann_loc, bwt_loc, pac_loc, sa_loc = au_h... | Tool for running indexers over a genome FASTA file | bwaIndexerTool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class bwaIndexerTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carrie... | stack_v2_sparse_classes_75kplus_train_005468 | 5,186 | permissive | [
{
"docstring": "Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.",
"name": "__init__",
"signature": "def __init__(self, configuration=None)"
},... | 3 | stack_v2_sparse_classes_30k_train_004472 | Implement the Python class `bwaIndexerTool` described below.
Class description:
Tool for running indexers over a genome FASTA file
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing ... | Implement the Python class `bwaIndexerTool` described below.
Class description:
Tool for running indexers over a genome FASTA file
Method signatures and docstrings:
- def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing ... | 50c7115c0c1a6af48dc34f275e469d1b9eb02999 | <|skeleton|>
class bwaIndexerTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carrie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class bwaIndexerTool:
"""Tool for running indexers over a genome FASTA file"""
def __init__(self, configuration=None):
"""Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which ... | the_stack_v2_python_sparse | tool/bwa_indexer.py | Multiscale-Genomics/mg-process-fastq | train | 2 |
802a3e15c55f940cd742e3878dbe87982b9ee50f | [
"m, n = (len(A) + 1, len(B) + 1)\ndp = [0] * n\nret = 0\nfor i in range(1, m):\n pre = 0\n for j in range(1, n):\n tmp = dp[j]\n if A[i - 1] == B[j - 1]:\n dp[j] = 1 + pre\n ret = max(ret, dp[j])\n else:\n dp[j] = 0\n pre = tmp\nreturn ret",
"memo... | <|body_start_0|>
m, n = (len(A) + 1, len(B) + 1)
dp = [0] * n
ret = 0
for i in range(1, m):
pre = 0
for j in range(1, n):
tmp = dp[j]
if A[i - 1] == B[j - 1]:
dp[j] = 1 + pre
ret = max(ret, dp... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLength(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int 4592ms"""
<|body_0|>
def findLength_1(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int 3092ms"""
<|body_1|>
def findLength_2(self, A, B):
... | stack_v2_sparse_classes_75kplus_train_005469 | 2,402 | no_license | [
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: int 4592ms",
"name": "findLength",
"signature": "def findLength(self, A, B)"
},
{
"docstring": ":type A: List[int] :type B: List[int] :rtype: int 3092ms",
"name": "findLength_1",
"signature": "def findLength_1(self, A, B)"
}... | 3 | stack_v2_sparse_classes_30k_train_005227 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 4592ms
- def findLength_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 3092ms
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLength(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 4592ms
- def findLength_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: int 3092ms
- de... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def findLength(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int 4592ms"""
<|body_0|>
def findLength_1(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int 3092ms"""
<|body_1|>
def findLength_2(self, A, B):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findLength(self, A, B):
""":type A: List[int] :type B: List[int] :rtype: int 4592ms"""
m, n = (len(A) + 1, len(B) + 1)
dp = [0] * n
ret = 0
for i in range(1, m):
pre = 0
for j in range(1, n):
tmp = dp[j]
... | the_stack_v2_python_sparse | MaximumLengthOfRepeatedSubarray_MID_718.py | 953250587/leetcode-python | train | 2 | |
2758c9623c3e789ca373ef88e26c1ae09f840f8b | [
"super(CNN, self).__init__()\ndecreasing = 0\nif is_increasing != True:\n decreasing = 1\nself.num_layers = num_layers\nmap_conv_layer_to_filter_size = {4: [[3, 5, 5, 7], [7, 5, 5, 3]], 3: [[5, 5, 7], [7, 5, 5]], 2: [[5, 3], [5, 3]], 1: [[7], [7]]}\npool_output_height = int(np.floor(max_len_token / 2.0))\nfor i ... | <|body_start_0|>
super(CNN, self).__init__()
decreasing = 0
if is_increasing != True:
decreasing = 1
self.num_layers = num_layers
map_conv_layer_to_filter_size = {4: [[3, 5, 5, 7], [7, 5, 5, 3]], 3: [[5, 5, 7], [7, 5, 5]], 2: [[5, 3], [5, 3]], 1: [[7], [7]]}
p... | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
def __init__(self, is_increasing, num_layers, filter_counts, max_len_token):
"""param is_increasing: whether the filter sizes should be increasing or decreasing param num_layers: number of layers param filter_counts: dictionary of filter index to number of filters param max_len_toke... | stack_v2_sparse_classes_75kplus_train_005470 | 2,839 | no_license | [
{
"docstring": "param is_increasing: whether the filter sizes should be increasing or decreasing param num_layers: number of layers param filter_counts: dictionary of filter index to number of filters param max_len_token: maximum number of tokens",
"name": "__init__",
"signature": "def __init__(self, is... | 2 | stack_v2_sparse_classes_30k_train_019911 | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, is_increasing, num_layers, filter_counts, max_len_token): param is_increasing: whether the filter sizes should be increasing or decreasing param num_layers: number of la... | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, is_increasing, num_layers, filter_counts, max_len_token): param is_increasing: whether the filter sizes should be increasing or decreasing param num_layers: number of la... | c0b2f83a7d4c0d5fa5effb7584e0e0acc6f877a0 | <|skeleton|>
class CNN:
def __init__(self, is_increasing, num_layers, filter_counts, max_len_token):
"""param is_increasing: whether the filter sizes should be increasing or decreasing param num_layers: number of layers param filter_counts: dictionary of filter index to number of filters param max_len_toke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNN:
def __init__(self, is_increasing, num_layers, filter_counts, max_len_token):
"""param is_increasing: whether the filter sizes should be increasing or decreasing param num_layers: number of layers param filter_counts: dictionary of filter index to number of filters param max_len_token: maximum num... | the_stack_v2_python_sparse | src/main/base_models/architectures/CNN.py | iesl/institution_hierarchies | train | 3 | |
a1296aecd4f496ccbeac6f5c81968223cbaf6912 | [
"self.modelBuilder.doVar('SF[1.0,0.0,2.0]')\nself.modelBuilder.doSet('POI', 'SF')\nif self.options.mass != 0:\n if self.modelBuilder.out.var('MH'):\n self.modelBuilder.out.var('MH').removeRange()\n self.modelBuilder.out.var('MH').setVal(self.options.mass)\n else:\n self.modelBuilder.doVar... | <|body_start_0|>
self.modelBuilder.doVar('SF[1.0,0.0,2.0]')
self.modelBuilder.doSet('POI', 'SF')
if self.options.mass != 0:
if self.modelBuilder.out.var('MH'):
self.modelBuilder.out.var('MH').removeRange()
self.modelBuilder.out.var('MH').setVal(self.op... | TagAndProbe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagAndProbe:
def doParametersOfInterest(self):
"""Create POI and other parameters, and define the POI set."""
<|body_0|>
def getYieldScale(self, bin, process):
"""Return the name of a RooAbsReal to scale this yield by or the two special values 1 and 0 (don't scale, a... | stack_v2_sparse_classes_75kplus_train_005471 | 1,533 | no_license | [
{
"docstring": "Create POI and other parameters, and define the POI set.",
"name": "doParametersOfInterest",
"signature": "def doParametersOfInterest(self)"
},
{
"docstring": "Return the name of a RooAbsReal to scale this yield by or the two special values 1 and 0 (don't scale, and set to zero)"... | 2 | null | Implement the Python class `TagAndProbe` described below.
Class description:
Implement the TagAndProbe class.
Method signatures and docstrings:
- def doParametersOfInterest(self): Create POI and other parameters, and define the POI set.
- def getYieldScale(self, bin, process): Return the name of a RooAbsReal to scale... | Implement the Python class `TagAndProbe` described below.
Class description:
Implement the TagAndProbe class.
Method signatures and docstrings:
- def doParametersOfInterest(self): Create POI and other parameters, and define the POI set.
- def getYieldScale(self, bin, process): Return the name of a RooAbsReal to scale... | 5a56b57732ffa12ec1261a56f70820f596edb97a | <|skeleton|>
class TagAndProbe:
def doParametersOfInterest(self):
"""Create POI and other parameters, and define the POI set."""
<|body_0|>
def getYieldScale(self, bin, process):
"""Return the name of a RooAbsReal to scale this yield by or the two special values 1 and 0 (don't scale, a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TagAndProbe:
def doParametersOfInterest(self):
"""Create POI and other parameters, and define the POI set."""
self.modelBuilder.doVar('SF[1.0,0.0,2.0]')
self.modelBuilder.doSet('POI', 'SF')
if self.options.mass != 0:
if self.modelBuilder.out.var('MH'):
... | the_stack_v2_python_sparse | python/TagAndProbeModel.py | cms-analysis/HiggsAnalysis-CombinedLimit | train | 59 | |
2a29a36b777df39430757662e49ec5b5cf865c67 | [
"super(Lien, self).__init__(resource_id=name, resource_type=resource.ResourceType.LIEN, name='{}/liens/{}'.format(parent.name, name), display_name=name, parent=parent)\nself.full_name = '{}lien/{}/'.format(parent.full_name, name)\nself.restrictions = restrictions\nself.raw_json = raw_json",
"lien_dict = json.load... | <|body_start_0|>
super(Lien, self).__init__(resource_id=name, resource_type=resource.ResourceType.LIEN, name='{}/liens/{}'.format(parent.name, name), display_name=name, parent=parent)
self.full_name = '{}lien/{}/'.format(parent.full_name, name)
self.restrictions = restrictions
self.raw_j... | Lien Resource. | Lien | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lien:
"""Lien Resource."""
def __init__(self, parent, name, restrictions, raw_json):
"""Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json... | stack_v2_sparse_classes_75kplus_train_005472 | 2,171 | permissive | [
{
"docstring": "Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json of this lien.",
"name": "__init__",
"signature": "def __init__(self, parent, name, restrict... | 2 | stack_v2_sparse_classes_30k_train_036411 | Implement the Python class `Lien` described below.
Class description:
Lien Resource.
Method signatures and docstrings:
- def __init__(self, parent, name, restrictions, raw_json): Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrict... | Implement the Python class `Lien` described below.
Class description:
Lien Resource.
Method signatures and docstrings:
- def __init__(self, parent, name, restrictions, raw_json): Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrict... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Lien:
"""Lien Resource."""
def __init__(self, parent, name, restrictions, raw_json):
"""Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lien:
"""Lien Resource."""
def __init__(self, parent, name, restrictions, raw_json):
"""Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json of this lien... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_type/lien.py | kevensen/forseti-security | train | 1 |
6578ba23cbc997740ae688845b87f90ab82fa7a2 | [
"super(PerfilUsuarioCreateForm, self).__init__(*args, **kwargs)\nif self.instance.pk is None:\n self.fields['password'].widget = forms.PasswordInput()\nself.fields['groups'].widget.attrs.update({'class': 'one form-control'})\nself.fields['confirmar_pass'].widget.attrs.update({'data-fv-identical-field': 'password... | <|body_start_0|>
super(PerfilUsuarioCreateForm, self).__init__(*args, **kwargs)
if self.instance.pk is None:
self.fields['password'].widget = forms.PasswordInput()
self.fields['groups'].widget.attrs.update({'class': 'one form-control'})
self.fields['confirmar_pass'].widget.at... | Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Formulario de creación para los usuarios, en este se incluye un campo de confirmación de contraseña, el asterisco para campos requeridos y widgets para campos | PerfilUsuarioCreateForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerfilUsuarioCreateForm:
"""Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Formulario de creación para los usuarios, en este se incluye un campo de confirmación de contraseña, el asterisco para campos requeridos y widgets para campos"""
def __init__(self, *args, **kwargs):
"""Autor... | stack_v2_sparse_classes_75kplus_train_005473 | 5,185 | no_license | [
{
"docstring": "Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Método constructor en donde se asignan las propiedades de los campos, widgets, entre otros.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Autor: RADY CONSULTORES Fecha: 2 Septiembre 201... | 2 | stack_v2_sparse_classes_30k_train_024591 | Implement the Python class `PerfilUsuarioCreateForm` described below.
Class description:
Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Formulario de creación para los usuarios, en este se incluye un campo de confirmación de contraseña, el asterisco para campos requeridos y widgets para campos
Method signatures and... | Implement the Python class `PerfilUsuarioCreateForm` described below.
Class description:
Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Formulario de creación para los usuarios, en este se incluye un campo de confirmación de contraseña, el asterisco para campos requeridos y widgets para campos
Method signatures and... | 16b04f9c3e520f7ca54a1cc28ede3e1e533a33a5 | <|skeleton|>
class PerfilUsuarioCreateForm:
"""Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Formulario de creación para los usuarios, en este se incluye un campo de confirmación de contraseña, el asterisco para campos requeridos y widgets para campos"""
def __init__(self, *args, **kwargs):
"""Autor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PerfilUsuarioCreateForm:
"""Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Formulario de creación para los usuarios, en este se incluye un campo de confirmación de contraseña, el asterisco para campos requeridos y widgets para campos"""
def __init__(self, *args, **kwargs):
"""Autor: RADY CONSUL... | the_stack_v2_python_sparse | huellas/gestion_usuarios/forms.py | MarioPayan/asdasdwqe | train | 0 |
a93bc82583c2651779d40cc44add143944d8b4fb | [
"super(TransformerEncoder, self).__init__(**kw)\nself.maxlen = maxlen\nself.layers = torch.nn.ModuleList([q.TransformerEncoderBlock(dim, kdim=kdim, vdim=vdim, innerdim=innerdim, numheads=numheads, activation=activation, attention_dropout=attention_dropout, residual_dropout=residual_dropout, scale=scale, maxlen=maxl... | <|body_start_0|>
super(TransformerEncoder, self).__init__(**kw)
self.maxlen = maxlen
self.layers = torch.nn.ModuleList([q.TransformerEncoderBlock(dim, kdim=kdim, vdim=vdim, innerdim=innerdim, numheads=numheads, activation=activation, attention_dropout=attention_dropout, residual_dropout=residual... | TransformerEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=torch.nn.ReLU, embedding_dropout=0.0, attention_dropout=0.0, residual_dropout=0.0, scale=True, relpos=False, posemb=None, **kw):
""":param dim: see MultiHe... | stack_v2_sparse_classes_75kplus_train_005474 | 20,630 | permissive | [
{
"docstring": ":param dim: see MultiHeadAttention :param kdim: see MultiHeadAttention :param vdim: see MultiHeadAttention :param maxlen: see MultiHeadAttention :param numlayers: number of TransformerEncoderBlock layers used :param numheads: see MultiHeadAttention :param activation: which activation function to... | 2 | null | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=torch.nn.ReLU, embedding_dropout=0.0, attenti... | Implement the Python class `TransformerEncoder` described below.
Class description:
Implement the TransformerEncoder class.
Method signatures and docstrings:
- def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=torch.nn.ReLU, embedding_dropout=0.0, attenti... | 8cf2e697830ef09dca40692e7d254b61f9ffdf8d | <|skeleton|>
class TransformerEncoder:
def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=torch.nn.ReLU, embedding_dropout=0.0, attention_dropout=0.0, residual_dropout=0.0, scale=True, relpos=False, posemb=None, **kw):
""":param dim: see MultiHe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerEncoder:
def __init__(self, dim=512, kdim=None, vdim=None, innerdim=None, maxlen=512, numlayers=6, numheads=8, activation=torch.nn.ReLU, embedding_dropout=0.0, attention_dropout=0.0, residual_dropout=0.0, scale=True, relpos=False, posemb=None, **kw):
""":param dim: see MultiHeadAttention :p... | the_stack_v2_python_sparse | kbcqa/method_ir/grounding/semantic_matching/qelos/bert/model.py | BayLee001/SkeletonKBQA | train | 0 | |
9f2eb379e73a72522871ce36c0f7674bc4583095 | [
"self.aurora_cluster_info = aurora_cluster_info\nself.aws_iam_role = aws_iam_role\nself.overwrite = overwrite\nself.prev_full_sfdc_server_timestamp_usecs_map = prev_full_sfdc_server_timestamp_usecs_map\nself.restore_childs_object_vec = restore_childs_object_vec\nself.restore_parent_object_vec = restore_parent_objec... | <|body_start_0|>
self.aurora_cluster_info = aurora_cluster_info
self.aws_iam_role = aws_iam_role
self.overwrite = overwrite
self.prev_full_sfdc_server_timestamp_usecs_map = prev_full_sfdc_server_timestamp_usecs_map
self.restore_childs_object_vec = restore_childs_object_vec
... | Implementation of the 'SfdcRecoverJobParams' model. TODO: type description here. Attributes: aurora_cluster_info (AuroraClusterInfo): Contains the information of the Aurora database cluster. aws_iam_role (string): IAM role used to get access to the Aurora cluster and S3 bucket. overwrite (bool): Whether to overwrite or... | SfdcRecoverJobParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SfdcRecoverJobParams:
"""Implementation of the 'SfdcRecoverJobParams' model. TODO: type description here. Attributes: aurora_cluster_info (AuroraClusterInfo): Contains the information of the Aurora database cluster. aws_iam_role (string): IAM role used to get access to the Aurora cluster and S3 b... | stack_v2_sparse_classes_75kplus_train_005475 | 5,126 | permissive | [
{
"docstring": "Constructor for the SfdcRecoverJobParams class",
"name": "__init__",
"signature": "def __init__(self, aurora_cluster_info=None, aws_iam_role=None, overwrite=None, prev_full_sfdc_server_timestamp_usecs_map=None, restore_childs_object_vec=None, restore_parent_object_vec=None, run_start_tim... | 2 | stack_v2_sparse_classes_30k_train_028304 | Implement the Python class `SfdcRecoverJobParams` described below.
Class description:
Implementation of the 'SfdcRecoverJobParams' model. TODO: type description here. Attributes: aurora_cluster_info (AuroraClusterInfo): Contains the information of the Aurora database cluster. aws_iam_role (string): IAM role used to ge... | Implement the Python class `SfdcRecoverJobParams` described below.
Class description:
Implementation of the 'SfdcRecoverJobParams' model. TODO: type description here. Attributes: aurora_cluster_info (AuroraClusterInfo): Contains the information of the Aurora database cluster. aws_iam_role (string): IAM role used to ge... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SfdcRecoverJobParams:
"""Implementation of the 'SfdcRecoverJobParams' model. TODO: type description here. Attributes: aurora_cluster_info (AuroraClusterInfo): Contains the information of the Aurora database cluster. aws_iam_role (string): IAM role used to get access to the Aurora cluster and S3 b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SfdcRecoverJobParams:
"""Implementation of the 'SfdcRecoverJobParams' model. TODO: type description here. Attributes: aurora_cluster_info (AuroraClusterInfo): Contains the information of the Aurora database cluster. aws_iam_role (string): IAM role used to get access to the Aurora cluster and S3 bucket. overwr... | the_stack_v2_python_sparse | cohesity_management_sdk/models/sfdc_recover_job_params.py | cohesity/management-sdk-python | train | 24 |
a6663d9c1154db81bb9c325d4d87fbf214957add | [
"super(MLP, self).__init__()\nself.neurons = [input_dim] + hidden_dims + [output_class]\nself.layers = []\ndropout_each_layer = dropout\nif not isinstance(dropout_each_layer, (tuple, list)):\n dropout_each_layer = [dropout] * len(hidden_dims)\nfor idx, (in_dim, out_dim, dropout_this_layer) in enumerate(zip(self.... | <|body_start_0|>
super(MLP, self).__init__()
self.neurons = [input_dim] + hidden_dims + [output_class]
self.layers = []
dropout_each_layer = dropout
if not isinstance(dropout_each_layer, (tuple, list)):
dropout_each_layer = [dropout] * len(hidden_dims)
for idx... | >>> General class for multilayer perceptron >>> Suitable for MNIST | MLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
""">>> General class for multilayer perceptron >>> Suitable for MNIST"""
def __init__(self, input_dim=784, hidden_dims=[], output_class=10, dropout=None):
""">>> input_dim, hidden_dims, output_class: the dim of input neurons, hidden neurons and output neurons >>> dropout: the dr... | stack_v2_sparse_classes_75kplus_train_005476 | 1,712 | no_license | [
{
"docstring": ">>> input_dim, hidden_dims, output_class: the dim of input neurons, hidden neurons and output neurons >>> dropout: the dropout rate i.e. the probability to deactivate the neuron, None means no dropout",
"name": "__init__",
"signature": "def __init__(self, input_dim=784, hidden_dims=[], o... | 2 | stack_v2_sparse_classes_30k_train_034716 | Implement the Python class `MLP` described below.
Class description:
>>> General class for multilayer perceptron >>> Suitable for MNIST
Method signatures and docstrings:
- def __init__(self, input_dim=784, hidden_dims=[], output_class=10, dropout=None): >>> input_dim, hidden_dims, output_class: the dim of input neuro... | Implement the Python class `MLP` described below.
Class description:
>>> General class for multilayer perceptron >>> Suitable for MNIST
Method signatures and docstrings:
- def __init__(self, input_dim=784, hidden_dims=[], output_class=10, dropout=None): >>> input_dim, hidden_dims, output_class: the dim of input neuro... | 14d9bc5b25699dd275466c82b6d3748fd90e6e4e | <|skeleton|>
class MLP:
""">>> General class for multilayer perceptron >>> Suitable for MNIST"""
def __init__(self, input_dim=784, hidden_dims=[], output_class=10, dropout=None):
""">>> input_dim, hidden_dims, output_class: the dim of input neurons, hidden neurons and output neurons >>> dropout: the dr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
""">>> General class for multilayer perceptron >>> Suitable for MNIST"""
def __init__(self, input_dim=784, hidden_dims=[], output_class=10, dropout=None):
""">>> input_dim, hidden_dims, output_class: the dim of input neurons, hidden neurons and output neurons >>> dropout: the dropout rate i.... | the_stack_v2_python_sparse | pytorch/cv/mnist/models/mlp.py | liuchen11/dl_benchmark | train | 0 |
6306ad3f9ac237965772a392203c3f4b50808f98 | [
"if spacecraft.tle is None:\n raise Exception('No TLE found for Spacecraft, id = <' + str(spacecraft.identifier) + '>')\nelse:\n return {segment_serializers.SC_ID_K: spacecraft.identifier, segment_serializers.SC_TLE_ID_K: spacecraft.tle.identifier, TleSerializer.TLE_LINE_1_K: spacecraft.tle.first_line, TleSer... | <|body_start_0|>
if spacecraft.tle is None:
raise Exception('No TLE found for Spacecraft, id = <' + str(spacecraft.identifier) + '>')
else:
return {segment_serializers.SC_ID_K: spacecraft.identifier, segment_serializers.SC_TLE_ID_K: spacecraft.tle.identifier, TleSerializer.TLE_LI... | Class that holds the serializers methods for the TLE objects. | TleSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TleSerializer:
"""Class that holds the serializers methods for the TLE objects."""
def serialize_tle(spacecraft):
"""Method that serializes the information from a Spacecraft object including the information of the related TLE object. :param spacecraft: Spacecraft whose TLE has to be ... | stack_v2_sparse_classes_75kplus_train_005477 | 2,845 | permissive | [
{
"docstring": "Method that serializes the information from a Spacecraft object including the information of the related TLE object. :param spacecraft: Spacecraft whose TLE has to be serialized. :return: Object { spacecraft_id, tle_id, tle_line_1, tle_line_2 }",
"name": "serialize_tle",
"signature": "de... | 2 | null | Implement the Python class `TleSerializer` described below.
Class description:
Class that holds the serializers methods for the TLE objects.
Method signatures and docstrings:
- def serialize_tle(spacecraft): Method that serializes the information from a Spacecraft object including the information of the related TLE o... | Implement the Python class `TleSerializer` described below.
Class description:
Class that holds the serializers methods for the TLE objects.
Method signatures and docstrings:
- def serialize_tle(spacecraft): Method that serializes the information from a Spacecraft object including the information of the related TLE o... | 3bb15f4d4dcd543d6f95d1fda2cb737de0bb9a9b | <|skeleton|>
class TleSerializer:
"""Class that holds the serializers methods for the TLE objects."""
def serialize_tle(spacecraft):
"""Method that serializes the information from a Spacecraft object including the information of the related TLE object. :param spacecraft: Spacecraft whose TLE has to be ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TleSerializer:
"""Class that holds the serializers methods for the TLE objects."""
def serialize_tle(spacecraft):
"""Method that serializes the information from a Spacecraft object including the information of the related TLE object. :param spacecraft: Spacecraft whose TLE has to be serialized. :... | the_stack_v2_python_sparse | services/configuration/jrpc/serializers/tle.py | satnet-project/server | train | 4 |
8580ab68b1a1224cfbf648c229eefdb82420bfe9 | [
"if not np.array(X).dtype.type is np.str_:\n raise ValueError('You must give this preprocessor text as input.')\nself.fitted_ = True\nreturn self",
"if not np.array(X).dtype.type is np.str_:\n raise ValueError('You must give this preprocessor text as input.')\nself.fitted_ = True\nreturn self",
"check_is_... | <|body_start_0|>
if not np.array(X).dtype.type is np.str_:
raise ValueError('You must give this preprocessor text as input.')
self.fitted_ = True
return self
<|end_body_0|>
<|body_start_1|>
if not np.array(X).dtype.type is np.str_:
raise ValueError('You must give... | SklearnTransformerMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnTransformerMixin:
def fit(self, X, y=None):
"""Will fit the language model such that it is ready for use in scikit learn. Check out the [guide](https://koaning.github.io/whatlies/tutorial/languages/#scikit-learn) for more details."""
<|body_0|>
def partial_fit(self, X... | stack_v2_sparse_classes_75kplus_train_005478 | 1,652 | permissive | [
{
"docstring": "Will fit the language model such that it is ready for use in scikit learn. Check out the [guide](https://koaning.github.io/whatlies/tutorial/languages/#scikit-learn) for more details.",
"name": "fit",
"signature": "def fit(self, X, y=None)"
},
{
"docstring": "No-op.",
"name":... | 3 | stack_v2_sparse_classes_30k_train_032126 | Implement the Python class `SklearnTransformerMixin` described below.
Class description:
Implement the SklearnTransformerMixin class.
Method signatures and docstrings:
- def fit(self, X, y=None): Will fit the language model such that it is ready for use in scikit learn. Check out the [guide](https://koaning.github.io... | Implement the Python class `SklearnTransformerMixin` described below.
Class description:
Implement the SklearnTransformerMixin class.
Method signatures and docstrings:
- def fit(self, X, y=None): Will fit the language model such that it is ready for use in scikit learn. Check out the [guide](https://koaning.github.io... | b7672db9661bf68e9c46b5f06745e051a4f30c3c | <|skeleton|>
class SklearnTransformerMixin:
def fit(self, X, y=None):
"""Will fit the language model such that it is ready for use in scikit learn. Check out the [guide](https://koaning.github.io/whatlies/tutorial/languages/#scikit-learn) for more details."""
<|body_0|>
def partial_fit(self, X... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SklearnTransformerMixin:
def fit(self, X, y=None):
"""Will fit the language model such that it is ready for use in scikit learn. Check out the [guide](https://koaning.github.io/whatlies/tutorial/languages/#scikit-learn) for more details."""
if not np.array(X).dtype.type is np.str_:
... | the_stack_v2_python_sparse | whatlies/language/_common.py | tttthomasssss/whatlies | train | 1 | |
d7642f1b402cececc3d381060731219b96296fdc | [
"u = USER.objects.create_user(CONTACT_NUMBER, PASSWORD)\nassert u.contact_number == CONTACT_NUMBER\nassert u.is_staff == True\nassert u.is_superuser == False\nassert u.has_perm('', None) == False\nassert u.has_module_perms('') == False",
"u = USER.objects.create_superuser(CONTACT_NUMBER, PASSWORD)\nassert u.conta... | <|body_start_0|>
u = USER.objects.create_user(CONTACT_NUMBER, PASSWORD)
assert u.contact_number == CONTACT_NUMBER
assert u.is_staff == True
assert u.is_superuser == False
assert u.has_perm('', None) == False
assert u.has_module_perms('') == False
<|end_body_0|>
<|body_st... | UsersTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersTestCase:
def test_normal_user_creation(self):
"""Test Normal User Creation"""
<|body_0|>
def test_super_user_creation(self):
"""Test Super User Creation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
u = USER.objects.create_user(CONTACT_NUMBE... | stack_v2_sparse_classes_75kplus_train_005479 | 3,857 | permissive | [
{
"docstring": "Test Normal User Creation",
"name": "test_normal_user_creation",
"signature": "def test_normal_user_creation(self)"
},
{
"docstring": "Test Super User Creation",
"name": "test_super_user_creation",
"signature": "def test_super_user_creation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013673 | Implement the Python class `UsersTestCase` described below.
Class description:
Implement the UsersTestCase class.
Method signatures and docstrings:
- def test_normal_user_creation(self): Test Normal User Creation
- def test_super_user_creation(self): Test Super User Creation | Implement the Python class `UsersTestCase` described below.
Class description:
Implement the UsersTestCase class.
Method signatures and docstrings:
- def test_normal_user_creation(self): Test Normal User Creation
- def test_super_user_creation(self): Test Super User Creation
<|skeleton|>
class UsersTestCase:
de... | 93965a1437197102eca6cf6313ba3dbb4c3f5c3c | <|skeleton|>
class UsersTestCase:
def test_normal_user_creation(self):
"""Test Normal User Creation"""
<|body_0|>
def test_super_user_creation(self):
"""Test Super User Creation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsersTestCase:
def test_normal_user_creation(self):
"""Test Normal User Creation"""
u = USER.objects.create_user(CONTACT_NUMBER, PASSWORD)
assert u.contact_number == CONTACT_NUMBER
assert u.is_staff == True
assert u.is_superuser == False
assert u.has_perm('', No... | the_stack_v2_python_sparse | parkingmanagement/apps/users/tests.py | vivek-at-work/ridecell-code | train | 0 | |
34a833cc3edb0affa150773b0707f27fc86f6fd4 | [
"re = AlarmSetting(userLogin).setAlarm(send_data['parkName'], send_data['enterConfidence'])\nresult = re['status']\nAssertions().assert_text(result, expect['enableConfidenceAlarm'])",
"re = cloudparking_service(centerMonitorLogin).mockCarInOut(send_data['carNum'], 0, send_data['inClientID'], confidence=send_data[... | <|body_start_0|>
re = AlarmSetting(userLogin).setAlarm(send_data['parkName'], send_data['enterConfidence'])
result = re['status']
Assertions().assert_text(result, expect['enableConfidenceAlarm'])
<|end_body_0|>
<|body_start_1|>
re = cloudparking_service(centerMonitorLogin).mockCarInOut(... | 远程值班室收到置信度提醒-并校正车牌 | TestAdjustCarNumByConfidence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdjustCarNumByConfidence:
"""远程值班室收到置信度提醒-并校正车牌"""
def test_enableConfidenceAlarm(self, userLogin, send_data, expect):
"""开启告警配置-置信度告警功能"""
<|body_0|>
def test_mockCarIn(self, centerMonitorLogin, send_data, expect):
"""模拟进场"""
<|body_1|>
def test... | stack_v2_sparse_classes_75kplus_train_005480 | 2,956 | no_license | [
{
"docstring": "开启告警配置-置信度告警功能",
"name": "test_enableConfidenceAlarm",
"signature": "def test_enableConfidenceAlarm(self, userLogin, send_data, expect)"
},
{
"docstring": "模拟进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, centerMonitorLogin, send_data, expect)"
},... | 6 | stack_v2_sparse_classes_30k_train_025766 | Implement the Python class `TestAdjustCarNumByConfidence` described below.
Class description:
远程值班室收到置信度提醒-并校正车牌
Method signatures and docstrings:
- def test_enableConfidenceAlarm(self, userLogin, send_data, expect): 开启告警配置-置信度告警功能
- def test_mockCarIn(self, centerMonitorLogin, send_data, expect): 模拟进场
- def test_adj... | Implement the Python class `TestAdjustCarNumByConfidence` described below.
Class description:
远程值班室收到置信度提醒-并校正车牌
Method signatures and docstrings:
- def test_enableConfidenceAlarm(self, userLogin, send_data, expect): 开启告警配置-置信度告警功能
- def test_mockCarIn(self, centerMonitorLogin, send_data, expect): 模拟进场
- def test_adj... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestAdjustCarNumByConfidence:
"""远程值班室收到置信度提醒-并校正车牌"""
def test_enableConfidenceAlarm(self, userLogin, send_data, expect):
"""开启告警配置-置信度告警功能"""
<|body_0|>
def test_mockCarIn(self, centerMonitorLogin, send_data, expect):
"""模拟进场"""
<|body_1|>
def test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAdjustCarNumByConfidence:
"""远程值班室收到置信度提醒-并校正车牌"""
def test_enableConfidenceAlarm(self, userLogin, send_data, expect):
"""开启告警配置-置信度告警功能"""
re = AlarmSetting(userLogin).setAlarm(send_data['parkName'], send_data['enterConfidence'])
result = re['status']
Assertions().ass... | the_stack_v2_python_sparse | test_suite/parkingConfig/settingParking/alarmSetting/test_adjustCarNumByConfidence.py | oyebino/pomp_api | train | 1 |
907b81588ab02d14608e7dddba7c100b9aaf33a7 | [
"super().__init__(entry, controller, poolObject, **kwargs)\nself._attr_device_class = device_class\nself._rounding_factor = rounding_factor\nself._attr_state_class = SensorStateClass.MEASUREMENT",
"value = str(self._poolObject[self._attribute_key])\nif self._rounding_factor:\n value = str(int(round(int(value) ... | <|body_start_0|>
super().__init__(entry, controller, poolObject, **kwargs)
self._attr_device_class = device_class
self._rounding_factor = rounding_factor
self._attr_state_class = SensorStateClass.MEASUREMENT
<|end_body_0|>
<|body_start_1|>
value = str(self._poolObject[self._attr... | Representation of an Pentair sensor. | PoolSensor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoolSensor:
"""Representation of an Pentair sensor."""
def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):
"""Initialize."""
<|body_0|>
def state(self) -... | stack_v2_sparse_classes_75kplus_train_005481 | 7,986 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs)"
},
{
"docstring": "Return the state of the sensor.",
"name... | 3 | stack_v2_sparse_classes_30k_train_052355 | Implement the Python class `PoolSensor` described below.
Class description:
Representation of an Pentair sensor.
Method signatures and docstrings:
- def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):... | Implement the Python class `PoolSensor` described below.
Class description:
Representation of an Pentair sensor.
Method signatures and docstrings:
- def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):... | 625290c164c60611f501ee773583c06a85281300 | <|skeleton|>
class PoolSensor:
"""Representation of an Pentair sensor."""
def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):
"""Initialize."""
<|body_0|>
def state(self) -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PoolSensor:
"""Representation of an Pentair sensor."""
def __init__(self, entry: ConfigEntry, controller: ModelController, poolObject: PoolObject, device_class: Optional[SensorDeviceClass], rounding_factor: int=0, **kwargs):
"""Initialize."""
super().__init__(entry, controller, poolObject... | the_stack_v2_python_sparse | custom_components/intellicenter/sensor.py | ntalekt/homeassistant | train | 213 |
8b4ee260039b5b1e9fba90c8824887f72962fc99 | [
"args = user_request_required.parse_args()\nself.abortIfFtsUserDoesntExist(args['phone'], args['fts_key'])\nuser = User(username=args['username'], phone=args['phone'], fts_key=args['fts_key'])\nuser.hash_password(args['password'])\ntry:\n db.session.add(user)\n db.session.commit()\nexcept IntegrityError:\n ... | <|body_start_0|>
args = user_request_required.parse_args()
self.abortIfFtsUserDoesntExist(args['phone'], args['fts_key'])
user = User(username=args['username'], phone=args['phone'], fts_key=args['fts_key'])
user.hash_password(args['password'])
try:
db.session.add(user... | Operations with list of users | UserList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserList:
"""Operations with list of users"""
def post(self):
"""Create new user in database :return: New user with some data :rtype: dict/json"""
<|body_0|>
def abortIfFtsUserDoesntExist(phone, fts_key):
"""Return error JSON in 409 response if user doesn't exist... | stack_v2_sparse_classes_75kplus_train_005482 | 8,566 | no_license | [
{
"docstring": "Create new user in database :return: New user with some data :rtype: dict/json",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Return error JSON in 409 response if user doesn't exists in Federal Tax Service :param username: User phone number :type username: str... | 2 | null | Implement the Python class `UserList` described below.
Class description:
Operations with list of users
Method signatures and docstrings:
- def post(self): Create new user in database :return: New user with some data :rtype: dict/json
- def abortIfFtsUserDoesntExist(phone, fts_key): Return error JSON in 409 response ... | Implement the Python class `UserList` described below.
Class description:
Operations with list of users
Method signatures and docstrings:
- def post(self): Create new user in database :return: New user with some data :rtype: dict/json
- def abortIfFtsUserDoesntExist(phone, fts_key): Return error JSON in 409 response ... | 16b1daf2127f04e112a802b92513f49f5cf67dad | <|skeleton|>
class UserList:
"""Operations with list of users"""
def post(self):
"""Create new user in database :return: New user with some data :rtype: dict/json"""
<|body_0|>
def abortIfFtsUserDoesntExist(phone, fts_key):
"""Return error JSON in 409 response if user doesn't exist... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserList:
"""Operations with list of users"""
def post(self):
"""Create new user in database :return: New user with some data :rtype: dict/json"""
args = user_request_required.parse_args()
self.abortIfFtsUserDoesntExist(args['phone'], args['fts_key'])
user = User(username=... | the_stack_v2_python_sparse | server/app/rest/Users.py | dAN0n/receipt_analyzer | train | 0 |
5ee43d983070fccaa548c3bfe5bb3f4c8f43c6fd | [
"if not email:\n msg = _('Users must have an email address')\n raise ValueError(msg)\nif not last_name and (not first_name):\n msg = _('Users must have last and first name')\n raise ValueError(msg)\nuser = self.model(email=BookmarksUserManger.normalize_email(email), last_name=last_name, first_name=first... | <|body_start_0|>
if not email:
msg = _('Users must have an email address')
raise ValueError(msg)
if not last_name and (not first_name):
msg = _('Users must have last and first name')
raise ValueError(msg)
user = self.model(email=BookmarksUserManger... | BookmarksUserManger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookmarksUserManger:
def create_user(self, email, last_name, first_name, password=None):
"""Creates and saves a User with the given email, last_name, first_name and password"""
<|body_0|>
def create_superuser(self, email, last_name, first_name, password):
"""Creates ... | stack_v2_sparse_classes_75kplus_train_005483 | 3,697 | no_license | [
{
"docstring": "Creates and saves a User with the given email, last_name, first_name and password",
"name": "create_user",
"signature": "def create_user(self, email, last_name, first_name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, last name, first nam... | 2 | stack_v2_sparse_classes_30k_train_040298 | Implement the Python class `BookmarksUserManger` described below.
Class description:
Implement the BookmarksUserManger class.
Method signatures and docstrings:
- def create_user(self, email, last_name, first_name, password=None): Creates and saves a User with the given email, last_name, first_name and password
- def ... | Implement the Python class `BookmarksUserManger` described below.
Class description:
Implement the BookmarksUserManger class.
Method signatures and docstrings:
- def create_user(self, email, last_name, first_name, password=None): Creates and saves a User with the given email, last_name, first_name and password
- def ... | dc2b1f46e74c34c7a682be6f07427ba6d8c1907b | <|skeleton|>
class BookmarksUserManger:
def create_user(self, email, last_name, first_name, password=None):
"""Creates and saves a User with the given email, last_name, first_name and password"""
<|body_0|>
def create_superuser(self, email, last_name, first_name, password):
"""Creates ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookmarksUserManger:
def create_user(self, email, last_name, first_name, password=None):
"""Creates and saves a User with the given email, last_name, first_name and password"""
if not email:
msg = _('Users must have an email address')
raise ValueError(msg)
if no... | the_stack_v2_python_sparse | bookmarks/apps/users/models.py | geaden/bookmarkit | train | 0 | |
2e303c43098f5dbb41096616a5f2fe2682d33b78 | [
"super(GaussianProcessRegression, self).__init__(kernel=kernel, sigma=sigma, a=a, b=b, h=h, theta=theta)\nself.alpha = alpha\nself.beta = beta",
"self.X = X\nself.y = y\nC = self.gram_func(X) / self.alpha + np.eye(X.shape[0]) / self.beta\nself.C_inv = np.linalg.inv(C)",
"gram_mat = np.zeros((self.X.shape[0], X.... | <|body_start_0|>
super(GaussianProcessRegression, self).__init__(kernel=kernel, sigma=sigma, a=a, b=b, h=h, theta=theta)
self.alpha = alpha
self.beta = beta
<|end_body_0|>
<|body_start_1|>
self.X = X
self.y = y
C = self.gram_func(X) / self.alpha + np.eye(X.shape[0]) / se... | GaussianProcessregression Attributes: kernel_func (function) : kernel function k(x,y) gram_func (function) : function which make gram matrix alpha,beta (float) : hyperparameter C_inv (2-D array) : inverse of C | GaussianProcessRegression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcessRegression:
"""GaussianProcessregression Attributes: kernel_func (function) : kernel function k(x,y) gram_func (function) : function which make gram matrix alpha,beta (float) : hyperparameter C_inv (2-D array) : inverse of C"""
def __init__(self, alpha=1.0, beta=5.0, kernel='L... | stack_v2_sparse_classes_75kplus_train_005484 | 10,708 | permissive | [
{
"docstring": "Args: alpha,beta (float) : hyperparameter kernel (string) : kernel type (default \"Linear\"). you can choose \"Linear\",\"Gaussian\",\"Sigmoid\",\"RBF\",\"Exponential\" sigma (float) : for \"Gaussian\" kernel a,b (float) : for \"Sigmoid\" kernel h (function) : for \"RBF\" kernel theta (float) : ... | 3 | stack_v2_sparse_classes_30k_train_015646 | Implement the Python class `GaussianProcessRegression` described below.
Class description:
GaussianProcessregression Attributes: kernel_func (function) : kernel function k(x,y) gram_func (function) : function which make gram matrix alpha,beta (float) : hyperparameter C_inv (2-D array) : inverse of C
Method signatures... | Implement the Python class `GaussianProcessRegression` described below.
Class description:
GaussianProcessregression Attributes: kernel_func (function) : kernel function k(x,y) gram_func (function) : function which make gram matrix alpha,beta (float) : hyperparameter C_inv (2-D array) : inverse of C
Method signatures... | 992f2c07e88b2bad331e08303bdba84684f04d40 | <|skeleton|>
class GaussianProcessRegression:
"""GaussianProcessregression Attributes: kernel_func (function) : kernel function k(x,y) gram_func (function) : function which make gram matrix alpha,beta (float) : hyperparameter C_inv (2-D array) : inverse of C"""
def __init__(self, alpha=1.0, beta=5.0, kernel='L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianProcessRegression:
"""GaussianProcessregression Attributes: kernel_func (function) : kernel function k(x,y) gram_func (function) : function which make gram matrix alpha,beta (float) : hyperparameter C_inv (2-D array) : inverse of C"""
def __init__(self, alpha=1.0, beta=5.0, kernel='Linear', sigma... | the_stack_v2_python_sparse | prml/kernel_method.py | hedwig100/PRML | train | 1 |
c84b8704f253cf584ae64ea8ad2094ea1e7490a4 | [
"Base.__init__(self)\nself.id = id\nself.doi = str()\nself.authors = list()\nself.journal = tuple()",
"base_dict = super().as_dict()\nbase_dict.update({'id': self.id, 'doi': self.doi, 'authors': self.authors, 'journal': self.journal})\nreturn base_dict",
"self.title = check_extract(article, 'articletitle')\nsel... | <|body_start_0|>
Base.__init__(self)
self.id = id
self.doi = str()
self.authors = list()
self.journal = tuple()
<|end_body_0|>
<|body_start_1|>
base_dict = super().as_dict()
base_dict.update({'id': self.id, 'doi': self.doi, 'authors': self.authors, 'journal': sel... | Class for collecting and analyzing scientific papers. Attributes ---------- title : str Title of the paper or press release. text : str Text in the body of the press release or paper. year : str Year of publication. req : Requester() Object for handling URL requests. date : str Date that the paper or press release was ... | Paper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Paper:
"""Class for collecting and analyzing scientific papers. Attributes ---------- title : str Title of the paper or press release. text : str Text in the body of the press release or paper. year : str Year of publication. req : Requester() Object for handling URL requests. date : str Date tha... | stack_v2_sparse_classes_75kplus_train_005485 | 5,259 | no_license | [
{
"docstring": "Initializes an object to store paper data. Parameters ---------- id : str ID number of the paper from PubMed database.",
"name": "__init__",
"signature": "def __init__(self, id)"
},
{
"docstring": "Return a dictionary to store the paper object's attributes.",
"name": "as_dict... | 4 | stack_v2_sparse_classes_30k_train_001543 | Implement the Python class `Paper` described below.
Class description:
Class for collecting and analyzing scientific papers. Attributes ---------- title : str Title of the paper or press release. text : str Text in the body of the press release or paper. year : str Year of publication. req : Requester() Object for han... | Implement the Python class `Paper` described below.
Class description:
Class for collecting and analyzing scientific papers. Attributes ---------- title : str Title of the paper or press release. text : str Text in the body of the press release or paper. year : str Year of publication. req : Requester() Object for han... | 3b5220ed5fbd3aaca2254fcfd7bb7edf61359e35 | <|skeleton|>
class Paper:
"""Class for collecting and analyzing scientific papers. Attributes ---------- title : str Title of the paper or press release. text : str Text in the body of the press release or paper. year : str Year of publication. req : Requester() Object for handling URL requests. date : str Date tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Paper:
"""Class for collecting and analyzing scientific papers. Attributes ---------- title : str Title of the paper or press release. text : str Text in the body of the press release or paper. year : str Year of publication. req : Requester() Object for handling URL requests. date : str Date that the paper o... | the_stack_v2_python_sparse | consc/paper.py | wdfox/ConfidenceScanner | train | 3 |
0126f64812040aae7c9392b31cee9eae8dc1bc8e | [
"self.azdeg = azdeg\nself.altdeg = altdeg\nself.hsv_min_val = hsv_min_val\nself.hsv_max_val = hsv_max_val\nself.hsv_min_sat = hsv_min_sat\nself.hsv_max_sat = hsv_max_sat",
"if minval == None:\n minval = data.min()\nnormdata = (data - minval) / (data.max() - minval)\nrgb0 = cmap(normdata)\nrgb1 = self.shade_rgb... | <|body_start_0|>
self.azdeg = azdeg
self.altdeg = altdeg
self.hsv_min_val = hsv_min_val
self.hsv_max_val = hsv_max_val
self.hsv_min_sat = hsv_min_sat
self.hsv_max_sat = hsv_max_sat
<|end_body_0|>
<|body_start_1|>
if minval == None:
minval = data.min()... | Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data array. Original in matplotlib.colors, m... | LightSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightSource:
"""Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data ... | stack_v2_sparse_classes_75kplus_train_005486 | 5,066 | no_license | [
{
"docstring": "Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees. The color of the resulting image will be darkened by moving the (s,v) values (in hsv colorspace) toward (hsv_min_sat, hsv_min_val) in the shaded regions, o... | 3 | stack_v2_sparse_classes_30k_train_010180 | Implement the Python class `LightSource` described below.
Class description:
Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values ... | Implement the Python class `LightSource` described below.
Class description:
Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values ... | 6e39008842de8a0fb4a9879b53b8a67339b37aff | <|skeleton|>
class LightSource:
"""Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LightSource:
"""Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface. The :meth:`shade` is used to produce rgb values for a shaded relief image given a data array. Origin... | the_stack_v2_python_sparse | python/lib/myLightSource.py | gutmann/scripted_sufferin_succotash | train | 2 |
40bab044a5a1c1841d074f3a8e787b40207b71ce | [
"if search('^GET.*\\\\?.*' + self.httpIDRE, packet.payload, I) != None:\n return True\nelse:\n return False",
"if search('^GET.*\\\\?.*(;.*)*--.*' + self.httpIDRE, packet.payload, I) != None:\n return True\nelse:\n return False",
"sqlKeyWords = ['ADD', 'EXCEPT', 'PERCENT', 'ALL', 'EXEC', 'PLAN', 'AL... | <|body_start_0|>
if search('^GET.*\\?.*' + self.httpIDRE, packet.payload, I) != None:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if search('^GET.*\\?.*(;.*)*--.*' + self.httpIDRE, packet.payload, I) != None:
return True
else:
... | SQLInjectionAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLInjectionAnalyzer:
def isQuery(self, packet):
"""Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in"""
<|body_0|>
def hasSQLComment(self, packet):
"""Returns True if the packet is an HTTP GET tha... | stack_v2_sparse_classes_75kplus_train_005487 | 7,144 | no_license | [
{
"docstring": "Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in",
"name": "isQuery",
"signature": "def isQuery(self, packet)"
},
{
"docstring": "Returns True if the packet is an HTTP GET that looks like it has an sql comment... | 4 | stack_v2_sparse_classes_30k_train_027705 | Implement the Python class `SQLInjectionAnalyzer` described below.
Class description:
Implement the SQLInjectionAnalyzer class.
Method signatures and docstrings:
- def isQuery(self, packet): Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in
- def h... | Implement the Python class `SQLInjectionAnalyzer` described below.
Class description:
Implement the SQLInjectionAnalyzer class.
Method signatures and docstrings:
- def isQuery(self, packet): Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in
- def h... | 418abe9a105bfd1f54d420466a7ddb5318695a79 | <|skeleton|>
class SQLInjectionAnalyzer:
def isQuery(self, packet):
"""Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in"""
<|body_0|>
def hasSQLComment(self, packet):
"""Returns True if the packet is an HTTP GET tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SQLInjectionAnalyzer:
def isQuery(self, packet):
"""Returns True if the packet is an HTTP GET that looks like it has a query in it. @param packet - The packet to search in"""
if search('^GET.*\\?.*' + self.httpIDRE, packet.payload, I) != None:
return True
else:
... | the_stack_v2_python_sparse | src/honeynet_web/packetAnalysis/analyzers/sqlinj.py | finitem/pig | train | 0 | |
a108191536872015e59d848323810c30ce4dfcc4 | [
"if self.forward is UNDEF:\n return None\nif isinstance(value, (numpy.ndarray, list, tuple)):\n return tuple(map(self.forward, value))\nreturn self.forward(value)",
"if self.reverse is UNDEF:\n return None\nif isinstance(value, (numpy.ndarray, list, tuple)):\n return tuple(map(self.reverse, value))\nr... | <|body_start_0|>
if self.forward is UNDEF:
return None
if isinstance(value, (numpy.ndarray, list, tuple)):
return tuple(map(self.forward, value))
return self.forward(value)
<|end_body_0|>
<|body_start_1|>
if self.reverse is UNDEF:
return None
... | Converter is a simple scale-like tool to convert from one value to another by custom forward and reverse functions. Properties: forward: callable Specifies the function to be used for forward conversion. The function is expected to have just one argument for the input value and should return converted output. reverse: ... | Converter | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
"""Converter is a simple scale-like tool to convert from one value to another by custom forward and reverse functions. Properties: forward: callable Specifies the function to be used for forward conversion. The function is expected to have just one argument for the input value and shou... | stack_v2_sparse_classes_75kplus_train_005488 | 2,112 | permissive | [
{
"docstring": "Returns corresponding converted value for given input value. Args: value: any or (any,) Input value to be scaled. Returns: any Converted value.",
"name": "scale",
"signature": "def scale(self, value, *args, **kwargs)"
},
{
"docstring": "Returns corresponding reversed value for gi... | 2 | null | Implement the Python class `Converter` described below.
Class description:
Converter is a simple scale-like tool to convert from one value to another by custom forward and reverse functions. Properties: forward: callable Specifies the function to be used for forward conversion. The function is expected to have just on... | Implement the Python class `Converter` described below.
Class description:
Converter is a simple scale-like tool to convert from one value to another by custom forward and reverse functions. Properties: forward: callable Specifies the function to be used for forward conversion. The function is expected to have just on... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class Converter:
"""Converter is a simple scale-like tool to convert from one value to another by custom forward and reverse functions. Properties: forward: callable Specifies the function to be used for forward conversion. The function is expected to have just one argument for the input value and shou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Converter:
"""Converter is a simple scale-like tool to convert from one value to another by custom forward and reverse functions. Properties: forward: callable Specifies the function to be used for forward conversion. The function is expected to have just one argument for the input value and should return con... | the_stack_v2_python_sparse | pero/scales/converter.py | xxao/pero | train | 31 |
c4106a3a82de881295cbb5035a067e59df162f59 | [
"super().__init__()\nself.add_module('norm1', Norm(num_input_features))\nself.add_module('relu1', nn.ReLU(inplace=True))\nself.add_module('conv1', Conv(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False))\nself.add_module('norm2', Norm(bn_size * growth_rate))\nself.add_module('relu2', nn... | <|body_start_0|>
super().__init__()
self.add_module('norm1', Norm(num_input_features))
self.add_module('relu1', nn.ReLU(inplace=True))
self.add_module('conv1', Conv(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False))
self.add_module('norm2', Norm(bn_s... | _DenseLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DenseLayer:
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, Norm, Conv):
"""Constructor for _DenseLayer class. Parameters: num_input_features (int): Number of input channels to the layer. growth_rate (int): Number of output channels of each convolution operation ... | stack_v2_sparse_classes_75kplus_train_005489 | 12,081 | permissive | [
{
"docstring": "Constructor for _DenseLayer class. Parameters: num_input_features (int): Number of input channels to the layer. growth_rate (int): Number of output channels of each convolution operation in the layer. bn_size (int): Factor to scale the number of intermediate channels between the 1x1 and 3x3 conv... | 2 | stack_v2_sparse_classes_30k_train_048713 | Implement the Python class `_DenseLayer` described below.
Class description:
Implement the _DenseLayer class.
Method signatures and docstrings:
- def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, Norm, Conv): Constructor for _DenseLayer class. Parameters: num_input_features (int): Number of inpu... | Implement the Python class `_DenseLayer` described below.
Class description:
Implement the _DenseLayer class.
Method signatures and docstrings:
- def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, Norm, Conv): Constructor for _DenseLayer class. Parameters: num_input_features (int): Number of inpu... | 72eb99f68205afd5f8d49a3bb6cfc08cfd467582 | <|skeleton|>
class _DenseLayer:
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, Norm, Conv):
"""Constructor for _DenseLayer class. Parameters: num_input_features (int): Number of input channels to the layer. growth_rate (int): Number of output channels of each convolution operation ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _DenseLayer:
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, Norm, Conv):
"""Constructor for _DenseLayer class. Parameters: num_input_features (int): Number of input channels to the layer. growth_rate (int): Number of output channels of each convolution operation in the layer. ... | the_stack_v2_python_sparse | GANDLF/models/densenet.py | mlcommons/GaNDLF | train | 45 | |
4fab96b9292a35b2ea87f9b2395723953c4aaeb1 | [
"super().__init__(hyper_parameters)\nself.num_rnn_layers = hyper_parameters['graph'].get('num_rnn_layers', 2)\nself.crf_lr_multiplier = hyper_parameters.get('train', {}).get('crf_lr_multiplier', 1 if self.embed_type in ['WARD', 'RANDOM'] else 3200)",
"if self.rnn_type == 'LSTM':\n rnn_cell = L.LSTM\nelif self.... | <|body_start_0|>
super().__init__(hyper_parameters)
self.num_rnn_layers = hyper_parameters['graph'].get('num_rnn_layers', 2)
self.crf_lr_multiplier = hyper_parameters.get('train', {}).get('crf_lr_multiplier', 1 if self.embed_type in ['WARD', 'RANDOM'] else 3200)
<|end_body_0|>
<|body_start_1|>
... | BiLstmLANGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLstmLANGraph:
def __init__(self, hyper_parameters):
"""Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None"""
<|body_0|>
def build_model(self, input... | stack_v2_sparse_classes_75kplus_train_005490 | 2,833 | permissive | [
{
"docstring": "Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains \"sharing\", \"embed\", \"graph\", \"train\", \"save\" and \"data\". Returns: None",
"name": "__init__",
"signature": "def __init__(self, hyper_parameters)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_051887 | Implement the Python class `BiLstmLANGraph` described below.
Class description:
Implement the BiLstmLANGraph class.
Method signatures and docstrings:
- def __init__(self, hyper_parameters): Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "g... | Implement the Python class `BiLstmLANGraph` described below.
Class description:
Implement the BiLstmLANGraph class.
Method signatures and docstrings:
- def __init__(self, hyper_parameters): Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "g... | 5237381459db5909f392737e33618a16c1e0452a | <|skeleton|>
class BiLstmLANGraph:
def __init__(self, hyper_parameters):
"""Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None"""
<|body_0|>
def build_model(self, input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BiLstmLANGraph:
def __init__(self, hyper_parameters):
"""Init of hyper_parameters and build_embed. Args: hyper_parameters: hyper_parameters of all, which contains "sharing", "embed", "graph", "train", "save" and "data". Returns: None"""
super().__init__(hyper_parameters)
self.num_rnn_l... | the_stack_v2_python_sparse | macadam/sl/s05_bilstm_lan.py | payiz-asj/Macadam | train | 1 | |
e0d945833db806613962314e6285c0fa0e5d298f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationAssignmentDefaults()",
"from .education_added_student_action import EducationAddedStudentAction\nfrom .education_add_to_calendar_options import EducationAddToCalendarOptions\nfrom .entity import Entity\nfrom .education_added_s... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationAssignmentDefaults()
<|end_body_0|>
<|body_start_1|>
from .education_added_student_action import EducationAddedStudentAction
from .education_add_to_calendar_options import Educa... | EducationAssignmentDefaults | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationAssignmentDefaults:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentDefaults:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_75kplus_train_005491 | 4,032 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EducationAssignmentDefaults",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_036584 | Implement the Python class `EducationAssignmentDefaults` described below.
Class description:
Implement the EducationAssignmentDefaults class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentDefaults: Creates a new instance of the appr... | Implement the Python class `EducationAssignmentDefaults` described below.
Class description:
Implement the EducationAssignmentDefaults class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentDefaults: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationAssignmentDefaults:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentDefaults:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EducationAssignmentDefaults:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentDefaults:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | the_stack_v2_python_sparse | msgraph/generated/models/education_assignment_defaults.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
6065a78fc3830ca0b785e68b58e21096a83cef96 | [
"super(MLP, self).__init__()\nself.input_dim = input_dim\nself.hidden_dims = hidden_dims\nself.output_dim = output_dim\nself.nonlinear = nonlinear\nself.droput = dropout\nself.linears = nn.ModuleList([nn.Linear(self.input_dim, self.hidden_dims[0])])\nif self.droput:\n self.dropouts = nn.ModuleList([nn.Dropout(p=... | <|body_start_0|>
super(MLP, self).__init__()
self.input_dim = input_dim
self.hidden_dims = hidden_dims
self.output_dim = output_dim
self.nonlinear = nonlinear
self.droput = dropout
self.linears = nn.ModuleList([nn.Linear(self.input_dim, self.hidden_dims[0])])
... | MLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLP:
def __init__(self, input_dim, hidden_dims, output_dim, nonlinear=False, dropout=False):
""":param nonlinear: if False last layer is linear, if True is nonlinear. Default False."""
<|body_0|>
def forward(self, x):
""":param x: (n_features)"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_005492 | 1,466 | no_license | [
{
"docstring": ":param nonlinear: if False last layer is linear, if True is nonlinear. Default False.",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dims, output_dim, nonlinear=False, dropout=False)"
},
{
"docstring": ":param x: (n_features)",
"name": "forward",
... | 2 | stack_v2_sparse_classes_30k_train_046948 | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dims, output_dim, nonlinear=False, dropout=False): :param nonlinear: if False last layer is linear, if True is nonlinear. Default False.
- def forward(... | Implement the Python class `MLP` described below.
Class description:
Implement the MLP class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dims, output_dim, nonlinear=False, dropout=False): :param nonlinear: if False last layer is linear, if True is nonlinear. Default False.
- def forward(... | 1f43e58459e5b2aac9591ffe157f19c1e5d28538 | <|skeleton|>
class MLP:
def __init__(self, input_dim, hidden_dims, output_dim, nonlinear=False, dropout=False):
""":param nonlinear: if False last layer is linear, if True is nonlinear. Default False."""
<|body_0|>
def forward(self, x):
""":param x: (n_features)"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLP:
def __init__(self, input_dim, hidden_dims, output_dim, nonlinear=False, dropout=False):
""":param nonlinear: if False last layer is linear, if True is nonlinear. Default False."""
super(MLP, self).__init__()
self.input_dim = input_dim
self.hidden_dims = hidden_dims
... | the_stack_v2_python_sparse | src/models/MLP.py | iamxpy/Relation-Network-PyTorch | train | 0 | |
df76d797c60cefe8bfb44bcbaf67ca2c5725bb74 | [
"self.name = name\nself.function = function\nself.hindcast = hindcast\nself.probabilistic = probabilistic\nself.long_name = long_name\nself.aliases = aliases",
"summary = '----- Comparison metadata -----\\n'\nsummary += f'Name: {self.name}\\n'\nif not self.probabilistic:\n summary += 'Kind: deterministic\\n'\n... | <|body_start_0|>
self.name = name
self.function = function
self.hindcast = hindcast
self.probabilistic = probabilistic
self.long_name = long_name
self.aliases = aliases
<|end_body_0|>
<|body_start_1|>
summary = '----- Comparison metadata -----\n'
summary ... | Master class for all comparisons. See :ref:`comparisons`. | Comparison | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
... | stack_v2_sparse_classes_75kplus_train_005493 | 11,669 | permissive | [
{
"docstring": "Comparison initialization See :ref:`comparisons`. Args: name: name of comparison. function: comparison function. hindcast: Can comparison be used in :py:class:`.HindcastEnsemble`? ``False`` means only :py:class:`.PerfectModelEnsemble` probabilistic: Can this comparison be used for probabilistic ... | 2 | stack_v2_sparse_classes_30k_train_053003 | Implement the Python class `Comparison` described below.
Class description:
Master class for all comparisons. See :ref:`comparisons`.
Method signatures and docstrings:
- def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Op... | Implement the Python class `Comparison` described below.
Class description:
Master class for all comparisons. See :ref:`comparisons`.
Method signatures and docstrings:
- def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Op... | 1424e89e9bdf3eb1ae47d581be2953ede0b98996 | <|skeleton|>
class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Comparison:
"""Master class for all comparisons. See :ref:`comparisons`."""
def __init__(self, name: str, function: Callable[[Any, Any, Any], Tuple[xr.Dataset, xr.Dataset]], hindcast: bool, probabilistic: bool, long_name: Optional[str]=None, aliases: Optional[List[str]]=None) -> None:
"""Comparis... | the_stack_v2_python_sparse | climpred/comparisons.py | pangeo-data/climpred | train | 164 |
06a70b6dbc6b7f96f5f0e54756bb20f98e64dc00 | [
"if not root:\n return\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n current = queue.popleft()\n left = current.left\n right = current.right\n current.left = right\n current.right = left\n if left:\n queue.append(left)\n if right:\n queue.append(right)\nretur... | <|body_start_0|>
if not root:
return
queue = collections.deque()
queue.append(root)
while queue:
current = queue.popleft()
left = current.left
right = current.right
current.left = right
current.right = left
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def invertTree_recursive(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
retu... | stack_v2_sparse_classes_75kplus_train_005494 | 1,080 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree",
"signature": "def invertTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree_recursive",
"signature": "def invertTree_recursive(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042488 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def invertTree_recursive(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def invertTree_recursive(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solution:
... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def invertTree_recursive(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
if not root:
return
queue = collections.deque()
queue.append(root)
while queue:
current = queue.popleft()
left = current.left
right = curren... | the_stack_v2_python_sparse | Algorithm/226_Invert_Binary_Tree.py | Gi1ia/TechNoteBook | train | 7 | |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('flush_tokens', kwargs={'level': int(data['level']), 'semester': int(data['semester']), 'course': int(data['course'].id)})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = \"Choose Course To Flush It's T... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('flush_tokens', kwargs={'level': int(data['level']), 'semester': int(data['semester']), 'course': int(data['course'].id)})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_d... | View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid. | ShowFlushTokensView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowFlushTokensView:
"""View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
def g... | stack_v2_sparse_classes_75kplus_train_005495 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_022649 | Implement the Python class `ShowFlushTokensView` described below.
Class description:
View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success URL and... | Implement the Python class `ShowFlushTokensView` described below.
Class description:
View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success URL and... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class ShowFlushTokensView:
"""View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
def g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShowFlushTokensView:
"""View for selecting which tokens to Flush/Delete. Check that the user's account is still active. Redirects to flush_tokens view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleaned_data
s... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
b96dd6ce42c868c6a39665f53cb6644ae4a6d34f | [
"self.login()\ndata = dict(timeline=1)\nresponse = self.client.post(self.resource_url, data=json.dumps(data, ensure_ascii=False), content_type='application/json')\nself.assertEqual(response.status_code, HTTP_STATUS_CODE_OK)",
"self.login()\ndata = dict(timeline=2)\nresponse = self.client.post(self.resource_url, d... | <|body_start_0|>
self.login()
data = dict(timeline=1)
response = self.client.post(self.resource_url, data=json.dumps(data, ensure_ascii=False), content_type='application/json')
self.assertEqual(response.status_code, HTTP_STATUS_CODE_OK)
<|end_body_0|>
<|body_start_1|>
self.login... | Test TimelineList resource. | TimelineListResourceTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimelineListResourceTest:
"""Test TimelineList resource."""
def test_add_existing_timeline_resource(self):
"""Authenticated request to add a timeline to a sketch."""
<|body_0|>
def test_add_new_timeline_resource(self):
"""Authenticated request to add a timeline t... | stack_v2_sparse_classes_75kplus_train_005496 | 36,779 | permissive | [
{
"docstring": "Authenticated request to add a timeline to a sketch.",
"name": "test_add_existing_timeline_resource",
"signature": "def test_add_existing_timeline_resource(self)"
},
{
"docstring": "Authenticated request to add a timeline to a sketch.",
"name": "test_add_new_timeline_resource... | 2 | stack_v2_sparse_classes_30k_train_050684 | Implement the Python class `TimelineListResourceTest` described below.
Class description:
Test TimelineList resource.
Method signatures and docstrings:
- def test_add_existing_timeline_resource(self): Authenticated request to add a timeline to a sketch.
- def test_add_new_timeline_resource(self): Authenticated reques... | Implement the Python class `TimelineListResourceTest` described below.
Class description:
Test TimelineList resource.
Method signatures and docstrings:
- def test_add_existing_timeline_resource(self): Authenticated request to add a timeline to a sketch.
- def test_add_new_timeline_resource(self): Authenticated reques... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class TimelineListResourceTest:
"""Test TimelineList resource."""
def test_add_existing_timeline_resource(self):
"""Authenticated request to add a timeline to a sketch."""
<|body_0|>
def test_add_new_timeline_resource(self):
"""Authenticated request to add a timeline t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimelineListResourceTest:
"""Test TimelineList resource."""
def test_add_existing_timeline_resource(self):
"""Authenticated request to add a timeline to a sketch."""
self.login()
data = dict(timeline=1)
response = self.client.post(self.resource_url, data=json.dumps(data, e... | the_stack_v2_python_sparse | timesketch/api/v1/resources_test.py | google/timesketch | train | 2,263 |
06003e8d75ccbb4b176c4af3efe47c5937d45139 | [
"token = self.Locator(key, value, len(self))\nself._data.append(token)\nself._up_heap(len(self) - 1)\nreturn token",
"if not (0 <= loc._index < len(self) and loc is self._data[loc._index]):\n raise ValueError('Invaid locator')\nloc._key, loc._value = (newkey, newval)\nself._bubble(loc._index)",
"if not (0 <=... | <|body_start_0|>
token = self.Locator(key, value, len(self))
self._data.append(token)
self._up_heap(len(self) - 1)
return token
<|end_body_0|>
<|body_start_1|>
if not (0 <= loc._index < len(self) and loc is self._data[loc._index]):
raise ValueError('Invaid locator')
... | A min-oriented priority queue implemented with a heap. | AdaptablePriorityQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptablePriorityQueue:
"""A min-oriented priority queue implemented with a heap."""
def add(self, key, value):
"""Add a key-value pair and return a locator token."""
<|body_0|>
def update(self, loc, newkey, newval):
"""Update the key and value for the entry iden... | stack_v2_sparse_classes_75kplus_train_005497 | 2,603 | no_license | [
{
"docstring": "Add a key-value pair and return a locator token.",
"name": "add",
"signature": "def add(self, key, value)"
},
{
"docstring": "Update the key and value for the entry identified by Locator loc.",
"name": "update",
"signature": "def update(self, loc, newkey, newval)"
},
... | 5 | stack_v2_sparse_classes_30k_train_037473 | Implement the Python class `AdaptablePriorityQueue` described below.
Class description:
A min-oriented priority queue implemented with a heap.
Method signatures and docstrings:
- def add(self, key, value): Add a key-value pair and return a locator token.
- def update(self, loc, newkey, newval): Update the key and val... | Implement the Python class `AdaptablePriorityQueue` described below.
Class description:
A min-oriented priority queue implemented with a heap.
Method signatures and docstrings:
- def add(self, key, value): Add a key-value pair and return a locator token.
- def update(self, loc, newkey, newval): Update the key and val... | 70b23ead7a89e46a84d9d914e7c8fa678edd1f90 | <|skeleton|>
class AdaptablePriorityQueue:
"""A min-oriented priority queue implemented with a heap."""
def add(self, key, value):
"""Add a key-value pair and return a locator token."""
<|body_0|>
def update(self, loc, newkey, newval):
"""Update the key and value for the entry iden... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdaptablePriorityQueue:
"""A min-oriented priority queue implemented with a heap."""
def add(self, key, value):
"""Add a key-value pair and return a locator token."""
token = self.Locator(key, value, len(self))
self._data.append(token)
self._up_heap(len(self) - 1)
... | the_stack_v2_python_sparse | priority_queue_ch09/priqueues/adaptable_priority_queue.py | wanyikang/dsap | train | 1 |
91d49558ef3d3d5b8092493a8a375b3df14f9147 | [
"new_dtype = src_array.dtype.descr + [dtype]\nnew_array = np.array([list(x) for x in src_array])\nadd = []\nfor i in add_row:\n add.append([i])\nnew_array = np.append(new_array, add, 1)\nnew_array = np.array([tuple(x) for x in new_array], dtype=new_dtype)\nreturn new_array",
"new_dtype = []\nfor key, dtype in ... | <|body_start_0|>
new_dtype = src_array.dtype.descr + [dtype]
new_array = np.array([list(x) for x in src_array])
add = []
for i in add_row:
add.append([i])
new_array = np.append(new_array, add, 1)
new_array = np.array([tuple(x) for x in new_array], dtype=new_dt... | numpy array関連 | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
"""numpy array関連"""
def add_data(src_array, add_row, dtype):
"""ラベル付きarrayに新しい一次元dataを加える⇒commopy行き??"""
<|body_0|>
def extract(src_array, *labels):
"""labelsのデータのみを抽出してarrayをreturn"""
<|body_1|>
def trim(array, label, value):
"""label... | stack_v2_sparse_classes_75kplus_train_005498 | 17,123 | no_license | [
{
"docstring": "ラベル付きarrayに新しい一次元dataを加える⇒commopy行き??",
"name": "add_data",
"signature": "def add_data(src_array, add_row, dtype)"
},
{
"docstring": "labelsのデータのみを抽出してarrayをreturn",
"name": "extract",
"signature": "def extract(src_array, *labels)"
},
{
"docstring": "labelsのデータがva... | 6 | stack_v2_sparse_classes_30k_test_000727 | Implement the Python class `Array` described below.
Class description:
numpy array関連
Method signatures and docstrings:
- def add_data(src_array, add_row, dtype): ラベル付きarrayに新しい一次元dataを加える⇒commopy行き??
- def extract(src_array, *labels): labelsのデータのみを抽出してarrayをreturn
- def trim(array, label, value): labelsのデータがvalueと等しい... | Implement the Python class `Array` described below.
Class description:
numpy array関連
Method signatures and docstrings:
- def add_data(src_array, add_row, dtype): ラベル付きarrayに新しい一次元dataを加える⇒commopy行き??
- def extract(src_array, *labels): labelsのデータのみを抽出してarrayをreturn
- def trim(array, label, value): labelsのデータがvalueと等しい... | d210cf6f8fb370ff6deecc949c7dcb3df653d1ca | <|skeleton|>
class Array:
"""numpy array関連"""
def add_data(src_array, add_row, dtype):
"""ラベル付きarrayに新しい一次元dataを加える⇒commopy行き??"""
<|body_0|>
def extract(src_array, *labels):
"""labelsのデータのみを抽出してarrayをreturn"""
<|body_1|>
def trim(array, label, value):
"""label... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Array:
"""numpy array関連"""
def add_data(src_array, add_row, dtype):
"""ラベル付きarrayに新しい一次元dataを加える⇒commopy行き??"""
new_dtype = src_array.dtype.descr + [dtype]
new_array = np.array([list(x) for x in src_array])
add = []
for i in add_row:
add.append([i])
... | the_stack_v2_python_sparse | module/commopy.py | buriedwood/00_workSpace | train | 0 |
71d6b8e5360d095eeb997eb64fbd4e2461a2cdf6 | [
"self._points = points\nself._clusters = 0\nfor point in self._points:\n if point.is_visited():\n continue\n point.visit()\n neighbors_point = self.find_neighbours(point, eps)\n if len(neighbors_point) < min_points:\n point.set_cluster(-1)\n else:\n self._clusters = self._cluster... | <|body_start_0|>
self._points = points
self._clusters = 0
for point in self._points:
if point.is_visited():
continue
point.visit()
neighbors_point = self.find_neighbours(point, eps)
if len(neighbors_point) < min_points:
... | DBScan | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBScan:
def __init__(self, points, eps, min_points):
"""DBScan is initialized by passing a list of points, the eps, and a minimum number of points per cluster. Args: param1: The dataset of points to be analyzed param2: The eps neighborhood of a point param3: The minimum number of element... | stack_v2_sparse_classes_75kplus_train_005499 | 2,855 | permissive | [
{
"docstring": "DBScan is initialized by passing a list of points, the eps, and a minimum number of points per cluster. Args: param1: The dataset of points to be analyzed param2: The eps neighborhood of a point param3: The minimum number of elements per cluster.",
"name": "__init__",
"signature": "def _... | 4 | stack_v2_sparse_classes_30k_train_014575 | Implement the Python class `DBScan` described below.
Class description:
Implement the DBScan class.
Method signatures and docstrings:
- def __init__(self, points, eps, min_points): DBScan is initialized by passing a list of points, the eps, and a minimum number of points per cluster. Args: param1: The dataset of poin... | Implement the Python class `DBScan` described below.
Class description:
Implement the DBScan class.
Method signatures and docstrings:
- def __init__(self, points, eps, min_points): DBScan is initialized by passing a list of points, the eps, and a minimum number of points per cluster. Args: param1: The dataset of poin... | 4ae6ba54e90af14af236e03e435eb0402dcac787 | <|skeleton|>
class DBScan:
def __init__(self, points, eps, min_points):
"""DBScan is initialized by passing a list of points, the eps, and a minimum number of points per cluster. Args: param1: The dataset of points to be analyzed param2: The eps neighborhood of a point param3: The minimum number of element... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DBScan:
def __init__(self, points, eps, min_points):
"""DBScan is initialized by passing a list of points, the eps, and a minimum number of points per cluster. Args: param1: The dataset of points to be analyzed param2: The eps neighborhood of a point param3: The minimum number of elements per cluster.... | the_stack_v2_python_sparse | machine_learning/cluster_analysis/dbscan/python/DBScan.py | ZoranPandovski/al-go-rithms | train | 1,421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.