blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
690450bd3ce241ecf3aa62b947c2daa01c14a8c5 | [
"self.fstring = fstring\nself.prefix = prefix\nself.filename = filename\nself.fields = {}\nself.repl = ''\nself.res = None",
"prelen = len(self.prefix)\nquote = self.fstring[prelen]\nif self.fstring[prelen + 1] == quote:\n quote *= 3\ntemplate = self.fstring[prelen + len(quote):-len(quote)]\nwhile True:\n r... | <|body_start_0|>
self.fstring = fstring
self.prefix = prefix
self.filename = filename
self.fields = {}
self.repl = ''
self.res = None
<|end_body_0|>
<|body_start_1|>
prelen = len(self.prefix)
quote = self.fstring[prelen]
if self.fstring[prelen + 1... | Helper for parsing Xonsh syntax within f-strings. | FStringAdaptor | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FStringAdaptor:
"""Helper for parsing Xonsh syntax within f-strings."""
def __init__(self, fstring, prefix, filename=None):
"""Parses an f-string containing special Xonsh syntax and returns ast.JoinedStr AST node instance representing the input string. Parameters ---------- fstring :... | stack_v2_sparse_classes_36k_train_023500 | 7,443 | permissive | [
{
"docstring": "Parses an f-string containing special Xonsh syntax and returns ast.JoinedStr AST node instance representing the input string. Parameters ---------- fstring : str The input f-string. prefix : str Prefix of the f-string (e.g. \"fr\"). filename : str, optional File from which the code was read or a... | 6 | null | Implement the Python class `FStringAdaptor` described below.
Class description:
Helper for parsing Xonsh syntax within f-strings.
Method signatures and docstrings:
- def __init__(self, fstring, prefix, filename=None): Parses an f-string containing special Xonsh syntax and returns ast.JoinedStr AST node instance repre... | Implement the Python class `FStringAdaptor` described below.
Class description:
Helper for parsing Xonsh syntax within f-strings.
Method signatures and docstrings:
- def __init__(self, fstring, prefix, filename=None): Parses an f-string containing special Xonsh syntax and returns ast.JoinedStr AST node instance repre... | 60f0145ed893cb73bbfcf336c448238981010d41 | <|skeleton|>
class FStringAdaptor:
"""Helper for parsing Xonsh syntax within f-strings."""
def __init__(self, fstring, prefix, filename=None):
"""Parses an f-string containing special Xonsh syntax and returns ast.JoinedStr AST node instance representing the input string. Parameters ---------- fstring :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FStringAdaptor:
"""Helper for parsing Xonsh syntax within f-strings."""
def __init__(self, fstring, prefix, filename=None):
"""Parses an f-string containing special Xonsh syntax and returns ast.JoinedStr AST node instance representing the input string. Parameters ---------- fstring : str The inpu... | the_stack_v2_python_sparse | xonsh/parsers/fstring_adaptor.py | xonsh/xonsh | train | 6,374 |
08cfdcc97016edc56b3a099c5f01cd65edbe7b3d | [
"Part = self.old_state.apps.get_model('part', 'part')\nPartParameter = self.old_state.apps.get_model('part', 'partparameter')\nPartParameterTemlate = self.old_state.apps.get_model('part', 'partparametertemplate')\na = Part.objects.create(name='Part A', description='My part A', level=0, lft=0, rght=0, tree_id=0)\nb ... | <|body_start_0|>
Part = self.old_state.apps.get_model('part', 'part')
PartParameter = self.old_state.apps.get_model('part', 'partparameter')
PartParameterTemlate = self.old_state.apps.get_model('part', 'partparametertemplate')
a = Part.objects.create(name='Part A', description='My part A... | Unit test for part parameter migrations | TestParameterMigrations | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestParameterMigrations:
"""Unit test for part parameter migrations"""
def prepare(self):
"""Create some parts, and templates with parameters"""
<|body_0|>
def test_data_migration(self):
"""Test that the template units and values have been updated correctly"""
... | stack_v2_sparse_classes_36k_train_023501 | 8,200 | permissive | [
{
"docstring": "Create some parts, and templates with parameters",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test that the template units and values have been updated correctly",
"name": "test_data_migration",
"signature": "def test_data_migration(self)"
}
... | 2 | null | Implement the Python class `TestParameterMigrations` described below.
Class description:
Unit test for part parameter migrations
Method signatures and docstrings:
- def prepare(self): Create some parts, and templates with parameters
- def test_data_migration(self): Test that the template units and values have been up... | Implement the Python class `TestParameterMigrations` described below.
Class description:
Unit test for part parameter migrations
Method signatures and docstrings:
- def prepare(self): Create some parts, and templates with parameters
- def test_data_migration(self): Test that the template units and values have been up... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestParameterMigrations:
"""Unit test for part parameter migrations"""
def prepare(self):
"""Create some parts, and templates with parameters"""
<|body_0|>
def test_data_migration(self):
"""Test that the template units and values have been updated correctly"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestParameterMigrations:
"""Unit test for part parameter migrations"""
def prepare(self):
"""Create some parts, and templates with parameters"""
Part = self.old_state.apps.get_model('part', 'part')
PartParameter = self.old_state.apps.get_model('part', 'partparameter')
Part... | the_stack_v2_python_sparse | InvenTree/part/test_migrations.py | inventree/InvenTree | train | 3,077 |
4fdabc9f36e23d2f079c356b0ac7fd8af257383e | [
"data = self.get_json()\ntry:\n data['next_call'] = str(arrow.get(data.get('next_call')).datetime.replace(tzinfo=None))\nexcept arrow.ParserError:\n return self.error(f\"Invalid input for parameter next_call:{data.get('next_call')}\")\nif 'method' in data:\n data['method'] = data['method'].upper()\n if ... | <|body_start_0|>
data = self.get_json()
try:
data['next_call'] = str(arrow.get(data.get('next_call')).datetime.replace(tzinfo=None))
except arrow.ParserError:
return self.error(f"Invalid input for parameter next_call:{data.get('next_call')}")
if 'method' in data:
... | Handler for recurring APIs. | RecurringAPIHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurringAPIHandler:
"""Handler for recurring APIs."""
def post(self):
"""--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: ... | stack_v2_sparse_classes_36k_train_023502 | 7,029 | permissive | [
{
"docstring": "--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: type: string description: HTTP method of the API call. next_call: type: datetime descr... | 3 | null | Implement the Python class `RecurringAPIHandler` described below.
Class description:
Handler for recurring APIs.
Method signatures and docstrings:
- def post(self): --- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: typ... | Implement the Python class `RecurringAPIHandler` described below.
Class description:
Handler for recurring APIs.
Method signatures and docstrings:
- def post(self): --- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: typ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class RecurringAPIHandler:
"""Handler for recurring APIs."""
def post(self):
"""--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecurringAPIHandler:
"""Handler for recurring APIs."""
def post(self):
"""--- description: POST a new Recurring APIs. tags: - recurring_apis requestBody: content: application/json: schema: type: object properties: endpoint: type: string description: Endpoint of the API call. method: type: string ... | the_stack_v2_python_sparse | skyportal/handlers/api/recurring_api.py | skyportal/skyportal | train | 80 |
8584923d499efa0ce0587feddebfeda7232c416b | [
"if self.backend is None:\n raise QiskitError('backend not set. Cannot determine the center frequency.')\nreturn self._backend_data.drive_freqs[self.physical_qubits[0]]",
"circuit = QuantumCircuit(1)\ncircuit.append(Gate(name=self.__spec_gate_name__, num_qubits=1, params=[freq_param]), (0,))\ncircuit.measure_a... | <|body_start_0|>
if self.backend is None:
raise QiskitError('backend not set. Cannot determine the center frequency.')
return self._backend_data.drive_freqs[self.physical_qubits[0]]
<|end_body_0|>
<|body_start_1|>
circuit = QuantumCircuit(1)
circuit.append(Gate(name=self.__s... | A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy pulse-schedule embedded in a spectroscopy gate... | QubitSpectroscopy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy p... | stack_v2_sparse_classes_36k_train_023503 | 4,798 | permissive | [
{
"docstring": "Returns the center frequency of the experiment. Returns: The center frequency of the experiment. Raises: QiskitError: If the experiment does not have a backend set.",
"name": "_backend_center_frequency",
"signature": "def _backend_center_frequency(self) -> float"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_017885 | Implement the Python class `QubitSpectroscopy` described below.
Class description:
A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/═════... | Implement the Python class `QubitSpectroscopy` described below.
Class description:
A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/═════... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QubitSpectroscopy:
"""A spectroscopy experiment to obtain a frequency sweep of the qubit. # section: overview The circuits produced by spectroscopy, i.e. .. parsed-literal:: ┌────────────┐ ░ ┌─┐ q_0: ┤ Spec(freq) ├─░─┤M├ └────────────┘ ░ └╥┘ measure: 1/══════════════════╩═ 0 have a spectroscopy pulse-schedule... | the_stack_v2_python_sparse | qiskit_experiments/library/characterization/qubit_spectroscopy.py | oliverdial/qiskit-experiments | train | 0 |
d41edc288494d97c64ba1b2ad98e103d78e496c1 | [
"if settings.USER_ACCESS_TOKEN_WARNING:\n return [('all_token', 'All Token'), ('valid_token', 'Valid Token'), ('soon_expired_token', 'Soon Expired Token'), ('expired_token', 'Expired Token')]\nelse:\n return [('all_token', 'All Token'), ('valid_token', 'Valid Token'), ('Expired_token', 'Expired Token')]",
"... | <|body_start_0|>
if settings.USER_ACCESS_TOKEN_WARNING:
return [('all_token', 'All Token'), ('valid_token', 'Valid Token'), ('soon_expired_token', 'Soon Expired Token'), ('expired_token', 'Expired Token')]
else:
return [('all_token', 'All Token'), ('valid_token', 'Valid Token'), ... | TokenStatusFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenStatusFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar... | stack_v2_sparse_classes_36k_train_023504 | 31,712 | permissive | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | stack_v2_sparse_classes_30k_train_015111 | Implement the Python class `TokenStatusFilter` described below.
Class description:
Implement the TokenStatusFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL... | Implement the Python class `TokenStatusFilter` described below.
Class description:
Implement the TokenStatusFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL... | 9af33ac81db86a87770fb18b2f26b74d9636dafb | <|skeleton|>
class TokenStatusFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenStatusFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
i... | the_stack_v2_python_sparse | authome/admin/admin.py | dbca-wa/authome | train | 5 | |
90e4d8b4536dfa15c8b08594fc8ff4d52f35c69a | [
"if 'formatter' not in overrides:\n overrides['formatter'] = Formatter()\nsuper().__init__(**overrides)",
"start, end = (self.start, self.end)\nif start > end:\n start, end = (end, start)\nmajor_ticks = tuple((x for x in self.major_values if start <= x <= end))\nminor_ticks = tuple((x for x in self.minor_va... | <|body_start_0|>
if 'formatter' not in overrides:
overrides['formatter'] = Formatter()
super().__init__(**overrides)
<|end_body_0|>
<|body_start_1|>
start, end = (self.start, self.end)
if start > end:
start, end = (end, start)
major_ticks = tuple((x for x... | This type of ticker provides user-specified fixed ticks. The label 'formatter' is by default set to pero.Formatter, but can be changed if needed. Properties: major_values: tuple Specifies the values to be used as the major ticks and labels. minor_values: tuple Specifies the values to be used as the minor ticks. | FixTicker | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixTicker:
"""This type of ticker provides user-specified fixed ticks. The label 'formatter' is by default set to pero.Formatter, but can be changed if needed. Properties: major_values: tuple Specifies the values to be used as the major ticks and labels. minor_values: tuple Specifies the values t... | stack_v2_sparse_classes_36k_train_023505 | 1,613 | permissive | [
{
"docstring": "Initializes a new instance of FixTicker.",
"name": "__init__",
"signature": "def __init__(self, **overrides)"
},
{
"docstring": "Generates ticks according to current settings. Returns: (float,), (float,) Generated major and minor ticks.",
"name": "make_ticks",
"signature"... | 2 | null | Implement the Python class `FixTicker` described below.
Class description:
This type of ticker provides user-specified fixed ticks. The label 'formatter' is by default set to pero.Formatter, but can be changed if needed. Properties: major_values: tuple Specifies the values to be used as the major ticks and labels. min... | Implement the Python class `FixTicker` described below.
Class description:
This type of ticker provides user-specified fixed ticks. The label 'formatter' is by default set to pero.Formatter, but can be changed if needed. Properties: major_values: tuple Specifies the values to be used as the major ticks and labels. min... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class FixTicker:
"""This type of ticker provides user-specified fixed ticks. The label 'formatter' is by default set to pero.Formatter, but can be changed if needed. Properties: major_values: tuple Specifies the values to be used as the major ticks and labels. minor_values: tuple Specifies the values t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixTicker:
"""This type of ticker provides user-specified fixed ticks. The label 'formatter' is by default set to pero.Formatter, but can be changed if needed. Properties: major_values: tuple Specifies the values to be used as the major ticks and labels. minor_values: tuple Specifies the values to be used as ... | the_stack_v2_python_sparse | pero/tickers/fixed.py | xxao/pero | train | 31 |
3f9cecea547108d807bb1f2fb55d1adf8feebad1 | [
"ctrl = NonLinearQuadrocopterController()\nself.assertEquals(ctrl._zeta_z, 0.7)\nassert all(isclose(ctrl._params, [0.7, 0.7, 0.7, 0.5, 0.707]))\nself.assertIsNone(ctrl.reference)\nself.assertTrue(ctrl.initialized)\nself.assertIsInstance(ctrl._par_space, BoundedSpace)",
"ref = Reference('circle', 1 / 70.0)\nref.re... | <|body_start_0|>
ctrl = NonLinearQuadrocopterController()
self.assertEquals(ctrl._zeta_z, 0.7)
assert all(isclose(ctrl._params, [0.7, 0.7, 0.7, 0.5, 0.707]))
self.assertIsNone(ctrl.reference)
self.assertTrue(ctrl.initialized)
self.assertIsInstance(ctrl._par_space, Bounded... | Test NonLinearQuadrocopterController. | TestController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestController:
"""Test NonLinearQuadrocopterController."""
def test_controller_init(self):
"""Test: CONTROLLER: initialization."""
<|body_0|>
def test_controller_map(self):
"""Test: CONTROLLER: mapping."""
<|body_1|>
def test_controller_properties(s... | stack_v2_sparse_classes_36k_train_023506 | 5,830 | permissive | [
{
"docstring": "Test: CONTROLLER: initialization.",
"name": "test_controller_init",
"signature": "def test_controller_init(self)"
},
{
"docstring": "Test: CONTROLLER: mapping.",
"name": "test_controller_map",
"signature": "def test_controller_map(self)"
},
{
"docstring": "Test: C... | 3 | null | Implement the Python class `TestController` described below.
Class description:
Test NonLinearQuadrocopterController.
Method signatures and docstrings:
- def test_controller_init(self): Test: CONTROLLER: initialization.
- def test_controller_map(self): Test: CONTROLLER: mapping.
- def test_controller_properties(self)... | Implement the Python class `TestController` described below.
Class description:
Test NonLinearQuadrocopterController.
Method signatures and docstrings:
- def test_controller_init(self): Test: CONTROLLER: initialization.
- def test_controller_map(self): Test: CONTROLLER: mapping.
- def test_controller_properties(self)... | 8500c8dd90a2b59a91b988a3c83e529f6c69332f | <|skeleton|>
class TestController:
"""Test NonLinearQuadrocopterController."""
def test_controller_init(self):
"""Test: CONTROLLER: initialization."""
<|body_0|>
def test_controller_map(self):
"""Test: CONTROLLER: mapping."""
<|body_1|>
def test_controller_properties(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestController:
"""Test NonLinearQuadrocopterController."""
def test_controller_init(self):
"""Test: CONTROLLER: initialization."""
ctrl = NonLinearQuadrocopterController()
self.assertEquals(ctrl._zeta_z, 0.7)
assert all(isclose(ctrl._params, [0.7, 0.7, 0.7, 0.5, 0.707]))
... | the_stack_v2_python_sparse | Safe-RL/Safe-RL-Benchmark/SafeRLBench/policy/test.py | chauncygu/Safe-Reinforcement-Learning-Baselines | train | 233 |
b6ec725a9d4022943fc7b6073c9d6bb5bc1d5e5b | [
"aug_kwargs = cfg.aug_kwargs\naug_list = []\nif is_train:\n aug_list.extend([getattr(A, name)(**kwargs) for name, kwargs in aug_kwargs.items()])\nself.transform = A.Compose(aug_list, bbox_params=A.BboxParams(format='pascal_voc', label_fields=['category_ids']))\nself.is_train = is_train\nmode = 'training' if is_t... | <|body_start_0|>
aug_kwargs = cfg.aug_kwargs
aug_list = []
if is_train:
aug_list.extend([getattr(A, name)(**kwargs) for name, kwargs in aug_kwargs.items()])
self.transform = A.Compose(aug_list, bbox_params=A.BboxParams(format='pascal_voc', label_fields=['category_ids']))
... | AlbumentationsMapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbumentationsMapper:
def __init__(self, cfg, is_train: bool=True):
""":cfg: contains information about augmentations to apply :is_train: is_train = True for training only. is_train = False for validation and test"""
<|body_0|>
def __call__(self, dataset_dict):
""":d... | stack_v2_sparse_classes_36k_train_023507 | 18,732 | no_license | [
{
"docstring": ":cfg: contains information about augmentations to apply :is_train: is_train = True for training only. is_train = False for validation and test",
"name": "__init__",
"signature": "def __init__(self, cfg, is_train: bool=True)"
},
{
"docstring": ":dataset_dict: this contains a singl... | 2 | stack_v2_sparse_classes_30k_train_009743 | Implement the Python class `AlbumentationsMapper` described below.
Class description:
Implement the AlbumentationsMapper class.
Method signatures and docstrings:
- def __init__(self, cfg, is_train: bool=True): :cfg: contains information about augmentations to apply :is_train: is_train = True for training only. is_tra... | Implement the Python class `AlbumentationsMapper` described below.
Class description:
Implement the AlbumentationsMapper class.
Method signatures and docstrings:
- def __init__(self, cfg, is_train: bool=True): :cfg: contains information about augmentations to apply :is_train: is_train = True for training only. is_tra... | 4a7a248389ee82ef3cf7a207423f5b68d1bd0975 | <|skeleton|>
class AlbumentationsMapper:
def __init__(self, cfg, is_train: bool=True):
""":cfg: contains information about augmentations to apply :is_train: is_train = True for training only. is_train = False for validation and test"""
<|body_0|>
def __call__(self, dataset_dict):
""":d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlbumentationsMapper:
def __init__(self, cfg, is_train: bool=True):
""":cfg: contains information about augmentations to apply :is_train: is_train = True for training only. is_train = False for validation and test"""
aug_kwargs = cfg.aug_kwargs
aug_list = []
if is_train:
... | the_stack_v2_python_sparse | common/detectron2_utils.py | sheldonsebastian/vbd_cxr | train | 0 | |
294a01b88176af7806c788a0138eabd12a3e5e99 | [
"super(PCA, self).__init__(input_dim)\nself.whiten = whiten\nself.eigen_values = None\nself.projection_matrix = None\nself.unprojection_matrix = None",
"super(PCA, self).train(data)\nself.projection_matrix, self.eigen_values, _ = numx.linalg.svd(self.covariance_matrix)\nindex = numx.argsort(self.eigen_values)[::-... | <|body_start_0|>
super(PCA, self).__init__(input_dim)
self.whiten = whiten
self.eigen_values = None
self.projection_matrix = None
self.unprojection_matrix = None
<|end_body_0|>
<|body_start_1|>
super(PCA, self).train(data)
self.projection_matrix, self.eigen_value... | Principle component analysis (PCA) using Singular Value Decomposition (SVD) | PCA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCA:
"""Principle component analysis (PCA) using Singular Value Decomposition (SVD)"""
def __init__(self, input_dim, whiten=False):
"""Constructor. :param input_dim: Data dimensionality. :type input_dim: int :param whiten: If true the projected data will be de-correlated in all direc... | stack_v2_sparse_classes_36k_train_023508 | 13,683 | no_license | [
{
"docstring": "Constructor. :param input_dim: Data dimensionality. :type input_dim: int :param whiten: If true the projected data will be de-correlated in all directions. :type whiten: bool",
"name": "__init__",
"signature": "def __init__(self, input_dim, whiten=False)"
},
{
"docstring": "Train... | 4 | stack_v2_sparse_classes_30k_train_002804 | Implement the Python class `PCA` described below.
Class description:
Principle component analysis (PCA) using Singular Value Decomposition (SVD)
Method signatures and docstrings:
- def __init__(self, input_dim, whiten=False): Constructor. :param input_dim: Data dimensionality. :type input_dim: int :param whiten: If t... | Implement the Python class `PCA` described below.
Class description:
Principle component analysis (PCA) using Singular Value Decomposition (SVD)
Method signatures and docstrings:
- def __init__(self, input_dim, whiten=False): Constructor. :param input_dim: Data dimensionality. :type input_dim: int :param whiten: If t... | 997879373110b2ee69fba921d46a309443c8e374 | <|skeleton|>
class PCA:
"""Principle component analysis (PCA) using Singular Value Decomposition (SVD)"""
def __init__(self, input_dim, whiten=False):
"""Constructor. :param input_dim: Data dimensionality. :type input_dim: int :param whiten: If true the projected data will be de-correlated in all direc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCA:
"""Principle component analysis (PCA) using Singular Value Decomposition (SVD)"""
def __init__(self, input_dim, whiten=False):
"""Constructor. :param input_dim: Data dimensionality. :type input_dim: int :param whiten: If true the projected data will be de-correlated in all directions. :type ... | the_stack_v2_python_sparse | pydeep/preprocessing.py | MelJan/PyDeep | train | 50 |
24bf71d6df01f84a552941ec49922db3d9449c11 | [
"EasyFrame.__init__(self, title='Temperature Converter')\nself.model = model\nself.celsiusScale = self.addScale(label='Celsius', row=0, column=0, from_=-273.15, to=100.0, resolution=0.01, length=250, tickinterval=0, command=self.computeFahr)\nself.celsiusScale.set(model.getCelsius())\nself.fahrScale = self.addScale... | <|body_start_0|>
EasyFrame.__init__(self, title='Temperature Converter')
self.model = model
self.celsiusScale = self.addScale(label='Celsius', row=0, column=0, from_=-273.15, to=100.0, resolution=0.01, length=250, tickinterval=0, command=self.computeFahr)
self.celsiusScale.set(model.getC... | A termperature conversion program. Uses sliding scales. | ThermometerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThermometerView:
"""A termperature conversion program. Uses sliding scales."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
<|body_0|>
def computeFahr(self, degreesCelsius):
"""Inputs the Celsius degrees and outputs the Fa... | stack_v2_sparse_classes_36k_train_023509 | 2,218 | no_license | [
{
"docstring": "Sets up the view. The model comes in as an argument.",
"name": "__init__",
"signature": "def __init__(self, model)"
},
{
"docstring": "Inputs the Celsius degrees and outputs the Fahrenheit degrees.",
"name": "computeFahr",
"signature": "def computeFahr(self, degreesCelsiu... | 3 | stack_v2_sparse_classes_30k_train_009994 | Implement the Python class `ThermometerView` described below.
Class description:
A termperature conversion program. Uses sliding scales.
Method signatures and docstrings:
- def __init__(self, model): Sets up the view. The model comes in as an argument.
- def computeFahr(self, degreesCelsius): Inputs the Celsius degre... | Implement the Python class `ThermometerView` described below.
Class description:
A termperature conversion program. Uses sliding scales.
Method signatures and docstrings:
- def __init__(self, model): Sets up the view. The model comes in as an argument.
- def computeFahr(self, degreesCelsius): Inputs the Celsius degre... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class ThermometerView:
"""A termperature conversion program. Uses sliding scales."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
<|body_0|>
def computeFahr(self, degreesCelsius):
"""Inputs the Celsius degrees and outputs the Fa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThermometerView:
"""A termperature conversion program. Uses sliding scales."""
def __init__(self, model):
"""Sets up the view. The model comes in as an argument."""
EasyFrame.__init__(self, title='Temperature Converter')
self.model = model
self.celsiusScale = self.addScale... | the_stack_v2_python_sparse | gui/breezy/thermometerview2.py | lforet/robomow | train | 11 |
61d6de35ddbaf51c57afaa03d5f9079abd27c7e5 | [
"self.source_app_params = source_app_params\nself.vm_credentials = vm_credentials\nself.vmware_disk_exclusion_info = vmware_disk_exclusion_info",
"if dictionary is None:\n return None\nsource_app_params = cohesity_management_sdk.models.source_app_params.SourceAppParams.from_dictionary(dictionary.get('sourceApp... | <|body_start_0|>
self.source_app_params = source_app_params
self.vm_credentials = vm_credentials
self.vmware_disk_exclusion_info = vmware_disk_exclusion_info
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
source_app_params = cohesity_management_sd... | Implementation of the 'VmwareBackupSourceParams' model. Message to capture additional backup params for a VMware type source. Attributes: source_app_params (SourceAppParams): This message will capture params for applications that are running as part of the server. vm_credentials (Credentials): Target entity credentials... | VmwareBackupSourceParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareBackupSourceParams:
"""Implementation of the 'VmwareBackupSourceParams' model. Message to capture additional backup params for a VMware type source. Attributes: source_app_params (SourceAppParams): This message will capture params for applications that are running as part of the server. vm_... | stack_v2_sparse_classes_36k_train_023510 | 3,256 | permissive | [
{
"docstring": "Constructor for the VmwareBackupSourceParams class",
"name": "__init__",
"signature": "def __init__(self, source_app_params=None, vm_credentials=None, vmware_disk_exclusion_info=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | null | Implement the Python class `VmwareBackupSourceParams` described below.
Class description:
Implementation of the 'VmwareBackupSourceParams' model. Message to capture additional backup params for a VMware type source. Attributes: source_app_params (SourceAppParams): This message will capture params for applications that... | Implement the Python class `VmwareBackupSourceParams` described below.
Class description:
Implementation of the 'VmwareBackupSourceParams' model. Message to capture additional backup params for a VMware type source. Attributes: source_app_params (SourceAppParams): This message will capture params for applications that... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VmwareBackupSourceParams:
"""Implementation of the 'VmwareBackupSourceParams' model. Message to capture additional backup params for a VMware type source. Attributes: source_app_params (SourceAppParams): This message will capture params for applications that are running as part of the server. vm_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmwareBackupSourceParams:
"""Implementation of the 'VmwareBackupSourceParams' model. Message to capture additional backup params for a VMware type source. Attributes: source_app_params (SourceAppParams): This message will capture params for applications that are running as part of the server. vm_credentials (... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vmware_backup_source_params.py | cohesity/management-sdk-python | train | 24 |
e97b4472dca75bd28c03c1898b4212599b78f3b3 | [
"self.B = 1.0 * 11.96\nself.energy = lambda j: self.B * j * (j + 1)\nself.degeneracy = lambda j: 2 * j + 1\nself.n0 = 0",
"t_list = np.array([300, 500, 1000, 1500, 2000])\nq_exp_list = np.array([208.8907, 347.9285, 695.5234, 1043.118, 1390.713])\nfor temperature, q_exp in zip(t_list, q_exp_list):\n q_act = get... | <|body_start_0|>
self.B = 1.0 * 11.96
self.energy = lambda j: self.B * j * (j + 1)
self.degeneracy = lambda j: 2 * j + 1
self.n0 = 0
<|end_body_0|>
<|body_start_1|>
t_list = np.array([300, 500, 1000, 1500, 2000])
q_exp_list = np.array([208.8907, 347.9285, 695.5234, 1043.... | Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1. | TestSchrodinger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSchrodinger:
"""Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1."""
def setUp(self):
"""A function run before each unit... | stack_v2_sparse_classes_36k_train_023511 | 6,011 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the get_partition_function() method.",
"name": "test_get_partition_function",
"signature": "def test_get_partition_function(self)"
},
{
"d... | 6 | stack_v2_sparse_classes_30k_test_000622 | Implement the Python class `TestSchrodinger` described below.
Class description:
Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1.
Method signatures and docst... | Implement the Python class `TestSchrodinger` described below.
Class description:
Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1.
Method signatures and docst... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestSchrodinger:
"""Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1."""
def setUp(self):
"""A function run before each unit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSchrodinger:
"""Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1."""
def setUp(self):
"""A function run before each unit test in this... | the_stack_v2_python_sparse | rmgpy/statmech/schrodingerTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
8bd831f08308c039edeba572172d98a79e2e2a78 | [
"self.part_map = {}\nself.part_landmark_map = {}\nself.added_lane_ids = []\nself.added_landmark_ids = []\nself.removed_lane_ids = []\nself.removed_landmark_ids = []\nself.added_partitions = []\nself.removed_partitions = []",
"self.added_lane_ids = []\nself.added_landmark_ids = []\nself.removed_lane_ids = []\nself... | <|body_start_0|>
self.part_map = {}
self.part_landmark_map = {}
self.added_lane_ids = []
self.added_landmark_ids = []
self.removed_lane_ids = []
self.removed_landmark_ids = []
self.added_partitions = []
self.removed_partitions = []
<|end_body_0|>
<|body_s... | ... | PartitionManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartitionManager:
"""..."""
def __init__(self):
"""..."""
<|body_0|>
def reset(self):
"""..."""
<|body_1|>
def clear(self):
"""..."""
<|body_2|>
def add_lane(self, part, lane_id):
"""..."""
<|body_3|>
def rem... | stack_v2_sparse_classes_36k_train_023512 | 1,932 | permissive | [
{
"docstring": "...",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "...",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "...",
"name": "clear",
"signature": "def clear(self)"
},
{
"docstring": "...",
"name": "add_... | 6 | stack_v2_sparse_classes_30k_train_018162 | Implement the Python class `PartitionManager` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self): ...
- def reset(self): ...
- def clear(self): ...
- def add_lane(self, part, lane_id): ...
- def remove_lane(self, lane_id): ...
- def debug_print(self): ... | Implement the Python class `PartitionManager` described below.
Class description:
...
Method signatures and docstrings:
- def __init__(self): ...
- def reset(self): ...
- def clear(self): ...
- def add_lane(self, part, lane_id): ...
- def remove_lane(self, lane_id): ...
- def debug_print(self): ...
<|skeleton|>
clas... | cc9618fd005bc28ad08d0f89f30911bb7a75a41e | <|skeleton|>
class PartitionManager:
"""..."""
def __init__(self):
"""..."""
<|body_0|>
def reset(self):
"""..."""
<|body_1|>
def clear(self):
"""..."""
<|body_2|>
def add_lane(self, part, lane_id):
"""..."""
<|body_3|>
def rem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartitionManager:
"""..."""
def __init__(self):
"""..."""
self.part_map = {}
self.part_landmark_map = {}
self.added_lane_ids = []
self.added_landmark_ids = []
self.removed_lane_ids = []
self.removed_landmark_ids = []
self.added_partitions = ... | the_stack_v2_python_sparse | tools/ad_map_access_qgis/ad_map_access_qgis/PartitionManager.py | carla-simulator/map | train | 87 |
de213f968fcfdc57117ad8bd0f5270a113f38785 | [
"courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}\nresult = validate_courses(courses)\nself.assertEqual(result, ['CSC300', 'CSC200', 'CSC100'])",
"courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': [], 'BIO101': [], 'BIO102': ['BIO101'], 'BIO300': ['BIO101', '... | <|body_start_0|>
courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}
result = validate_courses(courses)
self.assertEqual(result, ['CSC300', 'CSC200', 'CSC100'])
<|end_body_0|>
<|body_start_1|>
courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'C... | TestValidateCourses | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestValidateCourses:
def test_courses_short_list(self):
"""This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument"""
<|body_0|>
def test_courses_long_list(self):
"""This test checks to... | stack_v2_sparse_classes_36k_train_023513 | 1,599 | permissive | [
{
"docstring": "This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument",
"name": "test_courses_short_list",
"signature": "def test_courses_short_list(self)"
},
{
"docstring": "This test checks to see if a valid lo... | 3 | stack_v2_sparse_classes_30k_train_013641 | Implement the Python class `TestValidateCourses` described below.
Class description:
Implement the TestValidateCourses class.
Method signatures and docstrings:
- def test_courses_short_list(self): This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses(... | Implement the Python class `TestValidateCourses` described below.
Class description:
Implement the TestValidateCourses class.
Method signatures and docstrings:
- def test_courses_short_list(self): This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses(... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class TestValidateCourses:
def test_courses_short_list(self):
"""This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument"""
<|body_0|>
def test_courses_long_list(self):
"""This test checks to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestValidateCourses:
def test_courses_short_list(self):
"""This test checks to see if a valid short list of courses is returned from the graph that is passed into validate_courses() as an argument"""
courses = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}
result ... | the_stack_v2_python_sparse | src/daily-coding-problem/hard/validate-courses/test_validate_courses.py | nwthomas/code-challenges | train | 2 | |
b69f442a65f2e9c8f819e76d75ef6f48b2cb1056 | [
"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!')",
"conte... | <|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... | The MruV server service provides procedures for managing game platform server actions. | MruVServerServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MruVServerServiceServicer:
"""The MruV server service provides procedures for managing game platform server actions."""
def RegisterServer(self, request, context):
"""Register instance of server for further managing."""
<|body_0|>
def GetRegisteredServers(self, request, ... | stack_v2_sparse_classes_36k_train_023514 | 9,501 | permissive | [
{
"docstring": "Register instance of server for further managing.",
"name": "RegisterServer",
"signature": "def RegisterServer(self, request, context)"
},
{
"docstring": "Get all registered servers.",
"name": "GetRegisteredServers",
"signature": "def GetRegisteredServers(self, request, c... | 5 | stack_v2_sparse_classes_30k_train_004446 | Implement the Python class `MruVServerServiceServicer` described below.
Class description:
The MruV server service provides procedures for managing game platform server actions.
Method signatures and docstrings:
- def RegisterServer(self, request, context): Register instance of server for further managing.
- def GetR... | Implement the Python class `MruVServerServiceServicer` described below.
Class description:
The MruV server service provides procedures for managing game platform server actions.
Method signatures and docstrings:
- def RegisterServer(self, request, context): Register instance of server for further managing.
- def GetR... | 2a640f7667d23f39e50ccc9ba73c98138c6839b5 | <|skeleton|>
class MruVServerServiceServicer:
"""The MruV server service provides procedures for managing game platform server actions."""
def RegisterServer(self, request, context):
"""Register instance of server for further managing."""
<|body_0|>
def GetRegisteredServers(self, request, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MruVServerServiceServicer:
"""The MruV server service provides procedures for managing game platform server actions."""
def RegisterServer(self, request, context):
"""Register instance of server for further managing."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_d... | the_stack_v2_python_sparse | server/server_pb2_grpc.py | MruV-RP/mruv-pb_python | train | 0 |
6aff1107f015f9fa3cda8365e0bc07eaabe9f197 | [
"count = 0\nn = len(A)\nif n == 0:\n return 0\ncount = 0\nn = len(A)\nif n == 0:\n return 0\nsum1 = {}\nsum2 = {}\nfor i in A:\n for j in B:\n temp = i + j\n if temp in sum1:\n sum1[temp] += 1\n else:\n sum1[temp] = 1\nfor i in C:\n for j in D:\n temp = ... | <|body_start_0|>
count = 0
n = len(A)
if n == 0:
return 0
count = 0
n = len(A)
if n == 0:
return 0
sum1 = {}
sum2 = {}
for i in A:
for j in B:
temp = i + j
if temp in sum1:
... | Ex454 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ex454:
def fourSumCount(self, A, B, C, D):
""":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int"""
<|body_0|>
def fourSumCount0(self, A, B, C, D):
""":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rt... | stack_v2_sparse_classes_36k_train_023515 | 1,878 | no_license | [
{
"docstring": ":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int",
"name": "fourSumCount",
"signature": "def fourSumCount(self, A, B, C, D)"
},
{
"docstring": ":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int",
"na... | 2 | null | Implement the Python class `Ex454` described below.
Class description:
Implement the Ex454 class.
Method signatures and docstrings:
- def fourSumCount(self, A, B, C, D): :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int
- def fourSumCount0(self, A, B, C, D): :type A: List[int] :t... | Implement the Python class `Ex454` described below.
Class description:
Implement the Ex454 class.
Method signatures and docstrings:
- def fourSumCount(self, A, B, C, D): :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int
- def fourSumCount0(self, A, B, C, D): :type A: List[int] :t... | 8f9327a1879949f61b462cc6c82e00e7c27b8b07 | <|skeleton|>
class Ex454:
def fourSumCount(self, A, B, C, D):
""":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int"""
<|body_0|>
def fourSumCount0(self, A, B, C, D):
""":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ex454:
def fourSumCount(self, A, B, C, D):
""":type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int"""
count = 0
n = len(A)
if n == 0:
return 0
count = 0
n = len(A)
if n == 0:
return 0
sum... | the_stack_v2_python_sparse | LeetCode/Ex400/Ex454.py | JasonVann/CrackingCodingInterview | train | 0 | |
8837459dd93fc82ecbf6d8313e798557c5af3b8b | [
"if len(tokens) != len(mask):\n raise ValueError('Dimention mismatch for tokens and mask')\nself.tokens = tokens\nself.mask = mask\nself.task_name = task_name",
"from IPython.display import HTML\nfrom IPython.display import display_html\ntoken_weights = [(escape(x), y) for x, y in zip(self.tokens, self.mask)]\... | <|body_start_0|>
if len(tokens) != len(mask):
raise ValueError('Dimention mismatch for tokens and mask')
self.tokens = tokens
self.mask = mask
self.task_name = task_name
<|end_body_0|>
<|body_start_1|>
from IPython.display import HTML
from IPython.display imp... | Class for visualizing important tokens for single document. | L2XExplanation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2XExplanation:
"""Class for visualizing important tokens for single document."""
def __init__(self, tokens: List[str], mask: List[Number], task_name: str):
"""Args: tokens: Tokens of tokenized document. mask: Mask for important tokens. Non zero elements correspond to importatnt toke... | stack_v2_sparse_classes_36k_train_023516 | 30,205 | permissive | [
{
"docstring": "Args: tokens: Tokens of tokenized document. mask: Mask for important tokens. Non zero elements correspond to importatnt tokens. task_name: Task name.",
"name": "__init__",
"signature": "def __init__(self, tokens: List[str], mask: List[Number], task_name: str)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_006537 | Implement the Python class `L2XExplanation` described below.
Class description:
Class for visualizing important tokens for single document.
Method signatures and docstrings:
- def __init__(self, tokens: List[str], mask: List[Number], task_name: str): Args: tokens: Tokens of tokenized document. mask: Mask for importan... | Implement the Python class `L2XExplanation` described below.
Class description:
Class for visualizing important tokens for single document.
Method signatures and docstrings:
- def __init__(self, tokens: List[str], mask: List[Number], task_name: str): Args: tokens: Tokens of tokenized document. mask: Mask for importan... | a4c3bfb4f1239d05c5d5d36a386c507c6f561324 | <|skeleton|>
class L2XExplanation:
"""Class for visualizing important tokens for single document."""
def __init__(self, tokens: List[str], mask: List[Number], task_name: str):
"""Args: tokens: Tokens of tokenized document. mask: Mask for important tokens. Non zero elements correspond to importatnt toke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class L2XExplanation:
"""Class for visualizing important tokens for single document."""
def __init__(self, tokens: List[str], mask: List[Number], task_name: str):
"""Args: tokens: Tokens of tokenized document. mask: Mask for important tokens. Non zero elements correspond to importatnt tokens. task_name... | the_stack_v2_python_sparse | lightautoml/addons/interpretation/l2x.py | sberbank-ai-lab/LightAutoML | train | 851 |
38603ef08b999a2ea644b28054d4b631ceac36f1 | [
"if inst is None:\n return self\nname = Nature.singlestrand.name\nval = next((i for i in inst.bindings if i.nature == name), None)\nif val is None:\n return Binding(max(inst.positions) * self.SINGLE_STRAND_FACTOR, onrate=0.0, offrate=0.0, nature=Nature.singlestrand)\nreturn val",
"val = _BindingsDescriptor.... | <|body_start_0|>
if inst is None:
return self
name = Nature.singlestrand.name
val = next((i for i in inst.bindings if i.nature == name), None)
if val is None:
return Binding(max(inst.positions) * self.SINGLE_STRAND_FACTOR, onrate=0.0, offrate=0.0, nature=Nature.si... | _SingleStrandBinding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SingleStrandBinding:
def __get__(self, inst, owner):
"""return the single strand binding"""
<|body_0|>
def __set__(self, inst, value):
"""set the single strand binding"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if inst is None:
ret... | stack_v2_sparse_classes_36k_train_023517 | 26,924 | no_license | [
{
"docstring": "return the single strand binding",
"name": "__get__",
"signature": "def __get__(self, inst, owner)"
},
{
"docstring": "set the single strand binding",
"name": "__set__",
"signature": "def __set__(self, inst, value)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000702 | Implement the Python class `_SingleStrandBinding` described below.
Class description:
Implement the _SingleStrandBinding class.
Method signatures and docstrings:
- def __get__(self, inst, owner): return the single strand binding
- def __set__(self, inst, value): set the single strand binding | Implement the Python class `_SingleStrandBinding` described below.
Class description:
Implement the _SingleStrandBinding class.
Method signatures and docstrings:
- def __get__(self, inst, owner): return the single strand binding
- def __set__(self, inst, value): set the single strand binding
<|skeleton|>
class _Sing... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class _SingleStrandBinding:
def __get__(self, inst, owner):
"""return the single strand binding"""
<|body_0|>
def __set__(self, inst, value):
"""set the single strand binding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _SingleStrandBinding:
def __get__(self, inst, owner):
"""return the single strand binding"""
if inst is None:
return self
name = Nature.singlestrand.name
val = next((i for i in inst.bindings if i.nature == name), None)
if val is None:
return Bind... | the_stack_v2_python_sparse | src/simulator/bindings.py | depixusgenome/trackanalysis | train | 0 | |
08f4c65c4ca87e0a69a4703284e6d750cda71864 | [
"try:\n id = [x['id'] for x in DegiroConfigHelper.DEGIRO_CONFIG['exchanges'] if 'id' in x and 'micCode' in x and (x['micCode'] == exchange_sym)][0]\n return id\nexcept KeyError:\n return None",
"try:\n return [x['id'] for x in DegiroConfigHelper.DEGIRO_CONFIG['countries'] if 'id' in x and 'name' in x ... | <|body_start_0|>
try:
id = [x['id'] for x in DegiroConfigHelper.DEGIRO_CONFIG['exchanges'] if 'id' in x and 'micCode' in x and (x['micCode'] == exchange_sym)][0]
return id
except KeyError:
return None
<|end_body_0|>
<|body_start_1|>
try:
return [x... | Helper class for degiro config file | DegiroConfigHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DegiroConfigHelper:
"""Helper class for degiro config file"""
def get_exchange_id(exchange_sym):
"""Returns the degiro id of exchange symbol (xetra, fra) :param exchange_sym: :return:"""
<|body_0|>
def get_country_id(country_sym):
"""Returns the degiro id of coun... | stack_v2_sparse_classes_36k_train_023518 | 3,649 | no_license | [
{
"docstring": "Returns the degiro id of exchange symbol (xetra, fra) :param exchange_sym: :return:",
"name": "get_exchange_id",
"signature": "def get_exchange_id(exchange_sym)"
},
{
"docstring": "Returns the degiro id of country symbol (DE, US) :param country_sym: :return:",
"name": "get_co... | 5 | null | Implement the Python class `DegiroConfigHelper` described below.
Class description:
Helper class for degiro config file
Method signatures and docstrings:
- def get_exchange_id(exchange_sym): Returns the degiro id of exchange symbol (xetra, fra) :param exchange_sym: :return:
- def get_country_id(country_sym): Returns ... | Implement the Python class `DegiroConfigHelper` described below.
Class description:
Helper class for degiro config file
Method signatures and docstrings:
- def get_exchange_id(exchange_sym): Returns the degiro id of exchange symbol (xetra, fra) :param exchange_sym: :return:
- def get_country_id(country_sym): Returns ... | a2b486d5941dbee01272c49e6e63e289edcf9966 | <|skeleton|>
class DegiroConfigHelper:
"""Helper class for degiro config file"""
def get_exchange_id(exchange_sym):
"""Returns the degiro id of exchange symbol (xetra, fra) :param exchange_sym: :return:"""
<|body_0|>
def get_country_id(country_sym):
"""Returns the degiro id of coun... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DegiroConfigHelper:
"""Helper class for degiro config file"""
def get_exchange_id(exchange_sym):
"""Returns the degiro id of exchange symbol (xetra, fra) :param exchange_sym: :return:"""
try:
id = [x['id'] for x in DegiroConfigHelper.DEGIRO_CONFIG['exchanges'] if 'id' in x and... | the_stack_v2_python_sparse | autotrader/broker/degiro/degiro_config_helper.py | SlashGordon/autotrader | train | 1 |
6153c97677bfd623b439f3de6e68e3af01962ac3 | [
"errors = []\nif not HAS_TTP:\n errors.append(missing_required_lib('ttp'))\nreturn {'errors': errors}",
"cli_output = to_native(self._task_args.get('text'), errors='surrogate_then_replace')\nres = self._check_reqs()\nif res.get('errors'):\n return {'errors': res.get('errors')}\ntemplate_path = to_native(sel... | <|body_start_0|>
errors = []
if not HAS_TTP:
errors.append(missing_required_lib('ttp'))
return {'errors': errors}
<|end_body_0|>
<|body_start_1|>
cli_output = to_native(self._task_args.get('text'), errors='surrogate_then_replace')
res = self._check_reqs()
if ... | The ttp parser class Convert raw text to structured data using ttp | CliParser | [
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CliParser:
"""The ttp parser class Convert raw text to structured data using ttp"""
def _check_reqs():
"""Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
"""Std entry... | stack_v2_sparse_classes_36k_train_023519 | 3,930 | permissive | [
{
"docstring": "Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path",
"name": "_check_reqs",
"signature": "def _check_reqs()"
},
{
"docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype: di... | 2 | stack_v2_sparse_classes_30k_train_018945 | Implement the Python class `CliParser` described below.
Class description:
The ttp parser class Convert raw text to structured data using ttp
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path
- def parse(self, *_args, ... | Implement the Python class `CliParser` described below.
Class description:
The ttp parser class Convert raw text to structured data using ttp
Method signatures and docstrings:
- def _check_reqs(): Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path
- def parse(self, *_args, ... | 2ea7d4f00212f502bc684ac257371ada73da1ca9 | <|skeleton|>
class CliParser:
"""The ttp parser class Convert raw text to structured data using ttp"""
def _check_reqs():
"""Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path"""
<|body_0|>
def parse(self, *_args, **_kwargs):
"""Std entry... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CliParser:
"""The ttp parser class Convert raw text to structured data using ttp"""
def _check_reqs():
"""Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path"""
errors = []
if not HAS_TTP:
errors.append(missing_required_lib('t... | the_stack_v2_python_sparse | intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/utils/plugins/sub_plugins/cli_parser/ttp_parser.py | SimonFangCisco/dne-dna-code | train | 0 |
052106bdada2345d0269fe4fa56f1d47dfe15708 | [
"super().__init__()\nself.reconstruction_module = torch.nn.ModuleList([reconstruction_model for _ in range(num_reconstruction_blocks)])\nself.model_name = self.reconstruction_module[0].__class__.__name__.lower()\nif self.model_name == 'modulelist':\n self.model_name = self.reconstruction_module[0][0].__class__._... | <|body_start_0|>
super().__init__()
self.reconstruction_module = torch.nn.ModuleList([reconstruction_model for _ in range(num_reconstruction_blocks)])
self.model_name = self.reconstruction_module[0].__class__.__name__.lower()
if self.model_name == 'modulelist':
self.model_nam... | Reconstruction Model block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network. | SERANetReconstructionBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SERANetReconstructionBlock:
"""Reconstruction Model block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network."""
def __init__... | stack_v2_sparse_classes_36k_train_023520 | 9,773 | permissive | [
{
"docstring": "Initialize the model block. Parameters ---------- num_reconstruction_blocks: Number of reconstruction blocks. reconstruction_model: Reconstruction model. fft_centered: Whether to center the fft. fft_normalization: The normalization of the fft. spatial_dims: The spatial dimensions of the data. co... | 3 | null | Implement the Python class `SERANetReconstructionBlock` described below.
Class description:
Reconstruction Model block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full va... | Implement the Python class `SERANetReconstructionBlock` described below.
Class description:
Reconstruction Model block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full va... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class SERANetReconstructionBlock:
"""Reconstruction Model block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network."""
def __init__... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SERANetReconstructionBlock:
"""Reconstruction Model block for End-to-End Recurrent Attention Network. This model applies a combination of soft data consistency with the input model as a regularizer. A series of these blocks can be stacked to form the full variational network."""
def __init__(self, num_re... | the_stack_v2_python_sparse | mridc/collections/segmentation/models/seranet_base/recon_block.py | wdika/mridc | train | 40 |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\nserializer = TableSerializer(username=username, repo_base=repo_base)\ntable_info = serializer.describe_table(repo_name, table, detail=False)\nreturn Response(table_info, status=status.HTTP_200_OK)",
"username = request.user.get_username()\nserializer = TableSerializer(user... | <|body_start_0|>
username = request.user.get_username()
serializer = TableSerializer(username=username, repo_base=repo_base)
table_info = serializer.describe_table(repo_name, table, detail=False)
return Response(table_info, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
... | Table | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
def get(self, request, repo_base, repo_name, table, format=None):
"""See the schema of a single table This endpoint does not throw an error if the table does not exist."""
<|body_0|>
def delete(self, request, repo_base, repo_name, table, format=None):
"""Delet... | stack_v2_sparse_classes_36k_train_023521 | 31,465 | permissive | [
{
"docstring": "See the schema of a single table This endpoint does not throw an error if the table does not exist.",
"name": "get",
"signature": "def get(self, request, repo_base, repo_name, table, format=None)"
},
{
"docstring": "Delete a single table Delete will fail is the table in question ... | 2 | stack_v2_sparse_classes_30k_val_000557 | Implement the Python class `Table` described below.
Class description:
Implement the Table class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, table, format=None): See the schema of a single table This endpoint does not throw an error if the table does not exist.
- def delete(self,... | Implement the Python class `Table` described below.
Class description:
Implement the Table class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, table, format=None): See the schema of a single table This endpoint does not throw an error if the table does not exist.
- def delete(self,... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class Table:
def get(self, request, repo_base, repo_name, table, format=None):
"""See the schema of a single table This endpoint does not throw an error if the table does not exist."""
<|body_0|>
def delete(self, request, repo_base, repo_name, table, format=None):
"""Delet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
def get(self, request, repo_base, repo_name, table, format=None):
"""See the schema of a single table This endpoint does not throw an error if the table does not exist."""
username = request.user.get_username()
serializer = TableSerializer(username=username, repo_base=repo_base)... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 | |
b56a033581dd529f285a21ea85b11b295499f7c2 | [
"args = {}\nargs.update(csrf(request))\nreturn render(request, 'authentication/register.html', args)",
"usersignupform = UserSignupForm(request.POST)\nemail = request.POST.get('email')\nsignup_new_user = User.objects.filter(email__exact=email)\nif signup_new_user:\n args = {}\n args.update(csrf(request))\n ... | <|body_start_0|>
args = {}
args.update(csrf(request))
return render(request, 'authentication/register.html', args)
<|end_body_0|>
<|body_start_1|>
usersignupform = UserSignupForm(request.POST)
email = request.POST.get('email')
signup_new_user = User.objects.filter(email_... | This class handles user signup. Attributes: template_name | UserRegistrationView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRegistrationView:
"""This class handles user signup. Attributes: template_name"""
def get(self, request, *args, **kwargs):
"""Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template."""
<|body_0|>
def post(self, request):... | stack_v2_sparse_classes_36k_train_023522 | 17,941 | permissive | [
{
"docstring": "Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Handles POST requests to 'register' named route. Raw data posted from form is received... | 2 | null | Implement the Python class `UserRegistrationView` described below.
Class description:
This class handles user signup. Attributes: template_name
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Handles the GET request to the 'register' named route. Returns: A HttpResponse with register temp... | Implement the Python class `UserRegistrationView` described below.
Class description:
This class handles user signup. Attributes: template_name
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Handles the GET request to the 'register' named route. Returns: A HttpResponse with register temp... | 3704cbe6e69ba3e4c53401d3bbc339208e9ebccd | <|skeleton|>
class UserRegistrationView:
"""This class handles user signup. Attributes: template_name"""
def get(self, request, *args, **kwargs):
"""Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template."""
<|body_0|>
def post(self, request):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRegistrationView:
"""This class handles user signup. Attributes: template_name"""
def get(self, request, *args, **kwargs):
"""Handles the GET request to the 'register' named route. Returns: A HttpResponse with register template."""
args = {}
args.update(csrf(request))
... | the_stack_v2_python_sparse | troupon/authentication/views.py | morristech/troupon | train | 0 |
31aa8afe923b6c38c1d1200b3a1d29eb3bb641ba | [
"def dfs(arr, b, e):\n mi = sys.maxint\n ma = -1\n if b == e:\n return (0, arr[b])\n for i in range(b, e):\n left_mi, left_ma = dfs(arr, b, i)\n right_mi, right_ma = dfs(arr, i + 1, e)\n if mi > left_ma * right_ma + left_mi + right_mi:\n mi = left_ma * right_ma + l... | <|body_start_0|>
def dfs(arr, b, e):
mi = sys.maxint
ma = -1
if b == e:
return (0, arr[b])
for i in range(b, e):
left_mi, left_ma = dfs(arr, b, i)
right_mi, right_ma = dfs(arr, i + 1, e)
if mi > left_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mctFromLeafValues_TLE(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def mctFromLeafValues(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(arr, b, e):
m... | stack_v2_sparse_classes_36k_train_023523 | 1,747 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "mctFromLeafValues_TLE",
"signature": "def mctFromLeafValues_TLE(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "mctFromLeafValues",
"signature": "def mctFromLeafValues(self, arr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018478 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mctFromLeafValues_TLE(self, arr): :type arr: List[int] :rtype: int
- def mctFromLeafValues(self, arr): :type arr: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mctFromLeafValues_TLE(self, arr): :type arr: List[int] :rtype: int
- def mctFromLeafValues(self, arr): :type arr: List[int] :rtype: int
<|skeleton|>
class Solution:
def... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def mctFromLeafValues_TLE(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def mctFromLeafValues(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mctFromLeafValues_TLE(self, arr):
""":type arr: List[int] :rtype: int"""
def dfs(arr, b, e):
mi = sys.maxint
ma = -1
if b == e:
return (0, arr[b])
for i in range(b, e):
left_mi, left_ma = dfs(arr, b, ... | the_stack_v2_python_sparse | SourceCode/Python/VSCode/1130.minimum-cost-tree-from-leaf-values.py | roger6blog/LeetCode | train | 0 | |
cef2fee5071999457a383e80e416345ba94f8430 | [
"if not quota_max_calls:\n use_rate_limiter = False\nself._buckets = None\nself._bucket_acls = None\nself._default_object_acls = None\nself._objects = None\nself._object_acls = None\nsuper(StorageRepositoryClient, self).__init__(API_NAME, versions=['v1'], credentials=credentials, quota_max_calls=quota_max_calls,... | <|body_start_0|>
if not quota_max_calls:
use_rate_limiter = False
self._buckets = None
self._bucket_acls = None
self._default_object_acls = None
self._objects = None
self._object_acls = None
super(StorageRepositoryClient, self).__init__(API_NAME, versi... | Storage API Respository. | StorageRepositoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StorageRepositoryClient:
"""Storage API Respository."""
def __init__(self, credentials=None, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: credentials (GoogleCredentials): An optional GoogleCredentials object to use. quota_max_calls (int): Allo... | stack_v2_sparse_classes_36k_train_023524 | 28,733 | permissive | [
{
"docstring": "Constructor. Args: credentials (GoogleCredentials): An optional GoogleCredentials object to use. quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to limit the requests within. use_rate_limiter (bool): Set to false to disable the use of... | 6 | null | Implement the Python class `StorageRepositoryClient` described below.
Class description:
Storage API Respository.
Method signatures and docstrings:
- def __init__(self, credentials=None, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True): Constructor. Args: credentials (GoogleCredentials): An optional Goo... | Implement the Python class `StorageRepositoryClient` described below.
Class description:
Storage API Respository.
Method signatures and docstrings:
- def __init__(self, credentials=None, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True): Constructor. Args: credentials (GoogleCredentials): An optional Goo... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class StorageRepositoryClient:
"""Storage API Respository."""
def __init__(self, credentials=None, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: credentials (GoogleCredentials): An optional GoogleCredentials object to use. quota_max_calls (int): Allo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StorageRepositoryClient:
"""Storage API Respository."""
def __init__(self, credentials=None, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: credentials (GoogleCredentials): An optional GoogleCredentials object to use. quota_max_calls (int): Allowed requests ... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/storage.py | kevensen/forseti-security | train | 1 |
90acdf7bf83e47335a7f46be59ee09655f5116a9 | [
"self.fields = fields\nself.data = data\nself.title = title\nself.sort_by = sort_by",
"doc = SimpleDocTemplate(filename, pagesize=letter)\nstyles = getSampleStyleSheet()\nstyleH = styles['Heading1']\nstory = []\nif self.title:\n story.append(Paragraph(self.title, styleH))\n story.append(Spacer(1, 0.25 * inc... | <|body_start_0|>
self.fields = fields
self.data = data
self.title = title
self.sort_by = sort_by
<|end_body_0|>
<|body_start_1|>
doc = SimpleDocTemplate(filename, pagesize=letter)
styles = getSampleStyleSheet()
styleH = styles['Heading1']
story = []
... | Export a list of dictionaries to a table in a PDF file. | DataToPdf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataToPdf:
"""Export a list of dictionaries to a table in a PDF file."""
def __init__(self, fields, data, sort_by=None, title=None):
"""Arguments: fields - A tuple of tuples ((fieldname/key, display_name)) specifying the fieldname/key and corresponding display name for the table head... | stack_v2_sparse_classes_36k_train_023525 | 11,906 | no_license | [
{
"docstring": "Arguments: fields - A tuple of tuples ((fieldname/key, display_name)) specifying the fieldname/key and corresponding display name for the table header. data - The data to insert to the table formatted as a list of dictionaries. sort_by - A tuple (sort_key, sort_order) specifying which field to s... | 3 | null | Implement the Python class `DataToPdf` described below.
Class description:
Export a list of dictionaries to a table in a PDF file.
Method signatures and docstrings:
- def __init__(self, fields, data, sort_by=None, title=None): Arguments: fields - A tuple of tuples ((fieldname/key, display_name)) specifying the fieldn... | Implement the Python class `DataToPdf` described below.
Class description:
Export a list of dictionaries to a table in a PDF file.
Method signatures and docstrings:
- def __init__(self, fields, data, sort_by=None, title=None): Arguments: fields - A tuple of tuples ((fieldname/key, display_name)) specifying the fieldn... | 8bd516e5cfb8c0a3324a3972ba36bb48e6b1323b | <|skeleton|>
class DataToPdf:
"""Export a list of dictionaries to a table in a PDF file."""
def __init__(self, fields, data, sort_by=None, title=None):
"""Arguments: fields - A tuple of tuples ((fieldname/key, display_name)) specifying the fieldname/key and corresponding display name for the table head... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataToPdf:
"""Export a list of dictionaries to a table in a PDF file."""
def __init__(self, fields, data, sort_by=None, title=None):
"""Arguments: fields - A tuple of tuples ((fieldname/key, display_name)) specifying the fieldname/key and corresponding display name for the table header. data - Th... | the_stack_v2_python_sparse | appointmentscheduler/views/exportbookings.py | prasannadas143/apps | train | 0 |
5c8ff6c1f9d180b00b5a459d6d5ef599d3929317 | [
"intermediate_result = word_tokenize(str_input)\nintermediate_result = BDATextProcessing.__stop_work_removal(intermediate_result)\nintermediate_result = BDATextProcessing.__word_lemmatizing(intermediate_result)\nreturn intermediate_result",
"result = []\nstop_words = set(stopwords.words('english'))\nfor word in s... | <|body_start_0|>
intermediate_result = word_tokenize(str_input)
intermediate_result = BDATextProcessing.__stop_work_removal(intermediate_result)
intermediate_result = BDATextProcessing.__word_lemmatizing(intermediate_result)
return intermediate_result
<|end_body_0|>
<|body_start_1|>
... | BDATextProcessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BDATextProcessing:
def simplify_text(str_input):
"""Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:"""
<|body_0|>
def __stop_work_removal(str_input):
"""Removes NLTK stop words from input stream :param str_i... | stack_v2_sparse_classes_36k_train_023526 | 1,876 | no_license | [
{
"docstring": "Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:",
"name": "simplify_text",
"signature": "def simplify_text(str_input)"
},
{
"docstring": "Removes NLTK stop words from input stream :param str_input: :return: result",
... | 4 | stack_v2_sparse_classes_30k_train_019563 | Implement the Python class `BDATextProcessing` described below.
Class description:
Implement the BDATextProcessing class.
Method signatures and docstrings:
- def simplify_text(str_input): Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:
- def __stop_work_remo... | Implement the Python class `BDATextProcessing` described below.
Class description:
Implement the BDATextProcessing class.
Method signatures and docstrings:
- def simplify_text(str_input): Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:
- def __stop_work_remo... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class BDATextProcessing:
def simplify_text(str_input):
"""Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:"""
<|body_0|>
def __stop_work_removal(str_input):
"""Removes NLTK stop words from input stream :param str_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BDATextProcessing:
def simplify_text(str_input):
"""Main callable cleaning method - ensures that input stream is properly formatted. :param str_input: :return:"""
intermediate_result = word_tokenize(str_input)
intermediate_result = BDATextProcessing.__stop_work_removal(intermediate_res... | the_stack_v2_python_sparse | recording/src/coding_framework/BDATextProcessing.py | eldrad294/ICS5114_Practical_Assignment | train | 0 | |
6bac4b38bf255de1852dc3ded938c17078b46940 | [
"if data is None:\n if n < 1:\n raise ValueError('n must be a positive value')\n else:\n self.n = n\n if p <= 0 or p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\n else:\n self.p = p\nelif type(data) is not list:\n raise TypeError('data must be a li... | <|body_start_0|>
if data is None:
if n < 1:
raise ValueError('n must be a positive value')
else:
self.n = n
if p <= 0 or p >= 1:
raise ValueError('p must be greater than 0 and less than 1')
else:
self... | class that represents Binomial distribution class constructor: def __init__(self, data=None, n=1, p=0.5) instance attributes: n [int]: the number of Bernoilli trials p [float]: the probability of a success instance methods: def pmf(self, k): calculates PMF for given number of successes def cdf(self, k): calculates CDF ... | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""class that represents Binomial distribution class constructor: def __init__(self, data=None, n=1, p=0.5) instance attributes: n [int]: the number of Bernoilli trials p [float]: the probability of a success instance methods: def pmf(self, k): calculates PMF for given number of success... | stack_v2_sparse_classes_36k_train_023527 | 3,624 | no_license | [
{
"docstring": "class constructor parameters: data [list]: data to be used to estimate the distibution n [int]: the number of Bernoilli trials p [float]: the probability of a success Sets the instance attributes n and p If data is not given: Use the given n and p Raise ValueError if n is not positive value Rais... | 3 | stack_v2_sparse_classes_30k_train_009896 | Implement the Python class `Binomial` described below.
Class description:
class that represents Binomial distribution class constructor: def __init__(self, data=None, n=1, p=0.5) instance attributes: n [int]: the number of Bernoilli trials p [float]: the probability of a success instance methods: def pmf(self, k): cal... | Implement the Python class `Binomial` described below.
Class description:
class that represents Binomial distribution class constructor: def __init__(self, data=None, n=1, p=0.5) instance attributes: n [int]: the number of Bernoilli trials p [float]: the probability of a success instance methods: def pmf(self, k): cal... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class Binomial:
"""class that represents Binomial distribution class constructor: def __init__(self, data=None, n=1, p=0.5) instance attributes: n [int]: the number of Bernoilli trials p [float]: the probability of a success instance methods: def pmf(self, k): calculates PMF for given number of success... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binomial:
"""class that represents Binomial distribution class constructor: def __init__(self, data=None, n=1, p=0.5) instance attributes: n [int]: the number of Bernoilli trials p [float]: the probability of a success instance methods: def pmf(self, k): calculates PMF for given number of successes def cdf(se... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
199b9eccde088ca58f142e193f0ae6fedb94c218 | [
"islands = []\nnum = len(positions)\nparents = range(num)\nseen = {}\ndelta = ((-1, 0), (0, -1), (1, 0), (0, 1))\ncount = 0\nfor i, (x, y) in enumerate(positions):\n x, y = positions[i]\n count += 1\n for dx, dy in delta:\n xx = x + dx\n yy = y + dy\n pos = (xx, yy)\n if xx >= 0... | <|body_start_0|>
islands = []
num = len(positions)
parents = range(num)
seen = {}
delta = ((-1, 0), (0, -1), (1, 0), (0, 1))
count = 0
for i, (x, y) in enumerate(positions):
x, y = positions[i]
count += 1
for dx, dy in delta:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands2(self, m, n, positions):
""":type m: int :type n: int :type positions: List[List[int]] :rtype: List[int]"""
<|body_0|>
def find(self, parents, i):
"""Find root parent. For root, it points to itself, parents[i] == i."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_023528 | 3,065 | no_license | [
{
"docstring": ":type m: int :type n: int :type positions: List[List[int]] :rtype: List[int]",
"name": "numIslands2",
"signature": "def numIslands2(self, m, n, positions)"
},
{
"docstring": "Find root parent. For root, it points to itself, parents[i] == i.",
"name": "find",
"signature": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands2(self, m, n, positions): :type m: int :type n: int :type positions: List[List[int]] :rtype: List[int]
- def find(self, parents, i): Find root parent. For root, it ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands2(self, m, n, positions): :type m: int :type n: int :type positions: List[List[int]] :rtype: List[int]
- def find(self, parents, i): Find root parent. For root, it ... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def numIslands2(self, m, n, positions):
""":type m: int :type n: int :type positions: List[List[int]] :rtype: List[int]"""
<|body_0|>
def find(self, parents, i):
"""Find root parent. For root, it points to itself, parents[i] == i."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands2(self, m, n, positions):
""":type m: int :type n: int :type positions: List[List[int]] :rtype: List[int]"""
islands = []
num = len(positions)
parents = range(num)
seen = {}
delta = ((-1, 0), (0, -1), (1, 0), (0, 1))
count = 0
... | the_stack_v2_python_sparse | search/leetcode_Number_Of_Island_II.py | monkeylyf/interviewjam | train | 59 | |
792e8eea26ff93e4711bb625b67cdda56a813db6 | [
"super(AlbertConfig, self).__init__(**kwargs)\nif inner_group_num != 1 or num_hidden_groups != 1:\n raise ValueError(\"We only support 'inner_group_num' and 'num_hidden_groups' as 1.\")",
"config = AlbertConfig(vocab_size=None)\nfor key, value in six.iteritems(json_object):\n config.__dict__[key] = value\nr... | <|body_start_0|>
super(AlbertConfig, self).__init__(**kwargs)
if inner_group_num != 1 or num_hidden_groups != 1:
raise ValueError("We only support 'inner_group_num' and 'num_hidden_groups' as 1.")
<|end_body_0|>
<|body_start_1|>
config = AlbertConfig(vocab_size=None)
for key... | Configuration for `ALBERT`. | AlbertConfig | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbertConfig:
"""Configuration for `ALBERT`."""
def __init__(self, num_hidden_groups=1, inner_group_num=1, **kwargs):
"""Constructs AlbertConfig. Args: num_hidden_groups: Number of group for the hidden layers, parameters in the same group are shared. Note that this value and also the... | stack_v2_sparse_classes_36k_train_023529 | 2,261 | permissive | [
{
"docstring": "Constructs AlbertConfig. Args: num_hidden_groups: Number of group for the hidden layers, parameters in the same group are shared. Note that this value and also the following 'inner_group_num' has to be 1 for now, because all released ALBERT models set them to 1. We may support arbitary valid val... | 2 | stack_v2_sparse_classes_30k_train_003215 | Implement the Python class `AlbertConfig` described below.
Class description:
Configuration for `ALBERT`.
Method signatures and docstrings:
- def __init__(self, num_hidden_groups=1, inner_group_num=1, **kwargs): Constructs AlbertConfig. Args: num_hidden_groups: Number of group for the hidden layers, parameters in the... | Implement the Python class `AlbertConfig` described below.
Class description:
Configuration for `ALBERT`.
Method signatures and docstrings:
- def __init__(self, num_hidden_groups=1, inner_group_num=1, **kwargs): Constructs AlbertConfig. Args: num_hidden_groups: Number of group for the hidden layers, parameters in the... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class AlbertConfig:
"""Configuration for `ALBERT`."""
def __init__(self, num_hidden_groups=1, inner_group_num=1, **kwargs):
"""Constructs AlbertConfig. Args: num_hidden_groups: Number of group for the hidden layers, parameters in the same group are shared. Note that this value and also the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlbertConfig:
"""Configuration for `ALBERT`."""
def __init__(self, num_hidden_groups=1, inner_group_num=1, **kwargs):
"""Constructs AlbertConfig. Args: num_hidden_groups: Number of group for the hidden layers, parameters in the same group are shared. Note that this value and also the following 'i... | the_stack_v2_python_sparse | models/official/nlp/albert/configs.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
88e40eb0db27fafa315cb79fae3c8ac392b0693e | [
"if len(password) < self.MIN_PASSWORD_LENGTH:\n raise exceptions.ValidationError(self.token, 'Password too short')\nif rank > 1 and rank > self.connection.level():\n raise exceptions.Unauthorized(self.token, 'Unauthorized to create user with rank %s' % rank)\npassword = hashlib.sha256(password.encode('utf-8')... | <|body_start_0|>
if len(password) < self.MIN_PASSWORD_LENGTH:
raise exceptions.ValidationError(self.token, 'Password too short')
if rank > 1 and rank > self.connection.level():
raise exceptions.Unauthorized(self.token, 'Unauthorized to create user with rank %s' % rank)
pa... | User class resource | UserResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserResource:
"""User class resource"""
def create(self, name, password, email=None, rank=1):
"""Create a new user"""
<|body_0|>
def login(self, name, password):
"""Login a new user in our database"""
<|body_1|>
def login_or_create(self, name, passwo... | stack_v2_sparse_classes_36k_train_023530 | 3,748 | permissive | [
{
"docstring": "Create a new user",
"name": "create",
"signature": "def create(self, name, password, email=None, rank=1)"
},
{
"docstring": "Login a new user in our database",
"name": "login",
"signature": "def login(self, name, password)"
},
{
"docstring": "Login or create a use... | 4 | stack_v2_sparse_classes_30k_train_013078 | Implement the Python class `UserResource` described below.
Class description:
User class resource
Method signatures and docstrings:
- def create(self, name, password, email=None, rank=1): Create a new user
- def login(self, name, password): Login a new user in our database
- def login_or_create(self, name, password):... | Implement the Python class `UserResource` described below.
Class description:
User class resource
Method signatures and docstrings:
- def create(self, name, password, email=None, rank=1): Create a new user
- def login(self, name, password): Login a new user in our database
- def login_or_create(self, name, password):... | cf20b363ed3d7bcb75101b17870e876a857ecd66 | <|skeleton|>
class UserResource:
"""User class resource"""
def create(self, name, password, email=None, rank=1):
"""Create a new user"""
<|body_0|>
def login(self, name, password):
"""Login a new user in our database"""
<|body_1|>
def login_or_create(self, name, passwo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserResource:
"""User class resource"""
def create(self, name, password, email=None, rank=1):
"""Create a new user"""
if len(password) < self.MIN_PASSWORD_LENGTH:
raise exceptions.ValidationError(self.token, 'Password too short')
if rank > 1 and rank > self.connection.... | the_stack_v2_python_sparse | smserver/resources/user_resource.py | Moutix/stepmania-server | train | 4 |
f9170b9912c228cfa84c28c689686b5386e0da78 | [
"if User.objects.filter(username__iexact=self.cleaned_data['username']):\n raise forms.ValidationError('A user with that username already exists.')\nreturn self.cleaned_data['username'].lower()",
"if self.errors:\n return\nuser = super(RegistrationForm, self).save(commit=False)\nuser.email = user.email.lowe... | <|body_start_0|>
if User.objects.filter(username__iexact=self.cleaned_data['username']):
raise forms.ValidationError('A user with that username already exists.')
return self.cleaned_data['username'].lower()
<|end_body_0|>
<|body_start_1|>
if self.errors:
return
u... | A form for creating new users. Includes all the required fields, plus a repeated password. | RegistrationForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_username(self):
"""Record the original username in case it is needed"""
<|body_0|>
def save(self):
"""Process the registration form"""
... | stack_v2_sparse_classes_36k_train_023531 | 26,163 | permissive | [
{
"docstring": "Record the original username in case it is needed",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Process the registration form",
"name": "save",
"signature": "def save(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013846 | Implement the Python class `RegistrationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_username(self): Record the original username in case it is needed
- def save(self): Process the reg... | Implement the Python class `RegistrationForm` described below.
Class description:
A form for creating new users. Includes all the required fields, plus a repeated password.
Method signatures and docstrings:
- def clean_username(self): Record the original username in case it is needed
- def save(self): Process the reg... | e7c8ed0b07a4c9a1b4007f6089f59aafa6a3ac57 | <|skeleton|>
class RegistrationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_username(self):
"""Record the original username in case it is needed"""
<|body_0|>
def save(self):
"""Process the registration form"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""A form for creating new users. Includes all the required fields, plus a repeated password."""
def clean_username(self):
"""Record the original username in case it is needed"""
if User.objects.filter(username__iexact=self.cleaned_data['username']):
raise fo... | the_stack_v2_python_sparse | physionet-django/user/forms.py | tompollard/physionet-build | train | 0 |
57d7c34129c22dac63ef653cc4c2fc82436b2022 | [
"self.test_case = test_case\nself.variation = variation\nself.LKFFBfilepath = LKFFBfilepath\nself.LSFfilepath = LSFfilepath\nself.AKF_savetopath = AKF_savetopath\nself.dataobject = le(self.test_case, self.variation, GPRP_load='No', LKFFB_load='Yes', LKFFB_path=self.LKFFBfilepath, AKF_load='No', LSF_load='Yes', LSF_... | <|body_start_0|>
self.test_case = test_case
self.variation = variation
self.LKFFBfilepath = LKFFBfilepath
self.LSFfilepath = LSFfilepath
self.AKF_savetopath = AKF_savetopath
self.dataobject = le(self.test_case, self.variation, GPRP_load='No', LKFFB_load='Yes', LKFFB_path=... | AKF_Optimisation Initiate a Bayes Risk Map instance for AKF. For each instance, use pre-generated random samples for (sigma, R)and true noise realisations for equivalent (test_case, variation) in LKKFB. AR weights calculated via LSF to define the dynamical model in AKF. Attributes: ---------- test_case (`int`): Global ... | AKF_Optimisation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AKF_Optimisation:
"""AKF_Optimisation Initiate a Bayes Risk Map instance for AKF. For each instance, use pre-generated random samples for (sigma, R)and true noise realisations for equivalent (test_case, variation) in LKKFB. AR weights calculated via LSF to define the dynamical model in AKF. Attri... | stack_v2_sparse_classes_36k_train_023532 | 5,995 | no_license | [
{
"docstring": "Initilizes a AKF_Optimisation class instance",
"name": "__init__",
"signature": "def __init__(self, test_case, variation, LKFFBfilepath, LSFfilepath, AKF_savetopath, skip_msmts=1, choose_step_fwds=1)"
},
{
"docstring": "Save .npz file for a Bayes Risk map for random (sigma, R) fo... | 2 | null | Implement the Python class `AKF_Optimisation` described below.
Class description:
AKF_Optimisation Initiate a Bayes Risk Map instance for AKF. For each instance, use pre-generated random samples for (sigma, R)and true noise realisations for equivalent (test_case, variation) in LKKFB. AR weights calculated via LSF to d... | Implement the Python class `AKF_Optimisation` described below.
Class description:
AKF_Optimisation Initiate a Bayes Risk Map instance for AKF. For each instance, use pre-generated random samples for (sigma, R)and true noise realisations for equivalent (test_case, variation) in LKKFB. AR weights calculated via LSF to d... | 7a658a87b754bff436352e0e821187338371c582 | <|skeleton|>
class AKF_Optimisation:
"""AKF_Optimisation Initiate a Bayes Risk Map instance for AKF. For each instance, use pre-generated random samples for (sigma, R)and true noise realisations for equivalent (test_case, variation) in LKKFB. AR weights calculated via LSF to define the dynamical model in AKF. Attri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AKF_Optimisation:
"""AKF_Optimisation Initiate a Bayes Risk Map instance for AKF. For each instance, use pre-generated random samples for (sigma, R)and true noise realisations for equivalent (test_case, variation) in LKKFB. AR weights calculated via LSF to define the dynamical model in AKF. Attributes: ------... | the_stack_v2_python_sparse | akf/akf_risk_analysis.py | riddhisw/predictiveest | train | 1 |
d0a54b39fed77226579e8a12690d2c2a161cdf6d | [
"sql = '\\n create table if not exists kw (\\n id int(32) not null auto_increment,\\n keyword varchar(64),\\n counter int default 1,\\n mark int default 0,\\n primary key (id),\\n unique index kw_index... | <|body_start_0|>
sql = '\n create table if not exists kw (\n id int(32) not null auto_increment,\n keyword varchar(64),\n counter int default 1,\n mark int default 0,\n primary key (id),\n unique i... | create kw tables | CommentJiebaDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentJiebaDB:
"""create kw tables"""
def create_kw(self):
"""create kw table 来自结巴"""
<|body_0|>
def create_kw_search(self):
"""create kw table"""
<|body_1|>
def create_kw_dict(self):
"""词库:存储无效词type=0,如:标点符号:,、等 存储组合词type=1,将有特殊意义的词作为一个关键词整... | stack_v2_sparse_classes_36k_train_023533 | 5,771 | no_license | [
{
"docstring": "create kw table 来自结巴",
"name": "create_kw",
"signature": "def create_kw(self)"
},
{
"docstring": "create kw table",
"name": "create_kw_search",
"signature": "def create_kw_search(self)"
},
{
"docstring": "词库:存储无效词type=0,如:标点符号:,、等 存储组合词type=1,将有特殊意义的词作为一个关键词整体",
... | 5 | stack_v2_sparse_classes_30k_train_020874 | Implement the Python class `CommentJiebaDB` described below.
Class description:
create kw tables
Method signatures and docstrings:
- def create_kw(self): create kw table 来自结巴
- def create_kw_search(self): create kw table
- def create_kw_dict(self): 词库:存储无效词type=0,如:标点符号:,、等 存储组合词type=1,将有特殊意义的词作为一个关键词整体
- def insertM... | Implement the Python class `CommentJiebaDB` described below.
Class description:
create kw tables
Method signatures and docstrings:
- def create_kw(self): create kw table 来自结巴
- def create_kw_search(self): create kw table
- def create_kw_dict(self): 词库:存储无效词type=0,如:标点符号:,、等 存储组合词type=1,将有特殊意义的词作为一个关键词整体
- def insertM... | 0288830d0b5d48e6037ae852ec69aa94dcfa9cf3 | <|skeleton|>
class CommentJiebaDB:
"""create kw tables"""
def create_kw(self):
"""create kw table 来自结巴"""
<|body_0|>
def create_kw_search(self):
"""create kw table"""
<|body_1|>
def create_kw_dict(self):
"""词库:存储无效词type=0,如:标点符号:,、等 存储组合词type=1,将有特殊意义的词作为一个关键词整... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentJiebaDB:
"""create kw tables"""
def create_kw(self):
"""create kw table 来自结巴"""
sql = '\n create table if not exists kw (\n id int(32) not null auto_increment,\n keyword varchar(64),\n counter int default 1,\n ... | the_stack_v2_python_sparse | jieba/kwtb.py | jeawy/comment | train | 0 |
d58c3d0ba58abc3161954ae2dd6df303f0f3b343 | [
"for i, matr in enumerate(self.transition_matrices):\n print(matrix_name + '_' + str(i), ':', file=file)\n matr_print(matr, file=file)\nprint('Average intensity:', self.avg_intensity, file=file)\nprint('Variation coefficient:', self.c_var, file=file)\nprint('Correlation coefficient:', self.c_cor, file=file)\n... | <|body_start_0|>
for i, matr in enumerate(self.transition_matrices):
print(matrix_name + '_' + str(i), ':', file=file)
matr_print(matr, file=file)
print('Average intensity:', self.avg_intensity, file=file)
print('Variation coefficient:', self.c_var, file=file)
pri... | MAP stream class. Contains two transition matrices, stream intensity, sum of transition matrices, variation coefficient and correlation coefficient. | MAPStream | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MAPStream:
"""MAP stream class. Contains two transition matrices, stream intensity, sum of transition matrices, variation coefficient and correlation coefficient."""
def print_characteristics(self, matrix_name, file=sys.stdout):
"""Prints characteristics of MAP stream: Average intens... | stack_v2_sparse_classes_36k_train_023534 | 15,627 | no_license | [
{
"docstring": "Prints characteristics of MAP stream: Average intensity Variation coefficient Correlation coefficient :return: None",
"name": "print_characteristics",
"signature": "def print_characteristics(self, matrix_name, file=sys.stdout)"
},
{
"docstring": "Constructor for MAPStream. :param... | 2 | stack_v2_sparse_classes_30k_val_000544 | Implement the Python class `MAPStream` described below.
Class description:
MAP stream class. Contains two transition matrices, stream intensity, sum of transition matrices, variation coefficient and correlation coefficient.
Method signatures and docstrings:
- def print_characteristics(self, matrix_name, file=sys.stdo... | Implement the Python class `MAPStream` described below.
Class description:
MAP stream class. Contains two transition matrices, stream intensity, sum of transition matrices, variation coefficient and correlation coefficient.
Method signatures and docstrings:
- def print_characteristics(self, matrix_name, file=sys.stdo... | 6173e0d279893f0da4f8ad09b824cd5897c4e5e7 | <|skeleton|>
class MAPStream:
"""MAP stream class. Contains two transition matrices, stream intensity, sum of transition matrices, variation coefficient and correlation coefficient."""
def print_characteristics(self, matrix_name, file=sys.stdout):
"""Prints characteristics of MAP stream: Average intens... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MAPStream:
"""MAP stream class. Contains two transition matrices, stream intensity, sum of transition matrices, variation coefficient and correlation coefficient."""
def print_characteristics(self, matrix_name, file=sys.stdout):
"""Prints characteristics of MAP stream: Average intensity Variation... | the_stack_v2_python_sparse | streams.py | pishchynski/magister_work | train | 0 |
08dd529b8bc7aaa349cbc42b693140ade43372f4 | [
"regexp = re.compile('image')\nif regexp.search(value.content_type) is None:\n raise serializers.ValidationError('Unsupported file type')\nreturn value",
"try:\n with transaction.atomic():\n attachment = Image.objects.create(**data)\n self._generate_thumbs(attachment)\n return attachmen... | <|body_start_0|>
regexp = re.compile('image')
if regexp.search(value.content_type) is None:
raise serializers.ValidationError('Unsupported file type')
return value
<|end_body_0|>
<|body_start_1|>
try:
with transaction.atomic():
attachment = Image.... | Serializer for Image. | ImageSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageSerializer:
"""Serializer for Image."""
def validate_data(self, value):
"""Validate data field."""
<|body_0|>
def create(self, data):
"""Create new attachment and creating thumb images."""
<|body_1|>
def _generate_thumbs(self, attachment):
... | stack_v2_sparse_classes_36k_train_023535 | 1,927 | no_license | [
{
"docstring": "Validate data field.",
"name": "validate_data",
"signature": "def validate_data(self, value)"
},
{
"docstring": "Create new attachment and creating thumb images.",
"name": "create",
"signature": "def create(self, data)"
},
{
"docstring": "Generate thumbs for the a... | 3 | null | Implement the Python class `ImageSerializer` described below.
Class description:
Serializer for Image.
Method signatures and docstrings:
- def validate_data(self, value): Validate data field.
- def create(self, data): Create new attachment and creating thumb images.
- def _generate_thumbs(self, attachment): Generate ... | Implement the Python class `ImageSerializer` described below.
Class description:
Serializer for Image.
Method signatures and docstrings:
- def validate_data(self, value): Validate data field.
- def create(self, data): Create new attachment and creating thumb images.
- def _generate_thumbs(self, attachment): Generate ... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class ImageSerializer:
"""Serializer for Image."""
def validate_data(self, value):
"""Validate data field."""
<|body_0|>
def create(self, data):
"""Create new attachment and creating thumb images."""
<|body_1|>
def _generate_thumbs(self, attachment):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageSerializer:
"""Serializer for Image."""
def validate_data(self, value):
"""Validate data field."""
regexp = re.compile('image')
if regexp.search(value.content_type) is None:
raise serializers.ValidationError('Unsupported file type')
return value
def c... | the_stack_v2_python_sparse | app/attachments/serializers.py | vsokoltsov/Interview360Server | train | 2 |
99368df4560221cdbc93856c68f303cb88bccb36 | [
"self.main_window = QtGui.QWidget()\nself.gui = Gui()\nself.gui.setupUi(self.main_window)\nself.gui.button_1.clicked.connect(lambda: self.make_move(1, self.gui.button_1))\nself.gui.button_2.clicked.connect(lambda: self.make_move(2, self.gui.button_2))\nself.gui.button_3.clicked.connect(lambda: self.make_move(3, sel... | <|body_start_0|>
self.main_window = QtGui.QWidget()
self.gui = Gui()
self.gui.setupUi(self.main_window)
self.gui.button_1.clicked.connect(lambda: self.make_move(1, self.gui.button_1))
self.gui.button_2.clicked.connect(lambda: self.make_move(2, self.gui.button_2))
self.gui... | Application class to create and control the gui. This version implements the Tic Tac Toe game using a grid of buttons. | App | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Application class to create and control the gui. This version implements the Tic Tac Toe game using a grid of buttons."""
def __init__(self):
"""Initialize the gui."""
<|body_0|>
def make_move(self, square, button):
"""Called when one of the buttons is cl... | stack_v2_sparse_classes_36k_train_023536 | 4,030 | no_license | [
{
"docstring": "Initialize the gui.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Called when one of the buttons is clicked. :param int square: Integer value indicating a square on the board. :param QtGui.QPushButton button: The button that was clicked. :return: None... | 2 | stack_v2_sparse_classes_30k_train_011620 | Implement the Python class `App` described below.
Class description:
Application class to create and control the gui. This version implements the Tic Tac Toe game using a grid of buttons.
Method signatures and docstrings:
- def __init__(self): Initialize the gui.
- def make_move(self, square, button): Called when one... | Implement the Python class `App` described below.
Class description:
Application class to create and control the gui. This version implements the Tic Tac Toe game using a grid of buttons.
Method signatures and docstrings:
- def __init__(self): Initialize the gui.
- def make_move(self, square, button): Called when one... | 0e3470085083012f893adb22aa46d46039016965 | <|skeleton|>
class App:
"""Application class to create and control the gui. This version implements the Tic Tac Toe game using a grid of buttons."""
def __init__(self):
"""Initialize the gui."""
<|body_0|>
def make_move(self, square, button):
"""Called when one of the buttons is cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class App:
"""Application class to create and control the gui. This version implements the Tic Tac Toe game using a grid of buttons."""
def __init__(self):
"""Initialize the gui."""
self.main_window = QtGui.QWidget()
self.gui = Gui()
self.gui.setupUi(self.main_window)
se... | the_stack_v2_python_sparse | CS_210 (Introduction to Programming)/TicTacToe/ButtonsApp.py | JacobOrner/USAFA | train | 0 |
c57ff9c6ae888e8c5f8df102f0f835ad4df175da | [
"self.is_horizontal = is_horizontal\nself.edge_colour = edge_colour\nself.bar_colour = bar_colour",
"plt.title(title)\nif self.is_horizontal:\n plt.xlabel(labels[1])\n plt.ylabel(labels[0])\n plt.barh(data[0], data[1], color=f'{self.bar_colour}', edgecolor=f'{self.edge_colour}')\nelse:\n plt.xlabel(la... | <|body_start_0|>
self.is_horizontal = is_horizontal
self.edge_colour = edge_colour
self.bar_colour = bar_colour
<|end_body_0|>
<|body_start_1|>
plt.title(title)
if self.is_horizontal:
plt.xlabel(labels[1])
plt.ylabel(labels[0])
plt.barh(data[0... | Represents an object that generates a bar graph when it is called and executed as a function | BarGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarGraph:
"""Represents an object that generates a bar graph when it is called and executed as a function"""
def __init__(self, edge_colour, bar_colour, is_horizontal=False):
"""Initializes a BarGraph object :param edge_colour: colour of the edge of the bar as a String :param bar_col... | stack_v2_sparse_classes_36k_train_023537 | 5,075 | no_license | [
{
"docstring": "Initializes a BarGraph object :param edge_colour: colour of the edge of the bar as a String :param bar_colour: colour of the bar in a bar graph as a String :param is_horizontal: tells if a graph is a horizontal graph as a Bool",
"name": "__init__",
"signature": "def __init__(self, edge_c... | 2 | stack_v2_sparse_classes_30k_train_015505 | Implement the Python class `BarGraph` described below.
Class description:
Represents an object that generates a bar graph when it is called and executed as a function
Method signatures and docstrings:
- def __init__(self, edge_colour, bar_colour, is_horizontal=False): Initializes a BarGraph object :param edge_colour:... | Implement the Python class `BarGraph` described below.
Class description:
Represents an object that generates a bar graph when it is called and executed as a function
Method signatures and docstrings:
- def __init__(self, edge_colour, bar_colour, is_horizontal=False): Initializes a BarGraph object :param edge_colour:... | e4953c9a4f574a6d92cbd0815e5150dd1523c31d | <|skeleton|>
class BarGraph:
"""Represents an object that generates a bar graph when it is called and executed as a function"""
def __init__(self, edge_colour, bar_colour, is_horizontal=False):
"""Initializes a BarGraph object :param edge_colour: colour of the edge of the bar as a String :param bar_col... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BarGraph:
"""Represents an object that generates a bar graph when it is called and executed as a function"""
def __init__(self, edge_colour, bar_colour, is_horizontal=False):
"""Initializes a BarGraph object :param edge_colour: colour of the edge of the bar as a String :param bar_colour: colour o... | the_stack_v2_python_sparse | Labs/Lab9/observers.py | kchung90/Python-Labs-Assignments | train | 0 |
358854b669c0f977b5d61976991de31126240edf | [
"inter.MNADevice.__init__(self, nodes, 0, **parameters)\nself.subckt = subckt\nself.parameters = parameters",
"self.port2node = {}\nfor p, n in zip(self.netlist.subckts[self.subckt].ports, self.nodes):\n self.port2node[p] = n"
] | <|body_start_0|>
inter.MNADevice.__init__(self, nodes, 0, **parameters)
self.subckt = subckt
self.parameters = parameters
<|end_body_0|>
<|body_start_1|>
self.port2node = {}
for p, n in zip(self.netlist.subckts[self.subckt].ports, self.nodes):
self.port2node[p] = n
<... | Subckt instance device (SPICE X) | X | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class X:
"""Subckt instance device (SPICE X)"""
def __init__(self, nodes, subckt, **parameters):
"""Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New s... | stack_v2_sparse_classes_36k_train_023538 | 3,583 | permissive | [
{
"docstring": "Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New subckt instance device",
"name": "__init__",
"signature": "def __init__(self, nodes, subckt, **para... | 2 | stack_v2_sparse_classes_30k_train_001053 | Implement the Python class `X` described below.
Class description:
Subckt instance device (SPICE X)
Method signatures and docstrings:
- def __init__(self, nodes, subckt, **parameters): Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary... | Implement the Python class `X` described below.
Class description:
Subckt instance device (SPICE X)
Method signatures and docstrings:
- def __init__(self, nodes, subckt, **parameters): Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary... | 0097735f71b19a4d3f95696d3af0a3df4a620e25 | <|skeleton|>
class X:
"""Subckt instance device (SPICE X)"""
def __init__(self, nodes, subckt, **parameters):
"""Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class X:
"""Subckt instance device (SPICE X)"""
def __init__(self, nodes, subckt, **parameters):
"""Creates a new subckt instance device :param nodes: Device extrnal node names :param subckt: Subckt name :param parameters: Dictionary of parameters for the subcircuit instance :return: New subckt instanc... | the_stack_v2_python_sparse | subcircuit/devices/x.py | joehood/SubCircuit | train | 7 |
f391c2ce27d7a556b11595bf0cc0b3cb3543cf7b | [
"if isinstance(labelOrFluxInstance, fluxModule.Flux):\n if temperature is None:\n raise RuntimeError('The flux temperature is required as the second argument.')\n label = labelOrFluxInstance.label\n data = labelOrFluxInstance.data.copy()\nelif isinstance(labelOrFluxInstance, Flux):\n label = labe... | <|body_start_0|>
if isinstance(labelOrFluxInstance, fluxModule.Flux):
if temperature is None:
raise RuntimeError('The flux temperature is required as the second argument.')
label = labelOrFluxInstance.label
data = labelOrFluxInstance.data.copy()
elif i... | The multi-group flux. | Flux | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flux:
"""The multi-group flux."""
def __init__(self, labelOrFluxInstance, temperature=None, data=None):
"""The constructor for the Flux class."""
<|body_0|>
def process(self, groupBoundaries):
"""Multi-group the flux and return as a ProcessedFlux instance."""
... | stack_v2_sparse_classes_36k_train_023539 | 18,060 | permissive | [
{
"docstring": "The constructor for the Flux class.",
"name": "__init__",
"signature": "def __init__(self, labelOrFluxInstance, temperature=None, data=None)"
},
{
"docstring": "Multi-group the flux and return as a ProcessedFlux instance.",
"name": "process",
"signature": "def process(sel... | 2 | stack_v2_sparse_classes_30k_train_007171 | Implement the Python class `Flux` described below.
Class description:
The multi-group flux.
Method signatures and docstrings:
- def __init__(self, labelOrFluxInstance, temperature=None, data=None): The constructor for the Flux class.
- def process(self, groupBoundaries): Multi-group the flux and return as a Processed... | Implement the Python class `Flux` described below.
Class description:
The multi-group flux.
Method signatures and docstrings:
- def __init__(self, labelOrFluxInstance, temperature=None, data=None): The constructor for the Flux class.
- def process(self, groupBoundaries): Multi-group the flux and return as a Processed... | 6ba80855ae47cb32c37f635d065b228fadb03412 | <|skeleton|>
class Flux:
"""The multi-group flux."""
def __init__(self, labelOrFluxInstance, temperature=None, data=None):
"""The constructor for the Flux class."""
<|body_0|>
def process(self, groupBoundaries):
"""Multi-group the flux and return as a ProcessedFlux instance."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Flux:
"""The multi-group flux."""
def __init__(self, labelOrFluxInstance, temperature=None, data=None):
"""The constructor for the Flux class."""
if isinstance(labelOrFluxInstance, fluxModule.Flux):
if temperature is None:
raise RuntimeError('The flux temperatu... | the_stack_v2_python_sparse | fudge/processing/deterministic/particles.py | LLNL/fudge | train | 21 |
565cee4e7f14fdf87357fdf17f7834edca161c07 | [
"super(AdaptativeAttention, self).__init__()\nself.linear_v = nn.Linear(decoder_dim, attention_dim)\nself.linear_h = nn.Linear(decoder_dim, attention_dim)\nself.linear_s = nn.Linear(decoder_dim, attention_dim)\nself.linear_att_v = nn.Linear(attention_dim, 1)\nself.linear_att_s = nn.Linear(attention_dim, 1)\nself.ta... | <|body_start_0|>
super(AdaptativeAttention, self).__init__()
self.linear_v = nn.Linear(decoder_dim, attention_dim)
self.linear_h = nn.Linear(decoder_dim, attention_dim)
self.linear_s = nn.Linear(decoder_dim, attention_dim)
self.linear_att_v = nn.Linear(attention_dim, 1)
s... | Attention Network. | AdaptativeAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptativeAttention:
"""Attention Network."""
def __init__(self, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k_train_023540 | 17,832 | no_license | [
{
"docstring": ":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network",
"name": "__init__",
"signature": "def __init__(self, decoder_dim, attention_dim)"
},
{
"docstring": "Forward propagation. :param enco... | 2 | stack_v2_sparse_classes_30k_train_009529 | Implement the Python class `AdaptativeAttention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the att... | Implement the Python class `AdaptativeAttention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the att... | 426d97b5d3688f6c52c51ef6e33872554d55751a | <|skeleton|>
class AdaptativeAttention:
"""Attention Network."""
def __init__(self, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdaptativeAttention:
"""Attention Network."""
def __init__(self, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
super(AdaptativeAttention, self).__init__()
... | the_stack_v2_python_sparse | src/models/continuous_encoder_decoder_models/encoder_decoder_variants/attention_adaptative_drop.py | RitaRamo/remote-sensing-images-caption | train | 3 |
3bb8a88a44f85f67263e33c347de5260be8c87ca | [
"super(EraModifier, self).__init__(modifier_dict)\nself.modifier_dict = modifier_dict\nself.default = default\nself.eras: List[str] = list(self.modifier_dict.keys())",
"if era in self.eras:\n return self.modifier_dict[era]\nelif self.default is not None:\n return self.default\nelse:\n raise EraConfigurat... | <|body_start_0|>
super(EraModifier, self).__init__(modifier_dict)
self.modifier_dict = modifier_dict
self.default = default
self.eras: List[str] = list(self.modifier_dict.keys())
<|end_body_0|>
<|body_start_1|>
if era in self.eras:
return self.modifier_dict[era]
... | EraModifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EraModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Era Modifier is a Modifier, that modifies the configuration based on the given era Args: modifier_dict : A dict containing the information, how a parameter should be... | stack_v2_sparse_classes_36k_train_023541 | 3,538 | permissive | [
{
"docstring": "A Era Modifier is a Modifier, that modifies the configuration based on the given era Args: modifier_dict : A dict containing the information, how a parameter should be modified based on the sample. default: If set, the default is used for all sample not specified in the modifier dict. Defaults t... | 2 | stack_v2_sparse_classes_30k_train_002644 | Implement the Python class `EraModifier` described below.
Class description:
Implement the EraModifier class.
Method signatures and docstrings:
- def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None): A Era Modifier is a Modifier, that modifies the configuration based... | Implement the Python class `EraModifier` described below.
Class description:
Implement the EraModifier class.
Method signatures and docstrings:
- def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None): A Era Modifier is a Modifier, that modifies the configuration based... | 229fac41ec8fb34fc4ae9584b1ea428ef95b914e | <|skeleton|>
class EraModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Era Modifier is a Modifier, that modifies the configuration based on the given era Args: modifier_dict : A dict containing the information, how a parameter should be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EraModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Era Modifier is a Modifier, that modifies the configuration based on the given era Args: modifier_dict : A dict containing the information, how a parameter should be modified base... | the_stack_v2_python_sparse | code_generation/modifiers.py | KIT-CMS/CROWN | train | 6 | |
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"super().__init__(num_locations, coverages_per_location)\nself.num_layers = num_layers\nself.dtypes = OrderedDict([('output', 'i'), ('agg_id', 'i'), ('layer_id', 'i')])\nself.data_length = num_locations * coverages_per_location * num_layers\nself.file_name = os.path.join(directory, 'fm_xref.bin')",
"layers = rang... | <|body_start_0|>
super().__init__(num_locations, coverages_per_location)
self.num_layers = num_layers
self.dtypes = OrderedDict([('output', 'i'), ('agg_id', 'i'), ('layer_id', 'i')])
self.data_length = num_locations * coverages_per_location * num_layers
self.file_name = os.path.j... | Generate data for Financial Model Cross Reference dummy model Oasis file. This file shows the mapping between the financial model output ID, and aggregate and layer IDs. Attributes: generate_data: Generate Financial Model Cross Reference dummy model Oasis file data. | FMXrefFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FMXrefFile:
"""Generate data for Financial Model Cross Reference dummy model Oasis file. This file shows the mapping between the financial model output ID, and aggregate and layer IDs. Attributes: generate_data: Generate Financial Model Cross Reference dummy model Oasis file data."""
def __i... | stack_v2_sparse_classes_36k_train_023542 | 39,722 | permissive | [
{
"docstring": "Initialise Financial Model Cross Reference file class. Args: num_locations (int): number of locations. coverages_per_location (int): number of coverage types per location. num_layers (int): number of layers. directory (str): dummy model file destination.",
"name": "__init__",
"signature"... | 2 | null | Implement the Python class `FMXrefFile` described below.
Class description:
Generate data for Financial Model Cross Reference dummy model Oasis file. This file shows the mapping between the financial model output ID, and aggregate and layer IDs. Attributes: generate_data: Generate Financial Model Cross Reference dummy... | Implement the Python class `FMXrefFile` described below.
Class description:
Generate data for Financial Model Cross Reference dummy model Oasis file. This file shows the mapping between the financial model output ID, and aggregate and layer IDs. Attributes: generate_data: Generate Financial Model Cross Reference dummy... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class FMXrefFile:
"""Generate data for Financial Model Cross Reference dummy model Oasis file. This file shows the mapping between the financial model output ID, and aggregate and layer IDs. Attributes: generate_data: Generate Financial Model Cross Reference dummy model Oasis file data."""
def __i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FMXrefFile:
"""Generate data for Financial Model Cross Reference dummy model Oasis file. This file shows the mapping between the financial model output ID, and aggregate and layer IDs. Attributes: generate_data: Generate Financial Model Cross Reference dummy model Oasis file data."""
def __init__(self, n... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
cabc1ded6accc5b6360ff2b10def6e2d30ac7e4d | [
"self.thresh = kwargs.get('thresh')\nsuper(PValuePixelSelector, self).__init__(*args, **kwargs)\nself.cache = {}\nself.done = []",
"if limit.name in self.cache:\n delta, delta2, neg = self.cache[limit.name]\n expectation = getattr(self.calMomentManager, limit.name)\nelse:\n val = getattr(self.momentManag... | <|body_start_0|>
self.thresh = kwargs.get('thresh')
super(PValuePixelSelector, self).__init__(*args, **kwargs)
self.cache = {}
self.done = []
<|end_body_0|>
<|body_start_1|>
if limit.name in self.cache:
delta, delta2, neg = self.cache[limit.name]
expectat... | A P-Value based pixel selector. This serves the same purpose as the PixelSelector, but computes a p-value for each pixel. The MomentLimits are used as 1-sigma thresholds, and the resulting sum of log(p) values is computed. Pixels meeting a specified threshold are kept. | PValuePixelSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PValuePixelSelector:
"""A P-Value based pixel selector. This serves the same purpose as the PixelSelector, but computes a p-value for each pixel. The MomentLimits are used as 1-sigma thresholds, and the resulting sum of log(p) values is computed. Pixels meeting a specified threshold are kept."""
... | stack_v2_sparse_classes_36k_train_023543 | 11,918 | no_license | [
{
"docstring": "Construct.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Test the significance of pixels for this MomentLimit. @param limit The MomentLimit to test.",
"name": "_test",
"signature": "def _test(self, limit)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_014157 | Implement the Python class `PValuePixelSelector` described below.
Class description:
A P-Value based pixel selector. This serves the same purpose as the PixelSelector, but computes a p-value for each pixel. The MomentLimits are used as 1-sigma thresholds, and the resulting sum of log(p) values is computed. Pixels meet... | Implement the Python class `PValuePixelSelector` described below.
Class description:
A P-Value based pixel selector. This serves the same purpose as the PixelSelector, but computes a p-value for each pixel. The MomentLimits are used as 1-sigma thresholds, and the resulting sum of log(p) values is computed. Pixels meet... | f826f98369125b9aa0aa6f7228913a503cea80a4 | <|skeleton|>
class PValuePixelSelector:
"""A P-Value based pixel selector. This serves the same purpose as the PixelSelector, but computes a p-value for each pixel. The MomentLimits are used as 1-sigma thresholds, and the resulting sum of log(p) values is computed. Pixels meeting a specified threshold are kept."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PValuePixelSelector:
"""A P-Value based pixel selector. This serves the same purpose as the PixelSelector, but computes a p-value for each pixel. The MomentLimits are used as 1-sigma thresholds, and the resulting sum of log(p) values is computed. Pixels meeting a specified threshold are kept."""
def __in... | the_stack_v2_python_sparse | python/lsst/meas/artifact/momentCalculator.py | lsst-dm/meas_artifact | train | 3 |
66c5ded168baa6f9480dc0d2a1cf8ea09b00b26e | [
"super(Transformer, self).__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"encoder_output = self.encoder(inputs, training, encoder_mas... | <|body_start_0|>
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_... | Transformer class | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""Transformer class"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Class constructor Args: N (int): the number of blocks in the encoder. dm (int): the dimensionality of the model. h (int): the number ... | stack_v2_sparse_classes_36k_train_023544 | 2,553 | no_license | [
{
"docstring": "Class constructor Args: N (int): the number of blocks in the encoder. dm (int): the dimensionality of the model. h (int): the number of heads. hidden (int): the number of hidden units in the fully connected layer. input_vocab (int): the size of the input vocabulary. target_vocab (int): the size ... | 2 | stack_v2_sparse_classes_30k_train_006446 | Implement the Python class `Transformer` described below.
Class description:
Transformer class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Class constructor Args: N (int): the number of blocks in the encoder. dm (in... | Implement the Python class `Transformer` described below.
Class description:
Transformer class
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Class constructor Args: N (int): the number of blocks in the encoder. dm (in... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class Transformer:
"""Transformer class"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Class constructor Args: N (int): the number of blocks in the encoder. dm (int): the dimensionality of the model. h (int): the number ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""Transformer class"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Class constructor Args: N (int): the number of blocks in the encoder. dm (int): the dimensionality of the model. h (int): the number of heads. hid... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/11-transformer.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
15eea0bc88a571c16d9fd15421b6ed1aed632f03 | [
"print('定义向上滑动方法')\nx1 = width * 0.5\ny1 = height * 0.9\ny2 = height * 0.25\ntime.sleep(3)\nprint('滑动前')\nfor i in range(n):\n print('第%d次滑屏' % i)\n time.sleep(3)\n driver.swipe(x1, y1, x1, y2)",
"print('定义向下滑动方法')\nx1 = width * 0.5\ny1 = height * 0.25\ny2 = height * 0.9\ntime.sleep(3)\nprint('滑动前')\nfor... | <|body_start_0|>
print('定义向上滑动方法')
x1 = width * 0.5
y1 = height * 0.9
y2 = height * 0.25
time.sleep(3)
print('滑动前')
for i in range(n):
print('第%d次滑屏' % i)
time.sleep(3)
driver.swipe(x1, y1, x1, y2)
<|end_body_0|>
<|body_start_1... | swipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class swipe:
def swipeUp(driver, n=5):
"""定义向上滑动方法"""
<|body_0|>
def swipeDown(driver, n=5):
"""定义向下滑动方法"""
<|body_1|>
def swipeLeft(driver, n=5):
"""定义向左滑动方法"""
<|body_2|>
def swipeRight(driver, n=5):
"""定义向右滑动方法"""
<|body... | stack_v2_sparse_classes_36k_train_023545 | 2,304 | no_license | [
{
"docstring": "定义向上滑动方法",
"name": "swipeUp",
"signature": "def swipeUp(driver, n=5)"
},
{
"docstring": "定义向下滑动方法",
"name": "swipeDown",
"signature": "def swipeDown(driver, n=5)"
},
{
"docstring": "定义向左滑动方法",
"name": "swipeLeft",
"signature": "def swipeLeft(driver, n=5)"
... | 4 | stack_v2_sparse_classes_30k_train_004674 | Implement the Python class `swipe` described below.
Class description:
Implement the swipe class.
Method signatures and docstrings:
- def swipeUp(driver, n=5): 定义向上滑动方法
- def swipeDown(driver, n=5): 定义向下滑动方法
- def swipeLeft(driver, n=5): 定义向左滑动方法
- def swipeRight(driver, n=5): 定义向右滑动方法 | Implement the Python class `swipe` described below.
Class description:
Implement the swipe class.
Method signatures and docstrings:
- def swipeUp(driver, n=5): 定义向上滑动方法
- def swipeDown(driver, n=5): 定义向下滑动方法
- def swipeLeft(driver, n=5): 定义向左滑动方法
- def swipeRight(driver, n=5): 定义向右滑动方法
<|skeleton|>
class swipe:
... | a184161fdbf4b35dbca8e9b050ad049c05b003ff | <|skeleton|>
class swipe:
def swipeUp(driver, n=5):
"""定义向上滑动方法"""
<|body_0|>
def swipeDown(driver, n=5):
"""定义向下滑动方法"""
<|body_1|>
def swipeLeft(driver, n=5):
"""定义向左滑动方法"""
<|body_2|>
def swipeRight(driver, n=5):
"""定义向右滑动方法"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class swipe:
def swipeUp(driver, n=5):
"""定义向上滑动方法"""
print('定义向上滑动方法')
x1 = width * 0.5
y1 = height * 0.9
y2 = height * 0.25
time.sleep(3)
print('滑动前')
for i in range(n):
print('第%d次滑屏' % i)
time.sleep(3)
driver.swi... | the_stack_v2_python_sparse | Utils/app_common/swipe.py | liuchengxu11/IM | train | 0 | |
cbb8cd4e8e83e23e52ee1c5079569069ea4233df | [
"if not api.base.is_service_enabled(request, 'compute'):\n raise rest_utils.AjaxError(501, _('Service Nova is disabled.'))\nquota_set = api.nova.default_quota_get(request, request.user.tenant_id)\ndisabled_quotas = quotas.get_disabled_quotas(request)\nfiltered_quotas = [quota for quota in quota_set if quota.name... | <|body_start_0|>
if not api.base.is_service_enabled(request, 'compute'):
raise rest_utils.AjaxError(501, _('Service Nova is disabled.'))
quota_set = api.nova.default_quota_get(request, request.user.tenant_id)
disabled_quotas = quotas.get_disabled_quotas(request)
filtered_quot... | API for getting default quotas for nova | DefaultQuotaSets | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultQuotaSets:
"""API for getting default quotas for nova"""
def get(self, request):
"""Get the values for Nova specific quotas Example GET: http://localhost/api/nova/quota-sets/defaults/"""
<|body_0|>
def patch(self, request):
"""Update the values for Nova sp... | stack_v2_sparse_classes_36k_train_023546 | 28,240 | permissive | [
{
"docstring": "Get the values for Nova specific quotas Example GET: http://localhost/api/nova/quota-sets/defaults/",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Update the values for Nova specific quotas This method returns HTTP 204 (no content) on success.",
"na... | 2 | stack_v2_sparse_classes_30k_train_008869 | Implement the Python class `DefaultQuotaSets` described below.
Class description:
API for getting default quotas for nova
Method signatures and docstrings:
- def get(self, request): Get the values for Nova specific quotas Example GET: http://localhost/api/nova/quota-sets/defaults/
- def patch(self, request): Update t... | Implement the Python class `DefaultQuotaSets` described below.
Class description:
API for getting default quotas for nova
Method signatures and docstrings:
- def get(self, request): Get the values for Nova specific quotas Example GET: http://localhost/api/nova/quota-sets/defaults/
- def patch(self, request): Update t... | 7896fd8c77a6766a1156a520946efaf792b76ca5 | <|skeleton|>
class DefaultQuotaSets:
"""API for getting default quotas for nova"""
def get(self, request):
"""Get the values for Nova specific quotas Example GET: http://localhost/api/nova/quota-sets/defaults/"""
<|body_0|>
def patch(self, request):
"""Update the values for Nova sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultQuotaSets:
"""API for getting default quotas for nova"""
def get(self, request):
"""Get the values for Nova specific quotas Example GET: http://localhost/api/nova/quota-sets/defaults/"""
if not api.base.is_service_enabled(request, 'compute'):
raise rest_utils.AjaxError(... | the_stack_v2_python_sparse | openstack_dashboard/api/rest/nova.py | openstack/horizon | train | 1,060 |
53d98c33dbd72f45194960afd2b9e90b928d3fda | [
"h = len(grid)\nw = len(grid[0])\n\n@lru_cache(maxsize=None)\ndef falling_path(row: int, col: int) -> int:\n if row == h:\n return 0\n if col < 0 or col >= w:\n return float('inf')\n sub_sol = min((falling_path(row + 1, col + i) for i in [-1, 0, 1]))\n return grid[row][col] + sub_sol\nretu... | <|body_start_0|>
h = len(grid)
w = len(grid[0])
@lru_cache(maxsize=None)
def falling_path(row: int, col: int) -> int:
if row == h:
return 0
if col < 0 or col >= w:
return float('inf')
sub_sol = min((falling_path(row + 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minFallingPathSum_top_down(self, grid: List[List[int]]) -> int:
"""Classing DP: - express row in terms of row - 1 - add memoization O(H * W) sub-problems Complexity is O(H * W) = O(N) Beats 12% (172 ms)"""
<|body_0|>
def minFallingPathSum(self, grid: List[List[... | stack_v2_sparse_classes_36k_train_023547 | 1,866 | no_license | [
{
"docstring": "Classing DP: - express row in terms of row - 1 - add memoization O(H * W) sub-problems Complexity is O(H * W) = O(N) Beats 12% (172 ms)",
"name": "minFallingPathSum_top_down",
"signature": "def minFallingPathSum_top_down(self, grid: List[List[int]]) -> int"
},
{
"docstring": "Doi... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minFallingPathSum_top_down(self, grid: List[List[int]]) -> int: Classing DP: - express row in terms of row - 1 - add memoization O(H * W) sub-problems Complexity is O(H * W) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minFallingPathSum_top_down(self, grid: List[List[int]]) -> int: Classing DP: - express row in terms of row - 1 - add memoization O(H * W) sub-problems Complexity is O(H * W) ... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def minFallingPathSum_top_down(self, grid: List[List[int]]) -> int:
"""Classing DP: - express row in terms of row - 1 - add memoization O(H * W) sub-problems Complexity is O(H * W) = O(N) Beats 12% (172 ms)"""
<|body_0|>
def minFallingPathSum(self, grid: List[List[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minFallingPathSum_top_down(self, grid: List[List[int]]) -> int:
"""Classing DP: - express row in terms of row - 1 - add memoization O(H * W) sub-problems Complexity is O(H * W) = O(N) Beats 12% (172 ms)"""
h = len(grid)
w = len(grid[0])
@lru_cache(maxsize=None)
... | the_stack_v2_python_sparse | dp/MinimumFallingPath.py | QuentinDuval/PythonExperiments | train | 3 | |
a0be54ea24ea73962408b5f1ad06910f47d63a5b | [
"super(ConvolutionalClassHead, self).__init__(name=name)\nself._is_training = is_training\nself._use_dropout = use_dropout\nself._dropout_keep_prob = dropout_keep_prob\nself._kernel_size = kernel_size\nself._class_prediction_bias_init = class_prediction_bias_init\nself._use_depthwise = use_depthwise\nself._num_clas... | <|body_start_0|>
super(ConvolutionalClassHead, self).__init__(name=name)
self._is_training = is_training
self._use_dropout = use_dropout
self._dropout_keep_prob = dropout_keep_prob
self._kernel_size = kernel_size
self._class_prediction_bias_init = class_prediction_bias_in... | Convolutional class prediction head. | ConvolutionalClassHead | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalClassHead:
"""Convolutional class prediction head."""
def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, class_prediction_bias_init=0.0, use_depthwise=False, name=None):
... | stack_v2_sparse_classes_36k_train_023548 | 6,360 | permissive | [
{
"docstring": "Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_class_slots: number of class slots. Note that num_class_slots may or may not include an implicit background category. use_dropout: Option to use dropout or not. Note that a single dropout op is applied he... | 2 | stack_v2_sparse_classes_30k_train_002818 | Implement the Python class `ConvolutionalClassHead` described below.
Class description:
Convolutional class prediction head.
Method signatures and docstrings:
- def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnor... | Implement the Python class `ConvolutionalClassHead` described below.
Class description:
Convolutional class prediction head.
Method signatures and docstrings:
- def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnor... | d32cf96575c995f4d5b634e4dbb876845e3bcd2a | <|skeleton|>
class ConvolutionalClassHead:
"""Convolutional class prediction head."""
def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, class_prediction_bias_init=0.0, use_depthwise=False, name=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvolutionalClassHead:
"""Convolutional class prediction head."""
def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, class_prediction_bias_init=0.0, use_depthwise=False, name=None):
"""Co... | the_stack_v2_python_sparse | research/object_detection/predictors/heads/keras_class_head.py | apacha/MusicObjectDetector-TF | train | 83 |
7b0d8b5cfafb5b2dc39eb2872c0b1b30e3dd1b9d | [
"user = mixer.blend(User, email='newuser@gmail.com', phone='12345678', password='test_password_1')\nuser.set_password('test_password_1')\nuser.save()\nrequest_data_cases = [{'grant_type': 'password', 'login': user.email, 'password': 'test_password_1'}, {'grant_type': 'password', 'login': user.phone, 'password': 'te... | <|body_start_0|>
user = mixer.blend(User, email='newuser@gmail.com', phone='12345678', password='test_password_1')
user.set_password('test_password_1')
user.save()
request_data_cases = [{'grant_type': 'password', 'login': user.email, 'password': 'test_password_1'}, {'grant_type': 'passwo... | TestCustomLoginView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCustomLoginView:
def test_post_with_email_and_phone(self):
"""Test: login by user with email / phone"""
<|body_0|>
def test_post_with_wallet_erc20(self):
"""Test: login by user with wallet ERC-20"""
<|body_1|>
def test_post_with_refresh_token(self):
... | stack_v2_sparse_classes_36k_train_023549 | 6,349 | permissive | [
{
"docstring": "Test: login by user with email / phone",
"name": "test_post_with_email_and_phone",
"signature": "def test_post_with_email_and_phone(self)"
},
{
"docstring": "Test: login by user with wallet ERC-20",
"name": "test_post_with_wallet_erc20",
"signature": "def test_post_with_w... | 6 | stack_v2_sparse_classes_30k_train_005080 | Implement the Python class `TestCustomLoginView` described below.
Class description:
Implement the TestCustomLoginView class.
Method signatures and docstrings:
- def test_post_with_email_and_phone(self): Test: login by user with email / phone
- def test_post_with_wallet_erc20(self): Test: login by user with wallet ER... | Implement the Python class `TestCustomLoginView` described below.
Class description:
Implement the TestCustomLoginView class.
Method signatures and docstrings:
- def test_post_with_email_and_phone(self): Test: login by user with email / phone
- def test_post_with_wallet_erc20(self): Test: login by user with wallet ER... | f8930ff1c009ad18e522ab29680b4bcd50a6020e | <|skeleton|>
class TestCustomLoginView:
def test_post_with_email_and_phone(self):
"""Test: login by user with email / phone"""
<|body_0|>
def test_post_with_wallet_erc20(self):
"""Test: login by user with wallet ERC-20"""
<|body_1|>
def test_post_with_refresh_token(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCustomLoginView:
def test_post_with_email_and_phone(self):
"""Test: login by user with email / phone"""
user = mixer.blend(User, email='newuser@gmail.com', phone='12345678', password='test_password_1')
user.set_password('test_password_1')
user.save()
request_data_ca... | the_stack_v2_python_sparse | src/auth/tests.py | evis-market/web-interface-backend | train | 2 | |
5e3935de485dc0eb4456add8bfb52ba36763a94b | [
"if self._async_current_entries():\n return self.async_abort(reason='already_setup')\nuser, error = await self._check_connection(conf[CONF_ACCESS_TOKEN])\nif error is not None:\n return self.async_abort(reason=error)\nawait self.async_set_unique_id(user.email)\nself._abort_if_unique_id_configured()\nreturn se... | <|body_start_0|>
if self._async_current_entries():
return self.async_abort(reason='already_setup')
user, error = await self._check_connection(conf[CONF_ACCESS_TOKEN])
if error is not None:
return self.async_abort(reason=error)
await self.async_set_unique_id(user.e... | Config flow for Awair. | AwairFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AwairFlowHandler:
"""Config flow for Awair."""
async def async_step_import(self, conf: dict):
"""Import a configuration from config.yaml."""
<|body_0|>
async def async_step_user(self, user_input: dict | None=None):
"""Handle a flow initialized by the user."""
... | stack_v2_sparse_classes_36k_train_023550 | 3,540 | permissive | [
{
"docstring": "Import a configuration from config.yaml.",
"name": "async_step_import",
"signature": "async def async_step_import(self, conf: dict)"
},
{
"docstring": "Handle a flow initialized by the user.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_i... | 4 | null | Implement the Python class `AwairFlowHandler` described below.
Class description:
Config flow for Awair.
Method signatures and docstrings:
- async def async_step_import(self, conf: dict): Import a configuration from config.yaml.
- async def async_step_user(self, user_input: dict | None=None): Handle a flow initialize... | Implement the Python class `AwairFlowHandler` described below.
Class description:
Config flow for Awair.
Method signatures and docstrings:
- async def async_step_import(self, conf: dict): Import a configuration from config.yaml.
- async def async_step_user(self, user_input: dict | None=None): Handle a flow initialize... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class AwairFlowHandler:
"""Config flow for Awair."""
async def async_step_import(self, conf: dict):
"""Import a configuration from config.yaml."""
<|body_0|>
async def async_step_user(self, user_input: dict | None=None):
"""Handle a flow initialized by the user."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AwairFlowHandler:
"""Config flow for Awair."""
async def async_step_import(self, conf: dict):
"""Import a configuration from config.yaml."""
if self._async_current_entries():
return self.async_abort(reason='already_setup')
user, error = await self._check_connection(con... | the_stack_v2_python_sparse | homeassistant/components/awair/config_flow.py | BenWoodford/home-assistant | train | 11 |
8115f3f0770fd2782fe0a9ed88ad93287f5fef99 | [
"super().__init__(time_provider, invocation_recorder, progress_reporter_factory)\nself._auth_token_stamper = auth_token_stamper\nself._storage_engine = storage_engine",
"try:\n auth_token = self._auth_token_stamper.verify_auth_token_general(session.auth_token_ext) if session.auth_token_ext else None\nexcept (I... | <|body_start_0|>
super().__init__(time_provider, invocation_recorder, progress_reporter_factory)
self._auth_token_stamper = auth_token_stamper
self._storage_engine = storage_engine
<|end_body_0|>
<|body_start_1|>
try:
auth_token = self._auth_token_stamper.verify_auth_token_g... | A command which does some sort of mutation for the app, but does not assume a logged-in user. | AppGuestMutationUseCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppGuestMutationUseCase:
"""A command which does some sort of mutation for the app, but does not assume a logged-in user."""
def __init__(self, time_provider: TimeProvider, invocation_recorder: MutationUseCaseInvocationRecorder, progress_reporter_factory: ProgressReporterFactory[AppGuestUseC... | stack_v2_sparse_classes_36k_train_023551 | 12,535 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, time_provider: TimeProvider, invocation_recorder: MutationUseCaseInvocationRecorder, progress_reporter_factory: ProgressReporterFactory[AppGuestUseCaseContext], auth_token_stamper: AuthTokenStamper, storage_engine: Domai... | 2 | null | Implement the Python class `AppGuestMutationUseCase` described below.
Class description:
A command which does some sort of mutation for the app, but does not assume a logged-in user.
Method signatures and docstrings:
- def __init__(self, time_provider: TimeProvider, invocation_recorder: MutationUseCaseInvocationRecor... | Implement the Python class `AppGuestMutationUseCase` described below.
Class description:
A command which does some sort of mutation for the app, but does not assume a logged-in user.
Method signatures and docstrings:
- def __init__(self, time_provider: TimeProvider, invocation_recorder: MutationUseCaseInvocationRecor... | 911ecd560142a9b4e57498f2b090f9469a0718a1 | <|skeleton|>
class AppGuestMutationUseCase:
"""A command which does some sort of mutation for the app, but does not assume a logged-in user."""
def __init__(self, time_provider: TimeProvider, invocation_recorder: MutationUseCaseInvocationRecorder, progress_reporter_factory: ProgressReporterFactory[AppGuestUseC... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppGuestMutationUseCase:
"""A command which does some sort of mutation for the app, but does not assume a logged-in user."""
def __init__(self, time_provider: TimeProvider, invocation_recorder: MutationUseCaseInvocationRecorder, progress_reporter_factory: ProgressReporterFactory[AppGuestUseCaseContext], ... | the_stack_v2_python_sparse | src/core/jupiter/core/use_cases/infra/use_cases.py | horia141/jupiter | train | 16 |
9ab2e0373d28cc580f231323a9211093dc7f7de4 | [
"self.logger = logging.getLogger('app')\nself.logger.debug('instantiated')\nself.cfg = cfg\nself.web_util = web_util\nself.session_manager = session_manager",
"user_token = req.context['user']['user']\nif self.web_util.check_csrf(user_token['ses'], csrf):\n self.logger.debug('Ending session %s for user %s', us... | <|body_start_0|>
self.logger = logging.getLogger('app')
self.logger.debug('instantiated')
self.cfg = cfg
self.web_util = web_util
self.session_manager = session_manager
<|end_body_0|>
<|body_start_1|>
user_token = req.context['user']['user']
if self.web_util.chec... | provides logout functionality | LogoutResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogoutResource:
"""provides logout functionality"""
def __init__(self, session_manager, cfg, web_util):
"""Initialization function"""
<|body_0|>
def on_get(self, req, resp, csrf):
"""Processes Get Request to logout, requires csrf token in url"""
<|body_1|... | stack_v2_sparse_classes_36k_train_023552 | 1,318 | no_license | [
{
"docstring": "Initialization function",
"name": "__init__",
"signature": "def __init__(self, session_manager, cfg, web_util)"
},
{
"docstring": "Processes Get Request to logout, requires csrf token in url",
"name": "on_get",
"signature": "def on_get(self, req, resp, csrf)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016449 | Implement the Python class `LogoutResource` described below.
Class description:
provides logout functionality
Method signatures and docstrings:
- def __init__(self, session_manager, cfg, web_util): Initialization function
- def on_get(self, req, resp, csrf): Processes Get Request to logout, requires csrf token in url | Implement the Python class `LogoutResource` described below.
Class description:
provides logout functionality
Method signatures and docstrings:
- def __init__(self, session_manager, cfg, web_util): Initialization function
- def on_get(self, req, resp, csrf): Processes Get Request to logout, requires csrf token in url... | 3c774731b054c38a273371450a451c951d73b726 | <|skeleton|>
class LogoutResource:
"""provides logout functionality"""
def __init__(self, session_manager, cfg, web_util):
"""Initialization function"""
<|body_0|>
def on_get(self, req, resp, csrf):
"""Processes Get Request to logout, requires csrf token in url"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogoutResource:
"""provides logout functionality"""
def __init__(self, session_manager, cfg, web_util):
"""Initialization function"""
self.logger = logging.getLogger('app')
self.logger.debug('instantiated')
self.cfg = cfg
self.web_util = web_util
self.sessi... | the_stack_v2_python_sparse | genesis/logoutresource.py | wbmartin/exodus-app | train | 0 |
cf6ffee68ce51fa649af4f0c816608b8e4ee6bce | [
"def pre_order(root, array):\n if not root:\n pass\n else:\n array.append(root.val)\n pre_order(root.left, array)\n pre_order(root.right, array)\n return array\nreturn ' '.join(map(str, pre_order(root, [])))",
"def helper(low=float('-inf'), high=float('inf')):\n if not data... | <|body_start_0|>
def pre_order(root, array):
if not root:
pass
else:
array.append(root.val)
pre_order(root.left, array)
pre_order(root.right, array)
return array
return ' '.join(map(str, pre_order(root, [... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def pre_order(... | stack_v2_sparse_classes_36k_train_023553 | 3,114 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 1bcf3206cd3acc428ec690cb883c612aaf708aac | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def pre_order(root, array):
if not root:
pass
else:
array.append(root.val)
pre_order(root.left, array)
pre_order(r... | the_stack_v2_python_sparse | problem-list/Tree/449.serialize-and-deserialize-bst.py | KevinChen1994/leetcode-algorithm | train | 2 | |
b14c241912377e20b9cd05c7dbf38419fc272ab7 | [
"l = height\nsize = 0\nfor i in range(len(l)):\n for j in range(i, len(l)):\n print(l[i], l[j])\n if l[i] < l[j]:\n size = max(size, l[i] * (j - i))\n else:\n size = max(size, l[j] * (j - i))\nreturn size",
"head = 0\ntail = len(height) - 1\nsize = 0\nwhile head < tai... | <|body_start_0|>
l = height
size = 0
for i in range(len(l)):
for j in range(i, len(l)):
print(l[i], l[j])
if l[i] < l[j]:
size = max(size, l[i] * (j - i))
else:
size = max(size, l[j] * (j - i))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaBrute(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = height
size = 0
for ... | stack_v2_sparse_classes_36k_train_023554 | 1,118 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxAreaBrute",
"signature": "def maxAreaBrute(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011475 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaBrute(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaBrute(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxAre... | 673fb7bb900e65844b68b5826a259eb6932c5fc4 | <|skeleton|>
class Solution:
def maxAreaBrute(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAreaBrute(self, height):
""":type height: List[int] :rtype: int"""
l = height
size = 0
for i in range(len(l)):
for j in range(i, len(l)):
print(l[i], l[j])
if l[i] < l[j]:
size = max(size, l[i] * (... | the_stack_v2_python_sparse | 11. Container With Most Water.py | MysticEEEE/LeetCodeProblems | train | 0 | |
92c592b1c1b9a0fbb0d703e41acb399017898dcb | [
"s = login_xadmin\ndetails = Contract_details(s, contractNo=20090900006)\nassert details['data']['baseInfo']['contractNo'] == 20090900006\nassert details['success'] == True",
"s = login_xadmin\ndetails = Contract_details(s, contractNo=200909000)\nassert details['success'] == False\nprint('66666666')\nassert '未搵到該... | <|body_start_0|>
s = login_xadmin
details = Contract_details(s, contractNo=20090900006)
assert details['data']['baseInfo']['contractNo'] == 20090900006
assert details['success'] == True
<|end_body_0|>
<|body_start_1|>
s = login_xadmin
details = Contract_details(s, contra... | 合同详情信息查询 | Test_Contract_details | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Contract_details:
"""合同详情信息查询"""
def test_Contract_details_34(self, login_xadmin):
"""验证输入有效的合同编号,可对合同详情信息进行查询"""
<|body_0|>
def test_Contract_details_35(self, login_xadmin):
"""验证输入无效的合同编号,查询的合同为空"""
<|body_1|>
def test_Contract_details_36(self... | stack_v2_sparse_classes_36k_train_023555 | 20,573 | no_license | [
{
"docstring": "验证输入有效的合同编号,可对合同详情信息进行查询",
"name": "test_Contract_details_34",
"signature": "def test_Contract_details_34(self, login_xadmin)"
},
{
"docstring": "验证输入无效的合同编号,查询的合同为空",
"name": "test_Contract_details_35",
"signature": "def test_Contract_details_35(self, login_xadmin)"
},... | 3 | stack_v2_sparse_classes_30k_train_004512 | Implement the Python class `Test_Contract_details` described below.
Class description:
合同详情信息查询
Method signatures and docstrings:
- def test_Contract_details_34(self, login_xadmin): 验证输入有效的合同编号,可对合同详情信息进行查询
- def test_Contract_details_35(self, login_xadmin): 验证输入无效的合同编号,查询的合同为空
- def test_Contract_details_36(self, lo... | Implement the Python class `Test_Contract_details` described below.
Class description:
合同详情信息查询
Method signatures and docstrings:
- def test_Contract_details_34(self, login_xadmin): 验证输入有效的合同编号,可对合同详情信息进行查询
- def test_Contract_details_35(self, login_xadmin): 验证输入无效的合同编号,查询的合同为空
- def test_Contract_details_36(self, lo... | 196ebbddaad6ee2acaf6b2b6ba40c856af2a35c3 | <|skeleton|>
class Test_Contract_details:
"""合同详情信息查询"""
def test_Contract_details_34(self, login_xadmin):
"""验证输入有效的合同编号,可对合同详情信息进行查询"""
<|body_0|>
def test_Contract_details_35(self, login_xadmin):
"""验证输入无效的合同编号,查询的合同为空"""
<|body_1|>
def test_Contract_details_36(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_Contract_details:
"""合同详情信息查询"""
def test_Contract_details_34(self, login_xadmin):
"""验证输入有效的合同编号,可对合同详情信息进行查询"""
s = login_xadmin
details = Contract_details(s, contractNo=20090900006)
assert details['data']['baseInfo']['contractNo'] == 20090900006
assert deta... | the_stack_v2_python_sparse | case/VC_project/Annual_contract/test_annual_contract.py | wuyouyaun/django_templte | train | 0 |
f8dccbb2c374a7c8ef6feb34511b8abdf7b7e6f9 | [
"n = len(matrix)\nfor r in range(n):\n for c in range(r + 1, n, 1):\n matrix[r][c], matrix[c][r] = (matrix[c][r], matrix[r][c])\nfor r in range(n):\n matrix[r].reverse()",
"n = len(matrix)\nfor r in range(n):\n for c in range(r + 1, n, 1):\n matrix[r][c], matrix[c][r] = (matrix[c][r], matri... | <|body_start_0|>
n = len(matrix)
for r in range(n):
for c in range(r + 1, n, 1):
matrix[r][c], matrix[c][r] = (matrix[c][r], matrix[r][c])
for r in range(n):
matrix[r].reverse()
<|end_body_0|>
<|body_start_1|>
n = len(matrix)
for r in rang... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateClockwise(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotateCounterClockwise(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anyt... | stack_v2_sparse_classes_36k_train_023556 | 2,063 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotateClockwise",
"signature": "def rotateClockwise(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-... | 2 | stack_v2_sparse_classes_30k_train_008238 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateClockwise(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotateCounterClockwise(self, matrix): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateClockwise(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotateCounterClockwise(self, matrix): ... | 9ac54720f571a4bea09d0cceb0039381a78df9e8 | <|skeleton|>
class Solution:
def rotateClockwise(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotateCounterClockwise(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anyt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotateClockwise(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
n = len(matrix)
for r in range(n):
for c in range(r + 1, n, 1):
matrix[r][c], matrix[c][r] = (matrix[c][r], ... | the_stack_v2_python_sparse | code/048_rotate-image.py | linhdvu14/leetcode-solutions | train | 2 | |
7ed3280b64944c8ae65bf69e47f47bf6852656a6 | [
"obj.save()\ngenerate_static_sku_detail_html(obj.sku.id)\nsku = obj.sku\nif not sku.default_image_url:\n sku.default_image_url = obj.image.url\n sku.save()",
"sku_id = obj.sku.id\nobj.delete()\ngenerate_static_sku_detail_html(sku_id)"
] | <|body_start_0|>
obj.save()
generate_static_sku_detail_html(obj.sku.id)
sku = obj.sku
if not sku.default_image_url:
sku.default_image_url = obj.image.url
sku.save()
<|end_body_0|>
<|body_start_1|>
sku_id = obj.sku.id
obj.delete()
generate_... | 自定义管理admin站点 -- sku图片 | SKUImageAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SKUImageAdmin:
"""自定义管理admin站点 -- sku图片"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj.save()
... | stack_v2_sparse_classes_36k_train_023557 | 3,322 | no_license | [
{
"docstring": "admin后台新增或修改了数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "admin后台删除了数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001635 | Implement the Python class `SKUImageAdmin` described below.
Class description:
自定义管理admin站点 -- sku图片
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用 | Implement the Python class `SKUImageAdmin` described below.
Class description:
自定义管理admin站点 -- sku图片
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用
<|skeleton|>
class SKUImageAdmin:
"""自定义管理admin站点 -... | c841e7d1aa0616b070b10924f44b2c418f222cd8 | <|skeleton|>
class SKUImageAdmin:
"""自定义管理admin站点 -- sku图片"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SKUImageAdmin:
"""自定义管理admin站点 -- sku图片"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
obj.save()
generate_static_sku_detail_html(obj.sku.id)
sku = obj.sku
if not sku.default_image_url:
sku.default_image_url = obj.image.ur... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/goods/admin.py | Echo-xie/meiduo_mall | train | 0 |
af03ec9ac10d6e4388997034ccd9215a7e18a820 | [
"self.language = language\nself.sum_eng = 0\nself.sum_fre = 0\nself.sum_ger = 0\nself.conn_eng = 0\nself.conn_fre = 0\nself.conn_ger = 0\nself.english_lang_percentage = None\nself.french_lang_percentage = None\nself.german_lang_percentage = None\nself.foreign_percentage = None",
"total = self.sum_eng + self.sum_f... | <|body_start_0|>
self.language = language
self.sum_eng = 0
self.sum_fre = 0
self.sum_ger = 0
self.conn_eng = 0
self.conn_fre = 0
self.conn_ger = 0
self.english_lang_percentage = None
self.french_lang_percentage = None
self.german_lang_perce... | LanguageSum class | LanguageSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageSum:
"""LanguageSum class"""
def __init__(self, language):
"""Constructor"""
<|body_0|>
def calculate_language_percentages(self):
"""Calculate percentage for each language"""
<|body_1|>
def calculate_foreign_percentage(self):
"""Calcu... | stack_v2_sparse_classes_36k_train_023558 | 4,643 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, language)"
},
{
"docstring": "Calculate percentage for each language",
"name": "calculate_language_percentages",
"signature": "def calculate_language_percentages(self)"
},
{
"docstring": "Calculate... | 4 | stack_v2_sparse_classes_30k_train_000021 | Implement the Python class `LanguageSum` described below.
Class description:
LanguageSum class
Method signatures and docstrings:
- def __init__(self, language): Constructor
- def calculate_language_percentages(self): Calculate percentage for each language
- def calculate_foreign_percentage(self): Calculate percentage... | Implement the Python class `LanguageSum` described below.
Class description:
LanguageSum class
Method signatures and docstrings:
- def __init__(self, language): Constructor
- def calculate_language_percentages(self): Calculate percentage for each language
- def calculate_foreign_percentage(self): Calculate percentage... | a717e6c0fa8d0b3a5787d1536a57c5875ffb5799 | <|skeleton|>
class LanguageSum:
"""LanguageSum class"""
def __init__(self, language):
"""Constructor"""
<|body_0|>
def calculate_language_percentages(self):
"""Calculate percentage for each language"""
<|body_1|>
def calculate_foreign_percentage(self):
"""Calcu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguageSum:
"""LanguageSum class"""
def __init__(self, language):
"""Constructor"""
self.language = language
self.sum_eng = 0
self.sum_fre = 0
self.sum_ger = 0
self.conn_eng = 0
self.conn_fre = 0
self.conn_ger = 0
self.english_lang_... | the_stack_v2_python_sparse | src/measures/cooccurrence/sum_languages.py | niutyut/author-topic-modeling-project | train | 0 |
159793f0158d9c7e34f0768a2754b38dbf8cfbbf | [
"query = self.query(Platform)\nsearch_args = search_arguments.parse_args()\nif search_args['q']:\n query = query.filter(Platform.search_filter(search_args['q']))\nreturn query",
"args = platform_arguments.parse_args()\nplatform = Platform(**args)\nself.session.add(platform)\nself.session.commit()\nreturn platf... | <|body_start_0|>
query = self.query(Platform)
search_args = search_arguments.parse_args()
if search_args['q']:
query = query.filter(Platform.search_filter(search_args['q']))
return query
<|end_body_0|>
<|body_start_1|>
args = platform_arguments.parse_args()
p... | List all platforms | PlatformList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlatformList:
"""List all platforms"""
def get(self):
"""List all platforms"""
<|body_0|>
def post(self):
"""Create a new platform :raises IntegrityError: Raised when the slug is not unique"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query =... | stack_v2_sparse_classes_36k_train_023559 | 3,154 | no_license | [
{
"docstring": "List all platforms",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new platform :raises IntegrityError: Raised when the slug is not unique",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021635 | Implement the Python class `PlatformList` described below.
Class description:
List all platforms
Method signatures and docstrings:
- def get(self): List all platforms
- def post(self): Create a new platform :raises IntegrityError: Raised when the slug is not unique | Implement the Python class `PlatformList` described below.
Class description:
List all platforms
Method signatures and docstrings:
- def get(self): List all platforms
- def post(self): Create a new platform :raises IntegrityError: Raised when the slug is not unique
<|skeleton|>
class PlatformList:
"""List all pl... | 5f4493bedb36c29e80740676bbb179901272d91e | <|skeleton|>
class PlatformList:
"""List all platforms"""
def get(self):
"""List all platforms"""
<|body_0|>
def post(self):
"""Create a new platform :raises IntegrityError: Raised when the slug is not unique"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlatformList:
"""List all platforms"""
def get(self):
"""List all platforms"""
query = self.query(Platform)
search_args = search_arguments.parse_args()
if search_args['q']:
query = query.filter(Platform.search_filter(search_args['q']))
return query
... | the_stack_v2_python_sparse | matcher/api/namespaces/platforms.py | sandhose/obs-matcher | train | 2 |
b0324499c7ea989b7f7f46b3bf63af936c4d4a32 | [
"self.name = name\nself.objective = objective\nself.wrapped_objective = ScoringFunctionWrapper(scoring_function=objective)\nself.contribution_specification = contribution_specification\nself.starting_population = starting_population",
"number_molecules_to_generate = max(self.contribution_specification.top_counts)... | <|body_start_0|>
self.name = name
self.objective = objective
self.wrapped_objective = ScoringFunctionWrapper(scoring_function=objective)
self.contribution_specification = contribution_specification
self.starting_population = starting_population
<|end_body_0|>
<|body_start_1|>
... | This class assesses how well a model is able to generate molecules satisfying a given objective. | GoalDirectedBenchmark | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoalDirectedBenchmark:
"""This class assesses how well a model is able to generate molecules satisfying a given objective."""
def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContributionSpecification, starting_population: Optional[List[str]]=None) -... | stack_v2_sparse_classes_36k_train_023560 | 5,427 | permissive | [
{
"docstring": "Args: name: Benchmark name objective: Objective for the goal-directed optimization contribution_specification: Specifies how to calculate the global benchmark score",
"name": "__init__",
"signature": "def __init__(self, name: str, objective: ScoringFunction, contribution_specification: S... | 2 | stack_v2_sparse_classes_30k_test_001138 | Implement the Python class `GoalDirectedBenchmark` described below.
Class description:
This class assesses how well a model is able to generate molecules satisfying a given objective.
Method signatures and docstrings:
- def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContrib... | Implement the Python class `GoalDirectedBenchmark` described below.
Class description:
This class assesses how well a model is able to generate molecules satisfying a given objective.
Method signatures and docstrings:
- def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContrib... | 60ebe1f6a396f16e08b834dce448e9343d259feb | <|skeleton|>
class GoalDirectedBenchmark:
"""This class assesses how well a model is able to generate molecules satisfying a given objective."""
def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContributionSpecification, starting_population: Optional[List[str]]=None) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoalDirectedBenchmark:
"""This class assesses how well a model is able to generate molecules satisfying a given objective."""
def __init__(self, name: str, objective: ScoringFunction, contribution_specification: ScoreContributionSpecification, starting_population: Optional[List[str]]=None) -> None:
... | the_stack_v2_python_sparse | guacamol/goal_directed_benchmark.py | BenevolentAI/guacamol | train | 328 |
2d8d3da96289f7a7390568daa929ccb6c1ae35d8 | [
"self.coarse_vehicle_location_time_histories = coarse_vehicle_location_time_histories\nself.flagged_vehicle_fault_events = flagged_vehicle_fault_events\nself.vehicle_performance_events = vehicle_performance_events\nself.vehicle_fault_code_events = vehicle_fault_code_events",
"if dictionary is None:\n return No... | <|body_start_0|>
self.coarse_vehicle_location_time_histories = coarse_vehicle_location_time_histories
self.flagged_vehicle_fault_events = flagged_vehicle_fault_events
self.vehicle_performance_events = vehicle_performance_events
self.vehicle_fault_code_events = vehicle_fault_code_events
<... | Implementation of the 'Get Fleet Vehicle Info response' model. TODO: type model description here. Attributes: coarse_vehicle_location_time_histories (VehicleLocationTimeHistory): TODO: type description here. flagged_vehicle_fault_events (list of VehicleFaultCodeEvent): all Flagged Vehicle Fault Code Events for all vehi... | GetFleetVehicleInfoResponse | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetFleetVehicleInfoResponse:
"""Implementation of the 'Get Fleet Vehicle Info response' model. TODO: type model description here. Attributes: coarse_vehicle_location_time_histories (VehicleLocationTimeHistory): TODO: type description here. flagged_vehicle_fault_events (list of VehicleFaultCodeEve... | stack_v2_sparse_classes_36k_train_023561 | 4,370 | permissive | [
{
"docstring": "Constructor for the GetFleetVehicleInfoResponse class",
"name": "__init__",
"signature": "def __init__(self, coarse_vehicle_location_time_histories=None, flagged_vehicle_fault_events=None, vehicle_performance_events=None, vehicle_fault_code_events=None)"
},
{
"docstring": "Create... | 2 | stack_v2_sparse_classes_30k_train_014100 | Implement the Python class `GetFleetVehicleInfoResponse` described below.
Class description:
Implementation of the 'Get Fleet Vehicle Info response' model. TODO: type model description here. Attributes: coarse_vehicle_location_time_histories (VehicleLocationTimeHistory): TODO: type description here. flagged_vehicle_fa... | Implement the Python class `GetFleetVehicleInfoResponse` described below.
Class description:
Implementation of the 'Get Fleet Vehicle Info response' model. TODO: type model description here. Attributes: coarse_vehicle_location_time_histories (VehicleLocationTimeHistory): TODO: type description here. flagged_vehicle_fa... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class GetFleetVehicleInfoResponse:
"""Implementation of the 'Get Fleet Vehicle Info response' model. TODO: type model description here. Attributes: coarse_vehicle_location_time_histories (VehicleLocationTimeHistory): TODO: type description here. flagged_vehicle_fault_events (list of VehicleFaultCodeEve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetFleetVehicleInfoResponse:
"""Implementation of the 'Get Fleet Vehicle Info response' model. TODO: type model description here. Attributes: coarse_vehicle_location_time_histories (VehicleLocationTimeHistory): TODO: type description here. flagged_vehicle_fault_events (list of VehicleFaultCodeEvent): all Flag... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/get_fleet_vehicle_info_response.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
c0334a3e31ada79d550120c0ba0143394deb2b72 | [
"Parametre.__init__(self, 'vacances', 'vacations')\nself.schema = '(<cle>)'\nself.aide_courte = 'affiche les joueurs en vacances'\nself.aide_longue = 'Cette commande permet de voir les joueurs actuellent en vacances. Sans paramètre, elle affiche la liste des joueurs en vacances. Vous pouvez préciser en paramètre |e... | <|body_start_0|>
Parametre.__init__(self, 'vacances', 'vacations')
self.schema = '(<cle>)'
self.aide_courte = 'affiche les joueurs en vacances'
self.aide_longue = 'Cette commande permet de voir les joueurs actuellent en vacances. Sans paramètre, elle affiche la liste des joueurs en vacan... | Commande 'auberge vacances'. | PrmVacances | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmVacances:
"""Commande 'auberge vacances'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Paramet... | stack_v2_sparse_classes_36k_train_023562 | 3,194 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmVacances` described below.
Class description:
Commande 'auberge vacances'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmVacances` described below.
Class description:
Commande 'auberge vacances'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmVacances:
"""Commande 'au... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmVacances:
"""Commande 'auberge vacances'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmVacances:
"""Commande 'auberge vacances'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'vacances', 'vacations')
self.schema = '(<cle>)'
self.aide_courte = 'affiche les joueurs en vacances'
self.aide_longue = 'Cette commande per... | the_stack_v2_python_sparse | src/secondaires/auberge/commandes/auberge/vacances.py | vincent-lg/tsunami | train | 5 |
6a9dbc47b4c2959db1688078f18f5e416c47357d | [
"self.addr = addr\nself.conf = os.path.expanduser('~/.rspwsafe')\nself._check_config()\ncp = SafeConfigParser()\ncp.read(self.conf)\nself.username = cp.get('auth', 'username').strip()\nself.password = cp.get('auth', 'password').strip()\nif cp.has_option('auth', 'token'):\n self.token = cp.get('auth', 'token').st... | <|body_start_0|>
self.addr = addr
self.conf = os.path.expanduser('~/.rspwsafe')
self._check_config()
cp = SafeConfigParser()
cp.read(self.conf)
self.username = cp.get('auth', 'username').strip()
self.password = cp.get('auth', 'password').strip()
if cp.has_... | base class that handles authentication to global auth returing token | PWSafeAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PWSafeAuth:
"""base class that handles authentication to global auth returing token"""
def __init__(self, addr='https://identity-internal.api.rackspacecloud.com'):
"""load credentials and authenticate"""
<|body_0|>
def _check_config(self):
"""prompt for credentia... | stack_v2_sparse_classes_36k_train_023563 | 8,387 | no_license | [
{
"docstring": "load credentials and authenticate",
"name": "__init__",
"signature": "def __init__(self, addr='https://identity-internal.api.rackspacecloud.com')"
},
{
"docstring": "prompt for credentials if conf file does not exist",
"name": "_check_config",
"signature": "def _check_con... | 5 | stack_v2_sparse_classes_30k_train_010021 | Implement the Python class `PWSafeAuth` described below.
Class description:
base class that handles authentication to global auth returing token
Method signatures and docstrings:
- def __init__(self, addr='https://identity-internal.api.rackspacecloud.com'): load credentials and authenticate
- def _check_config(self):... | Implement the Python class `PWSafeAuth` described below.
Class description:
base class that handles authentication to global auth returing token
Method signatures and docstrings:
- def __init__(self, addr='https://identity-internal.api.rackspacecloud.com'): load credentials and authenticate
- def _check_config(self):... | 4cc683c098f5971f5aee120d87a1a3bb534093f6 | <|skeleton|>
class PWSafeAuth:
"""base class that handles authentication to global auth returing token"""
def __init__(self, addr='https://identity-internal.api.rackspacecloud.com'):
"""load credentials and authenticate"""
<|body_0|>
def _check_config(self):
"""prompt for credentia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PWSafeAuth:
"""base class that handles authentication to global auth returing token"""
def __init__(self, addr='https://identity-internal.api.rackspacecloud.com'):
"""load credentials and authenticate"""
self.addr = addr
self.conf = os.path.expanduser('~/.rspwsafe')
self._... | the_stack_v2_python_sparse | volga-etl/airflow/dags/common/rspwsafe.py | LavanyaUmapathi/Exp | train | 0 |
edc06ce2aab9d882a9685ef01bbc52c50681b51b | [
"super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision=precision, entity=entity)\nself._time_window = window_size\nself._last_emitted_at: datetime | None = None\nself._only_numbers = False",
"window_start = new_state.timestamp - self._time_window\nif not self._last_emitted_at or self._last_emitted_at... | <|body_start_0|>
super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision=precision, entity=entity)
self._time_window = window_size
self._last_emitted_at: datetime | None = None
self._only_numbers = False
<|end_body_0|>
<|body_start_1|>
window_start = new_state.timesta... | Time Throttle Filter. One sample per time period. | TimeThrottleFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeThrottleFilter:
"""Time Throttle Filter. One sample per time period."""
def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None:
"""Initialize Filter."""
<|body_0|>
def _filter_state(self, new_state: FilterState) -> FilterState:... | stack_v2_sparse_classes_36k_train_023564 | 23,958 | permissive | [
{
"docstring": "Initialize Filter.",
"name": "__init__",
"signature": "def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None"
},
{
"docstring": "Implement the filter.",
"name": "_filter_state",
"signature": "def _filter_state(self, new_state: Filt... | 2 | null | Implement the Python class `TimeThrottleFilter` described below.
Class description:
Time Throttle Filter. One sample per time period.
Method signatures and docstrings:
- def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None: Initialize Filter.
- def _filter_state(self, new_sta... | Implement the Python class `TimeThrottleFilter` described below.
Class description:
Time Throttle Filter. One sample per time period.
Method signatures and docstrings:
- def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None: Initialize Filter.
- def _filter_state(self, new_sta... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TimeThrottleFilter:
"""Time Throttle Filter. One sample per time period."""
def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None:
"""Initialize Filter."""
<|body_0|>
def _filter_state(self, new_state: FilterState) -> FilterState:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeThrottleFilter:
"""Time Throttle Filter. One sample per time period."""
def __init__(self, *, window_size: timedelta, entity: str, precision: int | None=None) -> None:
"""Initialize Filter."""
super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision=precision, entity=entity)... | the_stack_v2_python_sparse | homeassistant/components/filter/sensor.py | home-assistant/core | train | 35,501 |
af85cb2303d68511dc56928426e13bf90c5f8550 | [
"def filter_max_length(x, y, max_length=max_len):\n \"\"\"\n filter method\n \"\"\"\n return tf.logical_and(tf.size(x) <= max_length, tf.size(y) <= max_length)\nexamples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, as_supervised=True)\nself.data_train = examples['... | <|body_start_0|>
def filter_max_length(x, y, max_length=max_len):
"""
filter method
"""
return tf.logical_and(tf.size(x) <= max_length, tf.size(y) <= max_length)
examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, ... | Class Dataset | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Class Dataset"""
def __init__(self, batch_size, max_len):
"""* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded ... | stack_v2_sparse_classes_36k_train_023565 | 4,590 | no_license | [
{
"docstring": "* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided * tokenizer_pt is the Portuguese tokenizer created from the training se... | 4 | null | Implement the Python class `Dataset` described below.
Class description:
Class Dataset
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): * data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_t... | Implement the Python class `Dataset` described below.
Class description:
Class Dataset
Method signatures and docstrings:
- def __init__(self, batch_size, max_len): * data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_t... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class Dataset:
"""Class Dataset"""
def __init__(self, batch_size, max_len):
"""* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Class Dataset"""
def __init__(self, batch_size, max_len):
"""* data_train, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided * data_valid, which contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/3-dataset.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
1b1424a7d1873d5e70c9000ceaa13f1755a8518e | [
"self.public_key = public_key\nself.precision = precision\nself.exponent = exponent\nn_length = math.frexp(self.public_key.n)[1]\nself.offset = n_length // 2\nbit_length = self.offset - RESERVED_BIT\nself._n = 1 << bit_length\nself.max_int = self._n // 2 - 1",
"assert len(grad) == len(hess), 'the length of grad a... | <|body_start_0|>
self.public_key = public_key
self.precision = precision
self.exponent = exponent
n_length = math.frexp(self.public_key.n)[1]
self.offset = n_length // 2
bit_length = self.offset - RESERVED_BIT
self._n = 1 << bit_length
self.max_int = self.... | Pack the Plaintext of Grad and Hess Attributes: public_key: public_key private_key: private_key precision: precision for fixed_point_number exponent: exponent for fixed_point_number offset: the offset position to place grad plaintext _n: the modulo when scalar is negative max_int: the maximum of plaintext absolute valu... | GradHessPacker | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradHessPacker:
"""Pack the Plaintext of Grad and Hess Attributes: public_key: public_key private_key: private_key precision: precision for fixed_point_number exponent: exponent for fixed_point_number offset: the offset position to place grad plaintext _n: the modulo when scalar is negative max_i... | stack_v2_sparse_classes_36k_train_023566 | 4,561 | permissive | [
{
"docstring": "Init GradHessPakcer",
"name": "__init__",
"signature": "def __init__(self, public_key, precision, exponent)"
},
{
"docstring": "Pack Grad and Hess into Plaintext Args: grad: list of grad value hess: list of hess value output: output ciphertext or encrypted number Returns: Plainte... | 4 | null | Implement the Python class `GradHessPacker` described below.
Class description:
Pack the Plaintext of Grad and Hess Attributes: public_key: public_key private_key: private_key precision: precision for fixed_point_number exponent: exponent for fixed_point_number offset: the offset position to place grad plaintext _n: t... | Implement the Python class `GradHessPacker` described below.
Class description:
Pack the Plaintext of Grad and Hess Attributes: public_key: public_key private_key: private_key precision: precision for fixed_point_number exponent: exponent for fixed_point_number offset: the offset position to place grad plaintext _n: t... | 436e4959952c970917ee8f47b920f0a76cd4dd05 | <|skeleton|>
class GradHessPacker:
"""Pack the Plaintext of Grad and Hess Attributes: public_key: public_key private_key: private_key precision: precision for fixed_point_number exponent: exponent for fixed_point_number offset: the offset position to place grad plaintext _n: the modulo when scalar is negative max_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradHessPacker:
"""Pack the Plaintext of Grad and Hess Attributes: public_key: public_key private_key: private_key precision: precision for fixed_point_number exponent: exponent for fixed_point_number offset: the offset position to place grad plaintext _n: the modulo when scalar is negative max_int: the maxim... | the_stack_v2_python_sparse | fedlearner/model/tree/packing.py | bytedance/fedlearner | train | 893 |
e7337b6e9dd27871838fb0bbd4b022abd2804d1c | [
"self.model_conf = model_conf\nself.inputs = inputs\nself.utils = utils\nself.layer = None",
"with tf.keras.backend.name_scope('BiLSTM'):\n mask = tf.keras.layers.Masking()(self.inputs)\n self.layer = tf.keras.layers.Bidirectional(layer=tf.keras.layers.LSTM(units=self.model_conf.units_num, return_sequences=... | <|body_start_0|>
self.model_conf = model_conf
self.inputs = inputs
self.utils = utils
self.layer = None
<|end_body_0|>
<|body_start_1|>
with tf.keras.backend.name_scope('BiLSTM'):
mask = tf.keras.layers.Masking()(self.inputs)
self.layer = tf.keras.layers.... | BiLSTM | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLSTM:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
"""同上"""
<|body_0|>
def build(self):
"""同上"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.model_conf = model_conf
self.inputs = inputs
... | stack_v2_sparse_classes_36k_train_023567 | 3,290 | permissive | [
{
"docstring": "同上",
"name": "__init__",
"signature": "def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils)"
},
{
"docstring": "同上",
"name": "build",
"signature": "def build(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019433 | Implement the Python class `BiLSTM` described below.
Class description:
Implement the BiLSTM class.
Method signatures and docstrings:
- def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): 同上
- def build(self): 同上 | Implement the Python class `BiLSTM` described below.
Class description:
Implement the BiLSTM class.
Method signatures and docstrings:
- def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): 同上
- def build(self): 同上
<|skeleton|>
class BiLSTM:
def __init__(self, model_conf: ModelCon... | 6fd35c0c789aaa43130de46d4c04622ec2948052 | <|skeleton|>
class BiLSTM:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
"""同上"""
<|body_0|>
def build(self):
"""同上"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiLSTM:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
"""同上"""
self.model_conf = model_conf
self.inputs = inputs
self.utils = utils
self.layer = None
def build(self):
"""同上"""
with tf.keras.backend.name_scope('... | the_stack_v2_python_sparse | network/LSTM.py | kerlomz/captcha_trainer | train | 2,977 | |
71b8a1725d73fe06ceec569f0831f69a84ca147d | [
"LogTool.info('----------请求开始----------')\nif request is None:\n LogTool.error('前端未发送request!')\n return ResponseTool.get_json_ret(CommRes(ErrorCode.REQ_IS_NONE))\nLogTool.info(f'url:【{request.path}】 model:【{request.method}】')\nif request.path not in ConfigTool.get_list('ignore', 'IGNORE_URL'):\n if reques... | <|body_start_0|>
LogTool.info('----------请求开始----------')
if request is None:
LogTool.error('前端未发送request!')
return ResponseTool.get_json_ret(CommRes(ErrorCode.REQ_IS_NONE))
LogTool.info(f'url:【{request.path}】 model:【{request.method}】')
if request.path not in Conf... | RequestTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestTool:
def handle_request():
"""预处理request :return:"""
<|body_0|>
def get_request_page(request):
"""获取分页信息 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
LogTool.info('----------请求开始----------')
if request is ... | stack_v2_sparse_classes_36k_train_023568 | 2,253 | no_license | [
{
"docstring": "预处理request :return:",
"name": "handle_request",
"signature": "def handle_request()"
},
{
"docstring": "获取分页信息 :param request: :return:",
"name": "get_request_page",
"signature": "def get_request_page(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009273 | Implement the Python class `RequestTool` described below.
Class description:
Implement the RequestTool class.
Method signatures and docstrings:
- def handle_request(): 预处理request :return:
- def get_request_page(request): 获取分页信息 :param request: :return: | Implement the Python class `RequestTool` described below.
Class description:
Implement the RequestTool class.
Method signatures and docstrings:
- def handle_request(): 预处理request :return:
- def get_request_page(request): 获取分页信息 :param request: :return:
<|skeleton|>
class RequestTool:
def handle_request():
... | 4bb0ab793c119153e9ee476274d8908c23e33a30 | <|skeleton|>
class RequestTool:
def handle_request():
"""预处理request :return:"""
<|body_0|>
def get_request_page(request):
"""获取分页信息 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestTool:
def handle_request():
"""预处理request :return:"""
LogTool.info('----------请求开始----------')
if request is None:
LogTool.error('前端未发送request!')
return ResponseTool.get_json_ret(CommRes(ErrorCode.REQ_IS_NONE))
LogTool.info(f'url:【{request.path}】 ... | the_stack_v2_python_sparse | python_wheel/lbj_flask/lbj_flask/request_tool.py | libaojie/python_package | train | 0 | |
bf19325112f6e33a520bc5e8f102caa1a172a423 | [
"app = current_application\nproject = biz.create_project(app, request.get_json())\nreturn (project, 201)",
"app = current_application\nprojects = biz.batch_create_projects(app, request.get_json())\nreturn (projects, 201)",
"app = current_application\nbiz.batch_update_projects(app, request.get_json())\nreturn (N... | <|body_start_0|>
app = current_application
project = biz.create_project(app, request.get_json())
return (project, 201)
<|end_body_0|>
<|body_start_1|>
app = current_application
projects = biz.batch_create_projects(app, request.get_json())
return (projects, 201)
<|end_bod... | 项目相关 | ProjectCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectCollection:
"""项目相关"""
def post(self):
"""创建项目"""
<|body_0|>
def put(self):
"""批量创建项目"""
<|body_1|>
def patch(self):
"""批量更新项目信息: owner, customers, leader, meta_data, scope_labels, class_labels"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_023569 | 6,400 | no_license | [
{
"docstring": "创建项目",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "批量创建项目",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "批量更新项目信息: owner, customers, leader, meta_data, scope_labels, class_labels",
"name": "patch",
"signature": "def p... | 3 | stack_v2_sparse_classes_30k_train_007121 | Implement the Python class `ProjectCollection` described below.
Class description:
项目相关
Method signatures and docstrings:
- def post(self): 创建项目
- def put(self): 批量创建项目
- def patch(self): 批量更新项目信息: owner, customers, leader, meta_data, scope_labels, class_labels | Implement the Python class `ProjectCollection` described below.
Class description:
项目相关
Method signatures and docstrings:
- def post(self): 创建项目
- def put(self): 批量创建项目
- def patch(self): 批量更新项目信息: owner, customers, leader, meta_data, scope_labels, class_labels
<|skeleton|>
class ProjectCollection:
"""项目相关"""
... | 37efe7819d5df5d0ebd4bdf9d0072a6848813d18 | <|skeleton|>
class ProjectCollection:
"""项目相关"""
def post(self):
"""创建项目"""
<|body_0|>
def put(self):
"""批量创建项目"""
<|body_1|>
def patch(self):
"""批量更新项目信息: owner, customers, leader, meta_data, scope_labels, class_labels"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectCollection:
"""项目相关"""
def post(self):
"""创建项目"""
app = current_application
project = biz.create_project(app, request.get_json())
return (project, 201)
def put(self):
"""批量创建项目"""
app = current_application
projects = biz.batch_create_pro... | the_stack_v2_python_sparse | src/app/apis/namespaces/app/project_resources.py | webee/customer-service-api | train | 0 |
be7342d4d522fe53a2f90341b2dbc94c9739f4c6 | [
"current_directory = os.path.dirname(os.path.abspath(__file__))\ntest_access_file = os.path.join(current_directory, 'TestData.json')\nwith open(test_access_file, 'r') as f:\n cls._data = json.load(f)\ncls._hostname = cls._data['organizations']['name']",
"user_rest_v1_failure = self._data['systemusers']['user_r... | <|body_start_0|>
current_directory = os.path.dirname(os.path.abspath(__file__))
test_access_file = os.path.join(current_directory, 'TestData.json')
with open(test_access_file, 'r') as f:
cls._data = json.load(f)
cls._hostname = cls._data['organizations']['name']
<|end_body_0|... | Test the Access module. | TestAccess | [
"GPL-3.0-only",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAccess:
"""Test the Access module."""
def setUpClass(cls):
"""Prepare test class. Get the Test Data from JSON (JavaScript Object Notation) file."""
<|body_0|>
def test_login_rest_v1_failure(self):
"""Test a failure of REST (REpresentational State Transfer) lo... | stack_v2_sparse_classes_36k_train_023570 | 2,569 | permissive | [
{
"docstring": "Prepare test class. Get the Test Data from JSON (JavaScript Object Notation) file.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Test a failure of REST (REpresentational State Transfer) login method. Get the failure username and password (user_rest... | 3 | stack_v2_sparse_classes_30k_train_001341 | Implement the Python class `TestAccess` described below.
Class description:
Test the Access module.
Method signatures and docstrings:
- def setUpClass(cls): Prepare test class. Get the Test Data from JSON (JavaScript Object Notation) file.
- def test_login_rest_v1_failure(self): Test a failure of REST (REpresentation... | Implement the Python class `TestAccess` described below.
Class description:
Test the Access module.
Method signatures and docstrings:
- def setUpClass(cls): Prepare test class. Get the Test Data from JSON (JavaScript Object Notation) file.
- def test_login_rest_v1_failure(self): Test a failure of REST (REpresentation... | 15d00019d496a2a401961e66e3fbb3876a9c6c9d | <|skeleton|>
class TestAccess:
"""Test the Access module."""
def setUpClass(cls):
"""Prepare test class. Get the Test Data from JSON (JavaScript Object Notation) file."""
<|body_0|>
def test_login_rest_v1_failure(self):
"""Test a failure of REST (REpresentational State Transfer) lo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAccess:
"""Test the Access module."""
def setUpClass(cls):
"""Prepare test class. Get the Test Data from JSON (JavaScript Object Notation) file."""
current_directory = os.path.dirname(os.path.abspath(__file__))
test_access_file = os.path.join(current_directory, 'TestData.json'... | the_stack_v2_python_sparse | projects/Python-D365API/D365API/TestAccess.py | rakasiwisurya/CodeWithFriends-Spring2020 | train | 1 |
54355bce51fe8b3075b380820570c5a6d6ce38fe | [
"self.seq_indexer = defaultdict(set)\nself.seq_store = list()\nself.seq2words = defaultdict(set)",
"self.seq_store.append(sequence)\nseq_index = len(self.seq_store) - 1\nfor i in range(len(sequence) - 2):\n word = sequence[i:i + 3]\n self.seq_indexer[word].add(seq_index)\n self.seq2words[sequence].add(wo... | <|body_start_0|>
self.seq_indexer = defaultdict(set)
self.seq_store = list()
self.seq2words = defaultdict(set)
<|end_body_0|>
<|body_start_1|>
self.seq_store.append(sequence)
seq_index = len(self.seq_store) - 1
for i in range(len(sequence) - 2):
word = sequen... | BlastDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlastDB:
def __init__(self):
"""Initialize the BlastDB class."""
<|body_0|>
def add_sequence(self, sequence):
"""Add a sequence to the database. :param sequence: a protein sequence (string)."""
<|body_1|>
def get_sequences(self, word):
"""Return ... | stack_v2_sparse_classes_36k_train_023571 | 21,782 | no_license | [
{
"docstring": "Initialize the BlastDB class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add a sequence to the database. :param sequence: a protein sequence (string).",
"name": "add_sequence",
"signature": "def add_sequence(self, sequence)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_014872 | Implement the Python class `BlastDB` described below.
Class description:
Implement the BlastDB class.
Method signatures and docstrings:
- def __init__(self): Initialize the BlastDB class.
- def add_sequence(self, sequence): Add a sequence to the database. :param sequence: a protein sequence (string).
- def get_sequen... | Implement the Python class `BlastDB` described below.
Class description:
Implement the BlastDB class.
Method signatures and docstrings:
- def __init__(self): Initialize the BlastDB class.
- def add_sequence(self, sequence): Add a sequence to the database. :param sequence: a protein sequence (string).
- def get_sequen... | be1e90c25c641d353fa8f3d16475fdb05d00f1d4 | <|skeleton|>
class BlastDB:
def __init__(self):
"""Initialize the BlastDB class."""
<|body_0|>
def add_sequence(self, sequence):
"""Add a sequence to the database. :param sequence: a protein sequence (string)."""
<|body_1|>
def get_sequences(self, word):
"""Return ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlastDB:
def __init__(self):
"""Initialize the BlastDB class."""
self.seq_indexer = defaultdict(set)
self.seq_store = list()
self.seq2words = defaultdict(set)
def add_sequence(self, sequence):
"""Add a sequence to the database. :param sequence: a protein sequence (... | the_stack_v2_python_sparse | pp1cs2020exercise5-ga24yek/blast.py | anhmt90/tum--ss20--protein-prediction-1-for-cs | train | 0 | |
7f3289c0bba4a73d47266163c1f442a656bbe54b | [
"resources = []\npermissions_boundary = kwargs.get('permissions_boundary')\npassthrough_resource_attributes = resource.get_passthrough_resource_attributes()\nevents_rule = EventsRule(self.logical_id, attributes=passthrough_resource_attributes)\nevents_rule.EventBusName = self.EventBusName\nevents_rule.EventPattern ... | <|body_start_0|>
resources = []
permissions_boundary = kwargs.get('permissions_boundary')
passthrough_resource_attributes = resource.get_passthrough_resource_attributes()
events_rule = EventsRule(self.logical_id, attributes=passthrough_resource_attributes)
events_rule.EventBusNam... | CloudWatch Events/EventBridge event source for SAM State Machine. | CloudWatchEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudWatchEvent:
"""CloudWatch Events/EventBridge event source for SAM State Machine."""
def to_cloudformation(self, resource, **kwargs):
"""Returns the CloudWatch Events/EventBridge Rule and IAM Role to which this CloudWatch Events/EventBridge event source corresponds. :param dict k... | stack_v2_sparse_classes_36k_train_023572 | 19,670 | permissive | [
{
"docstring": "Returns the CloudWatch Events/EventBridge Rule and IAM Role to which this CloudWatch Events/EventBridge event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this CloudWatch Events/EventBridge event ... | 2 | stack_v2_sparse_classes_30k_train_000510 | Implement the Python class `CloudWatchEvent` described below.
Class description:
CloudWatch Events/EventBridge event source for SAM State Machine.
Method signatures and docstrings:
- def to_cloudformation(self, resource, **kwargs): Returns the CloudWatch Events/EventBridge Rule and IAM Role to which this CloudWatch E... | Implement the Python class `CloudWatchEvent` described below.
Class description:
CloudWatch Events/EventBridge event source for SAM State Machine.
Method signatures and docstrings:
- def to_cloudformation(self, resource, **kwargs): Returns the CloudWatch Events/EventBridge Rule and IAM Role to which this CloudWatch E... | 1af3e97b2043369087729cc3849934f8cf838b7e | <|skeleton|>
class CloudWatchEvent:
"""CloudWatch Events/EventBridge event source for SAM State Machine."""
def to_cloudformation(self, resource, **kwargs):
"""Returns the CloudWatch Events/EventBridge Rule and IAM Role to which this CloudWatch Events/EventBridge event source corresponds. :param dict k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudWatchEvent:
"""CloudWatch Events/EventBridge event source for SAM State Machine."""
def to_cloudformation(self, resource, **kwargs):
"""Returns the CloudWatch Events/EventBridge Rule and IAM Role to which this CloudWatch Events/EventBridge event source corresponds. :param dict kwargs: no exi... | the_stack_v2_python_sparse | samtranslator/model/stepfunctions/events.py | jfuss/serverless-application-model | train | 2 |
3d63b5d5b5844ef5d07dac492f2a50d63d7422e5 | [
"if not root:\n return 0\nreturn self.get_node_num(root.left) + self.get_node_num(root.right) + 1",
"left_num = self.get_node_num(root.left)\nif k <= left_num:\n return self.kthSmallest(root.left, k)\nelif k == left_num + 1:\n return root.val\nelse:\n return self.kthSmallest(root.right, k - left_num -... | <|body_start_0|>
if not root:
return 0
return self.get_node_num(root.left) + self.get_node_num(root.right) + 1
<|end_body_0|>
<|body_start_1|>
left_num = self.get_node_num(root.left)
if k <= left_num:
return self.kthSmallest(root.left, k)
elif k == left_n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_node_num(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def kthSmallest(self, root, k):
"""The main idea is binary search. :type root: TreeNode :type k: int :rtype: int"""
<|body_1|>
def kthSmallest(self, root, k):
... | stack_v2_sparse_classes_36k_train_023573 | 1,991 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "get_node_num",
"signature": "def get_node_num(self, root)"
},
{
"docstring": "The main idea is binary search. :type root: TreeNode :type k: int :rtype: int",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root, k)"
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_node_num(self, root): :type root: TreeNode :rtype: int
- def kthSmallest(self, root, k): The main idea is binary search. :type root: TreeNode :type k: int :rtype: int
- d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_node_num(self, root): :type root: TreeNode :rtype: int
- def kthSmallest(self, root, k): The main idea is binary search. :type root: TreeNode :type k: int :rtype: int
- d... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def get_node_num(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def kthSmallest(self, root, k):
"""The main idea is binary search. :type root: TreeNode :type k: int :rtype: int"""
<|body_1|>
def kthSmallest(self, root, k):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_node_num(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
return self.get_node_num(root.left) + self.get_node_num(root.right) + 1
def kthSmallest(self, root, k):
"""The main idea is binary search. :type root: TreeNode ... | the_stack_v2_python_sparse | python_solution/BinarySearch/230_KthSmallestElementInABST.py | Dimen61/leetcode | train | 4 | |
9c072994be86a7e797221d3485afc8a76996e7ab | [
"self.a = a\nself.b = b\nself.c = c\nself.deltaMatrix = delta",
"x, y, z = args\nif self.deltaMatrix:\n matrix = [[self.a * (y - x), self.r * x - y - x * z, x * y - self.b * z], [-self.a * xx + self.a * xy, -self.a * yx + self.a * yy, -self.a * zx + self.a * zy], [xx * (self.r - z) - xy - x * xz, yx * (self.r ... | <|body_start_0|>
self.a = a
self.b = b
self.c = c
self.deltaMatrix = delta
<|end_body_0|>
<|body_start_1|>
x, y, z = args
if self.deltaMatrix:
matrix = [[self.a * (y - x), self.r * x - y - x * z, x * y - self.b * z], [-self.a * xx + self.a * xy, -self.a * yx ... | The Rossler system. Members: - ``a``, ``b``, ``c`` Parameters of the system - ``deltaMatrix`` | Rossler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rossler:
"""The Rossler system. Members: - ``a``, ``b``, ``c`` Parameters of the system - ``deltaMatrix``"""
def __init__(self, a, b, c, delta=False):
"""Create a Rossler object. Arguments: - ``a``, ``b``, ``c`` Parameters of the system - ``delta``"""
<|body_0|>
def __ca... | stack_v2_sparse_classes_36k_train_023574 | 3,011 | no_license | [
{
"docstring": "Create a Rossler object. Arguments: - ``a``, ``b``, ``c`` Parameters of the system - ``delta``",
"name": "__init__",
"signature": "def __init__(self, a, b, c, delta=False)"
},
{
"docstring": "Calculate a value in the system. Arguments: - ``args`` A list or tuple of 3 values - ``t... | 2 | null | Implement the Python class `Rossler` described below.
Class description:
The Rossler system. Members: - ``a``, ``b``, ``c`` Parameters of the system - ``deltaMatrix``
Method signatures and docstrings:
- def __init__(self, a, b, c, delta=False): Create a Rossler object. Arguments: - ``a``, ``b``, ``c`` Parameters of t... | Implement the Python class `Rossler` described below.
Class description:
The Rossler system. Members: - ``a``, ``b``, ``c`` Parameters of the system - ``deltaMatrix``
Method signatures and docstrings:
- def __init__(self, a, b, c, delta=False): Create a Rossler object. Arguments: - ``a``, ``b``, ``c`` Parameters of t... | 1f9099d40cc638d681eebbc85c0b8455dab21607 | <|skeleton|>
class Rossler:
"""The Rossler system. Members: - ``a``, ``b``, ``c`` Parameters of the system - ``deltaMatrix``"""
def __init__(self, a, b, c, delta=False):
"""Create a Rossler object. Arguments: - ``a``, ``b``, ``c`` Parameters of the system - ``delta``"""
<|body_0|>
def __ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rossler:
"""The Rossler system. Members: - ``a``, ``b``, ``c`` Parameters of the system - ``deltaMatrix``"""
def __init__(self, a, b, c, delta=False):
"""Create a Rossler object. Arguments: - ``a``, ``b``, ``c`` Parameters of the system - ``delta``"""
self.a = a
self.b = b
... | the_stack_v2_python_sparse | motion/py/Dance/Systems.py | qixiaobo/navi-misc | train | 0 |
2a011e14734a9bb742faf657d1b2d6b629697d31 | [
"n = len(nums)\nif val not in nums:\n return n\nleft, right = (0, 0)\nwhile left < n - 1 and right < n:\n if nums[left] != val:\n left += 1\n continue\n if right == 0:\n right = left + 1\n if nums[right] == val:\n right += 1\n continue\n nums[left], nums[right] = (n... | <|body_start_0|>
n = len(nums)
if val not in nums:
return n
left, right = (0, 0)
while left < n - 1 and right < n:
if nums[left] != val:
left += 1
continue
if right == 0:
right = left + 1
if n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_0|>
def removeElement2(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
if val not in nums:
... | stack_v2_sparse_classes_36k_train_023575 | 3,564 | no_license | [
{
"docstring": "双指针。",
"name": "removeElement",
"signature": "def removeElement(self, nums: List[int], val: int) -> int"
},
{
"docstring": "双指针。",
"name": "removeElement2",
"signature": "def removeElement2(self, nums: List[int], val: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_009445 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums: List[int], val: int) -> int: 双指针。
- def removeElement2(self, nums: List[int], val: int) -> int: 双指针。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums: List[int], val: int) -> int: 双指针。
- def removeElement2(self, nums: List[int], val: int) -> int: 双指针。
<|skeleton|>
class Solution:
def removeEl... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_0|>
def removeElement2(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""双指针。"""
n = len(nums)
if val not in nums:
return n
left, right = (0, 0)
while left < n - 1 and right < n:
if nums[left] != val:
left += 1
cont... | the_stack_v2_python_sparse | 0027_remove-element.py | Nigirimeshi/leetcode | train | 0 | |
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([vit_layer.attention.attention.query.weight, vit_layer.attention.attention.key.weight, vit_layer.attention.attention.value.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([vit_layer.attention.attention.query.bias, vit_layer.attention.atte... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([vit_layer.attention.attention.query.weight, vit_layer.attention.attention.key.weight, vit_layer.attention.attention.value.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([vit_layer.attention.attention.qu... | ViTLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViTLayerBetterTransformer:
def __init__(self, vit_layer, config):
"""A simple conversion of the ViTLayer to its `BetterTransformer` implementation. Args: vit_layer (`torch.nn.Module`): The original `ViTLayer` where the weights needs to be retrieved."""
<|body_0|>
def forward... | stack_v2_sparse_classes_36k_train_023576 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the ViTLayer to its `BetterTransformer` implementation. Args: vit_layer (`torch.nn.Module`): The original `ViTLayer` where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, vit_layer, config)"
},
{
"docstring": "This ... | 2 | stack_v2_sparse_classes_30k_train_015952 | Implement the Python class `ViTLayerBetterTransformer` described below.
Class description:
Implement the ViTLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, vit_layer, config): A simple conversion of the ViTLayer to its `BetterTransformer` implementation. Args: vit_layer (`torch.nn... | Implement the Python class `ViTLayerBetterTransformer` described below.
Class description:
Implement the ViTLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, vit_layer, config): A simple conversion of the ViTLayer to its `BetterTransformer` implementation. Args: vit_layer (`torch.nn... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ViTLayerBetterTransformer:
def __init__(self, vit_layer, config):
"""A simple conversion of the ViTLayer to its `BetterTransformer` implementation. Args: vit_layer (`torch.nn.Module`): The original `ViTLayer` where the weights needs to be retrieved."""
<|body_0|>
def forward... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViTLayerBetterTransformer:
def __init__(self, vit_layer, config):
"""A simple conversion of the ViTLayer to its `BetterTransformer` implementation. Args: vit_layer (`torch.nn.Module`): The original `ViTLayer` where the weights needs to be retrieved."""
super().__init__(config)
self.in_... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
7897cbb9f32b5ec64a5b8163ce36a3c6a583d770 | [
"try:\n self.dataUtil = dataModel()\n if open is True:\n self.hive_db = HiveData()\n self.mysql_db = MySQLData()\n self.hbase_db = HBaseData()\nexcept Exception:\n print('%s 数据库连接异常: %s' % (datetime.datetime.now(), traceback.format_exc()))\n sys.exit()",
"if use_table == 'ods_lin... | <|body_start_0|>
try:
self.dataUtil = dataModel()
if open is True:
self.hive_db = HiveData()
self.mysql_db = MySQLData()
self.hbase_db = HBaseData()
except Exception:
print('%s 数据库连接异常: %s' % (datetime.datetime.now(), t... | 工务数据导入 | Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""工务数据导入"""
def __init__(self, open=True):
"""初始化连接 :param open: 是否连接数据库"""
<|body_0|>
def runTrainLineWorkData(self, line_name, direction, use_table, final_hbase_tabName):
"""执行工务数据导入程序 :param line_name: 线路名称 :param direction: 行别 :param use_table: 工务数据表 ... | stack_v2_sparse_classes_36k_train_023577 | 3,638 | no_license | [
{
"docstring": "初始化连接 :param open: 是否连接数据库",
"name": "__init__",
"signature": "def __init__(self, open=True)"
},
{
"docstring": "执行工务数据导入程序 :param line_name: 线路名称 :param direction: 行别 :param use_table: 工务数据表 :param final_hbase_tabName: 数据导入的hbase表名 :return:",
"name": "runTrainLineWorkData",
... | 2 | stack_v2_sparse_classes_30k_train_009949 | Implement the Python class `Model` described below.
Class description:
工务数据导入
Method signatures and docstrings:
- def __init__(self, open=True): 初始化连接 :param open: 是否连接数据库
- def runTrainLineWorkData(self, line_name, direction, use_table, final_hbase_tabName): 执行工务数据导入程序 :param line_name: 线路名称 :param direction: 行别 :pa... | Implement the Python class `Model` described below.
Class description:
工务数据导入
Method signatures and docstrings:
- def __init__(self, open=True): 初始化连接 :param open: 是否连接数据库
- def runTrainLineWorkData(self, line_name, direction, use_table, final_hbase_tabName): 执行工务数据导入程序 :param line_name: 线路名称 :param direction: 行别 :pa... | 2d804420cea49148dbecb5cf6ff0774c24c3d7e6 | <|skeleton|>
class Model:
"""工务数据导入"""
def __init__(self, open=True):
"""初始化连接 :param open: 是否连接数据库"""
<|body_0|>
def runTrainLineWorkData(self, line_name, direction, use_table, final_hbase_tabName):
"""执行工务数据导入程序 :param line_name: 线路名称 :param direction: 行别 :param use_table: 工务数据表 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
"""工务数据导入"""
def __init__(self, open=True):
"""初始化连接 :param open: 是否连接数据库"""
try:
self.dataUtil = dataModel()
if open is True:
self.hive_db = HiveData()
self.mysql_db = MySQLData()
self.hbase_db = HBaseData()
... | the_stack_v2_python_sparse | MellivoraCapensis_王一淋的/train_line/LineLocationWorkDataProcessClass.py | star860/work_warehouse | train | 0 |
0a4b120ee42abefee06c448bd9402eb173f69b6a | [
"future = sorted(zip(Capital, Profits))[::-1]\ncurrent = []\nwhile k > 0:\n while future and future[-1][0] <= W:\n heappush(current, -future.pop()[1])\n if not current:\n break\n W -= heappop(current)\n k -= 1\nreturn W",
"t = sorted(zip(map(lambda x: -x, Profits), Capital), key=lambda x... | <|body_start_0|>
future = sorted(zip(Capital, Profits))[::-1]
current = []
while k > 0:
while future and future[-1][0] <= W:
heappush(current, -future.pop()[1])
if not current:
break
W -= heappop(current)
k -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaximizedCapital_OJBest(self, k, W, Profits, Capital):
""":type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int"""
<|body_0|>
def findMaximizedCapital(self, k, W, Profits, Capital):
""":type k: int :type W: int :typ... | stack_v2_sparse_classes_36k_train_023578 | 3,716 | no_license | [
{
"docstring": ":type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int",
"name": "findMaximizedCapital_OJBest",
"signature": "def findMaximizedCapital_OJBest(self, k, W, Profits, Capital)"
},
{
"docstring": ":type k: int :type W: int :type Profits: List[int] :typ... | 2 | stack_v2_sparse_classes_30k_train_005328 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximizedCapital_OJBest(self, k, W, Profits, Capital): :type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int
- def findMaximizedCapital(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaximizedCapital_OJBest(self, k, W, Profits, Capital): :type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int
- def findMaximizedCapital(... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def findMaximizedCapital_OJBest(self, k, W, Profits, Capital):
""":type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int"""
<|body_0|>
def findMaximizedCapital(self, k, W, Profits, Capital):
""":type k: int :type W: int :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaximizedCapital_OJBest(self, k, W, Profits, Capital):
""":type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int"""
future = sorted(zip(Capital, Profits))[::-1]
current = []
while k > 0:
while future and future[-1][... | the_stack_v2_python_sparse | code502IPO.py | cybelewang/leetcode-python | train | 0 | |
6c430eafa9e0a5e6493c7a0c725e43cfb199fed9 | [
"if G.Env.save_transformed_metrics:\n self.evaluate('oof', self.data_oof.target.T.fold, self.data_oof.prediction.T.run)\nelse:\n self.evaluate('oof', self.data_oof.target.fold, self.data_oof.prediction.run)\nsuper().on_run_end()",
"if G.Env.save_transformed_metrics:\n self.evaluate('oof', self.data_oof.t... | <|body_start_0|>
if G.Env.save_transformed_metrics:
self.evaluate('oof', self.data_oof.target.T.fold, self.data_oof.prediction.T.run)
else:
self.evaluate('oof', self.data_oof.target.fold, self.data_oof.prediction.run)
super().on_run_end()
<|end_body_0|>
<|body_start_1|>
... | EvaluatorOOF | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluatorOOF:
def on_run_end(self):
"""Evaluate out-of-fold predictions for the run"""
<|body_0|>
def on_fold_end(self):
"""Evaluate (run-averaged) out-of-fold predictions for the fold"""
<|body_1|>
def on_rep_end(self):
"""Evaluate (run-averaged... | stack_v2_sparse_classes_36k_train_023579 | 5,856 | permissive | [
{
"docstring": "Evaluate out-of-fold predictions for the run",
"name": "on_run_end",
"signature": "def on_run_end(self)"
},
{
"docstring": "Evaluate (run-averaged) out-of-fold predictions for the fold",
"name": "on_fold_end",
"signature": "def on_fold_end(self)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_val_000079 | Implement the Python class `EvaluatorOOF` described below.
Class description:
Implement the EvaluatorOOF class.
Method signatures and docstrings:
- def on_run_end(self): Evaluate out-of-fold predictions for the run
- def on_fold_end(self): Evaluate (run-averaged) out-of-fold predictions for the fold
- def on_rep_end(... | Implement the Python class `EvaluatorOOF` described below.
Class description:
Implement the EvaluatorOOF class.
Method signatures and docstrings:
- def on_run_end(self): Evaluate out-of-fold predictions for the run
- def on_fold_end(self): Evaluate (run-averaged) out-of-fold predictions for the fold
- def on_rep_end(... | 3709d5e97dd23efa0df1b79982ae029789e1af57 | <|skeleton|>
class EvaluatorOOF:
def on_run_end(self):
"""Evaluate out-of-fold predictions for the run"""
<|body_0|>
def on_fold_end(self):
"""Evaluate (run-averaged) out-of-fold predictions for the fold"""
<|body_1|>
def on_rep_end(self):
"""Evaluate (run-averaged... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluatorOOF:
def on_run_end(self):
"""Evaluate out-of-fold predictions for the run"""
if G.Env.save_transformed_metrics:
self.evaluate('oof', self.data_oof.target.T.fold, self.data_oof.prediction.T.run)
else:
self.evaluate('oof', self.data_oof.target.fold, self... | the_stack_v2_python_sparse | hyperparameter_hunter/callbacks/evaluators.py | shaoeric/hyperparameter_hunter | train | 0 | |
1a797dd667f86a6899b30a3d9d3a7fccc264c248 | [
"result = encoding.decode_message(b'\\x00\\x05\\x01\\x02\\x03\\x04')\nself.assertIsInstance(result, list, 'Must be a 2D list rather than %s' % type(result))\nself.assertGreater(len(result), 0, 'Result list contain no items')\naddr, word = result[0]\nself.assertEqual(addr, 5, 'Address not decoded properly: %X' % add... | <|body_start_0|>
result = encoding.decode_message(b'\x00\x05\x01\x02\x03\x04')
self.assertIsInstance(result, list, 'Must be a 2D list rather than %s' % type(result))
self.assertGreater(len(result), 0, 'Result list contain no items')
addr, word = result[0]
self.assertEqual(addr, 5... | TestDecodeMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDecodeMessage:
def test_basic(self):
"""Basic sanity check of the decode_message() function"""
<|body_0|>
def test_multi_response(self):
"""Test decode_message() with a series of addr,word responses..."""
<|body_1|>
def test_response_extra_bytes(self... | stack_v2_sparse_classes_36k_train_023580 | 3,968 | no_license | [
{
"docstring": "Basic sanity check of the decode_message() function",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test decode_message() with a series of addr,word responses...",
"name": "test_multi_response",
"signature": "def test_multi_response(self)"
... | 3 | null | Implement the Python class `TestDecodeMessage` described below.
Class description:
Implement the TestDecodeMessage class.
Method signatures and docstrings:
- def test_basic(self): Basic sanity check of the decode_message() function
- def test_multi_response(self): Test decode_message() with a series of addr,word resp... | Implement the Python class `TestDecodeMessage` described below.
Class description:
Implement the TestDecodeMessage class.
Method signatures and docstrings:
- def test_basic(self): Basic sanity check of the decode_message() function
- def test_multi_response(self): Test decode_message() with a series of addr,word resp... | 134aa85a6ec4b9ea0360784b7bfab6945ae6811a | <|skeleton|>
class TestDecodeMessage:
def test_basic(self):
"""Basic sanity check of the decode_message() function"""
<|body_0|>
def test_multi_response(self):
"""Test decode_message() with a series of addr,word responses..."""
<|body_1|>
def test_response_extra_bytes(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDecodeMessage:
def test_basic(self):
"""Basic sanity check of the decode_message() function"""
result = encoding.decode_message(b'\x00\x05\x01\x02\x03\x04')
self.assertIsInstance(result, list, 'Must be a 2D list rather than %s' % type(result))
self.assertGreater(len(result)... | the_stack_v2_python_sparse | percival_detector/carrier/test_encoding.py | percival-detector/percivalui | train | 0 | |
800a09a773e058cb6f17c4a4bc62468a2708014f | [
"eps = np.finfo(float).eps\nif not eps < scaling_factor < 1 - eps:\n raise ValueError('scaling_factor must be in (0, 1) within machine precision.')\nif len(tolerable_interval) != 2:\n raise ValueError('tolerable_interval must be a tuple of length 2')\nif not 0 <= tolerable_interval[0] < tolerable_interval[1]:... | <|body_start_0|>
eps = np.finfo(float).eps
if not eps < scaling_factor < 1 - eps:
raise ValueError('scaling_factor must be in (0, 1) within machine precision.')
if len(tolerable_interval) != 2:
raise ValueError('tolerable_interval must be a tuple of length 2')
if ... | Scales the lambda of the regularizer by some constant factor. Lambda is scaled up if the ratio of the validation loss to the training loss is above the tolerable interval, and scaled down if the ratio is below the tolerable interval. Nothing happens if the ratio is within the tolerable interval. | IntervalParamScaler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntervalParamScaler:
"""Scales the lambda of the regularizer by some constant factor. Lambda is scaled up if the ratio of the validation loss to the training loss is above the tolerable interval, and scaled down if the ratio is below the tolerable interval. Nothing happens if the ratio is within ... | stack_v2_sparse_classes_36k_train_023581 | 5,483 | permissive | [
{
"docstring": "Initialize the interval parameter scaler. Args: scaling_factor: The factor by which to scale the lambda, a value in (0, 1). tolerable_interval: The interval within which the ratio of the validation loss to the training loss is considered acceptable. A tuple whose first element is at least 0 and ... | 2 | null | Implement the Python class `IntervalParamScaler` described below.
Class description:
Scales the lambda of the regularizer by some constant factor. Lambda is scaled up if the ratio of the validation loss to the training loss is above the tolerable interval, and scaled down if the ratio is below the tolerable interval. ... | Implement the Python class `IntervalParamScaler` described below.
Class description:
Scales the lambda of the regularizer by some constant factor. Lambda is scaled up if the ratio of the validation loss to the training loss is above the tolerable interval, and scaled down if the ratio is below the tolerable interval. ... | 5b0b531bdf6fdfcaab93ff18f454aa1b54bb4355 | <|skeleton|>
class IntervalParamScaler:
"""Scales the lambda of the regularizer by some constant factor. Lambda is scaled up if the ratio of the validation loss to the training loss is above the tolerable interval, and scaled down if the ratio is below the tolerable interval. Nothing happens if the ratio is within ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntervalParamScaler:
"""Scales the lambda of the regularizer by some constant factor. Lambda is scaled up if the ratio of the validation loss to the training loss is above the tolerable interval, and scaled down if the ratio is below the tolerable interval. Nothing happens if the ratio is within the tolerable... | the_stack_v2_python_sparse | src/imitation/regularization/updaters.py | HumanCompatibleAI/imitation | train | 936 |
809dbdaf35c9f1d9c579f7c054c3957ee204aa1e | [
"output = [0] * len(nums)\nfor i in range(len(nums)):\n j = 1\n news = nums[:i] + nums[i + 1:]\n for k in news:\n j *= k\n output[i] = j\nreturn output",
"length = len(nums)\nL, R, answer = ([0] * length, [0] * length, [0] * length)\nL[0] = 1\nfor i in range(1, length):\n L[i] = nums[i - 1] ... | <|body_start_0|>
output = [0] * len(nums)
for i in range(len(nums)):
j = 1
news = nums[:i] + nums[i + 1:]
for k in news:
j *= k
output[i] = j
return output
<|end_body_0|>
<|body_start_1|>
length = len(nums)
L, R, an... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def productExceptSelf_0(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def productExceptSelf_2(self, nums):
""":type nu... | stack_v2_sparse_classes_36k_train_023582 | 3,634 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf_0",
"signature": "def productExceptSelf_0(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "productExceptSelf_1",
"signature": "def productExceptSelf_1(self, nums)"
},
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf_0(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_1(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def productExceptSelf_0(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_1(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSel... | 3f7b2ea959308eb80f4c65be35aaeed666570f80 | <|skeleton|>
class Solution:
def productExceptSelf_0(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def productExceptSelf_1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def productExceptSelf_2(self, nums):
""":type nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def productExceptSelf_0(self, nums):
""":type nums: List[int] :rtype: List[int]"""
output = [0] * len(nums)
for i in range(len(nums)):
j = 1
news = nums[:i] + nums[i + 1:]
for k in news:
j *= k
output[i] = j
... | the_stack_v2_python_sparse | 238. 除自身以外数组的乘积.py | dxc19951001/Everyday_LeetCode | train | 1 | |
8334c2021e2e658e7ecda5c366379f7baa60e6ee | [
"createdLocalSession = False\nif len(ids) == 0:\n return None\nif session == None:\n session = LogSetDao.getSession()\n createdLocalSession = True\nselectedLogSet = None\nrs = session.query(LogSet).filter(LogSet.id in ids)\nlogSets = []\nfor logSet in rs:\n logger.debug('--getLogSet() logSet name: ' + s... | <|body_start_0|>
createdLocalSession = False
if len(ids) == 0:
return None
if session == None:
session = LogSetDao.getSession()
createdLocalSession = True
selectedLogSet = None
rs = session.query(LogSet).filter(LogSet.id in ids)
logSets... | classdocs | LogSetDao | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogSetDao:
"""classdocs"""
def getLogSets(cls, ids, session=None):
"""gets logset of given id from database"""
<|body_0|>
def getLogSet(cls, id, session=None):
"""gets logset of given id from database"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023583 | 2,276 | permissive | [
{
"docstring": "gets logset of given id from database",
"name": "getLogSets",
"signature": "def getLogSets(cls, ids, session=None)"
},
{
"docstring": "gets logset of given id from database",
"name": "getLogSet",
"signature": "def getLogSet(cls, id, session=None)"
}
] | 2 | null | Implement the Python class `LogSetDao` described below.
Class description:
classdocs
Method signatures and docstrings:
- def getLogSets(cls, ids, session=None): gets logset of given id from database
- def getLogSet(cls, id, session=None): gets logset of given id from database | Implement the Python class `LogSetDao` described below.
Class description:
classdocs
Method signatures and docstrings:
- def getLogSets(cls, ids, session=None): gets logset of given id from database
- def getLogSet(cls, id, session=None): gets logset of given id from database
<|skeleton|>
class LogSetDao:
"""cla... | 20fba1b1fd1a42add223d9e8af2d267665bec493 | <|skeleton|>
class LogSetDao:
"""classdocs"""
def getLogSets(cls, ids, session=None):
"""gets logset of given id from database"""
<|body_0|>
def getLogSet(cls, id, session=None):
"""gets logset of given id from database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogSetDao:
"""classdocs"""
def getLogSets(cls, ids, session=None):
"""gets logset of given id from database"""
createdLocalSession = False
if len(ids) == 0:
return None
if session == None:
session = LogSetDao.getSession()
createdLocalSes... | the_stack_v2_python_sparse | db/core/logset/logsetdao.py | ABV-Hub/qreservoir | train | 0 |
02371dc25138fe118ea617a67b428dc90db544d2 | [
"output, stack = ([], [(root, False)])\nwhile stack:\n node, is_visited = stack.pop()\n if not node:\n continue\n if is_visited:\n output.append(node.val)\n else:\n stack.append((node.right, False))\n stack.append((node.left, False))\n stack.append((node, True))\nretur... | <|body_start_0|>
output, stack = ([], [(root, False)])
while stack:
node, is_visited = stack.pop()
if not node:
continue
if is_visited:
output.append(node.val)
else:
stack.append((node.right, False))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal_iterative2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def preorderTraversal_recursive(self, root):
... | stack_v2_sparse_classes_36k_train_023584 | 3,212 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal_iterative2",
"signature": "def preorderTraversal_iterative2(self, ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal_iterative2(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTra... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal_iterative2(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTra... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal_iterative2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def preorderTraversal_recursive(self, root):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
output, stack = ([], [(root, False)])
while stack:
node, is_visited = stack.pop()
if not node:
continue
if is_visited:
output.ap... | the_stack_v2_python_sparse | src/lt_144.py | oxhead/CodingYourWay | train | 0 | |
1fb1a16900058a227a6153d65b24965d0bb68ee6 | [
"if token.start_pos_del is not None and token.end_pos_del is not None:\n position = f'{token.start_pos_del}_{token.end_pos_del}'\nelse:\n position = token.start_pos_del\nif token.inserted_sequence1 is not None and token.inserted_sequence2 is not None:\n sequence = f'{token.inserted_sequence1}_{token.insert... | <|body_start_0|>
if token.start_pos_del is not None and token.end_pos_del is not None:
position = f'{token.start_pos_del}_{token.end_pos_del}'
else:
position = token.start_pos_del
if token.inserted_sequence1 is not None and token.inserted_sequence2 is not None:
... | The DelIns Validator Base class. | DelInsBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelInsBase:
"""The DelIns Validator Base class."""
def concise_description(self, transcript, token) -> str:
"""Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression"""
... | stack_v2_sparse_classes_36k_train_023585 | 1,722 | permissive | [
{
"docstring": "Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression",
"name": "concise_description",
"signature": "def concise_description(self, transcript, token) -> str"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_val_000623 | Implement the Python class `DelInsBase` described below.
Class description:
The DelIns Validator Base class.
Method signatures and docstrings:
- def concise_description(self, transcript, token) -> str: Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token toke... | Implement the Python class `DelInsBase` described below.
Class description:
The DelIns Validator Base class.
Method signatures and docstrings:
- def concise_description(self, transcript, token) -> str: Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token toke... | d41e9ee786b14f47d17ea8e458eed08ec00ba339 | <|skeleton|>
class DelInsBase:
"""The DelIns Validator Base class."""
def concise_description(self, transcript, token) -> str:
"""Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelInsBase:
"""The DelIns Validator Base class."""
def concise_description(self, transcript, token) -> str:
"""Return a HGVS description of the identified variation. :param str transcript: Transcript accession :param Token token: Classification token :return: HGVS expression"""
if token.s... | the_stack_v2_python_sparse | variation/validators/delins_base.py | richardhj/vicc-variation-normalization | train | 0 |
5ba893e3eabf8c8b829b30d5dbc442d913aa700d | [
"parser.add_argument('name', help='The name of the peered DNS domain to create.')\nparser.add_argument('--network', metavar='NETWORK', required=True, help='The network in the consumer project peered with the service.')\nparser.add_argument('--service', metavar='SERVICE', default='servicenetworking.googleapis.com', ... | <|body_start_0|>
parser.add_argument('name', help='The name of the peered DNS domain to create.')
parser.add_argument('--network', metavar='NETWORK', required=True, help='The network in the consumer project peered with the service.')
parser.add_argument('--service', metavar='SERVICE', default='s... | Create a peered DNS domain for a private service connection. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a peered DNS domain for a private service connection."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Position... | stack_v2_sparse_classes_36k_train_023586 | 4,396 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_015280 | Implement the Python class `Create` described below.
Class description:
Create a peered DNS domain for a private service connection.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments... | Implement the Python class `Create` described below.
Class description:
Create a peered DNS domain for a private service connection.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Create a peered DNS domain for a private service connection."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Position... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a peered DNS domain for a private service connection."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments ... | the_stack_v2_python_sparse | lib/surface/services/peered_dns_domains/create.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
8fe7b219fcbea0f0f7e49dfcd0b65f46d55de12c | [
"foo.m_conId = 0\nfoo.m_delta = 0\nfoo.m_price = 0",
"if self is p_other:\n return True\nif p_other is None or not foo(p_other, (UnderComp,)):\n return False\nl_theOther = p_other\nif foo.m_conId != foo.m_conId:\n return False\nif foo.m_delta != foo.m_delta:\n return False\nif foo.m_price != foo.m_pri... | <|body_start_0|>
foo.m_conId = 0
foo.m_delta = 0
foo.m_price = 0
<|end_body_0|>
<|body_start_1|>
if self is p_other:
return True
if p_other is None or not foo(p_other, (UnderComp,)):
return False
l_theOther = p_other
if foo.m_conId != foo.... | generated source for class UnderComp | UnderComp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnderComp:
"""generated source for class UnderComp"""
def __init__(self):
"""generated source for method __init__"""
<|body_0|>
def __eq__(self, p_other):
"""generated source for method equals"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
foo.... | stack_v2_sparse_classes_36k_train_023587 | 1,023 | no_license | [
{
"docstring": "generated source for method __init__",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "generated source for method equals",
"name": "__eq__",
"signature": "def __eq__(self, p_other)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004821 | Implement the Python class `UnderComp` described below.
Class description:
generated source for class UnderComp
Method signatures and docstrings:
- def __init__(self): generated source for method __init__
- def __eq__(self, p_other): generated source for method equals | Implement the Python class `UnderComp` described below.
Class description:
generated source for class UnderComp
Method signatures and docstrings:
- def __init__(self): generated source for method __init__
- def __eq__(self, p_other): generated source for method equals
<|skeleton|>
class UnderComp:
"""generated s... | d4ac77ed1644081e028c791d9b64e9dfebad06e8 | <|skeleton|>
class UnderComp:
"""generated source for class UnderComp"""
def __init__(self):
"""generated source for method __init__"""
<|body_0|>
def __eq__(self, p_other):
"""generated source for method equals"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnderComp:
"""generated source for class UnderComp"""
def __init__(self):
"""generated source for method __init__"""
foo.m_conId = 0
foo.m_delta = 0
foo.m_price = 0
def __eq__(self, p_other):
"""generated source for method equals"""
if self is p_other:... | the_stack_v2_python_sparse | data/output/459_processed | KqSMea8/pythonanalyzer | train | 0 |
91849bd87854fc621ce116483c69ee77ff3bd641 | [
"super().__init__(*args, data=data, **kwargs)\nif not data or not data.get('q', None):\n self.fields['sort'].widget.choices[0] = (self.SORT_CHOICES[0][0], {'label': self.SORT_CHOICES[0][1], 'disabled': True})",
"if self.is_valid():\n return bool({k: v for k, v in self.cleaned_data.items() if k not in ['q', ... | <|body_start_0|>
super().__init__(*args, data=data, **kwargs)
if not data or not data.get('q', None):
self.fields['sort'].widget.choices[0] = (self.SORT_CHOICES[0][0], {'label': self.SORT_CHOICES[0][1], 'disabled': True})
<|end_body_0|>
<|body_start_1|>
if self.is_valid():
... | DocumentSearchForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSearchForm:
def __init__(self, data=None, *args, **kwargs):
"""Override to set choices dynamically based on form kwargs."""
<|body_0|>
def filters_active(self):
"""Check if any filters are active; returns true if form fields other than sort or q are set"""
... | stack_v2_sparse_classes_36k_train_023588 | 15,339 | permissive | [
{
"docstring": "Override to set choices dynamically based on form kwargs.",
"name": "__init__",
"signature": "def __init__(self, data=None, *args, **kwargs)"
},
{
"docstring": "Check if any filters are active; returns true if form fields other than sort or q are set",
"name": "filters_active... | 5 | stack_v2_sparse_classes_30k_val_000774 | Implement the Python class `DocumentSearchForm` described below.
Class description:
Implement the DocumentSearchForm class.
Method signatures and docstrings:
- def __init__(self, data=None, *args, **kwargs): Override to set choices dynamically based on form kwargs.
- def filters_active(self): Check if any filters are... | Implement the Python class `DocumentSearchForm` described below.
Class description:
Implement the DocumentSearchForm class.
Method signatures and docstrings:
- def __init__(self, data=None, *args, **kwargs): Override to set choices dynamically based on form kwargs.
- def filters_active(self): Check if any filters are... | 65660de1a07c3bb3390d0161995f7fe305a5079b | <|skeleton|>
class DocumentSearchForm:
def __init__(self, data=None, *args, **kwargs):
"""Override to set choices dynamically based on form kwargs."""
<|body_0|>
def filters_active(self):
"""Check if any filters are active; returns true if form fields other than sort or q are set"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocumentSearchForm:
def __init__(self, data=None, *args, **kwargs):
"""Override to set choices dynamically based on form kwargs."""
super().__init__(*args, data=data, **kwargs)
if not data or not data.get('q', None):
self.fields['sort'].widget.choices[0] = (self.SORT_CHOICE... | the_stack_v2_python_sparse | geniza/corpus/forms.py | Princeton-CDH/geniza | train | 14 | |
282dd9a8667fbeaecfaaf673bbe729d01e7b2997 | [
"self.tot = 0\nself.size = size\nself.q = []",
"tot, size, q = (self.tot, self.size, self.q)\nq.append(val)\ntot += val\nif len(q) > size:\n tot -= q.pop(0)\nself.tot = tot\nreturn float(tot) / len(q)"
] | <|body_start_0|>
self.tot = 0
self.size = size
self.q = []
<|end_body_0|>
<|body_start_1|>
tot, size, q = (self.tot, self.size, self.q)
q.append(val)
tot += val
if len(q) > size:
tot -= q.pop(0)
self.tot = tot
return float(tot) / len(q... | MovingAverage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.tot = 0
self.size = size... | stack_v2_sparse_classes_36k_train_023589 | 642 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | bc0b01e44e121ea68724da16f25f7e24386c53de | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.tot = 0
self.size = size
self.q = []
def next(self, val):
""":type val: int :rtype: float"""
tot, size, q = (self.tot, self.size, self.q)
q.appe... | the_stack_v2_python_sparse | leetcode/346-Moving-Average-from-Data-Stream/MovingAvgfromDataStream.py | cc13ny/all-in | train | 2 | |
85e764b90d0d77015f4ddbfab16fcd57c1316d08 | [
"if level == None:\n level = self.level\ngrid_spacing = self.grid_spacing[level]\nprob_lo = self.prob_lo\nprob_hi = self.prob_hi\nxy = []\nfor dim in range(self.dimensions):\n xy.append(np.arange(prob_lo[dim], prob_hi[dim] + grid_spacing[dim], grid_spacing[dim]))\nreturn xy",
"if level == None:\n level =... | <|body_start_0|>
if level == None:
level = self.level
grid_spacing = self.grid_spacing[level]
prob_lo = self.prob_lo
prob_hi = self.prob_hi
xy = []
for dim in range(self.dimensions):
xy.append(np.arange(prob_lo[dim], prob_hi[dim] + grid_spacing[dim... | A version of boxlib.PlotFile that can easily make quick plots | PlotFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotFile:
"""A version of boxlib.PlotFile that can easily make quick plots"""
def get_xy_mesh(self, level=None):
"""Return spatial coordinates of zone boundaries"""
<|body_0|>
def plot(self, name, level=None, log=False):
"""Color plot of field with given name at ... | stack_v2_sparse_classes_36k_train_023590 | 3,116 | permissive | [
{
"docstring": "Return spatial coordinates of zone boundaries",
"name": "get_xy_mesh",
"signature": "def get_xy_mesh(self, level=None)"
},
{
"docstring": "Color plot of field with given name at given level",
"name": "plot",
"signature": "def plot(self, name, level=None, log=False)"
},
... | 5 | null | Implement the Python class `PlotFile` described below.
Class description:
A version of boxlib.PlotFile that can easily make quick plots
Method signatures and docstrings:
- def get_xy_mesh(self, level=None): Return spatial coordinates of zone boundaries
- def plot(self, name, level=None, log=False): Color plot of fiel... | Implement the Python class `PlotFile` described below.
Class description:
A version of boxlib.PlotFile that can easily make quick plots
Method signatures and docstrings:
- def get_xy_mesh(self, level=None): Return spatial coordinates of zone boundaries
- def plot(self, name, level=None, log=False): Color plot of fiel... | 98fc181bab054619d12ffa4173ad5c469803c2ec | <|skeleton|>
class PlotFile:
"""A version of boxlib.PlotFile that can easily make quick plots"""
def get_xy_mesh(self, level=None):
"""Return spatial coordinates of zone boundaries"""
<|body_0|>
def plot(self, name, level=None, log=False):
"""Color plot of field with given name at ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlotFile:
"""A version of boxlib.PlotFile that can easily make quick plots"""
def get_xy_mesh(self, level=None):
"""Return spatial coordinates of zone boundaries"""
if level == None:
level = self.level
grid_spacing = self.grid_spacing[level]
prob_lo = self.prob... | the_stack_v2_python_sparse | kepler_python_packages/python_scripts/boxlib/boxplot.py | adam-m-jcbs/xrb-sens-datashare | train | 1 |
de97932b394e3fda4fa7c784466d232c7704a599 | [
"super().__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attention = ScaledDotProductAttention(dropout)\nself.attn = None",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = query.size(0)\nquery, key, value = [l(x)... | <|body_start_0|>
super().__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attention = ScaledDotProductAttention(dropout)
self.attn = None
<|end_body_0|>
<|body_start_1|>
if ma... | Compute 'Multi-Head Attention' When we calculate attentions, usually key and value are the same tensor. For self-attention, query, key, value are all the same tensor. | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Compute 'Multi-Head Attention' When we calculate attentions, usually key and value are the same tensor. For self-attention, query, key, value are all the same tensor."""
def __init__(self, h, d_model, dropout=0.1):
""":param h: number of heads :param d_model: h... | stack_v2_sparse_classes_36k_train_023591 | 38,467 | no_license | [
{
"docstring": ":param h: number of heads :param d_model: hidden size :param dropout: attention dropout rate",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": ":param query: (batch_num, query_length, d_model) :param key: (batch_num, key_length, d_... | 2 | stack_v2_sparse_classes_30k_train_003610 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Compute 'Multi-Head Attention' When we calculate attentions, usually key and value are the same tensor. For self-attention, query, key, value are all the same tensor.
Method signatures and docstrings:
- def __init__(self, h, d_model, ... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Compute 'Multi-Head Attention' When we calculate attentions, usually key and value are the same tensor. For self-attention, query, key, value are all the same tensor.
Method signatures and docstrings:
- def __init__(self, h, d_model, ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MultiHeadAttention:
"""Compute 'Multi-Head Attention' When we calculate attentions, usually key and value are the same tensor. For self-attention, query, key, value are all the same tensor."""
def __init__(self, h, d_model, dropout=0.1):
""":param h: number of heads :param d_model: h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""Compute 'Multi-Head Attention' When we calculate attentions, usually key and value are the same tensor. For self-attention, query, key, value are all the same tensor."""
def __init__(self, h, d_model, dropout=0.1):
""":param h: number of heads :param d_model: hidden size :p... | the_stack_v2_python_sparse | generated/test_BangLiu_QANet_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 |
de67bcd220c0af23080f6c13144b8e65842f434d | [
"super().__init__(mesh_entities, interface_dim)\nif self.mesh_entities.entity_type not in ('nodes', 'edges', 'faces'):\n raise ValueError('Entities must be nodes, edges or faces')",
"all_interface_neighbors = self.mesh_entities.bridge_adjacencies(elements, self.interface_dim, self.target_dim)\nnum_neighbors = ... | <|body_start_0|>
super().__init__(mesh_entities, interface_dim)
if self.mesh_entities.entity_type not in ('nodes', 'edges', 'faces'):
raise ValueError('Entities must be nodes, edges or faces')
<|end_body_0|>
<|body_start_1|>
all_interface_neighbors = self.mesh_entities.bridge_adjace... | Implementation of the 2D MPFA-D entity ordering. | MPFAD2DOrdering | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPFAD2DOrdering:
"""Implementation of the 2D MPFA-D entity ordering."""
def __init__(self, mesh_entities, interface_dim):
"""Constructor"""
<|body_0|>
def sort_elements(self, elements, center):
"""Sort elements according to the MPFA-D ordering. Parameters -------... | stack_v2_sparse_classes_36k_train_023592 | 2,518 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, mesh_entities, interface_dim)"
},
{
"docstring": "Sort elements according to the MPFA-D ordering. Parameters ---------- elements: Numpy array Array containing the indices of the elements to be ordered. from_elemen... | 2 | stack_v2_sparse_classes_30k_train_009450 | Implement the Python class `MPFAD2DOrdering` described below.
Class description:
Implementation of the 2D MPFA-D entity ordering.
Method signatures and docstrings:
- def __init__(self, mesh_entities, interface_dim): Constructor
- def sort_elements(self, elements, center): Sort elements according to the MPFA-D orderin... | Implement the Python class `MPFAD2DOrdering` described below.
Class description:
Implementation of the 2D MPFA-D entity ordering.
Method signatures and docstrings:
- def __init__(self, mesh_entities, interface_dim): Constructor
- def sort_elements(self, elements, center): Sort elements according to the MPFA-D orderin... | 1d4103ff70e32b593cd204e85e0ae65ccba318a4 | <|skeleton|>
class MPFAD2DOrdering:
"""Implementation of the 2D MPFA-D entity ordering."""
def __init__(self, mesh_entities, interface_dim):
"""Constructor"""
<|body_0|>
def sort_elements(self, elements, center):
"""Sort elements according to the MPFA-D ordering. Parameters -------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPFAD2DOrdering:
"""Implementation of the 2D MPFA-D entity ordering."""
def __init__(self, mesh_entities, interface_dim):
"""Constructor"""
super().__init__(mesh_entities, interface_dim)
if self.mesh_entities.entity_type not in ('nodes', 'edges', 'faces'):
raise ValueE... | the_stack_v2_python_sparse | preprocessor/element_order/MPFAD2DOrdering.py | padmec-reservoir/impress | train | 6 |
c94a2880a63fbaf3791d26f5efd26b8bc47132d7 | [
"try:\n self.ident = ident\n self.norder = self._find_order('DISP_', ident, keylist)\n self.twodkeys = self._find_twodkeys('DLDP_', ident, keylist)\nexcept CKeyNotFound as e:\n try:\n self.twodkeys = self._find_twodkeys('DLD1P_', ident, keylist)\n except CKeyNotFound as e:\n raise DispN... | <|body_start_0|>
try:
self.ident = ident
self.norder = self._find_order('DISP_', ident, keylist)
self.twodkeys = self._find_twodkeys('DLDP_', ident, keylist)
except CKeyNotFound as e:
try:
self.twodkeys = self._find_twodkeys('DLD1P_', ident... | Configuration Beam object | ConfigDisp | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigDisp:
"""Configuration Beam object"""
def __init__(self, ident=None, keylist=None):
"""Initializer for the configuration dispersion object The method initializes a configuration dispersion object for a given beam identifier. All necessary keywords are extracted from an input ke... | stack_v2_sparse_classes_36k_train_023593 | 48,172 | permissive | [
{
"docstring": "Initializer for the configuration dispersion object The method initializes a configuration dispersion object for a given beam identifier. All necessary keywords are extracted from an input keyword list. In case of missing keywords an exception is fired. @param ident: beam identification @type id... | 2 | null | Implement the Python class `ConfigDisp` described below.
Class description:
Configuration Beam object
Method signatures and docstrings:
- def __init__(self, ident=None, keylist=None): Initializer for the configuration dispersion object The method initializes a configuration dispersion object for a given beam identifi... | Implement the Python class `ConfigDisp` described below.
Class description:
Configuration Beam object
Method signatures and docstrings:
- def __init__(self, ident=None, keylist=None): Initializer for the configuration dispersion object The method initializes a configuration dispersion object for a given beam identifi... | 043c173fd5497c18c2b1bfe8bcff65180bca3996 | <|skeleton|>
class ConfigDisp:
"""Configuration Beam object"""
def __init__(self, ident=None, keylist=None):
"""Initializer for the configuration dispersion object The method initializes a configuration dispersion object for a given beam identifier. All necessary keywords are extracted from an input ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigDisp:
"""Configuration Beam object"""
def __init__(self, ident=None, keylist=None):
"""Initializer for the configuration dispersion object The method initializes a configuration dispersion object for a given beam identifier. All necessary keywords are extracted from an input keyword list. I... | the_stack_v2_python_sparse | stsdas/pkg/analysis/slitless/axe/axesrc/configfile.py | spacetelescope/stsdas_stripped | train | 1 |
4d3c99df3922cb7b43e3519b589fbfc8b92bb5c7 | [
"if self.step_type not in _STEP_TYPES:\n raise TypeError(f'Invalid step type {self.step_type}')\nmp_func = _STEP_TYPES[self.step_type]\naccessor = mp_func\nparams = self.params\nfunc_text = f'.{mp_func}({self._get_param_string()})'\nif self.step_type == 'pivot':\n _, func = _get_entity_and_pivot(self.entity, ... | <|body_start_0|>
if self.step_type not in _STEP_TYPES:
raise TypeError(f'Invalid step type {self.step_type}')
mp_func = _STEP_TYPES[self.step_type]
accessor = mp_func
params = self.params
func_text = f'.{mp_func}({self._get_param_string()})'
if self.step_type ... | Pivot pipeline step class. | PipelineStep | [
"LicenseRef-scancode-generic-cla",
"LGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"ISC",
"LGPL-2.0-or-later",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"Unlicense",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"MIT",
"LGPL-2.1-or-later",
"GPL-2.... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineStep:
"""Pivot pipeline step class."""
def get_exec_step(self) -> PipelineExecStep:
"""Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters ... | stack_v2_sparse_classes_36k_train_023594 | 10,245 | permissive | [
{
"docstring": "Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters to be passed to the function text - the text representation of the accessor + params comment - optional com... | 2 | stack_v2_sparse_classes_30k_train_018568 | Implement the Python class `PipelineStep` described below.
Class description:
Pivot pipeline step class.
Method signatures and docstrings:
- def get_exec_step(self) -> PipelineExecStep: Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of th... | Implement the Python class `PipelineStep` described below.
Class description:
Pivot pipeline step class.
Method signatures and docstrings:
- def get_exec_step(self) -> PipelineExecStep: Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of th... | 44b1a390510f9be2772ec62cb95d0fc67dfc234b | <|skeleton|>
class PipelineStep:
"""Pivot pipeline step class."""
def get_exec_step(self) -> PipelineExecStep:
"""Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelineStep:
"""Pivot pipeline step class."""
def get_exec_step(self) -> PipelineExecStep:
"""Return the executable step details. Returns ------- PipelineExecStep Named tuple with the following fields accessor - the name of the pandas DataFrame accessor function params - parameters to be passed ... | the_stack_v2_python_sparse | msticpy/datamodel/pivot_pipeline.py | RiskIQ/msticpy | train | 1 |
171c26e834f675688278ea90020217897664dc1b | [
"lock_key = 'util:redis:lock:' + lock_name\nlock_identifier = str(uuid.uuid4())\nsleep_time = 0.05\nif wait_time < sleep_time:\n wait_time = sleep_time\nend = time.time() + wait_time\nwhile time.time() < end:\n if redis_client.set(lock_key, lock_identifier, ex=lock_expire_time, nx=True):\n return lock_... | <|body_start_0|>
lock_key = 'util:redis:lock:' + lock_name
lock_identifier = str(uuid.uuid4())
sleep_time = 0.05
if wait_time < sleep_time:
wait_time = sleep_time
end = time.time() + wait_time
while time.time() < end:
if redis_client.set(lock_key, ... | 基于redis的分布式锁 | RedisLock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisLock:
"""基于redis的分布式锁"""
def try_lock(redis_client: redis.Redis, lock_name, wait_time=10, lock_expire_time=10):
"""获取一个锁 :param redis_client: redis连接 :param lock_name: 锁的名称,加上前缀"util:redis:lock:" 后作为锁的redis key :param wait_time: 客户端获取锁的最大等待时间(秒),超时则获取失败 :param lock_expire_time: ... | stack_v2_sparse_classes_36k_train_023595 | 2,273 | no_license | [
{
"docstring": "获取一个锁 :param redis_client: redis连接 :param lock_name: 锁的名称,加上前缀\"util:redis:lock:\" 后作为锁的redis key :param wait_time: 客户端获取锁的最大等待时间(秒),超时则获取失败 :param lock_expire_time: 锁的过期时间(秒) :return: 锁的编号id,解锁时需要提供该编号。如果获取锁超时,则返回False",
"name": "try_lock",
"signature": "def try_lock(redis_client: redis... | 2 | null | Implement the Python class `RedisLock` described below.
Class description:
基于redis的分布式锁
Method signatures and docstrings:
- def try_lock(redis_client: redis.Redis, lock_name, wait_time=10, lock_expire_time=10): 获取一个锁 :param redis_client: redis连接 :param lock_name: 锁的名称,加上前缀"util:redis:lock:" 后作为锁的redis key :param wait... | Implement the Python class `RedisLock` described below.
Class description:
基于redis的分布式锁
Method signatures and docstrings:
- def try_lock(redis_client: redis.Redis, lock_name, wait_time=10, lock_expire_time=10): 获取一个锁 :param redis_client: redis连接 :param lock_name: 锁的名称,加上前缀"util:redis:lock:" 后作为锁的redis key :param wait... | 5fb62820fa697ffc45931c4c19a9b0775feb1fc5 | <|skeleton|>
class RedisLock:
"""基于redis的分布式锁"""
def try_lock(redis_client: redis.Redis, lock_name, wait_time=10, lock_expire_time=10):
"""获取一个锁 :param redis_client: redis连接 :param lock_name: 锁的名称,加上前缀"util:redis:lock:" 后作为锁的redis key :param wait_time: 客户端获取锁的最大等待时间(秒),超时则获取失败 :param lock_expire_time: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisLock:
"""基于redis的分布式锁"""
def try_lock(redis_client: redis.Redis, lock_name, wait_time=10, lock_expire_time=10):
"""获取一个锁 :param redis_client: redis连接 :param lock_name: 锁的名称,加上前缀"util:redis:lock:" 后作为锁的redis key :param wait_time: 客户端获取锁的最大等待时间(秒),超时则获取失败 :param lock_expire_time: 锁的过期时间(秒) :re... | the_stack_v2_python_sparse | app/util/redis/redis_lock.py | 9Echo/gc-goods-allocation | train | 0 |
6347296f455d23b49ed605fb4b9a9a80ba514c66 | [
"investigator = Investigator.query.get(kf_id)\nif investigator is None:\n abort(404, 'could not find {} `{}`'.format('investigator', kf_id))\nreturn InvestigatorSchema().jsonify(investigator)",
"body = request.get_json(force=True)\ninv = Investigator.query.get(kf_id)\nif inv is None:\n abort(404, 'could not... | <|body_start_0|>
investigator = Investigator.query.get(kf_id)
if investigator is None:
abort(404, 'could not find {} `{}`'.format('investigator', kf_id))
return InvestigatorSchema().jsonify(investigator)
<|end_body_0|>
<|body_start_1|>
body = request.get_json(force=True)
... | Investigator API | InvestigatorAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvestigatorAPI:
"""Investigator API"""
def get(self, kf_id):
"""Get a investigator by id --- template: path: get_by_id.yml properties: resource: Investigator"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing investigator. Allows partial update of resou... | stack_v2_sparse_classes_36k_train_023596 | 4,397 | permissive | [
{
"docstring": "Get a investigator by id --- template: path: get_by_id.yml properties: resource: Investigator",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing investigator. Allows partial update of resource --- template: path: update_by_id.yml properties... | 3 | null | Implement the Python class `InvestigatorAPI` described below.
Class description:
Investigator API
Method signatures and docstrings:
- def get(self, kf_id): Get a investigator by id --- template: path: get_by_id.yml properties: resource: Investigator
- def patch(self, kf_id): Update an existing investigator. Allows pa... | Implement the Python class `InvestigatorAPI` described below.
Class description:
Investigator API
Method signatures and docstrings:
- def get(self, kf_id): Get a investigator by id --- template: path: get_by_id.yml properties: resource: Investigator
- def patch(self, kf_id): Update an existing investigator. Allows pa... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class InvestigatorAPI:
"""Investigator API"""
def get(self, kf_id):
"""Get a investigator by id --- template: path: get_by_id.yml properties: resource: Investigator"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing investigator. Allows partial update of resou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvestigatorAPI:
"""Investigator API"""
def get(self, kf_id):
"""Get a investigator by id --- template: path: get_by_id.yml properties: resource: Investigator"""
investigator = Investigator.query.get(kf_id)
if investigator is None:
abort(404, 'could not find {} `{}`'.f... | the_stack_v2_python_sparse | dataservice/api/investigator/resources.py | kids-first/kf-api-dataservice | train | 9 |
763f9490730109c2da7828925eac3779114b652c | [
"tags = frozenset(tags)\nfor key in self.keys():\n if key.issuperset(tags) and len(key.difference(tags)) == 1:\n yield key",
"tags = frozenset(tags)\nfor key in list(self.keys()):\n if key.issuperset(tags):\n yield key"
] | <|body_start_0|>
tags = frozenset(tags)
for key in self.keys():
if key.issuperset(tags) and len(key.difference(tags)) == 1:
yield key
<|end_body_0|>
<|body_start_1|>
tags = frozenset(tags)
for key in list(self.keys()):
if key.issuperset(tags):
... | The grand unified cache backend which contains all cache items. | _CacheRegistry | [
"LicenseRef-scancode-unknown-license-reference",
"mpich2",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CacheRegistry:
"""The grand unified cache backend which contains all cache items."""
def iterate(self, *tags):
"""Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that hav... | stack_v2_sparse_classes_36k_train_023597 | 6,128 | permissive | [
{
"docstring": "Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that have been instantiated via :func:`Bcfg2.Server.Cache.Cache`.",
"name": "iterate",
"signature": "def iterate(self, *tags)"
... | 2 | null | Implement the Python class `_CacheRegistry` described below.
Class description:
The grand unified cache backend which contains all cache items.
Method signatures and docstrings:
- def iterate(self, *tags): Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get item... | Implement the Python class `_CacheRegistry` described below.
Class description:
The grand unified cache backend which contains all cache items.
Method signatures and docstrings:
- def iterate(self, *tags): Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get item... | 8605cd3d0cb4d549cb8b43de945d447f6d82892a | <|skeleton|>
class _CacheRegistry:
"""The grand unified cache backend which contains all cache items."""
def iterate(self, *tags):
"""Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that hav... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CacheRegistry:
"""The grand unified cache backend which contains all cache items."""
def iterate(self, *tags):
"""Iterate over all items that match the given tags *and* have exactly one additional tag. This is used to get items for :class:`Bcfg2.Server.Cache._Cache` objects that have been instan... | the_stack_v2_python_sparse | src/lib/Bcfg2/Server/Cache.py | Bcfg2/bcfg2 | train | 56 |
162b63bcfabeb91748de175a7d54365dfeb5c820 | [
"if self.request.method == 'POST':\n form = SearchForm(self.request.POST)\n if form.is_valid():\n search = form.cleaned_data['search']\n return HttpResponseRedirect(reverse('list_posts') + '?search=' + search)\n else:\n return HttpResponseRedirect(reverse('list_posts'))",
"location =... | <|body_start_0|>
if self.request.method == 'POST':
form = SearchForm(self.request.POST)
if form.is_valid():
search = form.cleaned_data['search']
return HttpResponseRedirect(reverse('list_posts') + '?search=' + search)
else:
retu... | ListPosts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListPosts:
def post(self, catch):
"""Add search words to a get url :param catch: unused parameter :return: HttpResponse with search querystring"""
<|body_0|>
def get_queryset(self):
"""Query for post list to return. Location is required. Check for other filters inclu... | stack_v2_sparse_classes_36k_train_023598 | 12,680 | no_license | [
{
"docstring": "Add search words to a get url :param catch: unused parameter :return: HttpResponse with search querystring",
"name": "post",
"signature": "def post(self, catch)"
},
{
"docstring": "Query for post list to return. Location is required. Check for other filters including order by top... | 3 | stack_v2_sparse_classes_30k_train_020066 | Implement the Python class `ListPosts` described below.
Class description:
Implement the ListPosts class.
Method signatures and docstrings:
- def post(self, catch): Add search words to a get url :param catch: unused parameter :return: HttpResponse with search querystring
- def get_queryset(self): Query for post list ... | Implement the Python class `ListPosts` described below.
Class description:
Implement the ListPosts class.
Method signatures and docstrings:
- def post(self, catch): Add search words to a get url :param catch: unused parameter :return: HttpResponse with search querystring
- def get_queryset(self): Query for post list ... | fdf7500e7593595bca86a0ac255413f2c33a4738 | <|skeleton|>
class ListPosts:
def post(self, catch):
"""Add search words to a get url :param catch: unused parameter :return: HttpResponse with search querystring"""
<|body_0|>
def get_queryset(self):
"""Query for post list to return. Location is required. Check for other filters inclu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListPosts:
def post(self, catch):
"""Add search words to a get url :param catch: unused parameter :return: HttpResponse with search querystring"""
if self.request.method == 'POST':
form = SearchForm(self.request.POST)
if form.is_valid():
search = form.cl... | the_stack_v2_python_sparse | peteslist/views.py | peteralfredoflynn/freds-list-evolved | train | 0 | |
056356f9a28fedd960234c23747ed3f7b72d625d | [
"if isinstance(key, int):\n return Packet(key)\nif key not in Packet._member_map_:\n return extend_enum(Packet, key, default)\nreturn Packet[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 6 <= value <= 127:\n retu... | <|body_start_0|>
if isinstance(key, int):
return Packet(key)
if key not in Packet._member_map_:
return extend_enum(Packet, key, default)
return Packet[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
raise ... | [Packet] OSPF Packet Types | Packet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Packet:
"""[Packet] OSPF Packet Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'Packet':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int') ... | stack_v2_sparse_classes_36k_train_023599 | 1,925 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'Packet'"
},
{
"docstring": "Lookup function used when value is not found. Args... | 2 | null | Implement the Python class `Packet` described below.
Class description:
[Packet] OSPF Packet Types
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Packet': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- d... | Implement the Python class `Packet` described below.
Class description:
[Packet] OSPF Packet Types
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Packet': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- d... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class Packet:
"""[Packet] OSPF Packet Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'Packet':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int') ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Packet:
"""[Packet] OSPF Packet Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'Packet':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return Packet(key)
... | the_stack_v2_python_sparse | pcapkit/const/ospf/packet.py | JarryShaw/PyPCAPKit | train | 204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.