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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f62766300d28025bac12466d40a1f893186065b | [
"output_type = self.OUTPUT_TYPE\ndata, num_filtered = ([], 0.0)\nself.uniq_labels = set()\nif index_by_file_id:\n self.mapping = {}\nfor feature_file, seq_label in zip(feature_files, seq_labels):\n label_tokens, uniq_labels_in_seq = self.relative_speaker_parser(seq_label)\n data.append(output_type(feature_... | <|body_start_0|>
output_type = self.OUTPUT_TYPE
data, num_filtered = ([], 0.0)
self.uniq_labels = set()
if index_by_file_id:
self.mapping = {}
for feature_file, seq_label in zip(feature_files, seq_labels):
label_tokens, uniq_labels_in_seq = self.relative_s... | List of feature sequence of label correspondence with preprocessing. | FeatureSequenceLabel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureSequenceLabel:
"""List of feature sequence of label correspondence with preprocessing."""
def __init__(self, feature_files: List[str], seq_labels: List[str], max_number: Optional[int]=None, index_by_file_id: bool=False):
"""Instantiates feature-SequenceLabel manifest with filt... | stack_v2_sparse_classes_36k_train_014700 | 49,669 | permissive | [
{
"docstring": "Instantiates feature-SequenceLabel manifest with filters and preprocessing. Args: feature_files: List of feature files. seq_labels: List of sequences of labels. max_number: Maximum number of samples to collect. index_by_file_id: If True, saves a mapping from filename base (ID) to index in data."... | 2 | stack_v2_sparse_classes_30k_train_007365 | Implement the Python class `FeatureSequenceLabel` described below.
Class description:
List of feature sequence of label correspondence with preprocessing.
Method signatures and docstrings:
- def __init__(self, feature_files: List[str], seq_labels: List[str], max_number: Optional[int]=None, index_by_file_id: bool=Fals... | Implement the Python class `FeatureSequenceLabel` described below.
Class description:
List of feature sequence of label correspondence with preprocessing.
Method signatures and docstrings:
- def __init__(self, feature_files: List[str], seq_labels: List[str], max_number: Optional[int]=None, index_by_file_id: bool=Fals... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class FeatureSequenceLabel:
"""List of feature sequence of label correspondence with preprocessing."""
def __init__(self, feature_files: List[str], seq_labels: List[str], max_number: Optional[int]=None, index_by_file_id: bool=False):
"""Instantiates feature-SequenceLabel manifest with filt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureSequenceLabel:
"""List of feature sequence of label correspondence with preprocessing."""
def __init__(self, feature_files: List[str], seq_labels: List[str], max_number: Optional[int]=None, index_by_file_id: bool=False):
"""Instantiates feature-SequenceLabel manifest with filters and prepr... | the_stack_v2_python_sparse | nemo/collections/common/parts/preprocessing/collections.py | NVIDIA/NeMo | train | 7,957 |
3248b044a38f8f177a84c24d2eda205f09e9c038 | [
"diagnostic = SupplyTempAIRCx()\nif isinstance(diagnostic, SupplyTempAIRCx):\n assert True\nelse:\n assert False",
"diagnostic = SupplyTempAIRCx()\ndata_window = td(minutes=1)\ndiagnostic.set_class_values({}, 1, data_window, False, {}, 4.0, 4.0, {}, {}, 2, 3, {}, 5, 'test', 'test_c', [])\nassert diagnostic.... | <|body_start_0|>
diagnostic = SupplyTempAIRCx()
if isinstance(diagnostic, SupplyTempAIRCx):
assert True
else:
assert False
<|end_body_0|>
<|body_start_1|>
diagnostic = SupplyTempAIRCx()
data_window = td(minutes=1)
diagnostic.set_class_values({}, 1... | Contains all the tests for SupplyTempAIRCx Diagnostic | TestDiagnosticsSupplyTempAIRCx | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDiagnosticsSupplyTempAIRCx:
"""Contains all the tests for SupplyTempAIRCx Diagnostic"""
def test_temp_sensor_dx_creation(self):
"""test the creation of temp sensor diagnostic class"""
<|body_0|>
def test_temp_sensor_dx_set_class_values(self):
"""test the crea... | stack_v2_sparse_classes_36k_train_014701 | 14,928 | permissive | [
{
"docstring": "test the creation of temp sensor diagnostic class",
"name": "test_temp_sensor_dx_creation",
"signature": "def test_temp_sensor_dx_creation(self)"
},
{
"docstring": "test the creation of temp sensor diagnostic class",
"name": "test_temp_sensor_dx_set_class_values",
"signat... | 6 | null | Implement the Python class `TestDiagnosticsSupplyTempAIRCx` described below.
Class description:
Contains all the tests for SupplyTempAIRCx Diagnostic
Method signatures and docstrings:
- def test_temp_sensor_dx_creation(self): test the creation of temp sensor diagnostic class
- def test_temp_sensor_dx_set_class_values... | Implement the Python class `TestDiagnosticsSupplyTempAIRCx` described below.
Class description:
Contains all the tests for SupplyTempAIRCx Diagnostic
Method signatures and docstrings:
- def test_temp_sensor_dx_creation(self): test the creation of temp sensor diagnostic class
- def test_temp_sensor_dx_set_class_values... | 24d50729aef8d91036cc13b0f5c03be76f3237ed | <|skeleton|>
class TestDiagnosticsSupplyTempAIRCx:
"""Contains all the tests for SupplyTempAIRCx Diagnostic"""
def test_temp_sensor_dx_creation(self):
"""test the creation of temp sensor diagnostic class"""
<|body_0|>
def test_temp_sensor_dx_set_class_values(self):
"""test the crea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDiagnosticsSupplyTempAIRCx:
"""Contains all the tests for SupplyTempAIRCx Diagnostic"""
def test_temp_sensor_dx_creation(self):
"""test the creation of temp sensor diagnostic class"""
diagnostic = SupplyTempAIRCx()
if isinstance(diagnostic, SupplyTempAIRCx):
assert... | the_stack_v2_python_sparse | EnergyEfficiency/AirsideRCxAgent/airside/test.py | shwethanidd/volttron-pnnl-applications-2 | train | 0 |
ff818bc81def7fd008bf083c2900d6104aa9ca8f | [
"cp_model.CpSolverSolutionCallback.__init__(self)\nself.origin_ = origin_\nself.college_ = college_\nself.course_ = course_\nself.solutions_ = 0",
"self.solutions_ = self.solutions_ + 1\nif self.solutions_ > 1:\n print()\nprint('Solution #{s}:'.format(s=self.solutions_))\nfor p in persons:\n print(' - {p}:'... | <|body_start_0|>
cp_model.CpSolverSolutionCallback.__init__(self)
self.origin_ = origin_
self.college_ = college_
self.course_ = course_
self.solutions_ = 0
<|end_body_0|>
<|body_start_1|>
self.solutions_ = self.solutions_ + 1
if self.solutions_ > 1:
... | SolutionPrinter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionPrinter:
def __init__(self, origin_, college_, course_):
"""Printer for outputting puzzle solutions during solver run. :param origin_: origin variables -- list :param college_: college variables -- list :param course_: course variables -- list"""
<|body_0|>
def OnSol... | stack_v2_sparse_classes_36k_train_014702 | 12,611 | no_license | [
{
"docstring": "Printer for outputting puzzle solutions during solver run. :param origin_: origin variables -- list :param college_: college variables -- list :param course_: course variables -- list",
"name": "__init__",
"signature": "def __init__(self, origin_, college_, course_)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_016657 | Implement the Python class `SolutionPrinter` described below.
Class description:
Implement the SolutionPrinter class.
Method signatures and docstrings:
- def __init__(self, origin_, college_, course_): Printer for outputting puzzle solutions during solver run. :param origin_: origin variables -- list :param college_:... | Implement the Python class `SolutionPrinter` described below.
Class description:
Implement the SolutionPrinter class.
Method signatures and docstrings:
- def __init__(self, origin_, college_, course_): Printer for outputting puzzle solutions during solver run. :param origin_: origin variables -- list :param college_:... | 3e87335932b70554250737d69af276c4544df51a | <|skeleton|>
class SolutionPrinter:
def __init__(self, origin_, college_, course_):
"""Printer for outputting puzzle solutions during solver run. :param origin_: origin variables -- list :param college_: college variables -- list :param course_: course variables -- list"""
<|body_0|>
def OnSol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionPrinter:
def __init__(self, origin_, college_, course_):
"""Printer for outputting puzzle solutions during solver run. :param origin_: origin variables -- list :param college_: college variables -- list :param course_: course variables -- list"""
cp_model.CpSolverSolutionCallback.__ini... | the_stack_v2_python_sparse | Decision Analytics/Constraing Programming/Solution/task-1.py | MichaelMcAleer/CollegeWork | train | 0 | |
13a34ca054a4fe4f87a9c843104c8e0775ca2689 | [
"self.endStringCounter = 0\nself.harcodingSection = 0\nself.listedQValuesDict = {}\nself.inputFiles = inputFiles\nself.pertQValuesDict = self.scientificNotation(pertDict)\nself.fileReconstruction()\nself.printInput(workingDir)",
"for key, value in pertDict.items():\n pertDict[key] = '%.3E' % Decimal(str(value)... | <|body_start_0|>
self.endStringCounter = 0
self.harcodingSection = 0
self.listedQValuesDict = {}
self.inputFiles = inputFiles
self.pertQValuesDict = self.scientificNotation(pertDict)
self.fileReconstruction()
self.printInput(workingDir)
<|end_body_0|>
<|body_star... | Parses the PHISICS decay Qvalue library located in the path folder (betadecay, alphadecay etc.) and replaces the nominal values by the perturbed values. | PathParser | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PathParser:
"""Parses the PHISICS decay Qvalue library located in the path folder (betadecay, alphadecay etc.) and replaces the nominal values by the perturbed values."""
def __init__(self, inputFiles, workingDir, **pertDict):
"""Constructor. @ In, inputFiles, string, decay Qvalue li... | stack_v2_sparse_classes_36k_train_014703 | 4,733 | permissive | [
{
"docstring": "Constructor. @ In, inputFiles, string, decay Qvalue library file @ In, workingDir, string, absolute path to working directory @ In, pertDict, dictionary, dictionary of perturbed variables @ Out, None",
"name": "__init__",
"signature": "def __init__(self, inputFiles, workingDir, **pertDic... | 5 | stack_v2_sparse_classes_30k_train_019550 | Implement the Python class `PathParser` described below.
Class description:
Parses the PHISICS decay Qvalue library located in the path folder (betadecay, alphadecay etc.) and replaces the nominal values by the perturbed values.
Method signatures and docstrings:
- def __init__(self, inputFiles, workingDir, **pertDict... | Implement the Python class `PathParser` described below.
Class description:
Parses the PHISICS decay Qvalue library located in the path folder (betadecay, alphadecay etc.) and replaces the nominal values by the perturbed values.
Method signatures and docstrings:
- def __init__(self, inputFiles, workingDir, **pertDict... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class PathParser:
"""Parses the PHISICS decay Qvalue library located in the path folder (betadecay, alphadecay etc.) and replaces the nominal values by the perturbed values."""
def __init__(self, inputFiles, workingDir, **pertDict):
"""Constructor. @ In, inputFiles, string, decay Qvalue li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PathParser:
"""Parses the PHISICS decay Qvalue library located in the path folder (betadecay, alphadecay etc.) and replaces the nominal values by the perturbed values."""
def __init__(self, inputFiles, workingDir, **pertDict):
"""Constructor. @ In, inputFiles, string, decay Qvalue library file @ ... | the_stack_v2_python_sparse | ravenframework/CodeInterfaceClasses/PHISICS/PathParser.py | idaholab/raven | train | 201 |
fbe84113b39a396850e5e214dbf81fbf1f002c25 | [
"l = 0\nfor s in S:\n if s.isdigit():\n l *= int(s)\n else:\n l += 1\nfor s in reversed(S):\n K %= l\n if K == 0 and s.isalpha():\n return s\n if s.isdigit():\n l //= int(s)\n else:\n l -= 1\nraise",
"K -= 1\ni = 0\nj = 0\nlast = None\nn = len(S)\nwhile j < n:\... | <|body_start_0|>
l = 0
for s in S:
if s.isdigit():
l *= int(s)
else:
l += 1
for s in reversed(S):
K %= l
if K == 0 and s.isalpha():
return s
if s.isdigit():
l //= int(s)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
"""walk backward"""
<|body_0|>
def decodeAtIndex_error(self, S: str, K: int) -> str:
"""don't generate the final string, too memory expensive two pointer understanding error, one digit will make the entire str... | stack_v2_sparse_classes_36k_train_014704 | 2,561 | no_license | [
{
"docstring": "walk backward",
"name": "decodeAtIndex",
"signature": "def decodeAtIndex(self, S: str, K: int) -> str"
},
{
"docstring": "don't generate the final string, too memory expensive two pointer understanding error, one digit will make the entire str repeated",
"name": "decodeAtInde... | 2 | stack_v2_sparse_classes_30k_train_015148 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S: str, K: int) -> str: walk backward
- def decodeAtIndex_error(self, S: str, K: int) -> str: don't generate the final string, too memory expensive two po... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S: str, K: int) -> str: walk backward
- def decodeAtIndex_error(self, S: str, K: int) -> str: don't generate the final string, too memory expensive two po... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
"""walk backward"""
<|body_0|>
def decodeAtIndex_error(self, S: str, K: int) -> str:
"""don't generate the final string, too memory expensive two pointer understanding error, one digit will make the entire str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
"""walk backward"""
l = 0
for s in S:
if s.isdigit():
l *= int(s)
else:
l += 1
for s in reversed(S):
K %= l
if K == 0 and s.isalpha():
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/880 Decoded String at Index.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
226a979165e8ad3415533729e51588f595d2bd0c | [
"self.verbose = verbose\nself.valid_indices = valid_indices\nself.test_indices = test_indices",
"num_datapoints = len(dataset)\nindices = np.arange(num_datapoints).tolist()\ntrain_indices = []\nif self.valid_indices is None:\n self.valid_indices = []\nif self.test_indices is None:\n self.test_indices = []\n... | <|body_start_0|>
self.verbose = verbose
self.valid_indices = valid_indices
self.test_indices = test_indices
<|end_body_0|>
<|body_start_1|>
num_datapoints = len(dataset)
indices = np.arange(num_datapoints).tolist()
train_indices = []
if self.valid_indices is None... | Class for splits based on input order. | IndiceSplitter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndiceSplitter:
"""Class for splits based on input order."""
def __init__(self, verbose=False, valid_indices=None, test_indices=None):
"""Parameters ----------- valid_indices: list of int indices of samples in the valid set test_indices: list of int indices of samples in the test set... | stack_v2_sparse_classes_36k_train_014705 | 26,497 | permissive | [
{
"docstring": "Parameters ----------- valid_indices: list of int indices of samples in the valid set test_indices: list of int indices of samples in the test set",
"name": "__init__",
"signature": "def __init__(self, verbose=False, valid_indices=None, test_indices=None)"
},
{
"docstring": "Spli... | 2 | null | Implement the Python class `IndiceSplitter` described below.
Class description:
Class for splits based on input order.
Method signatures and docstrings:
- def __init__(self, verbose=False, valid_indices=None, test_indices=None): Parameters ----------- valid_indices: list of int indices of samples in the valid set tes... | Implement the Python class `IndiceSplitter` described below.
Class description:
Class for splits based on input order.
Method signatures and docstrings:
- def __init__(self, verbose=False, valid_indices=None, test_indices=None): Parameters ----------- valid_indices: list of int indices of samples in the valid set tes... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class IndiceSplitter:
"""Class for splits based on input order."""
def __init__(self, verbose=False, valid_indices=None, test_indices=None):
"""Parameters ----------- valid_indices: list of int indices of samples in the valid set test_indices: list of int indices of samples in the test set... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndiceSplitter:
"""Class for splits based on input order."""
def __init__(self, verbose=False, valid_indices=None, test_indices=None):
"""Parameters ----------- valid_indices: list of int indices of samples in the valid set test_indices: list of int indices of samples in the test set"""
s... | the_stack_v2_python_sparse | contrib/atomicconv/splits/splitters.py | deepchem/deepchem | train | 4,876 |
184bb3b1c65e01625b1055ee541fa7395a7be579 | [
"request = Mock()\nrequest.user = User.objects.create_user(username=self.TEST_USER, password='pass')\npackage = Mock()\nwrong_user = User.objects.create_user(username=self.WRONG_USER, password='pass')\npackage.user = wrong_user\npackage.collaborators.all.return_value = []\nmock_get.return_value = package\n\n@get_pa... | <|body_start_0|>
request = Mock()
request.user = User.objects.create_user(username=self.TEST_USER, password='pass')
package = Mock()
wrong_user = User.objects.create_user(username=self.WRONG_USER, password='pass')
package.user = wrong_user
package.collaborators.all.return... | ShortcutTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShortcutTestCase:
def test_get_package_or_error(self, mock_get):
"""Tests exeapp.shortcuts.get_package_by_id_or_error convinience decorator"""
<|body_0|>
def package_and_node_or_error(self, mock_get_package, mock_get_node):
"""Tests exeapp.shortcuts.get_package_by_id... | stack_v2_sparse_classes_36k_train_014706 | 24,901 | no_license | [
{
"docstring": "Tests exeapp.shortcuts.get_package_by_id_or_error convinience decorator",
"name": "test_get_package_or_error",
"signature": "def test_get_package_or_error(self, mock_get)"
},
{
"docstring": "Tests exeapp.shortcuts.get_package_by_id_or_error with package and node",
"name": "pa... | 2 | stack_v2_sparse_classes_30k_train_003337 | Implement the Python class `ShortcutTestCase` described below.
Class description:
Implement the ShortcutTestCase class.
Method signatures and docstrings:
- def test_get_package_or_error(self, mock_get): Tests exeapp.shortcuts.get_package_by_id_or_error convinience decorator
- def package_and_node_or_error(self, mock_... | Implement the Python class `ShortcutTestCase` described below.
Class description:
Implement the ShortcutTestCase class.
Method signatures and docstrings:
- def test_get_package_or_error(self, mock_get): Tests exeapp.shortcuts.get_package_by_id_or_error convinience decorator
- def package_and_node_or_error(self, mock_... | 2cf50de25cdb8427668ec98c5ae3b17f3c2edbcf | <|skeleton|>
class ShortcutTestCase:
def test_get_package_or_error(self, mock_get):
"""Tests exeapp.shortcuts.get_package_by_id_or_error convinience decorator"""
<|body_0|>
def package_and_node_or_error(self, mock_get_package, mock_get_node):
"""Tests exeapp.shortcuts.get_package_by_id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShortcutTestCase:
def test_get_package_or_error(self, mock_get):
"""Tests exeapp.shortcuts.get_package_by_id_or_error convinience decorator"""
request = Mock()
request.user = User.objects.create_user(username=self.TEST_USER, password='pass')
package = Mock()
wrong_user ... | the_stack_v2_python_sparse | exeapp/tests.py | TUM-MZ/creyoco | train | 1 | |
bccb9f94cd6ab24551ad1aa5b0aebb88c3673991 | [
"self.setMassFrac('NI', 0.325)\nself.setMassFrac('CR', 0.21)\nself.setMassFrac('C', 0.00075)\nself.setMassFrac('MN', 0.015)\nself.setMassFrac('S', 0.00015)\nself.setMassFrac('SI', 0.01)\nself.setMassFrac('CU', 0.0075)\nself.setMassFrac('AL', 0.00375)\nself.setMassFrac('TI', 0.00375)\nself.setMassFrac('FE', 1.0 - su... | <|body_start_0|>
self.setMassFrac('NI', 0.325)
self.setMassFrac('CR', 0.21)
self.setMassFrac('C', 0.00075)
self.setMassFrac('MN', 0.015)
self.setMassFrac('S', 0.00015)
self.setMassFrac('SI', 0.01)
self.setMassFrac('CU', 0.0075)
self.setMassFrac('AL', 0.003... | Incoloy 800/800H (UNS N08800/N08810). .. [SM] Special Metals - Incoloy alloy 800 (https://www.specialmetals.com/assets/smc/documents/alloys/incoloy/incoloy-alloy-800.pdf) | Inconel800 | [
"Apache-2.0",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inconel800:
"""Incoloy 800/800H (UNS N08800/N08810). .. [SM] Special Metals - Incoloy alloy 800 (https://www.specialmetals.com/assets/smc/documents/alloys/incoloy/incoloy-alloy-800.pdf)"""
def setDefaultMassFracs(self):
"""Incoloy 800H mass fractions. From [SM]_."""
<|body_0|... | stack_v2_sparse_classes_36k_train_014707 | 2,857 | permissive | [
{
"docstring": "Incoloy 800H mass fractions. From [SM]_.",
"name": "setDefaultMassFracs",
"signature": "def setDefaultMassFracs(self)"
},
{
"docstring": "average thermal expansion dL/L. Used for computing hot dimensions. Parameters ---------- Tk : float temperature in (K) Tc : float Temperature ... | 3 | stack_v2_sparse_classes_30k_train_018321 | Implement the Python class `Inconel800` described below.
Class description:
Incoloy 800/800H (UNS N08800/N08810). .. [SM] Special Metals - Incoloy alloy 800 (https://www.specialmetals.com/assets/smc/documents/alloys/incoloy/incoloy-alloy-800.pdf)
Method signatures and docstrings:
- def setDefaultMassFracs(self): Inco... | Implement the Python class `Inconel800` described below.
Class description:
Incoloy 800/800H (UNS N08800/N08810). .. [SM] Special Metals - Incoloy alloy 800 (https://www.specialmetals.com/assets/smc/documents/alloys/incoloy/incoloy-alloy-800.pdf)
Method signatures and docstrings:
- def setDefaultMassFracs(self): Inco... | 360791847227df3f3a337a996ef561e00f846a09 | <|skeleton|>
class Inconel800:
"""Incoloy 800/800H (UNS N08800/N08810). .. [SM] Special Metals - Incoloy alloy 800 (https://www.specialmetals.com/assets/smc/documents/alloys/incoloy/incoloy-alloy-800.pdf)"""
def setDefaultMassFracs(self):
"""Incoloy 800H mass fractions. From [SM]_."""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inconel800:
"""Incoloy 800/800H (UNS N08800/N08810). .. [SM] Special Metals - Incoloy alloy 800 (https://www.specialmetals.com/assets/smc/documents/alloys/incoloy/incoloy-alloy-800.pdf)"""
def setDefaultMassFracs(self):
"""Incoloy 800H mass fractions. From [SM]_."""
self.setMassFrac('NI',... | the_stack_v2_python_sparse | armi/materials/inconel800.py | terrapower/armi | train | 204 |
43491ccb78ad5d926715538405e405a91ea56563 | [
"study_id = filter_params.pop('study_id', None)\nq = SequencingExperimentGenomicFile.query.filter_by(**filter_params)\nfrom dataservice.api.participant.models import Participant\nfrom dataservice.api.biospecimen.models import Biospecimen\nfrom dataservice.api.genomic_file.models import GenomicFile\nfrom dataservice... | <|body_start_0|>
study_id = filter_params.pop('study_id', None)
q = SequencingExperimentGenomicFile.query.filter_by(**filter_params)
from dataservice.api.participant.models import Participant
from dataservice.api.biospecimen.models import Biospecimen
from dataservice.api.genomic_... | SequencingExperimentGenomicFile List API | SequencingExperimentGenomicFileListAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequencingExperimentGenomicFileListAPI:
"""SequencingExperimentGenomicFile List API"""
def get(self, filter_params, after, limit):
"""Get a paginated sequencing_experiment_genomic_files --- template: path: get_list.yml properties: resource: SequencingExperimentGenomicFile"""
... | stack_v2_sparse_classes_36k_train_014708 | 5,985 | permissive | [
{
"docstring": "Get a paginated sequencing_experiment_genomic_files --- template: path: get_list.yml properties: resource: SequencingExperimentGenomicFile",
"name": "get",
"signature": "def get(self, filter_params, after, limit)"
},
{
"docstring": "Create a new sequencing_experiment_genomic_file... | 2 | stack_v2_sparse_classes_30k_train_004387 | Implement the Python class `SequencingExperimentGenomicFileListAPI` described below.
Class description:
SequencingExperimentGenomicFile List API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get a paginated sequencing_experiment_genomic_files --- template: path: get_list.yml properti... | Implement the Python class `SequencingExperimentGenomicFileListAPI` described below.
Class description:
SequencingExperimentGenomicFile List API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get a paginated sequencing_experiment_genomic_files --- template: path: get_list.yml properti... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class SequencingExperimentGenomicFileListAPI:
"""SequencingExperimentGenomicFile List API"""
def get(self, filter_params, after, limit):
"""Get a paginated sequencing_experiment_genomic_files --- template: path: get_list.yml properties: resource: SequencingExperimentGenomicFile"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequencingExperimentGenomicFileListAPI:
"""SequencingExperimentGenomicFile List API"""
def get(self, filter_params, after, limit):
"""Get a paginated sequencing_experiment_genomic_files --- template: path: get_list.yml properties: resource: SequencingExperimentGenomicFile"""
study_id = fi... | the_stack_v2_python_sparse | dataservice/api/sequencing_experiment_genomic_file/resources.py | kids-first/kf-api-dataservice | train | 9 |
87c3d3846859cfdc287fc2988c86086b95606edd | [
"user_id = payload['user_id']\napis = await join_blueprints_with(model=mApi, db=self.db, user_id=user_id)\napis_schema = ApiSchema(many=True)\napis_schema.context = {'user': user_id}\ndata, errors = apis_schema.dump(apis)\nif errors:\n return json_response({'error': errors}, status=400)\nreturn json_response({'a... | <|body_start_0|>
user_id = payload['user_id']
apis = await join_blueprints_with(model=mApi, db=self.db, user_id=user_id)
apis_schema = ApiSchema(many=True)
apis_schema.context = {'user': user_id}
data, errors = apis_schema.dump(apis)
if errors:
return json_res... | Create api and push api online. | APIs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIs:
"""Create api and push api online."""
async def get(self, payload: Mapping[str, Any]):
"""Get a list of APIs for the current user."""
<|body_0|>
async def post(self, payload: Mapping[str, Any]):
"""Create a new API."""
<|body_1|>
async def dele... | stack_v2_sparse_classes_36k_train_014709 | 3,198 | permissive | [
{
"docstring": "Get a list of APIs for the current user.",
"name": "get",
"signature": "async def get(self, payload: Mapping[str, Any])"
},
{
"docstring": "Create a new API.",
"name": "post",
"signature": "async def post(self, payload: Mapping[str, Any])"
},
{
"docstring": "Delet... | 3 | null | Implement the Python class `APIs` described below.
Class description:
Create api and push api online.
Method signatures and docstrings:
- async def get(self, payload: Mapping[str, Any]): Get a list of APIs for the current user.
- async def post(self, payload: Mapping[str, Any]): Create a new API.
- async def delete(s... | Implement the Python class `APIs` described below.
Class description:
Create api and push api online.
Method signatures and docstrings:
- async def get(self, payload: Mapping[str, Any]): Get a list of APIs for the current user.
- async def post(self, payload: Mapping[str, Any]): Create a new API.
- async def delete(s... | e94889ce784f4399ca74f78be3bc42a5cd880d70 | <|skeleton|>
class APIs:
"""Create api and push api online."""
async def get(self, payload: Mapping[str, Any]):
"""Get a list of APIs for the current user."""
<|body_0|>
async def post(self, payload: Mapping[str, Any]):
"""Create a new API."""
<|body_1|>
async def dele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIs:
"""Create api and push api online."""
async def get(self, payload: Mapping[str, Any]):
"""Get a list of APIs for the current user."""
user_id = payload['user_id']
apis = await join_blueprints_with(model=mApi, db=self.db, user_id=user_id)
apis_schema = ApiSchema(many=... | the_stack_v2_python_sparse | apis/views.py | cassinyio/cassiny-spawner | train | 1 |
3b2344d4e819a71c394760a6267bca2c906e3759 | [
"self._async_add_entities = async_add_entities\nself._client = client\nself._scan_interval = scan_interval\nself._show_archived = show_archived\nself.account_id = client.profile.account_id\nself.packages = {}\nself.show_delivered = show_delivered\nself.timezone = timezone\nself.summary = {}\nself.async_update = Thr... | <|body_start_0|>
self._async_add_entities = async_add_entities
self._client = client
self._scan_interval = scan_interval
self._show_archived = show_archived
self.account_id = client.profile.account_id
self.packages = {}
self.show_delivered = show_delivered
... | Define a data handler for 17track.net. | SeventeenTrackData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeventeenTrackData:
"""Define a data handler for 17track.net."""
def __init__(self, client, async_add_entities, scan_interval, show_archived, show_delivered, timezone):
"""Initialize."""
<|body_0|>
async def _async_update(self):
"""Get updated data from 17track.n... | stack_v2_sparse_classes_36k_train_014710 | 11,166 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, client, async_add_entities, scan_interval, show_archived, show_delivered, timezone)"
},
{
"docstring": "Get updated data from 17track.net.",
"name": "_async_update",
"signature": "async def _async_update(s... | 2 | null | Implement the Python class `SeventeenTrackData` described below.
Class description:
Define a data handler for 17track.net.
Method signatures and docstrings:
- def __init__(self, client, async_add_entities, scan_interval, show_archived, show_delivered, timezone): Initialize.
- async def _async_update(self): Get update... | Implement the Python class `SeventeenTrackData` described below.
Class description:
Define a data handler for 17track.net.
Method signatures and docstrings:
- def __init__(self, client, async_add_entities, scan_interval, show_archived, show_delivered, timezone): Initialize.
- async def _async_update(self): Get update... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SeventeenTrackData:
"""Define a data handler for 17track.net."""
def __init__(self, client, async_add_entities, scan_interval, show_archived, show_delivered, timezone):
"""Initialize."""
<|body_0|>
async def _async_update(self):
"""Get updated data from 17track.n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeventeenTrackData:
"""Define a data handler for 17track.net."""
def __init__(self, client, async_add_entities, scan_interval, show_archived, show_delivered, timezone):
"""Initialize."""
self._async_add_entities = async_add_entities
self._client = client
self._scan_interva... | the_stack_v2_python_sparse | homeassistant/components/seventeentrack/sensor.py | home-assistant/core | train | 35,501 |
c42145706873c6a924e3ab932bfa5561ad9c93c1 | [
"self.__checkFPKM()\nfpkmFile = open(self.fileStr + '.txt', 'r')\nfpkmAr = []\nfor line in fpkmFile:\n line = line.rstrip()\n lineAr = line.split('\\t')\n fpkmAr += [lineAr[0]]\nfpkmFile.close()\nreturn fpkmAr",
"self.__checkFPKM()\nfpkmFile = open(self.fileStr + '.txt', 'r')\nfpkmAr = []\nfpkmValueAr = ... | <|body_start_0|>
self.__checkFPKM()
fpkmFile = open(self.fileStr + '.txt', 'r')
fpkmAr = []
for line in fpkmFile:
line = line.rstrip()
lineAr = line.split('\t')
fpkmAr += [lineAr[0]]
fpkmFile.close()
return fpkmAr
<|end_body_0|>
<|body... | reading files with FPKM values for genes | FileFPKM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileFPKM:
"""reading files with FPKM values for genes"""
def getFPKMArray(self):
"""returns the array or genes ordered by fpkm"""
<|body_0|>
def getFPKMValueArray(self, subsetDict=None):
"""returns array of genes ordered by fpkm and array of the fpkms optional su... | stack_v2_sparse_classes_36k_train_014711 | 22,678 | no_license | [
{
"docstring": "returns the array or genes ordered by fpkm",
"name": "getFPKMArray",
"signature": "def getFPKMArray(self)"
},
{
"docstring": "returns array of genes ordered by fpkm and array of the fpkms optional subsetDict returns only genes listed in that array listed as the associated diction... | 5 | null | Implement the Python class `FileFPKM` described below.
Class description:
reading files with FPKM values for genes
Method signatures and docstrings:
- def getFPKMArray(self): returns the array or genes ordered by fpkm
- def getFPKMValueArray(self, subsetDict=None): returns array of genes ordered by fpkm and array of ... | Implement the Python class `FileFPKM` described below.
Class description:
reading files with FPKM values for genes
Method signatures and docstrings:
- def getFPKMArray(self): returns the array or genes ordered by fpkm
- def getFPKMValueArray(self, subsetDict=None): returns array of genes ordered by fpkm and array of ... | 189bf355f0f878c5603b09a06b3b50b61a11ad93 | <|skeleton|>
class FileFPKM:
"""reading files with FPKM values for genes"""
def getFPKMArray(self):
"""returns the array or genes ordered by fpkm"""
<|body_0|>
def getFPKMValueArray(self, subsetDict=None):
"""returns array of genes ordered by fpkm and array of the fpkms optional su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileFPKM:
"""reading files with FPKM values for genes"""
def getFPKMArray(self):
"""returns the array or genes ordered by fpkm"""
self.__checkFPKM()
fpkmFile = open(self.fileStr + '.txt', 'r')
fpkmAr = []
for line in fpkmFile:
line = line.rstrip()
... | the_stack_v2_python_sparse | python_util/bioFiles.py | bhofmei/analysis-scripts | train | 2 |
4b21f623501ef2b4eae6d072f9bf3119a3e067f1 | [
"res = []\nif not root:\n return []\nq = collections.deque([root])\nwhile q:\n for _ in range(len(q)):\n node = q.popleft()\n if node:\n res.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n res.append('null')\nreturn ... | <|body_start_0|>
res = []
if not root:
return []
q = collections.deque([root])
while q:
for _ in range(len(q)):
node = q.popleft()
if node:
res.append(str(node.val))
q.append(node.left)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_014712 | 3,153 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006247 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | fc1b0bec0e28d31e9a6ff722b3a66eacb0278148 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
if not root:
return []
q = collections.deque([root])
while q:
for _ in range(len(q)):
node = q.popleft()
... | the_stack_v2_python_sparse | 树/297二叉树的序列化与反序列化.py | LeopoldACC/Algorithm | train | 2 | |
2246ef973ccdc696e32679c11ba8016fd3cae9bd | [
"if not os.path.exists(folder_path):\n print('FileHasher can not compute SHA from not found folder: ', folder_path)\nsha = hashlib.sha1()\ngathered_files = []\nfor root, dirs, files in os.walk(folder_path):\n del dirs\n for names in files:\n if not FileHasher.is_file_name_extensions_allowed(names, e... | <|body_start_0|>
if not os.path.exists(folder_path):
print('FileHasher can not compute SHA from not found folder: ', folder_path)
sha = hashlib.sha1()
gathered_files = []
for root, dirs, files in os.walk(folder_path):
del dirs
for names in files:
... | This code helps us to hash files inside a folder. | FileHasher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHasher:
"""This code helps us to hash files inside a folder."""
def get_hash_from_files_in_a_folder(folder_path, extensions):
"""Returns a resulting hash from all the files in the folder"""
<|body_0|>
def is_file_name_extensions_allowed(name, extensions):
"""... | stack_v2_sparse_classes_36k_train_014713 | 1,639 | permissive | [
{
"docstring": "Returns a resulting hash from all the files in the folder",
"name": "get_hash_from_files_in_a_folder",
"signature": "def get_hash_from_files_in_a_folder(folder_path, extensions)"
},
{
"docstring": "Checks if a file extensions is allowed",
"name": "is_file_name_extensions_allo... | 2 | stack_v2_sparse_classes_30k_train_012250 | Implement the Python class `FileHasher` described below.
Class description:
This code helps us to hash files inside a folder.
Method signatures and docstrings:
- def get_hash_from_files_in_a_folder(folder_path, extensions): Returns a resulting hash from all the files in the folder
- def is_file_name_extensions_allowe... | Implement the Python class `FileHasher` described below.
Class description:
This code helps us to hash files inside a folder.
Method signatures and docstrings:
- def get_hash_from_files_in_a_folder(folder_path, extensions): Returns a resulting hash from all the files in the folder
- def is_file_name_extensions_allowe... | ab52133249a693b3cd2d8593c5d47408a3b0fce6 | <|skeleton|>
class FileHasher:
"""This code helps us to hash files inside a folder."""
def get_hash_from_files_in_a_folder(folder_path, extensions):
"""Returns a resulting hash from all the files in the folder"""
<|body_0|>
def is_file_name_extensions_allowed(name, extensions):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileHasher:
"""This code helps us to hash files inside a folder."""
def get_hash_from_files_in_a_folder(folder_path, extensions):
"""Returns a resulting hash from all the files in the folder"""
if not os.path.exists(folder_path):
print('FileHasher can not compute SHA from not ... | the_stack_v2_python_sparse | app/logic/bluesteelworker/download/core/FileHasher.py | imvu/bluesteel | train | 10 |
5c8858afdae7d40b663d90f047ba8184acf0ef90 | [
"try:\n registration_profile = self.get(activation_key=activation_key)\nexcept self.model.DoesNotExist:\n return None\nif not registration_profile.is_expired():\n user = registration_profile.user\n user.is_active = True\n user.save()\n registration_profile.delete()\n return user\nelse:\n ret... | <|body_start_0|>
try:
registration_profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return None
if not registration_profile.is_expired():
user = registration_profile.user
user.is_active = True
user.save(... | RegistrationManager Methods: activate_account create_inactive_user create_registration_profile | RegistrationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
"""RegistrationManager Methods: activate_account create_inactive_user create_registration_profile"""
def activate_account(self, activation_key):
"""Activate Account Given an activation key, this function queries the DB to see if there is a matching registration p... | stack_v2_sparse_classes_36k_train_014714 | 4,537 | no_license | [
{
"docstring": "Activate Account Given an activation key, this function queries the DB to see if there is a matching registration profile. If there is, the associated user is activated.",
"name": "activate_account",
"signature": "def activate_account(self, activation_key)"
},
{
"docstring": "Cre... | 3 | stack_v2_sparse_classes_30k_train_008854 | Implement the Python class `RegistrationManager` described below.
Class description:
RegistrationManager Methods: activate_account create_inactive_user create_registration_profile
Method signatures and docstrings:
- def activate_account(self, activation_key): Activate Account Given an activation key, this function qu... | Implement the Python class `RegistrationManager` described below.
Class description:
RegistrationManager Methods: activate_account create_inactive_user create_registration_profile
Method signatures and docstrings:
- def activate_account(self, activation_key): Activate Account Given an activation key, this function qu... | e04aae54afb6ba6c138f4253ca7be32faea0da81 | <|skeleton|>
class RegistrationManager:
"""RegistrationManager Methods: activate_account create_inactive_user create_registration_profile"""
def activate_account(self, activation_key):
"""Activate Account Given an activation key, this function queries the DB to see if there is a matching registration p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationManager:
"""RegistrationManager Methods: activate_account create_inactive_user create_registration_profile"""
def activate_account(self, activation_key):
"""Activate Account Given an activation key, this function queries the DB to see if there is a matching registration profile. If th... | the_stack_v2_python_sparse | src/debitum/accounts/models.py | keunhong/oweapp | train | 0 |
8db1b61c28980622f400d51dc5bcc14014beeba6 | [
"super().__init__()\nself.root = root\nfiles = glob.glob(os.path.join(root, '**.csv'))\nif not files:\n raise FileNotFoundError(f'Dataset not found in `root={self.root}`')\ntry:\n import pandas as pd\nexcept ImportError:\n raise ImportError('pandas is not installed and is required to use this dataset')\nda... | <|body_start_0|>
super().__init__()
self.root = root
files = glob.glob(os.path.join(root, '**.csv'))
if not files:
raise FileNotFoundError(f'Dataset not found in `root={self.root}`')
try:
import pandas as pd
except ImportError:
raise Im... | Dataset for the Global Biodiversity Information Facility. `GBIF <https://www.gbif.org/>`__, the Global Biodiversity Information Facility, is an international network and data infrastructure funded by the world's governments and aimed at providing anyone, anywhere, open access to data about all types of life on Earth. T... | GBIF | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GBIF:
"""Dataset for the Global Biodiversity Information Facility. `GBIF <https://www.gbif.org/>`__, the Global Biodiversity Information Facility, is an international network and data infrastructure funded by the world's governments and aimed at providing anyone, anywhere, open access to data abo... | stack_v2_sparse_classes_36k_train_014715 | 4,573 | permissive | [
{
"docstring": "Initialize a new Dataset instance. Args: root: root directory where dataset can be found Raises: FileNotFoundError: if no files are found in ``root`` ImportError: if pandas is not installed",
"name": "__init__",
"signature": "def __init__(self, root: str='data') -> None"
},
{
"do... | 2 | null | Implement the Python class `GBIF` described below.
Class description:
Dataset for the Global Biodiversity Information Facility. `GBIF <https://www.gbif.org/>`__, the Global Biodiversity Information Facility, is an international network and data infrastructure funded by the world's governments and aimed at providing an... | Implement the Python class `GBIF` described below.
Class description:
Dataset for the Global Biodiversity Information Facility. `GBIF <https://www.gbif.org/>`__, the Global Biodiversity Information Facility, is an international network and data infrastructure funded by the world's governments and aimed at providing an... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class GBIF:
"""Dataset for the Global Biodiversity Information Facility. `GBIF <https://www.gbif.org/>`__, the Global Biodiversity Information Facility, is an international network and data infrastructure funded by the world's governments and aimed at providing anyone, anywhere, open access to data abo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GBIF:
"""Dataset for the Global Biodiversity Information Facility. `GBIF <https://www.gbif.org/>`__, the Global Biodiversity Information Facility, is an international network and data infrastructure funded by the world's governments and aimed at providing anyone, anywhere, open access to data about all types ... | the_stack_v2_python_sparse | torchgeo/datasets/gbif.py | microsoft/torchgeo | train | 1,724 |
076926b67d83c0fe0984dcb00c3bf0a0a66c9375 | [
"loading_plans = [self.input_seg_loading_plan_path, self.prob_loading_plan_path] + list(self.additional_loading_plan_paths)\nfor loading_plan in loading_plans:\n for tgt in DestVolumeReader(loading_plan).get_source_targets():\n yield tgt",
"v1 = np.prod([2048, 2048, 100])\nm1 = (3685308 + 152132) * 1000... | <|body_start_0|>
loading_plans = [self.input_seg_loading_plan_path, self.prob_loading_plan_path] + list(self.additional_loading_plan_paths)
for loading_plan in loading_plans:
for tgt in DestVolumeReader(loading_plan).get_source_targets():
yield tgt
<|end_body_0|>
<|body_star... | NeuroproofStitchTaskMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuroproofStitchTaskMixin:
def input(self):
"""Yield the probability volume target and segmentation volume target"""
<|body_0|>
def estimate_memory_usage(self):
"""Return an estimate of bytes of memory required by this task"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_014716 | 16,148 | no_license | [
{
"docstring": "Yield the probability volume target and segmentation volume target",
"name": "input",
"signature": "def input(self)"
},
{
"docstring": "Return an estimate of bytes of memory required by this task",
"name": "estimate_memory_usage",
"signature": "def estimate_memory_usage(s... | 2 | stack_v2_sparse_classes_30k_train_011942 | Implement the Python class `NeuroproofStitchTaskMixin` described below.
Class description:
Implement the NeuroproofStitchTaskMixin class.
Method signatures and docstrings:
- def input(self): Yield the probability volume target and segmentation volume target
- def estimate_memory_usage(self): Return an estimate of byt... | Implement the Python class `NeuroproofStitchTaskMixin` described below.
Class description:
Implement the NeuroproofStitchTaskMixin class.
Method signatures and docstrings:
- def input(self): Yield the probability volume target and segmentation volume target
- def estimate_memory_usage(self): Return an estimate of byt... | cf100202997d3c848a21de441e15deb9f975042d | <|skeleton|>
class NeuroproofStitchTaskMixin:
def input(self):
"""Yield the probability volume target and segmentation volume target"""
<|body_0|>
def estimate_memory_usage(self):
"""Return an estimate of bytes of memory required by this task"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeuroproofStitchTaskMixin:
def input(self):
"""Yield the probability volume target and segmentation volume target"""
loading_plans = [self.input_seg_loading_plan_path, self.prob_loading_plan_path] + list(self.additional_loading_plan_paths)
for loading_plan in loading_plans:
... | the_stack_v2_python_sparse | ariadne_microns_pipeline/tasks/neuroproof_stitch.py | microns-ariadne/pipeline_engine | train | 2 | |
e13d57d4f621c33d911f0c6188ebcffdc4e7d1d5 | [
"handle = self._handle\nhandle.seek(pos)\nsentinel = b'Query:'\nwhile True:\n line = handle.readline().strip()\n if line.startswith(sentinel):\n break\n if not line:\n raise StopIteration\nqid, desc = _parse_hit_or_query_line(line.decode())\nreturn qid",
"handle = self._handle\nhandle.seek(... | <|body_start_0|>
handle = self._handle
handle.seek(pos)
sentinel = b'Query:'
while True:
line = handle.readline().strip()
if line.startswith(sentinel):
break
if not line:
raise StopIteration
qid, desc = _parse_hi... | Indexer class for Exonerate plain text. | ExonerateTextIndexer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExonerateTextIndexer:
"""Indexer class for Exonerate plain text."""
def get_qresult_id(self, pos):
"""Return the query ID from the nearest "Query:" line."""
<|body_0|>
def get_raw(self, offset):
"""Return the raw string of a QueryResult object from the given offs... | stack_v2_sparse_classes_36k_train_014717 | 20,436 | permissive | [
{
"docstring": "Return the query ID from the nearest \"Query:\" line.",
"name": "get_qresult_id",
"signature": "def get_qresult_id(self, pos)"
},
{
"docstring": "Return the raw string of a QueryResult object from the given offset.",
"name": "get_raw",
"signature": "def get_raw(self, offs... | 2 | null | Implement the Python class `ExonerateTextIndexer` described below.
Class description:
Indexer class for Exonerate plain text.
Method signatures and docstrings:
- def get_qresult_id(self, pos): Return the query ID from the nearest "Query:" line.
- def get_raw(self, offset): Return the raw string of a QueryResult objec... | Implement the Python class `ExonerateTextIndexer` described below.
Class description:
Indexer class for Exonerate plain text.
Method signatures and docstrings:
- def get_qresult_id(self, pos): Return the query ID from the nearest "Query:" line.
- def get_raw(self, offset): Return the raw string of a QueryResult objec... | 595c5c46794ae08a1f19716636eac7430cededa1 | <|skeleton|>
class ExonerateTextIndexer:
"""Indexer class for Exonerate plain text."""
def get_qresult_id(self, pos):
"""Return the query ID from the nearest "Query:" line."""
<|body_0|>
def get_raw(self, offset):
"""Return the raw string of a QueryResult object from the given offs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExonerateTextIndexer:
"""Indexer class for Exonerate plain text."""
def get_qresult_id(self, pos):
"""Return the query ID from the nearest "Query:" line."""
handle = self._handle
handle.seek(pos)
sentinel = b'Query:'
while True:
line = handle.readline()... | the_stack_v2_python_sparse | .venv/Lib/site-packages/Bio/SearchIO/ExonerateIO/exonerate_text.py | abner-lucas/tp-cruzi-db | train | 2 |
db2610ebdcd659bc44fa833e9d796ece998442e9 | [
"n = len(jewelList)\nMaxRevenue = np.zeros((n, G + 1))\nSolutionCount = np.zeros((n, G + 1))\nfor j in range(0, G + 1):\n SolutionCount[0][j] = 1\nfor i in range(1, n):\n for g in range(0, G + 1):\n q = -99999\n for q_i in range(0, jewelList[i].x + 1):\n if g - q_i * jewelList[i].w >=... | <|body_start_0|>
n = len(jewelList)
MaxRevenue = np.zeros((n, G + 1))
SolutionCount = np.zeros((n, G + 1))
for j in range(0, G + 1):
SolutionCount[0][j] = 1
for i in range(1, n):
for g in range(0, G + 1):
q = -99999
for q_i ... | JewelRCPAlgo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JewelRCPAlgo:
def optimalMaxRevenue(self, G, jewelList):
"""based on G and jewelList, return optimal solution and number of possible optimal solution"""
<|body_0|>
def enumerateSolution(self, s, jewelList, MaxRevenue, g, i):
"""printing entire solution using recursio... | stack_v2_sparse_classes_36k_train_014718 | 9,350 | no_license | [
{
"docstring": "based on G and jewelList, return optimal solution and number of possible optimal solution",
"name": "optimalMaxRevenue",
"signature": "def optimalMaxRevenue(self, G, jewelList)"
},
{
"docstring": "printing entire solution using recursion",
"name": "enumerateSolution",
"si... | 4 | stack_v2_sparse_classes_30k_train_001467 | Implement the Python class `JewelRCPAlgo` described below.
Class description:
Implement the JewelRCPAlgo class.
Method signatures and docstrings:
- def optimalMaxRevenue(self, G, jewelList): based on G and jewelList, return optimal solution and number of possible optimal solution
- def enumerateSolution(self, s, jewe... | Implement the Python class `JewelRCPAlgo` described below.
Class description:
Implement the JewelRCPAlgo class.
Method signatures and docstrings:
- def optimalMaxRevenue(self, G, jewelList): based on G and jewelList, return optimal solution and number of possible optimal solution
- def enumerateSolution(self, s, jewe... | 9cc59b53d1e0754d30041401d51976c01087e284 | <|skeleton|>
class JewelRCPAlgo:
def optimalMaxRevenue(self, G, jewelList):
"""based on G and jewelList, return optimal solution and number of possible optimal solution"""
<|body_0|>
def enumerateSolution(self, s, jewelList, MaxRevenue, g, i):
"""printing entire solution using recursio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JewelRCPAlgo:
def optimalMaxRevenue(self, G, jewelList):
"""based on G and jewelList, return optimal solution and number of possible optimal solution"""
n = len(jewelList)
MaxRevenue = np.zeros((n, G + 1))
SolutionCount = np.zeros((n, G + 1))
for j in range(0, G + 1):
... | the_stack_v2_python_sparse | algorithmAsg/jewelRCPAlgo.py | nidhitvaishnav/AlgorithmPractice | train | 4 | |
f70fd974c27e27efe546ebcb21fbaff8e3ff9664 | [
"path = super().save(dirpath, data, image, extension, **kwargs)\nif self.model is not None:\n with open(join(path, 'model.pkl'), 'wb') as file:\n pickle.dump(self.model, file)\nreturn path",
"io = IO()\nvalues_path = join(path, 'values.npy')\nif exists(values_path):\n values = io.read_npy(values_path... | <|body_start_0|>
path = super().save(dirpath, data, image, extension, **kwargs)
if self.model is not None:
with open(join(path, 'model.pkl'), 'wb') as file:
pickle.dump(self.model, file)
return path
<|end_body_0|>
<|body_start_1|>
io = IO()
values_pat... | Methods for saving and loading classifier objects. | MixtureModelIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixtureModelIO:
"""Methods for saving and loading classifier objects."""
def save(self, dirpath, data=False, image=True, extension=None, **kwargs):
"""Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save tra... | stack_v2_sparse_classes_36k_train_014719 | 9,152 | permissive | [
{
"docstring": "Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save training data image (bool) - if True, save labeled histogram image extension (str) - directory name extension kwargs: keyword arguments for image rendering",
"nam... | 2 | stack_v2_sparse_classes_30k_train_018590 | Implement the Python class `MixtureModelIO` described below.
Class description:
Methods for saving and loading classifier objects.
Method signatures and docstrings:
- def save(self, dirpath, data=False, image=True, extension=None, **kwargs): Save classifier to specified path. Args: dirpath (str) - directory in which ... | Implement the Python class `MixtureModelIO` described below.
Class description:
Methods for saving and loading classifier objects.
Method signatures and docstrings:
- def save(self, dirpath, data=False, image=True, extension=None, **kwargs): Save classifier to specified path. Args: dirpath (str) - directory in which ... | 4a622c3f5fed4456c3b9240f5a96428789fde9bd | <|skeleton|>
class MixtureModelIO:
"""Methods for saving and loading classifier objects."""
def save(self, dirpath, data=False, image=True, extension=None, **kwargs):
"""Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixtureModelIO:
"""Methods for saving and loading classifier objects."""
def save(self, dirpath, data=False, image=True, extension=None, **kwargs):
"""Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save training data im... | the_stack_v2_python_sparse | flyqma/annotation/classification/mixtures.py | sbernasek/flyqma | train | 1 |
d764cb7bd2c69d7ee18c303fd60e86d5d5b505af | [
"super().__init__(**kwargs)\nself.discriminator = []\nfor i in range(config.scales):\n self.discriminator += [TFMelGANDiscriminator(out_channels=config.out_channels, kernel_sizes=config.kernel_sizes, filters=config.filters, max_downsample_filters=config.max_downsample_filters, use_bias=config.use_bias, downsampl... | <|body_start_0|>
super().__init__(**kwargs)
self.discriminator = []
for i in range(config.scales):
self.discriminator += [TFMelGANDiscriminator(out_channels=config.out_channels, kernel_sizes=config.kernel_sizes, filters=config.filters, max_downsample_filters=config.max_downsample_fil... | MelGAN multi-scale discriminator module. | TFMelGANMultiScaleDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFMelGANMultiScaleDiscriminator:
"""MelGAN multi-scale discriminator module."""
def __init__(self, config, **kwargs):
"""Initilize MelGAN multi-scale discriminator module. Args: config: config object for melgan discriminator"""
<|body_0|>
def call(self, x, **kwargs):
... | stack_v2_sparse_classes_36k_train_014720 | 17,807 | permissive | [
{
"docstring": "Initilize MelGAN multi-scale discriminator module. Args: config: config object for melgan discriminator",
"name": "__init__",
"signature": "def __init__(self, config, **kwargs)"
},
{
"docstring": "Calculate forward propagation. Args: x (Tensor): Input noise signal (B, T, 1). Retu... | 2 | stack_v2_sparse_classes_30k_train_000596 | Implement the Python class `TFMelGANMultiScaleDiscriminator` described below.
Class description:
MelGAN multi-scale discriminator module.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Initilize MelGAN multi-scale discriminator module. Args: config: config object for melgan discriminator
- ... | Implement the Python class `TFMelGANMultiScaleDiscriminator` described below.
Class description:
MelGAN multi-scale discriminator module.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Initilize MelGAN multi-scale discriminator module. Args: config: config object for melgan discriminator
- ... | 136877136355c82d7ba474ceb7a8f133bd84767e | <|skeleton|>
class TFMelGANMultiScaleDiscriminator:
"""MelGAN multi-scale discriminator module."""
def __init__(self, config, **kwargs):
"""Initilize MelGAN multi-scale discriminator module. Args: config: config object for melgan discriminator"""
<|body_0|>
def call(self, x, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFMelGANMultiScaleDiscriminator:
"""MelGAN multi-scale discriminator module."""
def __init__(self, config, **kwargs):
"""Initilize MelGAN multi-scale discriminator module. Args: config: config object for melgan discriminator"""
super().__init__(**kwargs)
self.discriminator = []
... | the_stack_v2_python_sparse | tensorflow_tts/models/melgan.py | TensorSpeech/TensorFlowTTS | train | 2,889 |
2233c94d4d296fe2223b66a30bdfd27080119d5f | [
"super().__init__(self.PROBLEM_NAME)\nself.input_capacity_matrix = input_capacity_matrix\nself.source = source\nself.sink = sink",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nmax_rows = len(self.input_capacity_matrix)\nparent_list = [-1] * max_rows\nmax_flow = 0\nwhile self.breadth_first_search(se... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_capacity_matrix = input_capacity_matrix
self.source = source
self.sink = sink
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
max_rows = len(self.input_capacity_matr... | MaxFlowFordFulkersonAlgorithm | MaxFlowFordFulkersonAlgorithm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxFlowFordFulkersonAlgorithm:
"""MaxFlowFordFulkersonAlgorithm"""
def __init__(self, input_capacity_matrix, source, sink):
"""Max Flow (Ford Fulkerson) Args: input_capacity_matrix: Graph with vertex to vertex capacities Returns: None Raises: None"""
<|body_0|>
def solve... | stack_v2_sparse_classes_36k_train_014721 | 4,311 | no_license | [
{
"docstring": "Max Flow (Ford Fulkerson) Args: input_capacity_matrix: Graph with vertex to vertex capacities Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_capacity_matrix, source, sink)"
},
{
"docstring": "Solve the problem Note: O(MAX_FLOW * E) solutio... | 3 | stack_v2_sparse_classes_30k_train_014945 | Implement the Python class `MaxFlowFordFulkersonAlgorithm` described below.
Class description:
MaxFlowFordFulkersonAlgorithm
Method signatures and docstrings:
- def __init__(self, input_capacity_matrix, source, sink): Max Flow (Ford Fulkerson) Args: input_capacity_matrix: Graph with vertex to vertex capacities Return... | Implement the Python class `MaxFlowFordFulkersonAlgorithm` described below.
Class description:
MaxFlowFordFulkersonAlgorithm
Method signatures and docstrings:
- def __init__(self, input_capacity_matrix, source, sink): Max Flow (Ford Fulkerson) Args: input_capacity_matrix: Graph with vertex to vertex capacities Return... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class MaxFlowFordFulkersonAlgorithm:
"""MaxFlowFordFulkersonAlgorithm"""
def __init__(self, input_capacity_matrix, source, sink):
"""Max Flow (Ford Fulkerson) Args: input_capacity_matrix: Graph with vertex to vertex capacities Returns: None Raises: None"""
<|body_0|>
def solve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxFlowFordFulkersonAlgorithm:
"""MaxFlowFordFulkersonAlgorithm"""
def __init__(self, input_capacity_matrix, source, sink):
"""Max Flow (Ford Fulkerson) Args: input_capacity_matrix: Graph with vertex to vertex capacities Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
... | the_stack_v2_python_sparse | python/problems/graphs/max_flow_ford_fulkerson.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
efcd2a95c1583f52bdafe168336bec0d29651323 | [
"save_file = open('file.txt', 'w')\nfor i in game_matrix:\n string = ' '.join(i) + ' \\n'\n save_file.write(string)\nsave_file.close()",
"game_matrix = []\ntry:\n load_file = open('file.txt', 'r')\n data = load_file.readlines()\n load_file.close()\n for i in range(len(data)):\n line = dat... | <|body_start_0|>
save_file = open('file.txt', 'w')
for i in game_matrix:
string = ' '.join(i) + ' \n'
save_file.write(string)
save_file.close()
<|end_body_0|>
<|body_start_1|>
game_matrix = []
try:
load_file = open('file.txt', 'r')
... | GameIO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameIO:
def save_game(self, game_matrix):
"""Save game map in file. :param my_map: game area. :type my_map: list. :return: None."""
<|body_0|>
def load_game(self):
"""Load game map from file. :return: game map. :rtype: list."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_014722 | 1,000 | no_license | [
{
"docstring": "Save game map in file. :param my_map: game area. :type my_map: list. :return: None.",
"name": "save_game",
"signature": "def save_game(self, game_matrix)"
},
{
"docstring": "Load game map from file. :return: game map. :rtype: list.",
"name": "load_game",
"signature": "def... | 2 | null | Implement the Python class `GameIO` described below.
Class description:
Implement the GameIO class.
Method signatures and docstrings:
- def save_game(self, game_matrix): Save game map in file. :param my_map: game area. :type my_map: list. :return: None.
- def load_game(self): Load game map from file. :return: game ma... | Implement the Python class `GameIO` described below.
Class description:
Implement the GameIO class.
Method signatures and docstrings:
- def save_game(self, game_matrix): Save game map in file. :param my_map: game area. :type my_map: list. :return: None.
- def load_game(self): Load game map from file. :return: game ma... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class GameIO:
def save_game(self, game_matrix):
"""Save game map in file. :param my_map: game area. :type my_map: list. :return: None."""
<|body_0|>
def load_game(self):
"""Load game map from file. :return: game map. :rtype: list."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameIO:
def save_game(self, game_matrix):
"""Save game map in file. :param my_map: game area. :type my_map: list. :return: None."""
save_file = open('file.txt', 'w')
for i in game_matrix:
string = ' '.join(i) + ' \n'
save_file.write(string)
save_file.clo... | the_stack_v2_python_sparse | Serhii_Oliinyk/10/game/dungeon_game_save_and_load.py | SmischenkoB/campus_2018_python | train | 0 | |
19386566b362a1bc950e830faad6027f7f4c0c55 | [
"result = []\n\ndef dfs(previous_total, previous_value, pop, low_index, previous_str):\n \"\"\"\n :param previous_total: previous total, shoud not be modified.\n :param previous_value: previous single value.\n :param pop: previous op.\n \"\"\"\n if low_index == len(... | <|body_start_0|>
result = []
def dfs(previous_total, previous_value, pop, low_index, previous_str):
"""
:param previous_total: previous total, shoud not be modified.
:param previous_value: previous single value.
:param pop: previou... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addOperators(self, num, target):
""":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is '1' '00' -> '0' '01' -> '1' moving index"""
<|body_0|>
def rewrite(self, num, targe... | stack_v2_sparse_classes_36k_train_014723 | 5,268 | no_license | [
{
"docstring": ":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of \"001\" convert to int is '1' '00' -> '0' '01' -> '1' moving index",
"name": "addOperators",
"signature": "def addOperators(self, num, target)"
},
{
"docstring": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addOperators(self, num, target): :type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addOperators(self, num, target): :type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def addOperators(self, num, target):
""":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is '1' '00' -> '0' '01' -> '1' moving index"""
<|body_0|>
def rewrite(self, num, targe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addOperators(self, num, target):
""":type num: str :type target: int :rtype: List[str] 1 23 12 3 123 -- 1 23 1 2 3 1 23 -- 12 3 12 3 -- 123 123 beware of "001" convert to int is '1' '00' -> '0' '01' -> '1' moving index"""
result = []
def dfs(previous_total, previous_valu... | the_stack_v2_python_sparse | co_fb/282_Expression_Add_Operators.py | vsdrun/lc_public | train | 6 | |
ac86dfd9cff0926f58a8d34b81df05793481542b | [
"if not matrix:\n return False\nrow = len(matrix)\ncolumn = len(matrix[0])\ni, j = (0, column - 1)\nwhile i < row and j >= 0:\n if matrix[i][j] == target:\n return True\n elif matrix[i][j] > target:\n j -= 1\n else:\n i += 1\nreturn False",
"if not matrix:\n return False\nif no... | <|body_start_0|>
if not matrix:
return False
row = len(matrix)
column = len(matrix[0])
i, j = (0, column - 1)
while i < row and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
j -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_014724 | 2,043 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix2",
"signature": "def search... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix2(self, matrix, target): :type matrix: List[List[int]] :typ... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
row = len(matrix)
column = len(matrix[0])
i, j = (0, column - 1)
while i < row and j >= 0:
if... | the_stack_v2_python_sparse | code/74#Search a 2D Matrix.py | EachenKuang/LeetCode | train | 28 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nparticipation_list = adm.get_all_participations()\nreturn participation_list",
"adm = ProjectAdministration()\nproposal = Participation.from_dict(api.payload)\nif proposal is not None:\n 'Wir verwenden die participation_id des Proposals für die Erzeugung eines Participation-Obje... | <|body_start_0|>
adm = ProjectAdministration()
participation_list = adm.get_all_participations()
return participation_list
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
proposal = Participation.from_dict(api.payload)
if proposal is not None:
'... | ParticipationListOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipationListOperations:
def get(self):
"""Auslesen aller Participation-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen Participation-Objekts"""
<|body_1|>
def put(self):
"""Update eines bestimmten Participation-Objekts."""
... | stack_v2_sparse_classes_36k_train_014725 | 44,493 | no_license | [
{
"docstring": "Auslesen aller Participation-Objekte",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Anlegen eines neuen Participation-Objekts",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update eines bestimmten Participation-Objekts.",
... | 3 | stack_v2_sparse_classes_30k_train_011157 | Implement the Python class `ParticipationListOperations` described below.
Class description:
Implement the ParticipationListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller Participation-Objekte
- def post(self): Anlegen eines neuen Participation-Objekts
- def put(self): Update eine... | Implement the Python class `ParticipationListOperations` described below.
Class description:
Implement the ParticipationListOperations class.
Method signatures and docstrings:
- def get(self): Auslesen aller Participation-Objekte
- def post(self): Anlegen eines neuen Participation-Objekts
- def put(self): Update eine... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ParticipationListOperations:
def get(self):
"""Auslesen aller Participation-Objekte"""
<|body_0|>
def post(self):
"""Anlegen eines neuen Participation-Objekts"""
<|body_1|>
def put(self):
"""Update eines bestimmten Participation-Objekts."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticipationListOperations:
def get(self):
"""Auslesen aller Participation-Objekte"""
adm = ProjectAdministration()
participation_list = adm.get_all_participations()
return participation_list
def post(self):
"""Anlegen eines neuen Participation-Objekts"""
... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
41b1620c3c9de9a2de26b7ff9e7a41a6f47ab0ba | [
"self.files_and_folders_info = files_and_folders_info\nself.name = name\nself.source_object_info = source_object_info",
"if dictionary is None:\n return None\nfiles_and_folders_info = None\nif dictionary.get('filesAndFoldersInfo') != None:\n files_and_folders_info = list()\n for structure in dictionary.g... | <|body_start_0|>
self.files_and_folders_info = files_and_folders_info
self.name = name
self.source_object_info = source_object_info
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
files_and_folders_info = None
if dictionary.get('filesAndFol... | Implementation of the 'DownloadFilesAndFoldersParams' model. DownloadFilesAndFoldersParams holds the information to create a task for downloading list of files or folders Attributes: files_and_folders_info (list of FilesAndFoldersInfo): Specifies the absolute paths for list of files and folders to download. name (strin... | DownloadFilesAndFoldersParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadFilesAndFoldersParams:
"""Implementation of the 'DownloadFilesAndFoldersParams' model. DownloadFilesAndFoldersParams holds the information to create a task for downloading list of files or folders Attributes: files_and_folders_info (list of FilesAndFoldersInfo): Specifies the absolute pat... | stack_v2_sparse_classes_36k_train_014726 | 2,863 | permissive | [
{
"docstring": "Constructor for the DownloadFilesAndFoldersParams class",
"name": "__init__",
"signature": "def __init__(self, files_and_folders_info=None, name=None, source_object_info=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A... | 2 | stack_v2_sparse_classes_30k_train_018810 | Implement the Python class `DownloadFilesAndFoldersParams` described below.
Class description:
Implementation of the 'DownloadFilesAndFoldersParams' model. DownloadFilesAndFoldersParams holds the information to create a task for downloading list of files or folders Attributes: files_and_folders_info (list of FilesAndF... | Implement the Python class `DownloadFilesAndFoldersParams` described below.
Class description:
Implementation of the 'DownloadFilesAndFoldersParams' model. DownloadFilesAndFoldersParams holds the information to create a task for downloading list of files or folders Attributes: files_and_folders_info (list of FilesAndF... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DownloadFilesAndFoldersParams:
"""Implementation of the 'DownloadFilesAndFoldersParams' model. DownloadFilesAndFoldersParams holds the information to create a task for downloading list of files or folders Attributes: files_and_folders_info (list of FilesAndFoldersInfo): Specifies the absolute pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadFilesAndFoldersParams:
"""Implementation of the 'DownloadFilesAndFoldersParams' model. DownloadFilesAndFoldersParams holds the information to create a task for downloading list of files or folders Attributes: files_and_folders_info (list of FilesAndFoldersInfo): Specifies the absolute paths for list o... | the_stack_v2_python_sparse | cohesity_management_sdk/models/download_files_and_folders_params.py | cohesity/management-sdk-python | train | 24 |
ed86ecd23c3431869dad06cef9d5b717cd8a2453 | [
"if columns is not None:\n if isinstance(columns, list) or isinstance(columns, tuple):\n self.columns = columns\n else:\n raise TypeError('Invalid type {}'.format(type(columns)))\nelse:\n self.columns = columns\nself.drop = drop",
"if self.columns is None:\n self.columns = X.select_dtype... | <|body_start_0|>
if columns is not None:
if isinstance(columns, list) or isinstance(columns, tuple):
self.columns = columns
else:
raise TypeError('Invalid type {}'.format(type(columns)))
else:
self.columns = columns
self.drop = ... | This transformer applies log to skewed features. Attributes ---------- columns: npandas [n_columns] Examples -------- For usage examples, please see: https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FixSkewness/ | FixSkewness | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixSkewness:
"""This transformer applies log to skewed features. Attributes ---------- columns: npandas [n_columns] Examples -------- For usage examples, please see: https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FixSkewness/"""
def __init__(self, columns=None, drop=True):
... | stack_v2_sparse_classes_36k_train_014727 | 3,058 | permissive | [
{
"docstring": "Init log skewed.",
"name": "__init__",
"signature": "def __init__(self, columns=None, drop=True)"
},
{
"docstring": "Selecting skewed columns from the dataset. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n_samples is the number of sampl... | 3 | stack_v2_sparse_classes_30k_train_015274 | Implement the Python class `FixSkewness` described below.
Class description:
This transformer applies log to skewed features. Attributes ---------- columns: npandas [n_columns] Examples -------- For usage examples, please see: https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FixSkewness/
Method signatu... | Implement the Python class `FixSkewness` described below.
Class description:
This transformer applies log to skewed features. Attributes ---------- columns: npandas [n_columns] Examples -------- For usage examples, please see: https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FixSkewness/
Method signatu... | e768a4cad150b35fb5bf543ab28aa23764af51d9 | <|skeleton|>
class FixSkewness:
"""This transformer applies log to skewed features. Attributes ---------- columns: npandas [n_columns] Examples -------- For usage examples, please see: https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FixSkewness/"""
def __init__(self, columns=None, drop=True):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixSkewness:
"""This transformer applies log to skewed features. Attributes ---------- columns: npandas [n_columns] Examples -------- For usage examples, please see: https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/FixSkewness/"""
def __init__(self, columns=None, drop=True):
"""Ini... | the_stack_v2_python_sparse | mlearner/preprocessing/log_skewed.py | jaisenbe58r/MLearner | train | 9 |
e2fa4c0c3f045bd7b49d517d7b93a8aa4c0e66fb | [
"tokens = ['a', 'bb', 'ccc']\ntext = 'a bb ccc'\nspans = list(generic_token_spans(text, tokens))\nexpected = [Span(0, 1), Span(2, 4), Span(8, 11)]\nself.assertEquals(expected, spans)",
"tokens = ['a', 'b b', 'c c c']\ntext = 'a bb ccc'\nspans = list(generic_token_spans(text, tokens))\nexpected = [Span(0, 1)... | <|body_start_0|>
tokens = ['a', 'bb', 'ccc']
text = 'a bb ccc'
spans = list(generic_token_spans(text, tokens))
expected = [Span(0, 1), Span(2, 4), Span(8, 11)]
self.assertEquals(expected, spans)
<|end_body_0|>
<|body_start_1|>
tokens = ['a', 'b b', 'c c c']
te... | Working with part of speech taggers | PosTag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosTag:
"""Working with part of speech taggers"""
def test_simple_align(self):
"""trivial token realignment"""
<|body_0|>
def test_messy_align(self):
"""ignore whitespace in token"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tokens = ['a', 'b... | stack_v2_sparse_classes_36k_train_014728 | 978 | no_license | [
{
"docstring": "trivial token realignment",
"name": "test_simple_align",
"signature": "def test_simple_align(self)"
},
{
"docstring": "ignore whitespace in token",
"name": "test_messy_align",
"signature": "def test_messy_align(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000122 | Implement the Python class `PosTag` described below.
Class description:
Working with part of speech taggers
Method signatures and docstrings:
- def test_simple_align(self): trivial token realignment
- def test_messy_align(self): ignore whitespace in token | Implement the Python class `PosTag` described below.
Class description:
Working with part of speech taggers
Method signatures and docstrings:
- def test_simple_align(self): trivial token realignment
- def test_messy_align(self): ignore whitespace in token
<|skeleton|>
class PosTag:
"""Working with part of speech... | c550f4383016e05fe20ad7180a027979e3540d1f | <|skeleton|>
class PosTag:
"""Working with part of speech taggers"""
def test_simple_align(self):
"""trivial token realignment"""
<|body_0|>
def test_messy_align(self):
"""ignore whitespace in token"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PosTag:
"""Working with part of speech taggers"""
def test_simple_align(self):
"""trivial token realignment"""
tokens = ['a', 'bb', 'ccc']
text = 'a bb ccc'
spans = list(generic_token_spans(text, tokens))
expected = [Span(0, 1), Span(2, 4), Span(8, 11)]
... | the_stack_v2_python_sparse | educe/external/tests.py | kowey/educe | train | 1 |
ea528af4785b7df4535ffd317f9b5397290e0a05 | [
"dummy = TreeNode(0)\nself.prev = dummy\n\ndef inorder(root):\n if not root:\n return\n inorder(root.left)\n root.left = None\n self.prev.right = root\n self.prev = self.prev.right\n inorder(root.right)\ninorder(root)\nreturn dummy.right",
"new_root = TreeNode(0)\nnodes = []\n\ndef recons... | <|body_start_0|>
dummy = TreeNode(0)
self.prev = dummy
def inorder(root):
if not root:
return
inorder(root.left)
root.left = None
self.prev.right = root
self.prev = self.prev.right
inorder(root.right)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingBST(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def increasingBST_2(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy = TreeNode(0)
sel... | stack_v2_sparse_classes_36k_train_014729 | 2,163 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "increasingBST",
"signature": "def increasingBST(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "increasingBST_2",
"signature": "def increasingBST_2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001714 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingBST(self, root): :type root: TreeNode :rtype: TreeNode
- def increasingBST_2(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingBST(self, root): :type root: TreeNode :rtype: TreeNode
- def increasingBST_2(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solution:
d... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def increasingBST(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def increasingBST_2(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def increasingBST(self, root):
""":type root: TreeNode :rtype: TreeNode"""
dummy = TreeNode(0)
self.prev = dummy
def inorder(root):
if not root:
return
inorder(root.left)
root.left = None
self.prev.right... | the_stack_v2_python_sparse | python/897.increasing-order-search-tree.py | tainenko/Leetcode2019 | train | 5 | |
3ca38ffd1e8338c0bb56d99fe07cdc9eee4e59cf | [
"wordSet = set(wordList)\nif beginWord in wordSet:\n wordSet.remove(beginWord)\nqueue = [beginWord]\nlevel = 1\nwhile len(queue) > 0:\n neighbors = []\n for word in queue:\n if word == endWord:\n return level\n else:\n self._findNeighbors(word, neighbors, wordSet)\n l... | <|body_start_0|>
wordSet = set(wordList)
if beginWord in wordSet:
wordSet.remove(beginWord)
queue = [beginWord]
level = 1
while len(queue) > 0:
neighbors = []
for word in queue:
if word == endWord:
return lev... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int"""
<|body_0|>
def _findNeighbors(self, word, neighbors, wordSet):
""":type word: str :type neighbors: list :type wordSet: ... | stack_v2_sparse_classes_36k_train_014730 | 5,496 | no_license | [
{
"docstring": ":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int",
"name": "ladderLength",
"signature": "def ladderLength(self, beginWord, endWord, wordList)"
},
{
"docstring": ":type word: str :type neighbors: list :type wordSet: set",
"name": "_findNeighbors",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLength(self, beginWord, endWord, wordList): :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int
- def _findNeighbors(self, word, neighbors, wo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLength(self, beginWord, endWord, wordList): :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int
- def _findNeighbors(self, word, neighbors, wo... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int"""
<|body_0|>
def _findNeighbors(self, word, neighbors, wordSet):
""":type word: str :type neighbors: list :type wordSet: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int"""
wordSet = set(wordList)
if beginWord in wordSet:
wordSet.remove(beginWord)
queue = [beginWord]
level = 1
... | the_stack_v2_python_sparse | code127WordLadder.py | cybelewang/leetcode-python | train | 0 | |
a17834e35f6693b0822ccb96975de5500cdfa6dc | [
"self.confusion_matrix_tensor_name = confusion_matrix_tensor_name\nself.labels = labels\nself._summary_writer = summary_writer",
"cm = tensorflow.get_default_graph().get_tensor_by_name(self.confusion_matrix_tensor_name + ':0').eval(session=session).astype(int)\nglobal_step = tensorflow.train.get_global_step().eva... | <|body_start_0|>
self.confusion_matrix_tensor_name = confusion_matrix_tensor_name
self.labels = labels
self._summary_writer = summary_writer
<|end_body_0|>
<|body_start_1|>
cm = tensorflow.get_default_graph().get_tensor_by_name(self.confusion_matrix_tensor_name + ':0').eval(session=sess... | Saves a confusion matrix as a Summary so that it can be shown in tensorboard | SaverHook | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaverHook:
"""Saves a confusion matrix as a Summary so that it can be shown in tensorboard"""
def __init__(self, labels, confusion_matrix_tensor_name, summary_writer):
"""Initializes a `SaveConfusionMatrixHook`. :param labels: Iterable of String containing the labels to print for eac... | stack_v2_sparse_classes_36k_train_014731 | 9,078 | permissive | [
{
"docstring": "Initializes a `SaveConfusionMatrixHook`. :param labels: Iterable of String containing the labels to print for each row/column in the confusion matrix. :param confusion_matrix_tensor_name: The name of the tensor containing the confusion matrix :param summary_writer: The summary writer that will s... | 4 | stack_v2_sparse_classes_30k_train_013721 | Implement the Python class `SaverHook` described below.
Class description:
Saves a confusion matrix as a Summary so that it can be shown in tensorboard
Method signatures and docstrings:
- def __init__(self, labels, confusion_matrix_tensor_name, summary_writer): Initializes a `SaveConfusionMatrixHook`. :param labels: ... | Implement the Python class `SaverHook` described below.
Class description:
Saves a confusion matrix as a Summary so that it can be shown in tensorboard
Method signatures and docstrings:
- def __init__(self, labels, confusion_matrix_tensor_name, summary_writer): Initializes a `SaveConfusionMatrixHook`. :param labels: ... | 94a402cab47a2bd6241608308371490079af4d53 | <|skeleton|>
class SaverHook:
"""Saves a confusion matrix as a Summary so that it can be shown in tensorboard"""
def __init__(self, labels, confusion_matrix_tensor_name, summary_writer):
"""Initializes a `SaveConfusionMatrixHook`. :param labels: Iterable of String containing the labels to print for eac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaverHook:
"""Saves a confusion matrix as a Summary so that it can be shown in tensorboard"""
def __init__(self, labels, confusion_matrix_tensor_name, summary_writer):
"""Initializes a `SaveConfusionMatrixHook`. :param labels: Iterable of String containing the labels to print for each row/column ... | the_stack_v2_python_sparse | draugr/tensorboard_utilities/experimental/confusion_matrix.py | cnheider/draugr | train | 4 |
8ad78ab795a1faaf79d61c4ba99060f3f45717bb | [
"if random_seed is None or isinstance(random_seed, int):\n random_seed = np.random.default_rng(random_seed)\nself._building_blocks = tuple(building_blocks)\nself._is_replaceable = is_replaceable\nself._name = name\nself._generator = random_seed",
"replaceable_building_blocks = tuple(filter(self._is_replaceable... | <|body_start_0|>
if random_seed is None or isinstance(random_seed, int):
random_seed = np.random.default_rng(random_seed)
self._building_blocks = tuple(building_blocks)
self._is_replaceable = is_replaceable
self._name = name
self._generator = random_seed
<|end_body_0|... | Substitutes random building blocks. This mutator takes a :class:`.ConstructedMolecule` and substitutes the building blocks with one chosen at random from a given set. Examples: *Constructed Molecule Mutation* .. testcode:: constructed-molecule-mutation import stk # Create a molecule which is to be mutated. bb1 = stk.Bu... | RandomBuildingBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomBuildingBlock:
"""Substitutes random building blocks. This mutator takes a :class:`.ConstructedMolecule` and substitutes the building blocks with one chosen at random from a given set. Examples: *Constructed Molecule Mutation* .. testcode:: constructed-molecule-mutation import stk # Create ... | stack_v2_sparse_classes_36k_train_014732 | 4,936 | permissive | [
{
"docstring": "Parameters: building_blocks (list[BuildingBlock]): A group of molecules which are used to replace building blocks in molecules being mutated. is_replaceable: This function is applied to every building block in the molecule being mutated. Building blocks which returned ``True`` are liable for sub... | 2 | stack_v2_sparse_classes_30k_train_002176 | Implement the Python class `RandomBuildingBlock` described below.
Class description:
Substitutes random building blocks. This mutator takes a :class:`.ConstructedMolecule` and substitutes the building blocks with one chosen at random from a given set. Examples: *Constructed Molecule Mutation* .. testcode:: constructed... | Implement the Python class `RandomBuildingBlock` described below.
Class description:
Substitutes random building blocks. This mutator takes a :class:`.ConstructedMolecule` and substitutes the building blocks with one chosen at random from a given set. Examples: *Constructed Molecule Mutation* .. testcode:: constructed... | 9242c29dd4b9eb6927c202611d1326c19d73caea | <|skeleton|>
class RandomBuildingBlock:
"""Substitutes random building blocks. This mutator takes a :class:`.ConstructedMolecule` and substitutes the building blocks with one chosen at random from a given set. Examples: *Constructed Molecule Mutation* .. testcode:: constructed-molecule-mutation import stk # Create ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomBuildingBlock:
"""Substitutes random building blocks. This mutator takes a :class:`.ConstructedMolecule` and substitutes the building blocks with one chosen at random from a given set. Examples: *Constructed Molecule Mutation* .. testcode:: constructed-molecule-mutation import stk # Create a molecule wh... | the_stack_v2_python_sparse | src/stk/_internal/ea/mutation/random_building_block.py | andrewtarzia/stk | train | 0 |
5e8d18984337fad4f504008d5cb0aa90ea0e57a1 | [
"urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nself.timeout = timeout or Configuration.http_request_timeout\nself.session = requests.session()\nif max_retries and retry_interval:\n retries = Retry(total=max_retries, backoff_factor=retry_interval)\n self.session.mount('http://', HTTPAdap... | <|body_start_0|>
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
self.timeout = timeout or Configuration.http_request_timeout
self.session = requests.session()
if max_retries and retry_interval:
retries = Retry(total=max_retries, backoff_factor=retry_inter... | An implementation of HttpClient that uses Requests as its HTTP Client Attributes: timeout (int): The default timeout for all API requests. | RequestsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsClient:
"""An implementation of HttpClient that uses Requests as its HTTP Client Attributes: timeout (int): The default timeout for all API requests."""
def __init__(self, timeout=None, cache=False, max_retries=None, retry_interval=None):
"""The constructor. Args: timeout (fl... | stack_v2_sparse_classes_36k_train_014733 | 3,761 | permissive | [
{
"docstring": "The constructor. Args: timeout (float): The default global timeout(seconds).",
"name": "__init__",
"signature": "def __init__(self, timeout=None, cache=False, max_retries=None, retry_interval=None)"
},
{
"docstring": "Execute a given HttpRequest to get a string response back Args... | 4 | null | Implement the Python class `RequestsClient` described below.
Class description:
An implementation of HttpClient that uses Requests as its HTTP Client Attributes: timeout (int): The default timeout for all API requests.
Method signatures and docstrings:
- def __init__(self, timeout=None, cache=False, max_retries=None,... | Implement the Python class `RequestsClient` described below.
Class description:
An implementation of HttpClient that uses Requests as its HTTP Client Attributes: timeout (int): The default timeout for all API requests.
Method signatures and docstrings:
- def __init__(self, timeout=None, cache=False, max_retries=None,... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RequestsClient:
"""An implementation of HttpClient that uses Requests as its HTTP Client Attributes: timeout (int): The default timeout for all API requests."""
def __init__(self, timeout=None, cache=False, max_retries=None, retry_interval=None):
"""The constructor. Args: timeout (fl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsClient:
"""An implementation of HttpClient that uses Requests as its HTTP Client Attributes: timeout (int): The default timeout for all API requests."""
def __init__(self, timeout=None, cache=False, max_retries=None, retry_interval=None):
"""The constructor. Args: timeout (float): The def... | the_stack_v2_python_sparse | cohesity_management_sdk/http/requests_client.py | cohesity/management-sdk-python | train | 24 |
194057b16c5aa66526301b1d2b0d2aff4e206cd9 | [
"threading.Thread.__init__(self)\nself.daemon = True\nself.queue = queue\nself.found = found\nself.featuredText = featuredText",
"while True:\n url = self.queue.get()\n try:\n fd = urllib2.urlopen(url, timeout=urlOpenTimeout)\n html = fd.read()\n if html.find(self.featuredText) >= 0:\n ... | <|body_start_0|>
threading.Thread.__init__(self)
self.daemon = True
self.queue = queue
self.found = found
self.featuredText = featuredText
<|end_body_0|>
<|body_start_1|>
while True:
url = self.queue.get()
try:
fd = urllib2.urlopen... | Checker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
def __init__(self, queue, found, featuredText):
"""Инициализация"""
<|body_0|>
def run(self):
"""Проверяем ссылки из очереди на наличие текста"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threading.Thread.__init__(self)
self.daem... | stack_v2_sparse_classes_36k_train_014734 | 4,389 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self, queue, found, featuredText)"
},
{
"docstring": "Проверяем ссылки из очереди на наличие текста",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def __init__(self, queue, found, featuredText): Инициализация
- def run(self): Проверяем ссылки из очереди на наличие текста | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def __init__(self, queue, found, featuredText): Инициализация
- def run(self): Проверяем ссылки из очереди на наличие текста
<|skeleton|>
class Checker:
def __init__(self, qu... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class Checker:
def __init__(self, queue, found, featuredText):
"""Инициализация"""
<|body_0|>
def run(self):
"""Проверяем ссылки из очереди на наличие текста"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Checker:
def __init__(self, queue, found, featuredText):
"""Инициализация"""
threading.Thread.__init__(self)
self.daemon = True
self.queue = queue
self.found = found
self.featuredText = featuredText
def run(self):
"""Проверяем ссылки из очереди на н... | the_stack_v2_python_sparse | doorsagents/basechecker.py | cash2one/doorscenter | train | 0 | |
a179366b55ae69ffc58b46dfb65f2ac15fc193a6 | [
"super().__init__(n)\nself.angle = torch.tensor(np.pi * angle / 180.0).float()\nself.Y = self.potential_func(self.X[:, 0], self.X[:, 1])\nself.X = self.X[torch.abs(self.Y) > 0.2][:self.n]\nself.Y = self.Y[torch.abs(self.Y) > 0.2][:self.n]\nself.Y = (self.Y > 0).long()",
"x = x * (torch.cos(self.angle) + torch.sin... | <|body_start_0|>
super().__init__(n)
self.angle = torch.tensor(np.pi * angle / 180.0).float()
self.Y = self.potential_func(self.X[:, 0], self.X[:, 1])
self.X = self.X[torch.abs(self.Y) > 0.2][:self.n]
self.Y = self.Y[torch.abs(self.Y) > 0.2][:self.n]
self.Y = (self.Y > 0)... | A linearly inseparable datasets containing of three stripes of points of class 1, 0, and again 1, crossing the plane at an angle. Attributes: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with respect to the x-axis) at which the stripes cross the cartesian plane. X : to... | Stripe | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stripe:
"""A linearly inseparable datasets containing of three stripes of points of class 1, 0, and again 1, crossing the plane at an angle. Attributes: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with respect to the x-axis) at which the stripes... | stack_v2_sparse_classes_36k_train_014735 | 8,649 | permissive | [
{
"docstring": "Randomly initializes n points of the dataset. Parameters: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with respect to the x-axis) at which the stripes cross the cartesian plane.",
"name": "__init__",
"signature": "def __init__(self, n=1... | 2 | stack_v2_sparse_classes_30k_train_017013 | Implement the Python class `Stripe` described below.
Class description:
A linearly inseparable datasets containing of three stripes of points of class 1, 0, and again 1, crossing the plane at an angle. Attributes: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with resp... | Implement the Python class `Stripe` described below.
Class description:
A linearly inseparable datasets containing of three stripes of points of class 1, 0, and again 1, crossing the plane at an angle. Attributes: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with resp... | 158445785da79c0667a78f3ca890c3210d00af77 | <|skeleton|>
class Stripe:
"""A linearly inseparable datasets containing of three stripes of points of class 1, 0, and again 1, crossing the plane at an angle. Attributes: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with respect to the x-axis) at which the stripes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stripe:
"""A linearly inseparable datasets containing of three stripes of points of class 1, 0, and again 1, crossing the plane at an angle. Attributes: ----------- n : int, default: 100 Number of points in dataset. angle : float Angle (in degrees, with respect to the x-axis) at which the stripes cross the ca... | the_stack_v2_python_sparse | physics_aware_training/datasets.py | bharathijeeva/Physics-Aware-Training | train | 0 |
056944e23ef4a406a65a8d028260ad145efa2ddf | [
"d = {}\nfor t in tasks:\n if t in d:\n d[t] += 1\n else:\n d[t] = 1\npq = queue.PriorityQueue()\nfor k, v in d.items():\n pq.put(-v)\nans = 0\nwhile not pq.empty():\n time = 0\n tmp = []\n while time <= n and (not pq.empty()):\n v = pq.get()\n if -v > 1:\n t... | <|body_start_0|>
d = {}
for t in tasks:
if t in d:
d[t] += 1
else:
d[t] = 1
pq = queue.PriorityQueue()
for k, v in d.items():
pq.put(-v)
ans = 0
while not pq.empty():
time = 0
tmp ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leastInterval1(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
def leastInterval3(self, tasks, n):
... | stack_v2_sparse_classes_36k_train_014736 | 2,596 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval2",
"signature": "def leastInterval2(self, tasks, n)"
},
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval1",
"signature": "def leastInterval1(self, tasks, n)"
... | 4 | stack_v2_sparse_classes_30k_train_005152 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval2(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leastInterval1(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def le... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval2(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leastInterval1(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def le... | 763674fcbe271af3d21eed790c3968c4d33f7b09 | <|skeleton|>
class Solution:
def leastInterval2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leastInterval1(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_1|>
def leastInterval3(self, tasks, n):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leastInterval2(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
d = {}
for t in tasks:
if t in d:
d[t] += 1
else:
d[t] = 1
pq = queue.PriorityQueue()
for k, v in d.items():
... | the_stack_v2_python_sparse | 621_task_scheduler/621.py | guzhoudiaoke/leetcode_python3 | train | 0 | |
4fd4fd868eda5cf8923087d3284945f99ba4edcc | [
"if istart > iend or pstart > pend:\n return None\nroot = TreeNode(postorder[pend])\nrindex = indexDict.get(postorder[pend])\nleft = self.buildTreeIndex(inorder, istart, rindex - 1, postorder, pstart, pstart + rindex - istart - 1, indexDict)\nright = self.buildTreeIndex(inorder, rindex + 1, iend, postorder, psta... | <|body_start_0|>
if istart > iend or pstart > pend:
return None
root = TreeNode(postorder[pend])
rindex = indexDict.get(postorder[pend])
left = self.buildTreeIndex(inorder, istart, rindex - 1, postorder, pstart, pstart + rindex - istart - 1, indexDict)
right = self.bu... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTreeIndex(self, inorder, istart, iend, postorder, pstart, pend, indexDict):
"""check the last element in postorder, find the position in the inorder get the left part of the tree and the right part of the tree"""
<|body_0|>
def buildTree(self, inorder, pos... | stack_v2_sparse_classes_36k_train_014737 | 1,512 | permissive | [
{
"docstring": "check the last element in postorder, find the position in the inorder get the left part of the tree and the right part of the tree",
"name": "buildTreeIndex",
"signature": "def buildTreeIndex(self, inorder, istart, iend, postorder, pstart, pend, indexDict)"
},
{
"docstring": ":ty... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTreeIndex(self, inorder, istart, iend, postorder, pstart, pend, indexDict): check the last element in postorder, find the position in the inorder get the left part of th... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTreeIndex(self, inorder, istart, iend, postorder, pstart, pend, indexDict): check the last element in postorder, find the position in the inorder get the left part of th... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def buildTreeIndex(self, inorder, istart, iend, postorder, pstart, pend, indexDict):
"""check the last element in postorder, find the position in the inorder get the left part of the tree and the right part of the tree"""
<|body_0|>
def buildTree(self, inorder, pos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTreeIndex(self, inorder, istart, iend, postorder, pstart, pend, indexDict):
"""check the last element in postorder, find the position in the inorder get the left part of the tree and the right part of the tree"""
if istart > iend or pstart > pend:
return None
... | the_stack_v2_python_sparse | 106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/solution.py | Tanych/CodeTracking | train | 0 | |
5fc02428f038e4955491e10646b8ceac2ea10497 | [
"super(MetaLearner, self).__init__()\nself.n_way = n_way\nself.k_shot = k_shot\nself.meta_batchsz = meta_batchsz\nself.beta = beta\nself.num_updates = num_updates\nself.learner = Learner(net_cls, *net_cls_args)\nself.optimizer = optim.Adam(self.learner.parameters(), lr=beta)",
"hooks = []\nfor i, v in enumerate(s... | <|body_start_0|>
super(MetaLearner, self).__init__()
self.n_way = n_way
self.k_shot = k_shot
self.meta_batchsz = meta_batchsz
self.beta = beta
self.num_updates = num_updates
self.learner = Learner(net_cls, *net_cls_args)
self.optimizer = optim.Adam(self.le... | As we have mentioned in Learner class, the metalearner class will receive a series of loss on different tasks/episodes on theta_pi network, and it will merage all loss and then sum over it. The summed loss will be backproped on theta network to update theta parameters, which is the initialization point we want to find. | MetaLearner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaLearner:
"""As we have mentioned in Learner class, the metalearner class will receive a series of loss on different tasks/episodes on theta_pi network, and it will merage all loss and then sum over it. The summed loss will be backproped on theta network to update theta parameters, which is th... | stack_v2_sparse_classes_36k_train_014738 | 9,798 | no_license | [
{
"docstring": ":param net_cls: class, not instance. the class of specific Network for learner :param net_cls_args: tuple, args for net_cls, like (n_way, imgsz) :param n_way: :param k_shot: :param meta_batchsz: number of tasks/episode :param beta: learning rate for meta-learner :param num_updates: number of upd... | 4 | stack_v2_sparse_classes_30k_train_000998 | Implement the Python class `MetaLearner` described below.
Class description:
As we have mentioned in Learner class, the metalearner class will receive a series of loss on different tasks/episodes on theta_pi network, and it will merage all loss and then sum over it. The summed loss will be backproped on theta network ... | Implement the Python class `MetaLearner` described below.
Class description:
As we have mentioned in Learner class, the metalearner class will receive a series of loss on different tasks/episodes on theta_pi network, and it will merage all loss and then sum over it. The summed loss will be backproped on theta network ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class MetaLearner:
"""As we have mentioned in Learner class, the metalearner class will receive a series of loss on different tasks/episodes on theta_pi network, and it will merage all loss and then sum over it. The summed loss will be backproped on theta network to update theta parameters, which is th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaLearner:
"""As we have mentioned in Learner class, the metalearner class will receive a series of loss on different tasks/episodes on theta_pi network, and it will merage all loss and then sum over it. The summed loss will be backproped on theta network to update theta parameters, which is the initializat... | the_stack_v2_python_sparse | generated/test_dragen1860_Reptile_Pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('name')\nself.parser.add_argument('token')\nsuper(CtaStrategyVar, self).__init__()",
"args = self.parser.parse_args()\nname = 'strategyHedge_syt'\nengine = me.getApp('CtaStrategy')\nl = engine.getStrategyVar(name)\nreturn {'result_code': 'success',... | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyVar, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
name = 'strategyHedge_syt'
engine = m... | 查询策略变量 | CtaStrategyVar | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaStrategyVar:
"""查询策略变量"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_ar... | stack_v2_sparse_classes_36k_train_014739 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "订阅",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009811 | Implement the Python class `CtaStrategyVar` described below.
Class description:
查询策略变量
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 订阅 | Implement the Python class `CtaStrategyVar` described below.
Class description:
查询策略变量
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 订阅
<|skeleton|>
class CtaStrategyVar:
"""查询策略变量"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class CtaStrategyVar:
"""查询策略变量"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtaStrategyVar:
"""查询策略变量"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyVar, self).__init__()
def get(self):
"""订阅"""
args = self.pars... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
24ff7ba8da85cfe20aa3a230b6977a4b0c8a5858 | [
"n = len(nums)\nself.sum1, temp = ([0 for i in range(n)], 0)\nfor i in range(n):\n temp += nums[i]\n self.sum1[i] = temp",
"if i - 1 >= 0:\n return self.sum1[j] - self.sum1[i - 1]\nreturn self.sum1[j]"
] | <|body_start_0|>
n = len(nums)
self.sum1, temp = ([0 for i in range(n)], 0)
for i in range(n):
temp += nums[i]
self.sum1[i] = temp
<|end_body_0|>
<|body_start_1|>
if i - 1 >= 0:
return self.sum1[j] - self.sum1[i - 1]
return self.sum1[j]
<|end_... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
self.sum1, temp = ([0 for i in range(... | stack_v2_sparse_classes_36k_train_014740 | 597 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | c7dc709a7a9b83ef85fbc2d0aad7a8829f1035d1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
n = len(nums)
self.sum1, temp = ([0 for i in range(n)], 0)
for i in range(n):
temp += nums[i]
self.sum1[i] = temp
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: ... | the_stack_v2_python_sparse | leetcode303.py | Marco2018/leetcode | train | 0 | |
a11226c4a582bfd8c7d35eff436015eff0c36c6b | [
"if att > 0:\n self.completion_percentage = com / att\n self.yards_per_attempt = yds / att\n self.tds_per_attempt = tds / att\n self.ints_per_attempt = ints / att\nelse:\n self.completion_percentage, self.yards_per_attempt, self.tds_per_attempt, self.ints_per_attempt = (0, 0, 0, 0)\nself.com = com\ns... | <|body_start_0|>
if att > 0:
self.completion_percentage = com / att
self.yards_per_attempt = yds / att
self.tds_per_attempt = tds / att
self.ints_per_attempt = ints / att
else:
self.completion_percentage, self.yards_per_attempt, self.tds_per_at... | Nfl_Qb_Rating class. | Nfl_Qb_Rating | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nfl_Qb_Rating:
"""Nfl_Qb_Rating class."""
def __init__(self, com=0, att=0, yds=0, tds=0, ints=0):
"""Quaterback Object to calculate the NFL QB Rating. Arguments: com = Completed Passes att = Attempted Passes yds = Passing Yards tds = TD Passes ints = Interceptions Usage: Nfl_Qb_Ratin... | stack_v2_sparse_classes_36k_train_014741 | 3,085 | permissive | [
{
"docstring": "Quaterback Object to calculate the NFL QB Rating. Arguments: com = Completed Passes att = Attempted Passes yds = Passing Yards tds = TD Passes ints = Interceptions Usage: Nfl_Qb_Rating( com, att, yds, tds, ints )",
"name": "__init__",
"signature": "def __init__(self, com=0, att=0, yds=0,... | 3 | stack_v2_sparse_classes_30k_train_012522 | Implement the Python class `Nfl_Qb_Rating` described below.
Class description:
Nfl_Qb_Rating class.
Method signatures and docstrings:
- def __init__(self, com=0, att=0, yds=0, tds=0, ints=0): Quaterback Object to calculate the NFL QB Rating. Arguments: com = Completed Passes att = Attempted Passes yds = Passing Yards... | Implement the Python class `Nfl_Qb_Rating` described below.
Class description:
Nfl_Qb_Rating class.
Method signatures and docstrings:
- def __init__(self, com=0, att=0, yds=0, tds=0, ints=0): Quaterback Object to calculate the NFL QB Rating. Arguments: com = Completed Passes att = Attempted Passes yds = Passing Yards... | f5dceca0bdbe9de6197b26858600b792f6adff8a | <|skeleton|>
class Nfl_Qb_Rating:
"""Nfl_Qb_Rating class."""
def __init__(self, com=0, att=0, yds=0, tds=0, ints=0):
"""Quaterback Object to calculate the NFL QB Rating. Arguments: com = Completed Passes att = Attempted Passes yds = Passing Yards tds = TD Passes ints = Interceptions Usage: Nfl_Qb_Ratin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Nfl_Qb_Rating:
"""Nfl_Qb_Rating class."""
def __init__(self, com=0, att=0, yds=0, tds=0, ints=0):
"""Quaterback Object to calculate the NFL QB Rating. Arguments: com = Completed Passes att = Attempted Passes yds = Passing Yards tds = TD Passes ints = Interceptions Usage: Nfl_Qb_Rating( com, att, ... | the_stack_v2_python_sparse | cb_scripts/qb_rating.py | christopher-burke/python-scripts | train | 1 |
e46bd182b15cac1f78a021239cd9b7e86fae80ba | [
"vims = get_vims()\nfunctions = get_func()\nlocations = mongoUtils.find_all('location')\nresources = {'VIMs': vims, 'Functions': functions, 'Locations': locations}\nreturn (dumps(resources), 200)",
"location_id = uuid.lower()\nif not mongoUtils.find('location', {'id': location_id}):\n return (f'Location {uuid}... | <|body_start_0|>
vims = get_vims()
functions = get_func()
locations = mongoUtils.find_all('location')
resources = {'VIMs': vims, 'Functions': functions, 'Locations': locations}
return (dumps(resources), 200)
<|end_body_0|>
<|body_start_1|>
location_id = uuid.lower()
... | ResourcesView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourcesView:
def index(self):
"""Returns the available resources on platform, used by: `katana resource ls`"""
<|body_0|>
def get(self, uuid):
"""Returns the available resources on platform, used by: `katana resource location <location>`"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_014742 | 3,842 | permissive | [
{
"docstring": "Returns the available resources on platform, used by: `katana resource ls`",
"name": "index",
"signature": "def index(self)"
},
{
"docstring": "Returns the available resources on platform, used by: `katana resource location <location>`",
"name": "get",
"signature": "def g... | 3 | stack_v2_sparse_classes_30k_train_020565 | Implement the Python class `ResourcesView` described below.
Class description:
Implement the ResourcesView class.
Method signatures and docstrings:
- def index(self): Returns the available resources on platform, used by: `katana resource ls`
- def get(self, uuid): Returns the available resources on platform, used by:... | Implement the Python class `ResourcesView` described below.
Class description:
Implement the ResourcesView class.
Method signatures and docstrings:
- def index(self): Returns the available resources on platform, used by: `katana resource ls`
- def get(self, uuid): Returns the available resources on platform, used by:... | 2e7a14a41fc85bd7188d71ef9beaf51acc94015c | <|skeleton|>
class ResourcesView:
def index(self):
"""Returns the available resources on platform, used by: `katana resource ls`"""
<|body_0|>
def get(self, uuid):
"""Returns the available resources on platform, used by: `katana resource location <location>`"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourcesView:
def index(self):
"""Returns the available resources on platform, used by: `katana resource ls`"""
vims = get_vims()
functions = get_func()
locations = mongoUtils.find_all('location')
resources = {'VIMs': vims, 'Functions': functions, 'Locations': location... | the_stack_v2_python_sparse | katana-nbi/katana/api/resource.py | tgogos/katana-slice_manager | train | 0 | |
bac71bc0083e45eccfd200f32632e5115cdb9a51 | [
"cov_factor = 1.0\ncov_factor *= sqrt(1 + self._r)\naffected = True\nreturn (cov_factor, affected)",
"nstate, nens = ensemble.shape\nnobs = obs.shape[0]\nG = self._G\nfor i in range(nobs):\n ro = self._Ro[i]\n obs_ensemble = G(ensemble, i=i, axis=0)\n ob = obs[i]\n obs_inc, errflag = obs_increment_EAK... | <|body_start_0|>
cov_factor = 1.0
cov_factor *= sqrt(1 + self._r)
affected = True
return (cov_factor, affected)
<|end_body_0|>
<|body_start_1|>
nstate, nens = ensemble.shape
nobs = obs.shape[0]
G = self._G
for i in range(nobs):
ro = self._Ro[i... | Object for performing ensemble kalman filters on independent observations A localization interface is implemented, but by default, no localization is performed. Subclasses with localization should override `_localized`. Args: G (callable): prototype `G(ensemble, i=i)` returns the ith observation for each ensemble membe... | SequentialKFAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequentialKFAnalysis:
"""Object for performing ensemble kalman filters on independent observations A localization interface is implemented, but by default, no localization is performed. Subclasses with localization should override `_localized`. Args: G (callable): prototype `G(ensemble, i=i)` ret... | stack_v2_sparse_classes_36k_train_014743 | 10,503 | no_license | [
{
"docstring": "Return localization information given observation and state indices",
"name": "_localized",
"signature": "def _localized(self, idx_obs, idx_state)"
},
{
"docstring": "Calculate analysis given prior ensemble and observations Args: ensemble (2d array): Array containing ensemble mem... | 2 | stack_v2_sparse_classes_30k_train_021412 | Implement the Python class `SequentialKFAnalysis` described below.
Class description:
Object for performing ensemble kalman filters on independent observations A localization interface is implemented, but by default, no localization is performed. Subclasses with localization should override `_localized`. Args: G (call... | Implement the Python class `SequentialKFAnalysis` described below.
Class description:
Object for performing ensemble kalman filters on independent observations A localization interface is implemented, but by default, no localization is performed. Subclasses with localization should override `_localized`. Args: G (call... | 6cf38886fad397dd90c2a2590e469e354d61e809 | <|skeleton|>
class SequentialKFAnalysis:
"""Object for performing ensemble kalman filters on independent observations A localization interface is implemented, but by default, no localization is performed. Subclasses with localization should override `_localized`. Args: G (callable): prototype `G(ensemble, i=i)` ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequentialKFAnalysis:
"""Object for performing ensemble kalman filters on independent observations A localization interface is implemented, but by default, no localization is performed. Subclasses with localization should override `_localized`. Args: G (callable): prototype `G(ensemble, i=i)` returns the ith ... | the_stack_v2_python_sparse | python/gnl/filter/ensemble.py | nbren12/gnl | train | 1 |
b944d90d4784de8c2f92b8ac1bae26e5718db186 | [
"super(coord_latent, self).__init__()\nself.fc_coord = nn.Linear(2, out_dim)\nself.fc_latent = nn.Linear(latent_dim, out_dim, bias=False)\nself.activation = nn.Tanh() if activation else None",
"batch_dim, n = x_coord.size()[:2]\nx_coord = x_coord.reshape(batch_dim * n, -1)\nh_x = self.fc_coord(x_coord)\nh_x = h_x... | <|body_start_0|>
super(coord_latent, self).__init__()
self.fc_coord = nn.Linear(2, out_dim)
self.fc_latent = nn.Linear(latent_dim, out_dim, bias=False)
self.activation = nn.Tanh() if activation else None
<|end_body_0|>
<|body_start_1|>
batch_dim, n = x_coord.size()[:2]
x... | The "spatial" part of the rVAE's decoder that allows for translational and rotational invariance (based on https://arxiv.org/abs/1909.11663) Args: latent_dim: number of latent dimensions associated with images content out_dim: number of output dimensions (usually equal to number of hidden units in the first layer of th... | coord_latent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class coord_latent:
"""The "spatial" part of the rVAE's decoder that allows for translational and rotational invariance (based on https://arxiv.org/abs/1909.11663) Args: latent_dim: number of latent dimensions associated with images content out_dim: number of output dimensions (usually equal to number ... | stack_v2_sparse_classes_36k_train_014744 | 28,462 | permissive | [
{
"docstring": "Initiate parameters",
"name": "__init__",
"signature": "def __init__(self, latent_dim: int, out_dim: int, activation: bool=False) -> None"
},
{
"docstring": "Forward pass",
"name": "forward",
"signature": "def forward(self, x_coord: torch.Tensor, z: torch.Tensor) -> torch... | 2 | stack_v2_sparse_classes_30k_val_000579 | Implement the Python class `coord_latent` described below.
Class description:
The "spatial" part of the rVAE's decoder that allows for translational and rotational invariance (based on https://arxiv.org/abs/1909.11663) Args: latent_dim: number of latent dimensions associated with images content out_dim: number of outp... | Implement the Python class `coord_latent` described below.
Class description:
The "spatial" part of the rVAE's decoder that allows for translational and rotational invariance (based on https://arxiv.org/abs/1909.11663) Args: latent_dim: number of latent dimensions associated with images content out_dim: number of outp... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class coord_latent:
"""The "spatial" part of the rVAE's decoder that allows for translational and rotational invariance (based on https://arxiv.org/abs/1909.11663) Args: latent_dim: number of latent dimensions associated with images content out_dim: number of output dimensions (usually equal to number ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class coord_latent:
"""The "spatial" part of the rVAE's decoder that allows for translational and rotational invariance (based on https://arxiv.org/abs/1909.11663) Args: latent_dim: number of latent dimensions associated with images content out_dim: number of output dimensions (usually equal to number of hidden uni... | the_stack_v2_python_sparse | atomai/nets/ed.py | pycroscopy/atomai | train | 157 |
2b05cca085cf68b03e50d64f62caa55a46390e11 | [
"if n < 3:\n return 0\nprimes = [False] * n\ncount = n / 2\ni = 3\nwhile i * i < n:\n if not primes[i]:\n j = i * i\n while j < n:\n if not primes[j]:\n count -= 1\n primes[j] = True\n j += 2 * i\n i += 2\nreturn count",
"if n < 3:\n re... | <|body_start_0|>
if n < 3:
return 0
primes = [False] * n
count = n / 2
i = 3
while i * i < n:
if not primes[i]:
j = i * i
while j < n:
if not primes[j]:
count -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def allPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 3:
return 0
primes = [False] * n
cou... | stack_v2_sparse_classes_36k_train_014745 | 1,571 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "allPrimes",
"signature": "def allPrimes(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012720 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def allPrimes(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def allPrimes(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def countPrimes(self, n):
""":typ... | 33c623f226981942780751554f0593f2c71cf458 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def allPrimes(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
if n < 3:
return 0
primes = [False] * n
count = n / 2
i = 3
while i * i < n:
if not primes[i]:
j = i * i
while j < n:
i... | the_stack_v2_python_sparse | math/leetcode_Count_Primes.py | monkeylyf/interviewjam | train | 59 | |
80b2c664bf95039f3f1c8abb460ba7dc04c81b88 | [
"self.flip_coin_hflip = ops.CoinFlip(probability=p)\nself.image_hflip = ops.Flip(device='gpu')\nself.bbox_hflip = ops.BbFlip(device='cpu')\nself.ldmrks_hflip = ops.CoordFlip(layout='xy', device='cpu')",
"data = EasyDict(data)\nhflip_coin = self.flip_coin_hflip()\ndata.images = self.image_hflip(data.images, horizo... | <|body_start_0|>
self.flip_coin_hflip = ops.CoinFlip(probability=p)
self.image_hflip = ops.Flip(device='gpu')
self.bbox_hflip = ops.BbFlip(device='cpu')
self.ldmrks_hflip = ops.CoordFlip(layout='xy', device='cpu')
<|end_body_0|>
<|body_start_1|>
data = EasyDict(data)
hfl... | Flip image in horizontal axis. Supports coordinates sensitive labels | HorizontalFlip | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HorizontalFlip:
"""Flip image in horizontal axis. Supports coordinates sensitive labels"""
def __init__(self, p: float=0.5):
"""Initialization Args: p (float, optional): Probability to apply this transformation. Defaults to 0.5."""
<|body_0|>
def __call__(self, **data):
... | stack_v2_sparse_classes_36k_train_014746 | 22,608 | no_license | [
{
"docstring": "Initialization Args: p (float, optional): Probability to apply this transformation. Defaults to 0.5.",
"name": "__init__",
"signature": "def __init__(self, p: float=0.5)"
},
{
"docstring": "This function will receive keyword args which will be processed as a dict. Inside the dict... | 2 | stack_v2_sparse_classes_30k_train_008429 | Implement the Python class `HorizontalFlip` described below.
Class description:
Flip image in horizontal axis. Supports coordinates sensitive labels
Method signatures and docstrings:
- def __init__(self, p: float=0.5): Initialization Args: p (float, optional): Probability to apply this transformation. Defaults to 0.5... | Implement the Python class `HorizontalFlip` described below.
Class description:
Flip image in horizontal axis. Supports coordinates sensitive labels
Method signatures and docstrings:
- def __init__(self, p: float=0.5): Initialization Args: p (float, optional): Probability to apply this transformation. Defaults to 0.5... | 1532db8447d03e75d5ec26f93111270a4ccb7a7e | <|skeleton|>
class HorizontalFlip:
"""Flip image in horizontal axis. Supports coordinates sensitive labels"""
def __init__(self, p: float=0.5):
"""Initialization Args: p (float, optional): Probability to apply this transformation. Defaults to 0.5."""
<|body_0|>
def __call__(self, **data):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HorizontalFlip:
"""Flip image in horizontal axis. Supports coordinates sensitive labels"""
def __init__(self, p: float=0.5):
"""Initialization Args: p (float, optional): Probability to apply this transformation. Defaults to 0.5."""
self.flip_coin_hflip = ops.CoinFlip(probability=p)
... | the_stack_v2_python_sparse | src/development/vortex/development/utils/data/augment/modules/nvidia_dali/modules.py | jesslynsepthiaa/vortex | train | 0 |
8e95d308ef5d686aa068a1050d4965350314c80b | [
"json_dict = json.loads(request.body.decode())\nreceiver = json_dict.get('receiver')\nprovince_id = json_dict.get('province_id')\ncity_id = json_dict.get('city_id')\ndistrict_id = json_dict.get('district_id')\nplace = json_dict.get('place')\nmobile = json_dict.get('mobile')\ntel = json_dict.get('tel')\nemail = json... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = jso... | 修改和删除地址 | UpdateDestroyAddressView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dict = json.loads(request.body.decode())
... | stack_v2_sparse_classes_36k_train_014747 | 29,582 | permissive | [
{
"docstring": "修改地址",
"name": "put",
"signature": "def put(self, request, address_id)"
},
{
"docstring": "删除地址",
"name": "delete",
"signature": "def delete(self, request, address_id)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000798 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址 | Implement the Python class `UpdateDestroyAddressView` described below.
Class description:
修改和删除地址
Method signatures and docstrings:
- def put(self, request, address_id): 修改地址
- def delete(self, request, address_id): 删除地址
<|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, addre... | 5b3ca1fba8205c2c0a2b91d951f812f1c30e12ae | <|skeleton|>
class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
<|body_0|>
def delete(self, request, address_id):
"""删除地址"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateDestroyAddressView:
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_... | the_stack_v2_python_sparse | meiduo1/apps/user/views.py | woobrain/nginx-uwsgi-web | train | 0 |
f4b7f9538553f7d5dacc0ee57aa7d8397c659e1c | [
"super(Generator, self).__init__()\nself.conv_dim = conv_dim\nself.fc1 = nn.Linear(z_size, conv_dim * 4 * 4 * 4)\nself.t_conv1 = deconv(conv_dim * 4, conv_dim * 2, 4)\nself.t_conv2 = deconv(conv_dim * 2, conv_dim, 4)\nself.t_conv3 = deconv(conv_dim, 3, 4, batch_norm=False)",
"x = self.fc1(x)\nx = x.view(-1, self.... | <|body_start_0|>
super(Generator, self).__init__()
self.conv_dim = conv_dim
self.fc1 = nn.Linear(z_size, conv_dim * 4 * 4 * 4)
self.t_conv1 = deconv(conv_dim * 4, conv_dim * 2, 4)
self.t_conv2 = deconv(conv_dim * 2, conv_dim, 4)
self.t_conv3 = deconv(conv_dim, 3, 4, batch... | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
def __init__(self, z_size, conv_dim):
"""Initialize the Generator Module :param z_size: The length of the input latent vector, z :param conv_dim: The depth of the inputs to the *last* transpose convolutional layer"""
<|body_0|>
def forward(self, x):
"""For... | stack_v2_sparse_classes_36k_train_014748 | 16,057 | no_license | [
{
"docstring": "Initialize the Generator Module :param z_size: The length of the input latent vector, z :param conv_dim: The depth of the inputs to the *last* transpose convolutional layer",
"name": "__init__",
"signature": "def __init__(self, z_size, conv_dim)"
},
{
"docstring": "Forward propag... | 2 | stack_v2_sparse_classes_30k_train_020972 | Implement the Python class `Generator` described below.
Class description:
Implement the Generator class.
Method signatures and docstrings:
- def __init__(self, z_size, conv_dim): Initialize the Generator Module :param z_size: The length of the input latent vector, z :param conv_dim: The depth of the inputs to the *l... | Implement the Python class `Generator` described below.
Class description:
Implement the Generator class.
Method signatures and docstrings:
- def __init__(self, z_size, conv_dim): Initialize the Generator Module :param z_size: The length of the input latent vector, z :param conv_dim: The depth of the inputs to the *l... | 727cedd3e3aca715b9326f625548bedb5a0c1b9b | <|skeleton|>
class Generator:
def __init__(self, z_size, conv_dim):
"""Initialize the Generator Module :param z_size: The length of the input latent vector, z :param conv_dim: The depth of the inputs to the *last* transpose convolutional layer"""
<|body_0|>
def forward(self, x):
"""For... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
def __init__(self, z_size, conv_dim):
"""Initialize the Generator Module :param z_size: The length of the input latent vector, z :param conv_dim: The depth of the inputs to the *last* transpose convolutional layer"""
super(Generator, self).__init__()
self.conv_dim = conv_dim... | the_stack_v2_python_sparse | generative_adversial_networks/generate_faces/generate_faces_dcgan.py | sivaneshl/deep_learning_course | train | 0 | |
f1ccd5fc246c1867060ab596aeeb901b64be8a58 | [
"class Node:\n\n def __init__(self, chr):\n self.chr = chr\n self.end = False\n self.children = defaultdict(lambda: None)\n\nclass Trie:\n\n def __init__(self):\n self.root = Node(None)\n\n def insert(self, cur, s, i):\n if not cur:\n cur = Node(s[i])\n ... | <|body_start_0|>
class Node:
def __init__(self, chr):
self.chr = chr
self.end = False
self.children = defaultdict(lambda: None)
class Trie:
def __init__(self):
self.root = Node(None)
def insert(self, ... | MagicDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def buildDict(self, dic: List[str]) -> None:
"""Build a dictionary through a list of words"""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if... | stack_v2_sparse_classes_36k_train_014749 | 2,727 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Build a dictionary through a list of words",
"name": "buildDict",
"signature": "def buildDict(self, dic: List[str]) -> None"
},
{
"docstring": "Returns ... | 3 | stack_v2_sparse_classes_30k_train_015828 | Implement the Python class `MagicDictionary` described below.
Class description:
Implement the MagicDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def buildDict(self, dic: List[str]) -> None: Build a dictionary through a list of words
- def search(self... | Implement the Python class `MagicDictionary` described below.
Class description:
Implement the MagicDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def buildDict(self, dic: List[str]) -> None: Build a dictionary through a list of words
- def search(self... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def buildDict(self, dic: List[str]) -> None:
"""Build a dictionary through a list of words"""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MagicDictionary:
def __init__(self):
"""Initialize your data structure here."""
class Node:
def __init__(self, chr):
self.chr = chr
self.end = False
self.children = defaultdict(lambda: None)
class Trie:
def __in... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/676 Implement Magic Dictionary.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
966fa0628c2c25ad169d05c02191e8cd27334b15 | [
"files = os.listdir('kaggledatasets/' + username + '/')\npaths = [os.path.join('kaggledatasets/' + username + '/', basename) for basename in files]\nlatest_file = max(paths, key=os.path.getctime)\nprint(latest_file)\ntreeinfo = {}\nwith open(latest_file) as json_file:\n data = json.load(json_file)\n exp = lis... | <|body_start_0|>
files = os.listdir('kaggledatasets/' + username + '/')
paths = [os.path.join('kaggledatasets/' + username + '/', basename) for basename in files]
latest_file = max(paths, key=os.path.getctime)
print(latest_file)
treeinfo = {}
with open(latest_file) as jso... | DataProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataProcessor:
def getsets(self, username):
"""gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user"""
<|body_0|>
def uploadrawdata(self, username):
"""uploads current dataset to Kaggle :type username: string :param... | stack_v2_sparse_classes_36k_train_014750 | 6,862 | permissive | [
{
"docstring": "gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user",
"name": "getsets",
"signature": "def getsets(self, username)"
},
{
"docstring": "uploads current dataset to Kaggle :type username: string :param username: the Kaggle usernam... | 2 | stack_v2_sparse_classes_30k_train_019854 | Implement the Python class `DataProcessor` described below.
Class description:
Implement the DataProcessor class.
Method signatures and docstrings:
- def getsets(self, username): gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user
- def uploadrawdata(self, username... | Implement the Python class `DataProcessor` described below.
Class description:
Implement the DataProcessor class.
Method signatures and docstrings:
- def getsets(self, username): gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user
- def uploadrawdata(self, username... | 02822901edda2d3e27e9d79052437c8a6fddc249 | <|skeleton|>
class DataProcessor:
def getsets(self, username):
"""gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user"""
<|body_0|>
def uploadrawdata(self, username):
"""uploads current dataset to Kaggle :type username: string :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataProcessor:
def getsets(self, username):
"""gets datasets from Kaggle :type username: string :param username: the Kaggle username of the active user"""
files = os.listdir('kaggledatasets/' + username + '/')
paths = [os.path.join('kaggledatasets/' + username + '/', basename) for base... | the_stack_v2_python_sparse | apps/kaggle2.py | Andrew-Ritchie/Web-Based-Dashboard-for-Nanoindentation-Experiments | train | 1 | |
d45662f4dd4be5a127e11579b8d510877b610a82 | [
"self.ss = ss\nself.n_step = n_step\nself.mu = mu\nself.sigma = sigma\nself.step_time = step_time",
"step_vector = np.abs([round(gauss(self.mu, self.sigma), 1) for _ in range(self.n_step)])\nu = np.zeros(shape=dim)\nj = 0\nfor i in range(len(t)):\n if t[i] % self.step_time == 0 and t[i] != 0 and (j + 1 != len(... | <|body_start_0|>
self.ss = ss
self.n_step = n_step
self.mu = mu
self.sigma = sigma
self.step_time = step_time
<|end_body_0|>
<|body_start_1|>
step_vector = np.abs([round(gauss(self.mu, self.sigma), 1) for _ in range(self.n_step)])
u = np.zeros(shape=dim)
... | GaussStep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussStep:
def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None):
"""Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set... | stack_v2_sparse_classes_36k_train_014751 | 8,036 | no_license | [
{
"docstring": "Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set.",
"name": "__init__",
"signature": "def __init__(self, step_time, mu=None, sigma=None,... | 2 | stack_v2_sparse_classes_30k_train_009304 | Implement the Python class `GaussStep` described below.
Class description:
Implement the GaussStep class.
Method signatures and docstrings:
- def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None): Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step chan... | Implement the Python class `GaussStep` described below.
Class description:
Implement the GaussStep class.
Method signatures and docstrings:
- def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None): Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step chan... | cf548475295f25407ba968546c2fc85c26f9343c | <|skeleton|>
class GaussStep:
def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None):
"""Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussStep:
def __init__(self, step_time, mu=None, sigma=None, n_step=None, ss=None):
"""Settings for a Gauss step sequence Args: mu (float) sigma (float) step_time: Time to perform step change n_step (int): Number of steps Notes: Preferred signal for closed-loop control training data set."""
s... | the_stack_v2_python_sparse | SourceCode/simulation/signal.py | martin-bachorik/Master-Thesis-Project | train | 0 | |
05d977327a64ff8394b5c46cd3c8c16b3489c856 | [
"if not nums:\n return 0\nn = len(nums)\nif n <= 2:\n return max(nums)\ndp = [0] * n\ndp[0] = nums[0]\ndp[1] = max(nums[0], nums[1])\nfor i in range(2, n):\n dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])\n'\\n N = len(nums)\\n dp = [0] * (N + 1)\\n dp[0] = 0\\n dp[1] = nums[0]\\n ... | <|body_start_0|>
if not nums:
return 0
n = len(nums)
if n <= 2:
return max(nums)
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
'\n N =... | 三道打家劫舍问题 | HouseRobber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HouseRobber:
"""三道打家劫舍问题"""
def rob1(self, nums: List[int]) -> int:
"""198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组, 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 :param nums:[1,2,3,1] :return:4 dp[i] = max(dp[i - 1... | stack_v2_sparse_classes_36k_train_014752 | 9,733 | no_license | [
{
"docstring": "198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组, 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 :param nums:[1,2,3,1] :return:4 dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])",
"name": "rob1",
"signature": "def rob1(self, nums... | 3 | stack_v2_sparse_classes_30k_train_010192 | Implement the Python class `HouseRobber` described below.
Class description:
三道打家劫舍问题
Method signatures and docstrings:
- def rob1(self, nums: List[int]) -> int: 198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组, 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最... | Implement the Python class `HouseRobber` described below.
Class description:
三道打家劫舍问题
Method signatures and docstrings:
- def rob1(self, nums: List[int]) -> int: 198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组, 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最... | 330330ef6bc42eeb17f4dea53c30d230506b4e8f | <|skeleton|>
class HouseRobber:
"""三道打家劫舍问题"""
def rob1(self, nums: List[int]) -> int:
"""198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组, 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 :param nums:[1,2,3,1] :return:4 dp[i] = max(dp[i - 1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HouseRobber:
"""三道打家劫舍问题"""
def rob1(self, nums: List[int]) -> int:
"""198. 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组, 计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 :param nums:[1,2,3,1] :return:4 dp[i] = max(dp[i - 1], dp[i - 2] ... | the_stack_v2_python_sparse | Demo/Algorithm/DynamicProgramming.py | NiceToMeeetU/ToGetReady | train | 0 |
72dc51b2886e5e29ecdbe64d06575923c7005209 | [
"super().__init__()\npose = ((0.487, 0.109, 0.438), p.getQuaternionFromEuler((np.pi, 0, 0)))\nbase = p.loadURDF('assets/ur5/suction/suction-base.urdf', pose[0], pose[1])\np.createConstraint(parentBodyUniqueId=robot, parentLinkIndex=ee, childBodyUniqueId=base, childLinkIndex=-1, jointType=p.JOINT_FIXED, jointAxis=(0... | <|body_start_0|>
super().__init__()
pose = ((0.487, 0.109, 0.438), p.getQuaternionFromEuler((np.pi, 0, 0)))
base = p.loadURDF('assets/ur5/suction/suction-base.urdf', pose[0], pose[1])
p.createConstraint(parentBodyUniqueId=robot, parentLinkIndex=ee, childBodyUniqueId=base, childLinkIndex=... | Simulate simple suction dynamics. | Suction | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Suction:
"""Simulate simple suction dynamics."""
def __init__(self, robot, ee, obj_ids):
"""Creates suction and 'attaches' it to the robot. Has special cases when dealing with rigid vs deformables. For rigid, only need to check contact_constraint for any constraint. For soft bodies (... | stack_v2_sparse_classes_36k_train_014753 | 8,660 | permissive | [
{
"docstring": "Creates suction and 'attaches' it to the robot. Has special cases when dealing with rigid vs deformables. For rigid, only need to check contact_constraint for any constraint. For soft bodies (i.e., cloth or bags), use cloth_threshold to check distances from gripper body (self.body) to any vertex... | 5 | null | Implement the Python class `Suction` described below.
Class description:
Simulate simple suction dynamics.
Method signatures and docstrings:
- def __init__(self, robot, ee, obj_ids): Creates suction and 'attaches' it to the robot. Has special cases when dealing with rigid vs deformables. For rigid, only need to check... | Implement the Python class `Suction` described below.
Class description:
Simulate simple suction dynamics.
Method signatures and docstrings:
- def __init__(self, robot, ee, obj_ids): Creates suction and 'attaches' it to the robot. Has special cases when dealing with rigid vs deformables. For rigid, only need to check... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Suction:
"""Simulate simple suction dynamics."""
def __init__(self, robot, ee, obj_ids):
"""Creates suction and 'attaches' it to the robot. Has special cases when dealing with rigid vs deformables. For rigid, only need to check contact_constraint for any constraint. For soft bodies (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Suction:
"""Simulate simple suction dynamics."""
def __init__(self, robot, ee, obj_ids):
"""Creates suction and 'attaches' it to the robot. Has special cases when dealing with rigid vs deformables. For rigid, only need to check contact_constraint for any constraint. For soft bodies (i.e., cloth o... | the_stack_v2_python_sparse | ravens/ravens/grippers.py | Jimmy-INL/google-research | train | 1 |
f0d1ae87e21a16855d6abe712c2858603703604f | [
"self.scenarios = scenarios\nself.output_path = Path(output_path)\nself.output_path.mkdir(exist_ok=True, parents=True)",
"for scenario in self.scenarios:\n scenario_folder = self.output_path / scenario.name\n scenario_folder.mkdir()\n pv_models = []\n pv_models.append(f'! PV Scenario for {scenario.pv_... | <|body_start_0|>
self.scenarios = scenarios
self.output_path = Path(output_path)
self.output_path.mkdir(exist_ok=True, parents=True)
<|end_body_0|>
<|body_start_1|>
for scenario in self.scenarios:
scenario_folder = self.output_path / scenario.name
scenario_folder... | Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios. | OpenDSSPVScenarioWriter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenDSSPVScenarioWriter:
"""Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios."""
def __init__(self, scenarios: List[data_model.DistPVScenarioModel... | stack_v2_sparse_classes_36k_train_014754 | 2,280 | permissive | [
{
"docstring": "Constructor for `OpenDSSPVScenarioWriter` class. Args: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios.",
"name": "__init__",
"signature": "def __init__(self, scenarios: List[data_model.DistPVScenarioModel], ... | 2 | stack_v2_sparse_classes_30k_train_006324 | Implement the Python class `OpenDSSPVScenarioWriter` described below.
Class description:
Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios.
Method signatures and docstrings:... | Implement the Python class `OpenDSSPVScenarioWriter` described below.
Class description:
Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios.
Method signatures and docstrings:... | 2185f4facec30b747f62618861321599b595d107 | <|skeleton|>
class OpenDSSPVScenarioWriter:
"""Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios."""
def __init__(self, scenarios: List[data_model.DistPVScenarioModel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenDSSPVScenarioWriter:
"""Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios."""
def __init__(self, scenarios: List[data_model.DistPVScenarioModel], output_pat... | the_stack_v2_python_sparse | emerge/scenarios/opendss_writer.py | NREL/EMeRGE | train | 9 |
0950c0a24497879c17bc72802b627d0fffe2d15e | [
"if n < 2:\n return 1\ndp = [0] * (n + 1)\ndp[0], dp[1] = (1, 1)\nfor i in range(2, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nreturn dp[n]",
"if n < 2:\n return n\na, b, sum = (1, 1, 0)\nfor _ in range(2, n + 1):\n sum = a + b\n a = b\n b = sum\nreturn sum"
] | <|body_start_0|>
if n < 2:
return 1
dp = [0] * (n + 1)
dp[0], dp[1] = (1, 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
<|end_body_0|>
<|body_start_1|>
if n < 2:
return n
a, b, sum = (1, 1, 0)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n: int) -> int:
"""递归方程:f(n) = f(n-1) + f(n-2),n >= 2"""
<|body_0|>
def climbStairs1(self, n: int) -> int:
"""空间复杂度:O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 2:
return 1
dp = [0] ... | stack_v2_sparse_classes_36k_train_014755 | 1,471 | permissive | [
{
"docstring": "递归方程:f(n) = f(n-1) + f(n-2),n >= 2",
"name": "climbStairs",
"signature": "def climbStairs(self, n: int) -> int"
},
{
"docstring": "空间复杂度:O(1)",
"name": "climbStairs1",
"signature": "def climbStairs1(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_012047 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: 递归方程:f(n) = f(n-1) + f(n-2),n >= 2
- def climbStairs1(self, n: int) -> int: 空间复杂度:O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n: int) -> int: 递归方程:f(n) = f(n-1) + f(n-2),n >= 2
- def climbStairs1(self, n: int) -> int: 空间复杂度:O(1)
<|skeleton|>
class Solution:
def climbStairs(se... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def climbStairs(self, n: int) -> int:
"""递归方程:f(n) = f(n-1) + f(n-2),n >= 2"""
<|body_0|>
def climbStairs1(self, n: int) -> int:
"""空间复杂度:O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n: int) -> int:
"""递归方程:f(n) = f(n-1) + f(n-2),n >= 2"""
if n < 2:
return 1
dp = [0] * (n + 1)
dp[0], dp[1] = (1, 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
def climbStairs... | the_stack_v2_python_sparse | 70-climbing-stairs.py | yuenliou/leetcode | train | 0 | |
8281f0d786a0cc0bea83db55da98f503b8fb96e2 | [
"A = [[]] * (n + 1)\nfor i in range(n + 1):\n if i == 0:\n A[i] = []\n elif i == 1:\n A[i] = [TreeNode(1)]\n else:\n for j in range(1, i + 1):\n left = A[j - 1]\n right = A[i - j]\n if left != [] and right != []:\n for left_temp in left:\... | <|body_start_0|>
A = [[]] * (n + 1)
for i in range(n + 1):
if i == 0:
A[i] = []
elif i == 1:
A[i] = [TreeNode(1)]
else:
for j in range(1, i + 1):
left = A[j - 1]
right = A[i - j]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def changeTreeValue(self, node, change):
""":param head: TreeNode :param change: int :return: None"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
A = [[]] * ... | stack_v2_sparse_classes_36k_train_014756 | 2,393 | no_license | [
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees",
"signature": "def generateTrees(self, n)"
},
{
"docstring": ":param head: TreeNode :param change: int :return: None",
"name": "changeTreeValue",
"signature": "def changeTreeValue(self, node, change)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017414 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def changeTreeValue(self, node, change): :param head: TreeNode :param change: int :return: None | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def changeTreeValue(self, node, change): :param head: TreeNode :param change: int :return: None
<|skeleton|>
cl... | 0fc972e5cd2baf1b5ddf8b192962629f40bc3bf4 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def changeTreeValue(self, node, change):
""":param head: TreeNode :param change: int :return: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
A = [[]] * (n + 1)
for i in range(n + 1):
if i == 0:
A[i] = []
elif i == 1:
A[i] = [TreeNode(1)]
else:
for j in range(1, i... | the_stack_v2_python_sparse | problems/95. Unique Binary Search Trees II.py | yukiii-zhong/Leetcode | train | 2 | |
2b985e52be982d5294acdb410ef0087d463c9e4e | [
"sstream = RosettaFunctionConstructs._ATOMPAIR\nsstream += 'BOUNDED {lower_bound: >.3f} {upper_bound: >.3f} 1 0.5 #'\nreturn sstream",
"sstream = RosettaFunctionConstructs._ATOMPAIR\nsstream += RosettaFunctionConstructs._SCALARWEIGHTED\nsstream += 'BOUNDED 0 {lower_bound: >.3f} 1 0.5'\nreturn sstream",
"sstream... | <|body_start_0|>
sstream = RosettaFunctionConstructs._ATOMPAIR
sstream += 'BOUNDED {lower_bound: >.3f} {upper_bound: >.3f} 1 0.5 #'
return sstream
<|end_body_0|>
<|body_start_1|>
sstream = RosettaFunctionConstructs._ATOMPAIR
sstream += RosettaFunctionConstructs._SCALARWEIGHTED
... | Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/rosetta_basics/file_types/constraint-file>`_ | RosettaFunctionConstructs | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RosettaFunctionConstructs:
"""Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/r... | stack_v2_sparse_classes_36k_train_014757 | 4,869 | permissive | [
{
"docstring": "Simple bounded energy function",
"name": "BOUNDED_default",
"signature": "def BOUNDED_default(self)"
},
{
"docstring": "Energy function according to [#]_ References ---------- .. [#] Ovchinnekov et al. (2015). Large-scale determination of previously unsolved protein structures us... | 6 | stack_v2_sparse_classes_30k_train_014321 | Implement the Python class `RosettaFunctionConstructs` described below.
Class description:
Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https... | Implement the Python class `RosettaFunctionConstructs` described below.
Class description:
Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https... | 926f194a660d95350e9172d236c9c002e8a921a3 | <|skeleton|>
class RosettaFunctionConstructs:
"""Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RosettaFunctionConstructs:
"""Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/rosetta_basics... | the_stack_v2_python_sparse | conkit/misc/energyfunction.py | rigdenlab/conkit | train | 19 |
77948fd0f40b7bc2cdc08edd44e66349428f8467 | [
"p = Phenotype.query.get(kf_id)\nif p is None:\n abort(404, 'could not find {} `{}`'.format('phenotype', kf_id))\nreturn PhenotypeSchema().jsonify(p)",
"body = request.get_json(force=True) or {}\np = Phenotype.query.get(kf_id)\nif p is None:\n abort(404, 'could not find {} `{}`'.format('phenotype', kf_id))\... | <|body_start_0|>
p = Phenotype.query.get(kf_id)
if p is None:
abort(404, 'could not find {} `{}`'.format('phenotype', kf_id))
return PhenotypeSchema().jsonify(p)
<|end_body_0|>
<|body_start_1|>
body = request.get_json(force=True) or {}
p = Phenotype.query.get(kf_id)
... | Phenotype REST API | PhenotypeAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhenotypeAPI:
"""Phenotype REST API"""
def get(self, kf_id):
"""Get a phenotype by id --- template: path: get_by_id.yml properties: resource: Phenotype"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing phenotype Allows partial update of resource --- tem... | stack_v2_sparse_classes_36k_train_014758 | 4,652 | permissive | [
{
"docstring": "Get a phenotype by id --- template: path: get_by_id.yml properties: resource: Phenotype",
"name": "get",
"signature": "def get(self, kf_id)"
},
{
"docstring": "Update an existing phenotype Allows partial update of resource --- template: path: update_by_id.yml properties: resource... | 3 | null | Implement the Python class `PhenotypeAPI` described below.
Class description:
Phenotype REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a phenotype by id --- template: path: get_by_id.yml properties: resource: Phenotype
- def patch(self, kf_id): Update an existing phenotype Allows partial updat... | Implement the Python class `PhenotypeAPI` described below.
Class description:
Phenotype REST API
Method signatures and docstrings:
- def get(self, kf_id): Get a phenotype by id --- template: path: get_by_id.yml properties: resource: Phenotype
- def patch(self, kf_id): Update an existing phenotype Allows partial updat... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class PhenotypeAPI:
"""Phenotype REST API"""
def get(self, kf_id):
"""Get a phenotype by id --- template: path: get_by_id.yml properties: resource: Phenotype"""
<|body_0|>
def patch(self, kf_id):
"""Update an existing phenotype Allows partial update of resource --- tem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhenotypeAPI:
"""Phenotype REST API"""
def get(self, kf_id):
"""Get a phenotype by id --- template: path: get_by_id.yml properties: resource: Phenotype"""
p = Phenotype.query.get(kf_id)
if p is None:
abort(404, 'could not find {} `{}`'.format('phenotype', kf_id))
... | the_stack_v2_python_sparse | dataservice/api/phenotype/resources.py | kids-first/kf-api-dataservice | train | 9 |
93516bf860a87190dee719d7d8fc5341eb3ab589 | [
"if cls.USE_PLUGIN_MANAGER:\n return set(cls.get_available_plugins().values())\nelse:\n return set()",
"hash_obj = sha1()\nsorted_transformers = sorted(cls.get_registered_transformers(), key=lambda t: t.name())\nfor transformer in sorted_transformers:\n hash_obj.update(transformer.name().encode())\n h... | <|body_start_0|>
if cls.USE_PLUGIN_MANAGER:
return set(cls.get_available_plugins().values())
else:
return set()
<|end_body_0|>
<|body_start_1|>
hash_obj = sha1()
sorted_transformers = sorted(cls.get_registered_transformers(), key=lambda t: t.name())
for t... | Registry for all of the block structure transformers that have been made available. All block structure transformers should implement `BlockStructureTransformer`. | TransformerRegistry | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerRegistry:
"""Registry for all of the block structure transformers that have been made available. All block structure transformers should implement `BlockStructureTransformer`."""
def get_registered_transformers(cls):
"""Returns a set of all registered transformers. Returns... | stack_v2_sparse_classes_36k_train_014759 | 2,371 | permissive | [
{
"docstring": "Returns a set of all registered transformers. Returns: {BlockStructureTransformer} - All transformers that are registered with the platform's PluginManager.",
"name": "get_registered_transformers",
"signature": "def get_registered_transformers(cls)"
},
{
"docstring": "Returns a d... | 3 | stack_v2_sparse_classes_30k_train_020278 | Implement the Python class `TransformerRegistry` described below.
Class description:
Registry for all of the block structure transformers that have been made available. All block structure transformers should implement `BlockStructureTransformer`.
Method signatures and docstrings:
- def get_registered_transformers(cl... | Implement the Python class `TransformerRegistry` described below.
Class description:
Registry for all of the block structure transformers that have been made available. All block structure transformers should implement `BlockStructureTransformer`.
Method signatures and docstrings:
- def get_registered_transformers(cl... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class TransformerRegistry:
"""Registry for all of the block structure transformers that have been made available. All block structure transformers should implement `BlockStructureTransformer`."""
def get_registered_transformers(cls):
"""Returns a set of all registered transformers. Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerRegistry:
"""Registry for all of the block structure transformers that have been made available. All block structure transformers should implement `BlockStructureTransformer`."""
def get_registered_transformers(cls):
"""Returns a set of all registered transformers. Returns: {BlockStruc... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content/block_structure/transformer_registry.py | luque/better-ways-of-thinking-about-software | train | 3 |
088cb8f74b04db6d6b1a636dd6cfc3498a69bbd3 | [
"data = dicInput.get('data')\nif isinstance(data, type(None)):\n raise Exception('no input data')\nentity_id = dicParams.get('entityId')\nif entity_id is None:\n raise Exception('entityId could not be None.')\nnumeric_cols = dicParams.get('numericCols')\ncategory_cols = dicParams.get('categoryCols')\nagg_prim... | <|body_start_0|>
data = dicInput.get('data')
if isinstance(data, type(None)):
raise Exception('no input data')
entity_id = dicParams.get('entityId')
if entity_id is None:
raise Exception('entityId could not be None.')
numeric_cols = dicParams.get('numericC... | 功能 利用featuretools执行特征衍生(不含时间窗功能) 输入 原始数据 数据帧类型 data 控制 类别实体id 字符串类型 entityId 控制 数值特征列 列表类型 numericCols None 控制 类别特征列 列表类型 categoryCols None 控制 聚合算法集合 列表类型 aggPrimitives [] 控制 转换算法集合 列表类型 transPrimitives [] 控制 where算法集合 列表类型 wherePrimitives [] 控制 特征衍生深度 列表类型 max_depth 2 输出 衍生的特征数据 数据帧类型 matrix | EntityFeaturesService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityFeaturesService:
"""功能 利用featuretools执行特征衍生(不含时间窗功能) 输入 原始数据 数据帧类型 data 控制 类别实体id 字符串类型 entityId 控制 数值特征列 列表类型 numericCols None 控制 类别特征列 列表类型 categoryCols None 控制 聚合算法集合 列表类型 aggPrimitives [] 控制 转换算法集合 列表类型 transPrimitives [] 控制 where算法集合 列表类型 wherePrimitives [] 控制 特征衍生深度 列表类型 max_depth 2 输... | stack_v2_sparse_classes_36k_train_014760 | 5,190 | no_license | [
{
"docstring": "组件接口 :param dicInput: 包含数据集的字典 :param dicParams: 包含空值参数的字典 :return: 结果数据字典",
"name": "process",
"signature": "def process(self, dicInput, dicParams)"
},
{
"docstring": "利用featuretools执行特征衍生。 此方法计算一个实体的特征衍生。 此方法未涉及时间窗特征衍生的计算。 :param data: 原始数据 dataframe :param entity_id: 被计算实体的id ... | 2 | null | Implement the Python class `EntityFeaturesService` described below.
Class description:
功能 利用featuretools执行特征衍生(不含时间窗功能) 输入 原始数据 数据帧类型 data 控制 类别实体id 字符串类型 entityId 控制 数值特征列 列表类型 numericCols None 控制 类别特征列 列表类型 categoryCols None 控制 聚合算法集合 列表类型 aggPrimitives [] 控制 转换算法集合 列表类型 transPrimitives [] 控制 where算法集合 列表类型 wherePri... | Implement the Python class `EntityFeaturesService` described below.
Class description:
功能 利用featuretools执行特征衍生(不含时间窗功能) 输入 原始数据 数据帧类型 data 控制 类别实体id 字符串类型 entityId 控制 数值特征列 列表类型 numericCols None 控制 类别特征列 列表类型 categoryCols None 控制 聚合算法集合 列表类型 aggPrimitives [] 控制 转换算法集合 列表类型 transPrimitives [] 控制 where算法集合 列表类型 wherePri... | b5a0b97772f006ab64580bc178a0e5d611fda8cb | <|skeleton|>
class EntityFeaturesService:
"""功能 利用featuretools执行特征衍生(不含时间窗功能) 输入 原始数据 数据帧类型 data 控制 类别实体id 字符串类型 entityId 控制 数值特征列 列表类型 numericCols None 控制 类别特征列 列表类型 categoryCols None 控制 聚合算法集合 列表类型 aggPrimitives [] 控制 转换算法集合 列表类型 transPrimitives [] 控制 where算法集合 列表类型 wherePrimitives [] 控制 特征衍生深度 列表类型 max_depth 2 输... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityFeaturesService:
"""功能 利用featuretools执行特征衍生(不含时间窗功能) 输入 原始数据 数据帧类型 data 控制 类别实体id 字符串类型 entityId 控制 数值特征列 列表类型 numericCols None 控制 类别特征列 列表类型 categoryCols None 控制 聚合算法集合 列表类型 aggPrimitives [] 控制 转换算法集合 列表类型 transPrimitives [] 控制 where算法集合 列表类型 wherePrimitives [] 控制 特征衍生深度 列表类型 max_depth 2 输出 衍生的特征数据 数据帧... | the_stack_v2_python_sparse | ServiceImplByDask/EntityFeaturesService.py | MarkHe735/tgtks | train | 0 |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.getParser = reqparse.RequestParser()\nself.getParser.add_argument('token')\nself.postParser = reqparse.RequestParser()\nself.postParser.add_argument('vtSymbol')\nself.postParser.add_argument('price')\nself.postParser.add_argument('volume')\nself.postParser.add_argument('priceType')\nself.postParser.add_argume... | <|body_start_0|>
self.getParser = reqparse.RequestParser()
self.getParser.add_argument('token')
self.postParser = reqparse.RequestParser()
self.postParser.add_argument('vtSymbol')
self.postParser.add_argument('price')
self.postParser.add_argument('volume')
self.po... | 委托 | Order | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Order:
"""委托"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""查询"""
<|body_1|>
def post(self):
"""发单"""
<|body_2|>
def delete(self):
"""撤单"""
<|body_3|>
def cancel(self, order):
"""撤单"""
... | stack_v2_sparse_classes_36k_train_014761 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "查询",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "发单",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "撤单",
"name": "delete",
... | 5 | stack_v2_sparse_classes_30k_train_020774 | Implement the Python class `Order` described below.
Class description:
委托
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 查询
- def post(self): 发单
- def delete(self): 撤单
- def cancel(self, order): 撤单 | Implement the Python class `Order` described below.
Class description:
委托
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 查询
- def post(self): 发单
- def delete(self): 撤单
- def cancel(self, order): 撤单
<|skeleton|>
class Order:
"""委托"""
def __init__(self):
"""初始化"""
... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class Order:
"""委托"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""查询"""
<|body_1|>
def post(self):
"""发单"""
<|body_2|>
def delete(self):
"""撤单"""
<|body_3|>
def cancel(self, order):
"""撤单"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Order:
"""委托"""
def __init__(self):
"""初始化"""
self.getParser = reqparse.RequestParser()
self.getParser.add_argument('token')
self.postParser = reqparse.RequestParser()
self.postParser.add_argument('vtSymbol')
self.postParser.add_argument('price')
se... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
c5e95738543b9c7a54e24250215490226983110b | [
"for i in range(len(nums)):\n if nums[i] >= target:\n nums.insert(i, target)\n return i\nnums.insert(len(nums) - 1, target)\nreturn len(nums) - 1",
"left = 0\nright = len(nums) - 1\nif target > nums[right]:\n return right + 1\nwhile left < right:\n mid = int((left + right) / 2)\n if nums... | <|body_start_0|>
for i in range(len(nums)):
if nums[i] >= target:
nums.insert(i, target)
return i
nums.insert(len(nums) - 1, target)
return len(nums) - 1
<|end_body_0|>
<|body_start_1|>
left = 0
right = len(nums) - 1
if target ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsert(self, nums, target):
""":param nums: List[int] :param target: int :return: int"""
<|body_0|>
def searchInsert2(self, nums, target):
""":param nums: List[int] :param target: int :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_014762 | 1,085 | no_license | [
{
"docstring": ":param nums: List[int] :param target: int :return: int",
"name": "searchInsert",
"signature": "def searchInsert(self, nums, target)"
},
{
"docstring": ":param nums: List[int] :param target: int :return: int",
"name": "searchInsert2",
"signature": "def searchInsert2(self, ... | 2 | stack_v2_sparse_classes_30k_train_007479 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums, target): :param nums: List[int] :param target: int :return: int
- def searchInsert2(self, nums, target): :param nums: List[int] :param target: int :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums, target): :param nums: List[int] :param target: int :return: int
- def searchInsert2(self, nums, target): :param nums: List[int] :param target: int :r... | 3afcfc2a0ff5156cfb40614418e1b846ede84da0 | <|skeleton|>
class Solution:
def searchInsert(self, nums, target):
""":param nums: List[int] :param target: int :return: int"""
<|body_0|>
def searchInsert2(self, nums, target):
""":param nums: List[int] :param target: int :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchInsert(self, nums, target):
""":param nums: List[int] :param target: int :return: int"""
for i in range(len(nums)):
if nums[i] >= target:
nums.insert(i, target)
return i
nums.insert(len(nums) - 1, target)
return le... | the_stack_v2_python_sparse | src/easy/Search_Insertion_Position.py | TuGengs/LeetCode | train | 4 | |
66b0d04f9ff8ff6a25a73968d0081278f7593e60 | [
"entity = get_entity(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['entity_name'])\nentity['entity_values'] = settings.TOKENFIELD_DELIMITER.join(entity['entity_values'])\nself.initial = entity\nreturn super(EntitiesUpdateView, self).get_initial(**kwargs)",
"context = super(EntitiesUpd... | <|body_start_0|>
entity = get_entity(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['entity_name'])
entity['entity_values'] = settings.TOKENFIELD_DELIMITER.join(entity['entity_values'])
self.initial = entity
return super(EntitiesUpdateView, self).get_initial(*... | Single Entity view | EntitiesUpdateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntitiesUpdateView:
"""Single Entity view"""
def get_initial(self, **kwargs):
"""Get and prepare Entity data"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Provide entity name for the template"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_014763 | 39,842 | permissive | [
{
"docstring": "Get and prepare Entity data",
"name": "get_initial",
"signature": "def get_initial(self, **kwargs)"
},
{
"docstring": "Provide entity name for the template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016717 | Implement the Python class `EntitiesUpdateView` described below.
Class description:
Single Entity view
Method signatures and docstrings:
- def get_initial(self, **kwargs): Get and prepare Entity data
- def get_context_data(self, **kwargs): Provide entity name for the template | Implement the Python class `EntitiesUpdateView` described below.
Class description:
Single Entity view
Method signatures and docstrings:
- def get_initial(self, **kwargs): Get and prepare Entity data
- def get_context_data(self, **kwargs): Provide entity name for the template
<|skeleton|>
class EntitiesUpdateView:
... | d632d00f9a22a7a826bba4896a7102b2ac8690ff | <|skeleton|>
class EntitiesUpdateView:
"""Single Entity view"""
def get_initial(self, **kwargs):
"""Get and prepare Entity data"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Provide entity name for the template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntitiesUpdateView:
"""Single Entity view"""
def get_initial(self, **kwargs):
"""Get and prepare Entity data"""
entity = get_entity(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['entity_name'])
entity['entity_values'] = settings.TOKENFIELD_DELIMITER.jo... | the_stack_v2_python_sparse | src/studio/views.py | hutomadotAI/web-console | train | 6 |
4b49e5dafe85bdf719ea71f7ca194712e047becf | [
"pattern = re.compile(pattern)\nfor node, path in self._explore(node=folder, path=primitives.path()):\n match = pattern.match(str(path))\n if match:\n yield (node, match)\nreturn",
"yield (node, path)\nif not node.isFolder:\n return\nfor name, child in node.contents.items():\n yield from self._... | <|body_start_0|>
pattern = re.compile(pattern)
for node, path in self._explore(node=folder, path=primitives.path()):
match = pattern.match(str(path))
if match:
yield (node, match)
return
<|end_body_0|>
<|body_start_1|>
yield (node, path)
i... | A visitor that generates a list of the contents of a filesystem | Finder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Finder:
"""A visitor that generates a list of the contents of a filesystem"""
def explore(self, folder, pattern='.*'):
"""Traverse the folder and return contents that match the given pattern"""
<|body_0|>
def _explore(self, node, path):
"""The recursive workhorse... | stack_v2_sparse_classes_36k_train_014764 | 1,535 | permissive | [
{
"docstring": "Traverse the folder and return contents that match the given pattern",
"name": "explore",
"signature": "def explore(self, folder, pattern='.*')"
},
{
"docstring": "The recursive workhorse for folder exploration",
"name": "_explore",
"signature": "def _explore(self, node, ... | 2 | null | Implement the Python class `Finder` described below.
Class description:
A visitor that generates a list of the contents of a filesystem
Method signatures and docstrings:
- def explore(self, folder, pattern='.*'): Traverse the folder and return contents that match the given pattern
- def _explore(self, node, path): Th... | Implement the Python class `Finder` described below.
Class description:
A visitor that generates a list of the contents of a filesystem
Method signatures and docstrings:
- def explore(self, folder, pattern='.*'): Traverse the folder and return contents that match the given pattern
- def _explore(self, node, path): Th... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Finder:
"""A visitor that generates a list of the contents of a filesystem"""
def explore(self, folder, pattern='.*'):
"""Traverse the folder and return contents that match the given pattern"""
<|body_0|>
def _explore(self, node, path):
"""The recursive workhorse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Finder:
"""A visitor that generates a list of the contents of a filesystem"""
def explore(self, folder, pattern='.*'):
"""Traverse the folder and return contents that match the given pattern"""
pattern = re.compile(pattern)
for node, path in self._explore(node=folder, path=primiti... | the_stack_v2_python_sparse | packages/pyre/filesystem/Finder.py | pyre/pyre | train | 27 |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(QRDQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif head_hidden_size is None:\n head_hidden_size = encoder_hidden_size_list[-1]\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activatio... | <|body_start_0|>
super(QRDQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if head_hidden_size is None:
head_hidden_size = encoder_hidden_size_list[-1]
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = F... | QRDQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: ... | stack_v2_sparse_classes_36k_train_014765 | 30,380 | permissive | [
{
"docstring": "Overview: Init the QRDQN Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation's space. - action_shape (:obj:`Union[int, SequenceType]`): Action's space. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pass to... | 2 | stack_v2_sparse_classes_30k_train_002020 | Implement the Python class `QRDQN` described below.
Class description:
Implement the QRDQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=N... | Implement the Python class `QRDQN` described below.
Class description:
Implement the QRDQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=N... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QRDQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: Optional[int]=None, head_layer_num: int=1, num_quantiles: int=32, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 | |
ddc5220a9e9b46bff12d9a98cf530b69dc24abbf | [
"super(NdtMatchingTask, self).__init__(node)\nself._data_player = None\nself._speed_metric = None\nself._shutdown_counter = 0\nself._speed_formatter = None",
"input_topic = getParameter(self.node, 'input_topic')\nbenchmarked_out_topic = getParameter(self.node, 'benchmarked_output_topic')\nresult_path = getParamet... | <|body_start_0|>
super(NdtMatchingTask, self).__init__(node)
self._data_player = None
self._speed_metric = None
self._shutdown_counter = 0
self._speed_formatter = None
<|end_body_0|>
<|body_start_1|>
input_topic = getParameter(self.node, 'input_topic')
benchmarke... | The NdtMatchingTask class benchmarks the lidar localization. It is a specialized BenchmarkTask class holding all the peculiarities of the ndt_matching node. | NdtMatchingTask | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NdtMatchingTask:
"""The NdtMatchingTask class benchmarks the lidar localization. It is a specialized BenchmarkTask class holding all the peculiarities of the ndt_matching node."""
def __init__(self, node):
"""Create a NdtMatchingTask object. @param node: ROS2 node @type node: rclpy.n... | stack_v2_sparse_classes_36k_train_014766 | 6,183 | permissive | [
{
"docstring": "Create a NdtMatchingTask object. @param node: ROS2 node @type node: rclpy.node.Node",
"name": "__init__",
"signature": "def __init__(self, node)"
},
{
"docstring": "Initialize the task structure. The task computes one metric: - speed @return: True on success, False on failure",
... | 4 | null | Implement the Python class `NdtMatchingTask` described below.
Class description:
The NdtMatchingTask class benchmarks the lidar localization. It is a specialized BenchmarkTask class holding all the peculiarities of the ndt_matching node.
Method signatures and docstrings:
- def __init__(self, node): Create a NdtMatchi... | Implement the Python class `NdtMatchingTask` described below.
Class description:
The NdtMatchingTask class benchmarks the lidar localization. It is a specialized BenchmarkTask class holding all the peculiarities of the ndt_matching node.
Method signatures and docstrings:
- def __init__(self, node): Create a NdtMatchi... | ff8950abbb72366ed3072de790c405de8875ecc3 | <|skeleton|>
class NdtMatchingTask:
"""The NdtMatchingTask class benchmarks the lidar localization. It is a specialized BenchmarkTask class holding all the peculiarities of the ndt_matching node."""
def __init__(self, node):
"""Create a NdtMatchingTask object. @param node: ROS2 node @type node: rclpy.n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NdtMatchingTask:
"""The NdtMatchingTask class benchmarks the lidar localization. It is a specialized BenchmarkTask class holding all the peculiarities of the ndt_matching node."""
def __init__(self, node):
"""Create a NdtMatchingTask object. @param node: ROS2 node @type node: rclpy.node.Node"""
... | the_stack_v2_python_sparse | src/tools/benchmark_tool/benchmark_tool/benchmark_task/ndt_matching_task.py | bytetok/vde | train | 0 |
eb0dd1d6301893897020037559076902ed8522a2 | [
"if not request.user.is_superuser:\n self.queryset = Patient.objects.filter(user__pk=request.user.id)\nreturn super().list(request, args, kwargs)",
"queryset = Patient.objects.get(pk=request.GET['pk'])\nserializer = PatientReadSerializer(queryset, many=False)\nreturn Response(serializer.data)",
"serializer =... | <|body_start_0|>
if not request.user.is_superuser:
self.queryset = Patient.objects.filter(user__pk=request.user.id)
return super().list(request, args, kwargs)
<|end_body_0|>
<|body_start_1|>
queryset = Patient.objects.get(pk=request.GET['pk'])
serializer = PatientReadSeriali... | PatientViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientViewSet:
def list(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_1|>
def create(self, request, *args, **kwargs)... | stack_v2_sparse_classes_36k_train_014767 | 8,609 | no_license | [
{
"docstring": "Override method to check permissions",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "Override method to check permissions",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring... | 6 | stack_v2_sparse_classes_30k_train_019456 | Implement the Python class `PatientViewSet` described below.
Class description:
Implement the PatientViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): Override method to check permissions
- def retrieve(self, request, *args, **kwargs): Override method to check permissions
- ... | Implement the Python class `PatientViewSet` described below.
Class description:
Implement the PatientViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): Override method to check permissions
- def retrieve(self, request, *args, **kwargs): Override method to check permissions
- ... | cf1b9e973be872540dd0f5730df4830c987b9e33 | <|skeleton|>
class PatientViewSet:
def list(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_0|>
def retrieve(self, request, *args, **kwargs):
"""Override method to check permissions"""
<|body_1|>
def create(self, request, *args, **kwargs)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatientViewSet:
def list(self, request, *args, **kwargs):
"""Override method to check permissions"""
if not request.user.is_superuser:
self.queryset = Patient.objects.filter(user__pk=request.user.id)
return super().list(request, args, kwargs)
def retrieve(self, request... | the_stack_v2_python_sparse | backend/modules/patient/views.py | acca90/SleepWeb | train | 0 | |
c259767bc282f129e3c2b572ab2961d2753ade62 | [
"if not root:\n return []\nlevels = []\n\ndef helper(node, level):\n if len(levels) == level:\n levels.append([])\n levels[level].append(node.val)\n if node.left:\n helper(node.left, level + 1)\n if node.right:\n helper(node.right, level + 1)\nhelper(root, 0)\nreturn levels",
"... | <|body_start_0|>
if not root:
return []
levels = []
def helper(node, level):
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
if node.left:
helper(node.left, level + 1)
if node.r... | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:"""
<|body_0|>
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Appr... | stack_v2_sparse_classes_36k_train_014768 | 1,611 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:",
"name": "get_level_order_traversal",
"signature": "def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]"
},
{
"docstring": "Approach: Iteration Time Complexity: O(n) Space C... | 2 | null | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]: Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:
- def get_level... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]: Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:
- def get_level... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class BinaryTree:
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:"""
<|body_0|>
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Appr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryTree:
def get_level_order_traversal(self, root: TreeNode) -> List[List[int]]:
"""Approach: Recursion Time Complexity: O(n) Space Complexity: O(n) :param root: :return:"""
if not root:
return []
levels = []
def helper(node, level):
if len(levels) =... | the_stack_v2_python_sparse | data_structures/tree_node/bst_level_order_traversal.py | Shiv2157k/leet_code | train | 1 | |
405b5c41d8264945db2d199eaab9bc43661cd4d9 | [
"if sys.platform == 'win32':\n return QWinSplitterHandle(self.orientation(), self)\nreturn QSplitterHandle(self.orientation(), self)",
"old = self.orientation()\nif old != orientation:\n super(QCustomSplitter, self).setOrientation(orientation)\n if sys.platform == 'win32':\n for idx in xrange(self... | <|body_start_0|>
if sys.platform == 'win32':
return QWinSplitterHandle(self.orientation(), self)
return QSplitterHandle(self.orientation(), self)
<|end_body_0|>
<|body_start_1|>
old = self.orientation()
if old != orientation:
super(QCustomSplitter, self).setOrien... | A custom QSplitter which handles children of type QSplitItem. | QCustomSplitter | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCustomSplitter:
"""A custom QSplitter which handles children of type QSplitItem."""
def createHandle(self):
"""A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing... | stack_v2_sparse_classes_36k_train_014769 | 8,068 | permissive | [
{
"docstring": "A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing nicely. On all other platforms, a normal QSplitterHandler widget.",
"name": "createHandle",
"signature": "def creat... | 3 | stack_v2_sparse_classes_30k_train_020584 | Implement the Python class `QCustomSplitter` described below.
Class description:
A custom QSplitter which handles children of type QSplitItem.
Method signatures and docstrings:
- def createHandle(self): A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterH... | Implement the Python class `QCustomSplitter` described below.
Class description:
A custom QSplitter which handles children of type QSplitItem.
Method signatures and docstrings:
- def createHandle(self): A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterH... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class QCustomSplitter:
"""A custom QSplitter which handles children of type QSplitItem."""
def createHandle(self):
"""A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCustomSplitter:
"""A custom QSplitter which handles children of type QSplitItem."""
def createHandle(self):
"""A reimplemented virtual method to create splitter handles. On win32 platforms, this will return a custom QSplitterHandle which works around an issue with handle not drawing nicely. On a... | the_stack_v2_python_sparse | enaml/qt/qt_splitter.py | enthought/enaml | train | 17 |
b5ee02de4d4bea5f6a615576363a5972f436d29e | [
"min_num = nums[0]\nfor i in nums:\n if i < min_num:\n min_num = i\nreturn min_num",
"if len(nums) == 1:\n return nums[0]\nleft, right = (0, len(nums) - 1)\nif nums[right] > nums[0]:\n return nums[0]\nwhile left < right:\n mid = (right + left) // 2\n if nums[mid] > nums[mid + 1]:\n re... | <|body_start_0|>
min_num = nums[0]
for i in nums:
if i < min_num:
min_num = i
return min_num
<|end_body_0|>
<|body_start_1|>
if len(nums) == 1:
return nums[0]
left, right = (0, len(nums) - 1)
if nums[right] > nums[0]:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums: List[int]) -> int:
"""暴力搜索,时间复杂度O(n)"""
<|body_0|>
def findMin_2(self, nums: List[int]) -> int:
"""二分查找"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
min_num = nums[0]
for i in nums:
if i < min... | stack_v2_sparse_classes_36k_train_014770 | 1,623 | no_license | [
{
"docstring": "暴力搜索,时间复杂度O(n)",
"name": "findMin",
"signature": "def findMin(self, nums: List[int]) -> int"
},
{
"docstring": "二分查找",
"name": "findMin_2",
"signature": "def findMin_2(self, nums: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_010969 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums: List[int]) -> int: 暴力搜索,时间复杂度O(n)
- def findMin_2(self, nums: List[int]) -> int: 二分查找 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums: List[int]) -> int: 暴力搜索,时间复杂度O(n)
- def findMin_2(self, nums: List[int]) -> int: 二分查找
<|skeleton|>
class Solution:
def findMin(self, nums: List[int]... | 13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08 | <|skeleton|>
class Solution:
def findMin(self, nums: List[int]) -> int:
"""暴力搜索,时间复杂度O(n)"""
<|body_0|>
def findMin_2(self, nums: List[int]) -> int:
"""二分查找"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin(self, nums: List[int]) -> int:
"""暴力搜索,时间复杂度O(n)"""
min_num = nums[0]
for i in nums:
if i < min_num:
min_num = i
return min_num
def findMin_2(self, nums: List[int]) -> int:
"""二分查找"""
if len(nums) == 1:
... | the_stack_v2_python_sparse | Algorithms/153_Find_Minimum_in_Rotated_Sorted_Array/Find_Minimum_in_Rotated_Sorted_Array.py | lirui-ML/my_leetcode | train | 1 | |
f03f52ad0238cb94acff1e497f325e4a40245a2f | [
"if not head or not head.next:\n return True\nmid_node = self.get_mid_node(head)\nnew_head = self.reverse_list(mid_node)\nwhile head and new_head:\n if new_head.val != head.val:\n return False\n new_head = new_head.next\n head = head.next\nreturn True",
"slow = node\nfast = node.next\nwhile fas... | <|body_start_0|>
if not head or not head.next:
return True
mid_node = self.get_mid_node(head)
new_head = self.reverse_list(mid_node)
while head and new_head:
if new_head.val != head.val:
return False
new_head = new_head.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def get_mid_node(self, node):
"""Returns middle node of the list"""
<|body_1|>
def reverse_list(self, node):
"""Reverses the list."""
<|body_2|>
<... | stack_v2_sparse_classes_36k_train_014771 | 1,526 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": "Returns middle node of the list",
"name": "get_mid_node",
"signature": "def get_mid_node(self, node)"
},
{
"docstring": "Reverses the list.",... | 3 | stack_v2_sparse_classes_30k_train_011895 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def get_mid_node(self, node): Returns middle node of the list
- def reverse_list(self, node): Reverses the list. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def get_mid_node(self, node): Returns middle node of the list
- def reverse_list(self, node): Reverses the list.... | 1639a4b13c692d87c658a7e0a11212bf0e98d443 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def get_mid_node(self, node):
"""Returns middle node of the list"""
<|body_1|>
def reverse_list(self, node):
"""Reverses the list."""
<|body_2|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
if not head or not head.next:
return True
mid_node = self.get_mid_node(head)
new_head = self.reverse_list(mid_node)
while head and new_head:
if new_head.val != head.v... | the_stack_v2_python_sparse | easy/is_linked_list_palindrome.py | Hashah1/Leetcode-Practice | train | 0 | |
241bbd174e254690c8a3190583e377200ffc152b | [
"self._project = project\nself._zone = zone\nself._instance_group = instance_group\nself._job_name = job_name\nself._port = port\nself._credentials = credentials\nif credentials == 'default':\n if _GOOGLE_API_CLIENT_INSTALLED:\n self._credentials = GoogleCredentials.get_application_default()\nif service i... | <|body_start_0|>
self._project = project
self._zone = zone
self._instance_group = instance_group
self._job_name = job_name
self._port = port
self._credentials = credentials
if credentials == 'default':
if _GOOGLE_API_CLIENT_INSTALLED:
s... | Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance group and return a Cluster Resolver object suita... | GceClusterResolver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GceClusterResolver:
"""Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance gr... | stack_v2_sparse_classes_36k_train_014772 | 5,116 | permissive | [
{
"docstring": "Creates a new GceClusterResolver object. This takes in a few parameters and creates a GceClusterResolver project. It will then use these parameters to query the GCE API for the IP addresses of each instance in the instance group. Args: project: Name of the GCE project zone: Zone of the GCE insta... | 2 | null | Implement the Python class `GceClusterResolver` described below.
Class description:
Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of a... | Implement the Python class `GceClusterResolver` described below.
Class description:
Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of a... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class GceClusterResolver:
"""Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance gr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GceClusterResolver:
"""Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance group and retur... | the_stack_v2_python_sparse | Tensorflow_Pandas_Numpy/source3.6/tensorflow/contrib/cluster_resolver/python/training/gce_cluster_resolver.py | ryfeus/lambda-packs | train | 1,283 |
b4c85ea22f86b770e02b54f593325a061217c67b | [
"self.model = model\nself.handle = []\nself.relu_outputs = []",
"def _record_gradients(module, grad_in, grad_out):\n self.gradients = grad_in[0]\nfor _, module in self.model.named_modules():\n if isinstance(module, nn.modules.conv.Conv2d) and module.in_channels == 3:\n backward_handle = module.regist... | <|body_start_0|>
self.model = model
self.handle = []
self.relu_outputs = []
<|end_body_0|>
<|body_start_1|>
def _record_gradients(module, grad_in, grad_out):
self.gradients = grad_in[0]
for _, module in self.model.named_modules():
if isinstance(module, nn... | Base class for backpropagation. | BaseProp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseProp:
"""Base class for backpropagation."""
def __init__(self, model):
"""Init # Arguments: model: torchvision.models. A pretrained model. handle: list. Handle list that register a hook function. relu_outputs: list. Forward output after relu."""
<|body_0|>
def _regis... | stack_v2_sparse_classes_36k_train_014773 | 2,125 | permissive | [
{
"docstring": "Init # Arguments: model: torchvision.models. A pretrained model. handle: list. Handle list that register a hook function. relu_outputs: list. Forward output after relu.",
"name": "__init__",
"signature": "def __init__(self, model)"
},
{
"docstring": "Register hook function to sav... | 3 | stack_v2_sparse_classes_30k_train_012380 | Implement the Python class `BaseProp` described below.
Class description:
Base class for backpropagation.
Method signatures and docstrings:
- def __init__(self, model): Init # Arguments: model: torchvision.models. A pretrained model. handle: list. Handle list that register a hook function. relu_outputs: list. Forward... | Implement the Python class `BaseProp` described below.
Class description:
Base class for backpropagation.
Method signatures and docstrings:
- def __init__(self, model): Init # Arguments: model: torchvision.models. A pretrained model. handle: list. Handle list that register a hook function. relu_outputs: list. Forward... | c2f0323b0ec55d684ee24dbe35a6046fe0074663 | <|skeleton|>
class BaseProp:
"""Base class for backpropagation."""
def __init__(self, model):
"""Init # Arguments: model: torchvision.models. A pretrained model. handle: list. Handle list that register a hook function. relu_outputs: list. Forward output after relu."""
<|body_0|>
def _regis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseProp:
"""Base class for backpropagation."""
def __init__(self, model):
"""Init # Arguments: model: torchvision.models. A pretrained model. handle: list. Handle list that register a hook function. relu_outputs: list. Forward output after relu."""
self.model = model
self.handle ... | the_stack_v2_python_sparse | xdeep/xlocal/gradient/backprop/base.py | datamllab/xdeep | train | 40 |
3c54d4d5a6dbb932dbd355a2eed5e7d066a8e03b | [
"self.parsing_error = None\nself.tree = None\ntry:\n self.tree = lxml.etree.fromstring(data)\nexcept lxml.etree.XMLSyntaxError as ex:\n self.parsing_error = 'Parsing error: ' + str(ex)",
"if self.parsing_error:\n return self.parsing_error\nfor node in self.tree.iter():\n if isinstance(node, lxml.etree... | <|body_start_0|>
self.parsing_error = None
self.tree = None
try:
self.tree = lxml.etree.fromstring(data)
except lxml.etree.XMLSyntaxError as ex:
self.parsing_error = 'Parsing error: ' + str(ex)
<|end_body_0|>
<|body_start_1|>
if self.parsing_error:
... | XMLTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLTree:
def __init__(self, data):
"""The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str"""
<|body_0|>
def is_data_unclean(self):
"""Ensure that the tree parses as XML and... | stack_v2_sparse_classes_36k_train_014774 | 4,781 | no_license | [
{
"docstring": "The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Ensure that the tree parses as XML and that it conta... | 4 | stack_v2_sparse_classes_30k_train_010664 | Implement the Python class `XMLTree` described below.
Class description:
Implement the XMLTree class.
Method signatures and docstrings:
- def __init__(self, data): The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str
- def i... | Implement the Python class `XMLTree` described below.
Class description:
Implement the XMLTree class.
Method signatures and docstrings:
- def __init__(self, data): The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str
- def i... | ea54b58ef15a738500547e73e02935d95775c798 | <|skeleton|>
class XMLTree:
def __init__(self, data):
"""The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str"""
<|body_0|>
def is_data_unclean(self):
"""Ensure that the tree parses as XML and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XMLTree:
def __init__(self, data):
"""The XML tree representation of the data. Allows performing operations on this tree or querying it. :param data: The data to parse. :type data: str"""
self.parsing_error = None
self.tree = None
try:
self.tree = lxml.etree.fromstr... | the_stack_v2_python_sparse | lexicography/xml.py | keisetsu/btw | train | 0 | |
b29511feb7f7d636c70655a20c6c97d5e73d788b | [
"self.n_sample = n_sample\nself.pos_iou_thresh = pos_iou_thresh\nself.neg_iou_thresh = neg_iou_thresh\nself.pos_ratio = pos_ratio",
"img_width, img_height = img_size\ninside_index = get_inside_index(anchors, img_width, img_height)\ninside_anchors = anchors[inside_index]\nargmax_ious, labels = self._create_label(i... | <|body_start_0|>
self.n_sample = n_sample
self.pos_iou_thresh = pos_iou_thresh
self.neg_iou_thresh = neg_iou_thresh
self.pos_ratio = pos_ratio
<|end_body_0|>
<|body_start_1|>
img_width, img_height = img_size
inside_index = get_inside_index(anchors, img_width, img_height)... | AnchorTargetCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnchorTargetCreator:
def __init__(self, n_sample=256, pos_iou_thresh=0.7, neg_iou_thresh=0.3, pos_ratio=0.5):
"""function description: AnchorTargetCreator构造函数 :param n_sample: 256, target的总数量 :param pos_iou_thresh: 和boxes的iou的阈值,超过此值为"正"样本, label会置为1 :param neg_iou_thresh: 和boxes的iou的阈值,... | stack_v2_sparse_classes_36k_train_014775 | 6,653 | no_license | [
{
"docstring": "function description: AnchorTargetCreator构造函数 :param n_sample: 256, target的总数量 :param pos_iou_thresh: 和boxes的iou的阈值,超过此值为\"正\"样本, label会置为1 :param neg_iou_thresh: 和boxes的iou的阈值,低于此之为\"负\"样本, label会置为0 :param pos_ratio: target总数量中\"正\"样本的比例",
"name": "__init__",
"signature": "def __init__... | 4 | stack_v2_sparse_classes_30k_test_000188 | Implement the Python class `AnchorTargetCreator` described below.
Class description:
Implement the AnchorTargetCreator class.
Method signatures and docstrings:
- def __init__(self, n_sample=256, pos_iou_thresh=0.7, neg_iou_thresh=0.3, pos_ratio=0.5): function description: AnchorTargetCreator构造函数 :param n_sample: 256,... | Implement the Python class `AnchorTargetCreator` described below.
Class description:
Implement the AnchorTargetCreator class.
Method signatures and docstrings:
- def __init__(self, n_sample=256, pos_iou_thresh=0.7, neg_iou_thresh=0.3, pos_ratio=0.5): function description: AnchorTargetCreator构造函数 :param n_sample: 256,... | b4fb6ff7af6c9f906eabd836c6727ab7d9f18576 | <|skeleton|>
class AnchorTargetCreator:
def __init__(self, n_sample=256, pos_iou_thresh=0.7, neg_iou_thresh=0.3, pos_ratio=0.5):
"""function description: AnchorTargetCreator构造函数 :param n_sample: 256, target的总数量 :param pos_iou_thresh: 和boxes的iou的阈值,超过此值为"正"样本, label会置为1 :param neg_iou_thresh: 和boxes的iou的阈值,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnchorTargetCreator:
def __init__(self, n_sample=256, pos_iou_thresh=0.7, neg_iou_thresh=0.3, pos_ratio=0.5):
"""function description: AnchorTargetCreator构造函数 :param n_sample: 256, target的总数量 :param pos_iou_thresh: 和boxes的iou的阈值,超过此值为"正"样本, label会置为1 :param neg_iou_thresh: 和boxes的iou的阈值,低于此之为"负"样本, la... | the_stack_v2_python_sparse | nets/anchor_target_creator.py | xiguanlezz/Faster-RCNN | train | 13 | |
c4e01cf6bcdf0f289e6ca94943139fcde6fbaae5 | [
"super().__init__('object_detection_2d_yolov5_node')\nself.image_subscriber = self.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)\nif output_rgb_image_topic is not None:\n self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_topic, 1)\nelse:\n self.image_publisher ... | <|body_start_0|>
super().__init__('object_detection_2d_yolov5_node')
self.image_subscriber = self.create_subscription(ROS_Image, input_rgb_image_topic, self.callback, 1)
if output_rgb_image_topic is not None:
self.image_publisher = self.create_publisher(ROS_Image, output_rgb_image_to... | ObjectDetectionYOLOV5Node | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectDetectionYOLOV5Node:
def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda', model='yolov5s'):
"""Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_... | stack_v2_sparse_classes_36k_train_014776 | 6,214 | permissive | [
{
"docstring": "Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_rgb_image_topic: Topic to which we are publishing the annotated image (if None, no annotated image is published) :typ... | 2 | stack_v2_sparse_classes_30k_train_010515 | Implement the Python class `ObjectDetectionYOLOV5Node` described below.
Class description:
Implement the ObjectDetectionYOLOV5Node class.
Method signatures and docstrings:
- def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/object... | Implement the Python class `ObjectDetectionYOLOV5Node` described below.
Class description:
Implement the ObjectDetectionYOLOV5Node class.
Method signatures and docstrings:
- def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/object... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class ObjectDetectionYOLOV5Node:
def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda', model='yolov5s'):
"""Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectDetectionYOLOV5Node:
def __init__(self, input_rgb_image_topic='image_raw', output_rgb_image_topic='/opendr/image_objects_annotated', detections_topic='/opendr/objects', device='cuda', model='yolov5s'):
"""Creates a ROS2 Node for object detection with YOLOV5. :param input_rgb_image_topic: Topic f... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_perception/opendr_perception/object_detection_2d_yolov5_node.py | opendr-eu/opendr | train | 535 | |
432a57348a4a1d18a0242f56411c0987b0a7dd9d | [
"start, end, l, r = (-1, -1, 0, len(nums) - 1)\nwhile l <= r:\n mid = l + r >> 1\n if nums[mid] > target:\n r = mid - 1\n elif nums[mid] < target:\n l = mid + 1\n else:\n start = mid\n break\nif start != -1:\n l, r = (start, start)\n while nums[l] == nums[start] and l >... | <|body_start_0|>
start, end, l, r = (-1, -1, 0, len(nums) - 1)
while l <= r:
mid = l + r >> 1
if nums[mid] > target:
r = mid - 1
elif nums[mid] < target:
l = mid + 1
else:
start = mid
break
... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary Search + expand The best time is O(logN) and the worst is O(N)"""
<|body_0|>
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary search twice and the time is... | stack_v2_sparse_classes_36k_train_014777 | 1,864 | permissive | [
{
"docstring": "Binary Search + expand The best time is O(logN) and the worst is O(N)",
"name": "searchRange",
"signature": "def searchRange(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Binary search twice and the time is O(2logN)",
"name": "searchRange",
"signatu... | 2 | stack_v2_sparse_classes_30k_val_000984 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums: List[int], target: int) -> List[int]: Binary Search + expand The best time is O(logN) and the worst is O(N)
- def searchRange(self, nums: List[int], t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums: List[int], target: int) -> List[int]: Binary Search + expand The best time is O(logN) and the worst is O(N)
- def searchRange(self, nums: List[int], t... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary Search + expand The best time is O(logN) and the worst is O(N)"""
<|body_0|>
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary search twice and the time is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""Binary Search + expand The best time is O(logN) and the worst is O(N)"""
start, end, l, r = (-1, -1, 0, len(nums) - 1)
while l <= r:
mid = l + r >> 1
if nums[mid] > target:
... | the_stack_v2_python_sparse | Leetcode/Intermediate/Sort and search/34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
05e3f156ebc537a3fa03dc0c8c32802d4954f670 | [
"if 'case_name' not in kwargs:\n kwargs['case_name'] = 'rally_jobs'\nsuper().__init__(**kwargs)\nself.task_file = os.path.join(self.rally_dir, 'rally_jobs.yaml')\nself.task_yaml = None",
"super().prepare_run(**kwargs)\nwith open(os.path.join(self.rally_dir, 'rally_jobs.yaml'), 'r', encoding='utf-8') as task_fi... | <|body_start_0|>
if 'case_name' not in kwargs:
kwargs['case_name'] = 'rally_jobs'
super().__init__(**kwargs)
self.task_file = os.path.join(self.rally_dir, 'rally_jobs.yaml')
self.task_yaml = None
<|end_body_0|>
<|body_start_1|>
super().prepare_run(**kwargs)
w... | Rally OpenStack CI testcase implementation. | RallyJobs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RallyJobs:
"""Rally OpenStack CI testcase implementation."""
def __init__(self, **kwargs):
"""Initialize RallyJobs object."""
<|body_0|>
def prepare_run(self, **kwargs):
"""Create resources needed by test scenarios."""
<|body_1|>
def apply_blacklist(... | stack_v2_sparse_classes_36k_train_014778 | 32,891 | permissive | [
{
"docstring": "Initialize RallyJobs object.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Create resources needed by test scenarios.",
"name": "prepare_run",
"signature": "def prepare_run(self, **kwargs)"
},
{
"docstring": "Apply blacklist.... | 5 | stack_v2_sparse_classes_30k_train_001755 | Implement the Python class `RallyJobs` described below.
Class description:
Rally OpenStack CI testcase implementation.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize RallyJobs object.
- def prepare_run(self, **kwargs): Create resources needed by test scenarios.
- def apply_blacklist(self... | Implement the Python class `RallyJobs` described below.
Class description:
Rally OpenStack CI testcase implementation.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize RallyJobs object.
- def prepare_run(self, **kwargs): Create resources needed by test scenarios.
- def apply_blacklist(self... | 27107d1f871dd7eb9eeab5f7c51086f3ef7e2ebe | <|skeleton|>
class RallyJobs:
"""Rally OpenStack CI testcase implementation."""
def __init__(self, **kwargs):
"""Initialize RallyJobs object."""
<|body_0|>
def prepare_run(self, **kwargs):
"""Create resources needed by test scenarios."""
<|body_1|>
def apply_blacklist(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RallyJobs:
"""Rally OpenStack CI testcase implementation."""
def __init__(self, **kwargs):
"""Initialize RallyJobs object."""
if 'case_name' not in kwargs:
kwargs['case_name'] = 'rally_jobs'
super().__init__(**kwargs)
self.task_file = os.path.join(self.rally_di... | the_stack_v2_python_sparse | functest/opnfv_tests/openstack/rally/rally.py | opnfv/functest | train | 23 |
f637f9cb2a861f961b64d149d01f109268077f38 | [
"try:\n return states.index(state_name)\nexcept ValueError:\n raise StateException(\"Unknown state '%s'\" % state_name)",
"if state < 0 or state > len(states):\n raise StateException('Unknown state #%s' % state)\nreturn states[state]"
] | <|body_start_0|>
try:
return states.index(state_name)
except ValueError:
raise StateException("Unknown state '%s'" % state_name)
<|end_body_0|>
<|body_start_1|>
if state < 0 or state > len(states):
raise StateException('Unknown state #%s' % state)
ret... | Generic class for keeping track of the current state | AbstractState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractState:
"""Generic class for keeping track of the current state"""
def get_state(cls, states, state_name):
"""Return the numeric value of the named state state_name - named state"""
<|body_0|>
def state_string(cls, states, state):
"""Return the string asso... | stack_v2_sparse_classes_36k_train_014779 | 29,675 | no_license | [
{
"docstring": "Return the numeric value of the named state state_name - named state",
"name": "get_state",
"signature": "def get_state(cls, states, state_name)"
},
{
"docstring": "Return the string associated with a numeric state state - numeric state value",
"name": "state_string",
"si... | 2 | null | Implement the Python class `AbstractState` described below.
Class description:
Generic class for keeping track of the current state
Method signatures and docstrings:
- def get_state(cls, states, state_name): Return the numeric value of the named state state_name - named state
- def state_string(cls, states, state): R... | Implement the Python class `AbstractState` described below.
Class description:
Generic class for keeping track of the current state
Method signatures and docstrings:
- def get_state(cls, states, state_name): Return the numeric value of the named state state_name - named state
- def state_string(cls, states, state): R... | 718189be62907a6a8031980fe0c41fa7e06b898d | <|skeleton|>
class AbstractState:
"""Generic class for keeping track of the current state"""
def get_state(cls, states, state_name):
"""Return the numeric value of the named state state_name - named state"""
<|body_0|>
def state_string(cls, states, state):
"""Return the string asso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractState:
"""Generic class for keeping track of the current state"""
def get_state(cls, states, state_name):
"""Return the numeric value of the named state state_name - named state"""
try:
return states.index(state_name)
except ValueError:
raise StateE... | the_stack_v2_python_sparse | liverun.py | dglo/dash | train | 0 |
8372a77511ee6b728d2c0e6a91a8577916fc4324 | [
"self.log = logging.getLogger(__name__)\nself.name = name\nself.clouds = {}\nself.group_resources = group_resources\nself.group_yamls = group_yamls\nself.metadata = metadata\nself.config = Config('/etc/cloudscheduler/cloudscheduler.yaml', [])",
"self.config.db_open()\nfor cloud in self.group_resources:\n try:\... | <|body_start_0|>
self.log = logging.getLogger(__name__)
self.name = name
self.clouds = {}
self.group_resources = group_resources
self.group_yamls = group_yamls
self.metadata = metadata
self.config = Config('/etc/cloudscheduler/cloudscheduler.yaml', [])
<|end_body_... | CloudManager class for holding a groups resources and their group yaml | CloudManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls, metadata):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resou... | stack_v2_sparse_classes_36k_train_014780 | 2,474 | permissive | [
{
"docstring": "Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :param group_yamls: the group's yaml from the database.",
"name": "__init__",
"signature": "def __init__(self, name, group_resources, group_yamls, metadata)"
... | 2 | null | Implement the Python class `CloudManager` described below.
Class description:
CloudManager class for holding a groups resources and their group yaml
Method signatures and docstrings:
- def __init__(self, name, group_resources, group_yamls, metadata): Create a new CloudManager. :param name: The name of the group :para... | Implement the Python class `CloudManager` described below.
Class description:
CloudManager class for holding a groups resources and their group yaml
Method signatures and docstrings:
- def __init__(self, name, group_resources, group_yamls, metadata): Create a new CloudManager. :param name: The name of the group :para... | 65323a6a208484ab0412e54fbbeeeb9070f861bb | <|skeleton|>
class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls, metadata):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudManager:
"""CloudManager class for holding a groups resources and their group yaml"""
def __init__(self, name, group_resources, group_yamls, metadata):
"""Create a new CloudManager. :param name: The name of the group :param group_resources: sqlalchemy result of this groups resources :param g... | the_stack_v2_python_sparse | cloudscheduler/cloudmanager.py | hep-gc/cloudscheduler | train | 5 |
257f33f17b131a4ec80bf1b68d581eaa48b13426 | [
"super(ShiftUnit, self).__init__(bits, no_reset=no_reset)\nif not register_work:\n register_work = std_logic.InputRegister(self.bits + times)\nself.input = self.add_input(inp)\nself.output = self.add_output(output)\nself.register_work = self.add_input(register_work)\nself.register_target = self.register_work.sli... | <|body_start_0|>
super(ShiftUnit, self).__init__(bits, no_reset=no_reset)
if not register_work:
register_work = std_logic.InputRegister(self.bits + times)
self.input = self.add_input(inp)
self.output = self.add_output(output)
self.register_work = self.add_input(regist... | This is an example of a basic structure of a command block array unit. | ShiftUnit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShiftUnit:
"""This is an example of a basic structure of a command block array unit."""
def __init__(self, bits=8, times=1, inp=std_logic.InputRegister, output=std_logic.OutputRegister, carry_out=None, register_work=None, no_reset=False):
""":param bits: size of the input and the out... | stack_v2_sparse_classes_36k_train_014781 | 2,107 | no_license | [
{
"docstring": ":param bits: size of the input and the output. :param times: how many times to shift the input. :param inp: input register. :param output: output register. :param carry_out: Pass port which will be set true if the shifted out bit is true. :param register_work: On this register all the operations... | 2 | null | Implement the Python class `ShiftUnit` described below.
Class description:
This is an example of a basic structure of a command block array unit.
Method signatures and docstrings:
- def __init__(self, bits=8, times=1, inp=std_logic.InputRegister, output=std_logic.OutputRegister, carry_out=None, register_work=None, no... | Implement the Python class `ShiftUnit` described below.
Class description:
This is an example of a basic structure of a command block array unit.
Method signatures and docstrings:
- def __init__(self, bits=8, times=1, inp=std_logic.InputRegister, output=std_logic.OutputRegister, carry_out=None, register_work=None, no... | 8bbb26b2c3bbaa0712b5321d85b9f3834a0016fb | <|skeleton|>
class ShiftUnit:
"""This is an example of a basic structure of a command block array unit."""
def __init__(self, bits=8, times=1, inp=std_logic.InputRegister, output=std_logic.OutputRegister, carry_out=None, register_work=None, no_reset=False):
""":param bits: size of the input and the out... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShiftUnit:
"""This is an example of a basic structure of a command block array unit."""
def __init__(self, bits=8, times=1, inp=std_logic.InputRegister, output=std_logic.OutputRegister, carry_out=None, register_work=None, no_reset=False):
""":param bits: size of the input and the output. :param t... | the_stack_v2_python_sparse | cbac/std_unit/shift_unit.py | bowiz2/cbac | train | 1 |
2bd0b4cb6b1f05c859fa785caa8b292446bf9bed | [
"Drawable.__init__(self, RIDE_SPRITE)\nself.start, self.end = (start, end)\nself.start_time, self.end_time = (times[0], times[1])",
"initial_longitude = self.start.location[0]\ninitial_latitude = self.start.location[1]\nfinal_longitude = self.end.location[0]\nfinal_latitude = self.end.location[1]\ntime_difference... | <|body_start_0|>
Drawable.__init__(self, RIDE_SPRITE)
self.start, self.end = (start, end)
self.start_time, self.end_time = (times[0], times[1])
<|end_body_0|>
<|body_start_1|>
initial_longitude = self.start.location[0]
initial_latitude = self.start.location[1]
final_long... | A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time | Ride | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start:... | stack_v2_sparse_classes_36k_train_014782 | 9,715 | no_license | [
{
"docstring": "Initialize a ride object with the given start and end information.",
"name": "__init__",
"signature": "def __init__(self, start: Station, end: Station, times: Tuple[datetime, datetime]) -> None"
},
{
"docstring": "Return the (long, lat) position of this ride for the given time. A... | 3 | stack_v2_sparse_classes_30k_train_007378 | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | 01185e1eab994b42d7e0ec33223eed742b83233e | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start: Station, end... | the_stack_v2_python_sparse | CSC148/assignments/a1/backup/bikeshare.py | rcase31/UofTCourses | train | 1 |
6c2ca81f10b03dab9a20586a6bca92323d023fb3 | [
"idx += 1\nself._attr_name = f'{entry[CONF_NAME]} {idx}'\nself._attr_device_class = entry.get(CONF_DEVICE_CLASS)\nself._attr_unique_id = entry.get(CONF_UNIQUE_ID)\nif self._attr_unique_id:\n self._attr_unique_id = f'{self._attr_unique_id}_{idx}'\nself._attr_available = False\nself._result_inx = idx\nsuper().__in... | <|body_start_0|>
idx += 1
self._attr_name = f'{entry[CONF_NAME]} {idx}'
self._attr_device_class = entry.get(CONF_DEVICE_CLASS)
self._attr_unique_id = entry.get(CONF_UNIQUE_ID)
if self._attr_unique_id:
self._attr_unique_id = f'{self._attr_unique_id}_{idx}'
self... | Modbus slave binary sensor. | SlaveSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlaveSensor:
"""Modbus slave binary sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus binary sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
""... | stack_v2_sparse_classes_36k_train_014783 | 5,764 | permissive | [
{
"docstring": "Initialize the Modbus binary sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None"
},
{
"docstring": "Handle entity which will be added.",
"name": "async_added_to_hass",
... | 3 | stack_v2_sparse_classes_30k_train_017704 | Implement the Python class `SlaveSensor` described below.
Class description:
Modbus slave binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None: Initialize the Modbus binary sensor.
- async def async_added_t... | Implement the Python class `SlaveSensor` described below.
Class description:
Modbus slave binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None: Initialize the Modbus binary sensor.
- async def async_added_t... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SlaveSensor:
"""Modbus slave binary sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus binary sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlaveSensor:
"""Modbus slave binary sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus binary sensor."""
idx += 1
self._attr_name = f'{entry[CONF_NAME]} {idx}'
self._attr_de... | the_stack_v2_python_sparse | homeassistant/components/modbus/binary_sensor.py | home-assistant/core | train | 35,501 |
e1b7d4eb0e8d63e8c2b87014d01f9ed063b0139b | [
"super(ParsingFilter, self).__init__()\nself.config = config\ntry:\n if self.config['filter']['whitelist'] and self.config['filter']['blacklist']:\n _LOGGER.warning(_('Both whitelist and blacklist filters found in configuration. Only one can be used at a time - only the whitelist filter will be used.'))\n... | <|body_start_0|>
super(ParsingFilter, self).__init__()
self.config = config
try:
if self.config['filter']['whitelist'] and self.config['filter']['blacklist']:
_LOGGER.warning(_('Both whitelist and blacklist filters found in configuration. Only one can be used at a tim... | Class that filters logs. | ParsingFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParsingFilter:
"""Class that filters logs."""
def __init__(self, config, *parse_list):
"""Create object to implement filtering."""
<|body_0|>
def filter(self, record):
"""Apply filter to the log message. This is a subset of Logger.filter, this method applies the ... | stack_v2_sparse_classes_36k_train_014784 | 6,253 | permissive | [
{
"docstring": "Create object to implement filtering.",
"name": "__init__",
"signature": "def __init__(self, config, *parse_list)"
},
{
"docstring": "Apply filter to the log message. This is a subset of Logger.filter, this method applies the logger filters and returns a bool. If the value is tru... | 2 | stack_v2_sparse_classes_30k_train_018214 | Implement the Python class `ParsingFilter` described below.
Class description:
Class that filters logs.
Method signatures and docstrings:
- def __init__(self, config, *parse_list): Create object to implement filtering.
- def filter(self, record): Apply filter to the log message. This is a subset of Logger.filter, thi... | Implement the Python class `ParsingFilter` described below.
Class description:
Class that filters logs.
Method signatures and docstrings:
- def __init__(self, config, *parse_list): Create object to implement filtering.
- def filter(self, record): Apply filter to the log message. This is a subset of Logger.filter, thi... | 41246da2f6f379a889dadd1d3b4e139b65d3c9fb | <|skeleton|>
class ParsingFilter:
"""Class that filters logs."""
def __init__(self, config, *parse_list):
"""Create object to implement filtering."""
<|body_0|>
def filter(self, record):
"""Apply filter to the log message. This is a subset of Logger.filter, this method applies the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParsingFilter:
"""Class that filters logs."""
def __init__(self, config, *parse_list):
"""Create object to implement filtering."""
super(ParsingFilter, self).__init__()
self.config = config
try:
if self.config['filter']['whitelist'] and self.config['filter']['b... | the_stack_v2_python_sparse | opsdroid/logging.py | opsdroid/opsdroid | train | 835 |
d49bf2124790386fd698506d000b51d78885c1f0 | [
"if not self._year:\n return\ntime_elements_structure = self._GetValueFromStructure(structure, 'date_time')\ntext = self._GetValueFromStructure(structure, 'text')\ntext = ' '.join(text.split())\nevent_data = XChatLogEventData()\nevent_data.added_time = self._ParseTimeElements(time_elements_structure)\nevent_data... | <|body_start_0|>
if not self._year:
return
time_elements_structure = self._GetValueFromStructure(structure, 'date_time')
text = self._GetValueFromStructure(structure, 'text')
text = ' '.join(text.split())
event_data = XChatLogEventData()
event_data.added_time ... | Text parser plugin for XChat log files. | XChatLogTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XChatLogTextPlugin:
"""Text parser plugin for XChat log files."""
def _ParseLogLine(self, parser_mediator, structure):
"""Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. structure (pypar... | stack_v2_sparse_classes_36k_train_014785 | 10,596 | permissive | [
{
"docstring": "Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file.",
"name": "_ParseLogLine",
"signature": "def _Pars... | 5 | null | Implement the Python class `XChatLogTextPlugin` described below.
Class description:
Text parser plugin for XChat log files.
Method signatures and docstrings:
- def _ParseLogLine(self, parser_mediator, structure): Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and othe... | Implement the Python class `XChatLogTextPlugin` described below.
Class description:
Text parser plugin for XChat log files.
Method signatures and docstrings:
- def _ParseLogLine(self, parser_mediator, structure): Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and othe... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class XChatLogTextPlugin:
"""Text parser plugin for XChat log files."""
def _ParseLogLine(self, parser_mediator, structure):
"""Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. structure (pypar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XChatLogTextPlugin:
"""Text parser plugin for XChat log files."""
def _ParseLogLine(self, parser_mediator, structure):
"""Parses a log line. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. structure (pyparsing.ParseRes... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/xchatlog.py | log2timeline/plaso | train | 1,506 |
e5df29c7af9c2c37732937ae4c1d4158f7a6872f | [
"self.id = id\nself.name = name\nself.extra = extra\nself.created = to_datetime_utc(created)\nself.modified = to_datetime_utc(modified)\nself.organisation = fetch_db_object(Organisation, organisation)\nself.telescope_type = fetch_db_object(TelescopeType, telescope_type)",
"if name is not None:\n self.name = na... | <|body_start_0|>
self.id = id
self.name = name
self.extra = extra
self.created = to_datetime_utc(created)
self.modified = to_datetime_utc(modified)
self.organisation = fetch_db_object(Organisation, organisation)
self.telescope_type = fetch_db_object(TelescopeType,... | Telescope | [
"MIT",
"BSD-2-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Telescope:
def __init__(self, id: int=None, name: str=None, extra: Dict=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None, organisation: Union[Organisation, Dict]=None, telescope_type: Union[TelescopeType, Dict]=None):
"""Construct a Telescope object. :param id: uni... | stack_v2_sparse_classes_36k_train_014786 | 12,117 | permissive | [
{
"docstring": "Construct a Telescope object. :param id: unique id. :param name: the telescope name. :param extra: additional metadata for a telescope, stored as JSON. :param created: datetime created in UTC. :param modified: datetime modified in UTC. :param organisation: the organisation associated with this t... | 2 | null | Implement the Python class `Telescope` described below.
Class description:
Implement the Telescope class.
Method signatures and docstrings:
- def __init__(self, id: int=None, name: str=None, extra: Dict=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None, organisation: Union[Organisation, Dict]=No... | Implement the Python class `Telescope` described below.
Class description:
Implement the Telescope class.
Method signatures and docstrings:
- def __init__(self, id: int=None, name: str=None, extra: Dict=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None, organisation: Union[Organisation, Dict]=No... | 64b62cba83110fea60e91506dff4a83ba9931ba9 | <|skeleton|>
class Telescope:
def __init__(self, id: int=None, name: str=None, extra: Dict=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None, organisation: Union[Organisation, Dict]=None, telescope_type: Union[TelescopeType, Dict]=None):
"""Construct a Telescope object. :param id: uni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Telescope:
def __init__(self, id: int=None, name: str=None, extra: Dict=None, created: pendulum.DateTime=None, modified: pendulum.DateTime=None, organisation: Union[Organisation, Dict]=None, telescope_type: Union[TelescopeType, Dict]=None):
"""Construct a Telescope object. :param id: unique id. :param... | the_stack_v2_python_sparse | observatory-api/observatory/api/server/orm.py | kieranroberts/observatory-platform | train | 0 | |
07f60284423005180da06fa63d615cb17c0a4532 | [
"self.obstacle = obstacle\nself.missed_det_updates = 0\ncenter_point = obstacle.bounding_box.get_center_point()\ntarget_pos = np.array([center_point.x, center_point.y])\ntarget_size = np.array([obstacle.bounding_box.get_width(), obstacle.bounding_box.get_height()])\nself._tracker = SiamRPN_init(frame.frame, target_... | <|body_start_0|>
self.obstacle = obstacle
self.missed_det_updates = 0
center_point = obstacle.bounding_box.get_center_point()
target_pos = np.array([center_point.x, center_point.y])
target_size = np.array([obstacle.bounding_box.get_width(), obstacle.bounding_box.get_height()])
... | SingleObjectDaSiamRPNTracker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleObjectDaSiamRPNTracker:
def __init__(self, frame, obstacle, siam_net):
"""Construct a single obstacle tracker. Args: frame (:py:class:`~pylot.perception.camera_frame.CameraFrame`): Frame to reinitialize with. obstacle: perception.detection.utils.DetectedObstacle."""
<|body_... | stack_v2_sparse_classes_36k_train_014787 | 5,992 | permissive | [
{
"docstring": "Construct a single obstacle tracker. Args: frame (:py:class:`~pylot.perception.camera_frame.CameraFrame`): Frame to reinitialize with. obstacle: perception.detection.utils.DetectedObstacle.",
"name": "__init__",
"signature": "def __init__(self, frame, obstacle, siam_net)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_001080 | Implement the Python class `SingleObjectDaSiamRPNTracker` described below.
Class description:
Implement the SingleObjectDaSiamRPNTracker class.
Method signatures and docstrings:
- def __init__(self, frame, obstacle, siam_net): Construct a single obstacle tracker. Args: frame (:py:class:`~pylot.perception.camera_frame... | Implement the Python class `SingleObjectDaSiamRPNTracker` described below.
Class description:
Implement the SingleObjectDaSiamRPNTracker class.
Method signatures and docstrings:
- def __init__(self, frame, obstacle, siam_net): Construct a single obstacle tracker. Args: frame (:py:class:`~pylot.perception.camera_frame... | 4be84404ae0930af313fc4271de711e91a362fce | <|skeleton|>
class SingleObjectDaSiamRPNTracker:
def __init__(self, frame, obstacle, siam_net):
"""Construct a single obstacle tracker. Args: frame (:py:class:`~pylot.perception.camera_frame.CameraFrame`): Frame to reinitialize with. obstacle: perception.detection.utils.DetectedObstacle."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleObjectDaSiamRPNTracker:
def __init__(self, frame, obstacle, siam_net):
"""Construct a single obstacle tracker. Args: frame (:py:class:`~pylot.perception.camera_frame.CameraFrame`): Frame to reinitialize with. obstacle: perception.detection.utils.DetectedObstacle."""
self.obstacle = obsta... | the_stack_v2_python_sparse | pylot/perception/tracking/da_siam_rpn_tracker.py | mawright/pylot | train | 0 | |
2fae4983fba0c3f1e6384fa52990e36b107925d8 | [
"self.char = ''\nself.d = {}\nself.end = False",
"c, n = (word[0], len(word))\nnode = self.d.get(c)\nif not node:\n self.d[c] = Trie()\n self.d[c].char = c\n node = self.d[c]\nif n == 1:\n node.end = True\nelse:\n node.insert(word[1:])",
"node = self\nfor c in word:\n node = node.d.get(c)\n ... | <|body_start_0|>
self.char = ''
self.d = {}
self.end = False
<|end_body_0|>
<|body_start_1|>
c, n = (word[0], len(word))
node = self.d.get(c)
if not node:
self.d[c] = Trie()
self.d[c].char = c
node = self.d[c]
if n == 1:
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_36k_train_014788 | 1,311 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | stack_v2_sparse_classes_30k_train_019582 | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 12f62a218e827e6be2578b206dee9ce256da8d3d | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.char = ''
self.d = {}
self.end = False
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
c, n = (word[0], len(word))
node = self.d.get(c)
if not... | the_stack_v2_python_sparse | Python3/0208_Implement_Trie.py | kiranani/playground | train | 0 | |
2c53d13b7ae326ddef8f704f51b7927ab00eb387 | [
"super().__init__(hass, _LOGGER, name=prom_data.name, update_interval=prom_data.update_interval)\nself.data: dict[str, Union[float, int]]\nself.url = prom_data.url\nself.query = prom_data.query\nself.unique_instance_key = prom_data.unique_instance_key\nself.instance_mapper = prom_data.instance_mapper",
"try:\n ... | <|body_start_0|>
super().__init__(hass, _LOGGER, name=prom_data.name, update_interval=prom_data.update_interval)
self.data: dict[str, Union[float, int]]
self.url = prom_data.url
self.query = prom_data.query
self.unique_instance_key = prom_data.unique_instance_key
self.ins... | prometheus query coordinator. | PrometheusQueryCoordinator | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrometheusQueryCoordinator:
"""prometheus query coordinator."""
def __init__(self, hass: HomeAssistant, prom_data: PromEntryData):
"""Initialize prometheus query coordinator."""
<|body_0|>
async def _async_update_data(self):
"""Fetch data from API endpoint. This ... | stack_v2_sparse_classes_36k_train_014789 | 9,547 | permissive | [
{
"docstring": "Initialize prometheus query coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, prom_data: PromEntryData)"
},
{
"docstring": "Fetch data from API endpoint. This is the place to pre-process the data to lookup tables so entities can quickly look... | 2 | null | Implement the Python class `PrometheusQueryCoordinator` described below.
Class description:
prometheus query coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, prom_data: PromEntryData): Initialize prometheus query coordinator.
- async def _async_update_data(self): Fetch data fro... | Implement the Python class `PrometheusQueryCoordinator` described below.
Class description:
prometheus query coordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, prom_data: PromEntryData): Initialize prometheus query coordinator.
- async def _async_update_data(self): Fetch data fro... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class PrometheusQueryCoordinator:
"""prometheus query coordinator."""
def __init__(self, hass: HomeAssistant, prom_data: PromEntryData):
"""Initialize prometheus query coordinator."""
<|body_0|>
async def _async_update_data(self):
"""Fetch data from API endpoint. This ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrometheusQueryCoordinator:
"""prometheus query coordinator."""
def __init__(self, hass: HomeAssistant, prom_data: PromEntryData):
"""Initialize prometheus query coordinator."""
super().__init__(hass, _LOGGER, name=prom_data.name, update_interval=prom_data.update_interval)
self.da... | the_stack_v2_python_sparse | custom_components/prometheus_query/sensor.py | bacco007/HomeAssistantConfig | train | 98 |
b944d90d4784de8c2f92b8ac1bae26e5718db186 | [
"super(fcDecoderNet, self).__init__()\nif len(out_dim) not in (1, 2, 3):\n raise ValueError('The output dimensions must be (length,) for 1D data and ' + '(height, width) or (height, width, channel) for 2D data')\nc = out_dim[-1] if len(out_dim) > 2 else 1\ndecoder = []\nfor i in range(num_layers):\n hidden_di... | <|body_start_0|>
super(fcDecoderNet, self).__init__()
if len(out_dim) not in (1, 2, 3):
raise ValueError('The output dimensions must be (length,) for 1D data and ' + '(height, width) or (height, width, channel) for 2D data')
c = out_dim[-1] if len(out_dim) > 2 else 1
decoder ... | Decoder network (for variational autoencoder) Args: out_dim: Output dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions associated with images content num_layers: number of fully connected layers hidden_dim: number of neurons i... | fcDecoderNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fcDecoderNet:
"""Decoder network (for variational autoencoder) Args: out_dim: Output dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions associated with images content num_layers: number of fully connecte... | stack_v2_sparse_classes_36k_train_014790 | 28,462 | permissive | [
{
"docstring": "Initializes network parameters",
"name": "__init__",
"signature": "def __init__(self, out_dim: Tuple[int], latent_dim: int, num_layers: int=2, hidden_dim: int=32) -> None"
},
{
"docstring": "Forward pass",
"name": "forward",
"signature": "def forward(self, z: torch.Tensor... | 2 | stack_v2_sparse_classes_30k_train_014401 | Implement the Python class `fcDecoderNet` described below.
Class description:
Decoder network (for variational autoencoder) Args: out_dim: Output dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions associated with images conte... | Implement the Python class `fcDecoderNet` described below.
Class description:
Decoder network (for variational autoencoder) Args: out_dim: Output dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions associated with images conte... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class fcDecoderNet:
"""Decoder network (for variational autoencoder) Args: out_dim: Output dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions associated with images content num_layers: number of fully connecte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class fcDecoderNet:
"""Decoder network (for variational autoencoder) Args: out_dim: Output dimensions. For images, it is (height, width) or (height, width, channels). For spectra, it is (length,) latent_dim: number of latent dimensions associated with images content num_layers: number of fully connected layers hidd... | the_stack_v2_python_sparse | atomai/nets/ed.py | pycroscopy/atomai | train | 157 |
09661ce982452e6a707632fea53d4b9fa7a33ce6 | [
"mod = 10 ** 9 + 7\nmemo = {}\n\ndef dfs(index, s):\n if index == 0 and s == 0:\n return 1\n if s < 0:\n return 0\n if (index, s) in memo:\n return memo[index, s]\n ans = 0\n ans += dfs(index, s - 1)\n if index < a - 1:\n ans += dfs(index + 1, s - 1)\n if index > 0:\... | <|body_start_0|>
mod = 10 ** 9 + 7
memo = {}
def dfs(index, s):
if index == 0 and s == 0:
return 1
if s < 0:
return 0
if (index, s) in memo:
return memo[index, s]
ans = 0
ans += dfs(index... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numWays1(self, s: int, a: int) -> int:
"""思路:记忆化递归 @param s: @param a: @return:"""
<|body_0|>
def numWays2(self, s: int, a: int) -> int:
"""思路:动态规划法 1. 超时 @param s: @param a: @return:"""
<|body_1|>
def numWays3(self, steps: int, arrLen: int... | stack_v2_sparse_classes_36k_train_014791 | 3,312 | no_license | [
{
"docstring": "思路:记忆化递归 @param s: @param a: @return:",
"name": "numWays1",
"signature": "def numWays1(self, s: int, a: int) -> int"
},
{
"docstring": "思路:动态规划法 1. 超时 @param s: @param a: @return:",
"name": "numWays2",
"signature": "def numWays2(self, s: int, a: int) -> int"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numWays1(self, s: int, a: int) -> int: 思路:记忆化递归 @param s: @param a: @return:
- def numWays2(self, s: int, a: int) -> int: 思路:动态规划法 1. 超时 @param s: @param a: @return:
- def nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numWays1(self, s: int, a: int) -> int: 思路:记忆化递归 @param s: @param a: @return:
- def numWays2(self, s: int, a: int) -> int: 思路:动态规划法 1. 超时 @param s: @param a: @return:
- def nu... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def numWays1(self, s: int, a: int) -> int:
"""思路:记忆化递归 @param s: @param a: @return:"""
<|body_0|>
def numWays2(self, s: int, a: int) -> int:
"""思路:动态规划法 1. 超时 @param s: @param a: @return:"""
<|body_1|>
def numWays3(self, steps: int, arrLen: int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numWays1(self, s: int, a: int) -> int:
"""思路:记忆化递归 @param s: @param a: @return:"""
mod = 10 ** 9 + 7
memo = {}
def dfs(index, s):
if index == 0 and s == 0:
return 1
if s < 0:
return 0
if (index, ... | the_stack_v2_python_sparse | LeetCode/记忆化/1269. 停在原地的方案数.py | yiming1012/MyLeetCode | train | 2 | |
2282d991bf310ae63d2249a689bf1a818c3e6b8b | [
"def outer(self, *args, **kwargs):\n logging.info('MetaView Outer: '.format(self.request))\n if self.request.get('google_login') == 'true':\n if self.get_current_user():\n refresh_url = util.set_query_parameters(self.request.url, google_login='')\n self.redirect(refresh_url)\n ... | <|body_start_0|>
def outer(self, *args, **kwargs):
logging.info('MetaView Outer: '.format(self.request))
if self.request.get('google_login') == 'true':
if self.get_current_user():
refresh_url = util.set_query_parameters(self.request.url, google_login='... | Allows code to be run before and after get and post methods. See: http://stackoverflow.com/questions/6780907/python-wrap-class-method | MetaView | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaView:
"""Allows code to be run before and after get and post methods. See: http://stackoverflow.com/questions/6780907/python-wrap-class-method"""
def wrap(method):
"""Return a wrapped instance method"""
<|body_0|>
def __new__(cls, name, bases, attrs):
"""If t... | stack_v2_sparse_classes_36k_train_014792 | 38,138 | permissive | [
{
"docstring": "Return a wrapped instance method",
"name": "wrap",
"signature": "def wrap(method)"
},
{
"docstring": "If the class has an http GET method, wrap it.",
"name": "__new__",
"signature": "def __new__(cls, name, bases, attrs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013425 | Implement the Python class `MetaView` described below.
Class description:
Allows code to be run before and after get and post methods. See: http://stackoverflow.com/questions/6780907/python-wrap-class-method
Method signatures and docstrings:
- def wrap(method): Return a wrapped instance method
- def __new__(cls, name... | Implement the Python class `MetaView` described below.
Class description:
Allows code to be run before and after get and post methods. See: http://stackoverflow.com/questions/6780907/python-wrap-class-method
Method signatures and docstrings:
- def wrap(method): Return a wrapped instance method
- def __new__(cls, name... | 14fbcf0830e47fb0c7a6af798ed01f7181147979 | <|skeleton|>
class MetaView:
"""Allows code to be run before and after get and post methods. See: http://stackoverflow.com/questions/6780907/python-wrap-class-method"""
def wrap(method):
"""Return a wrapped instance method"""
<|body_0|>
def __new__(cls, name, bases, attrs):
"""If t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaView:
"""Allows code to be run before and after get and post methods. See: http://stackoverflow.com/questions/6780907/python-wrap-class-method"""
def wrap(method):
"""Return a wrapped instance method"""
def outer(self, *args, **kwargs):
logging.info('MetaView Outer: '.form... | the_stack_v2_python_sparse | mindsetkit.py | Stanford-PERTS/mindsetkit | train | 0 |
4814fcb55d469e19d79b191152c1d7a8fb296340 | [
"ia.seed(1)\nif not isinstance(aug_config, AugmentConfig):\n raise TypeError(f'{aug_config} is not a AugmentConfig')\nelse:\n self.aug_config = aug_config\naug_seq = []\nif self.aug_config.random_horz_flip:\n aug_seq.append(iaa.Fliplr(self.aug_config.flip_prob, name='fliplr0'))\nif self.aug_config.random_v... | <|body_start_0|>
ia.seed(1)
if not isinstance(aug_config, AugmentConfig):
raise TypeError(f'{aug_config} is not a AugmentConfig')
else:
self.aug_config = aug_config
aug_seq = []
if self.aug_config.random_horz_flip:
aug_seq.append(iaa.Fliplr(sel... | ImageAugmentizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageAugmentizer:
def __init__(self, aug_config):
""":param nrm_config: :type nrm_config: NormalizeConfig"""
<|body_0|>
def augmentize(self, images: np.ndarray):
""":param images: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ia.seed(1)
... | stack_v2_sparse_classes_36k_train_014793 | 2,683 | permissive | [
{
"docstring": ":param nrm_config: :type nrm_config: NormalizeConfig",
"name": "__init__",
"signature": "def __init__(self, aug_config)"
},
{
"docstring": ":param images: :return:",
"name": "augmentize",
"signature": "def augmentize(self, images: np.ndarray)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003444 | Implement the Python class `ImageAugmentizer` described below.
Class description:
Implement the ImageAugmentizer class.
Method signatures and docstrings:
- def __init__(self, aug_config): :param nrm_config: :type nrm_config: NormalizeConfig
- def augmentize(self, images: np.ndarray): :param images: :return: | Implement the Python class `ImageAugmentizer` described below.
Class description:
Implement the ImageAugmentizer class.
Method signatures and docstrings:
- def __init__(self, aug_config): :param nrm_config: :type nrm_config: NormalizeConfig
- def augmentize(self, images: np.ndarray): :param images: :return:
<|skelet... | 02ecf1f52ee91e3050b2d30f602a3161ff0726cf | <|skeleton|>
class ImageAugmentizer:
def __init__(self, aug_config):
""":param nrm_config: :type nrm_config: NormalizeConfig"""
<|body_0|>
def augmentize(self, images: np.ndarray):
""":param images: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageAugmentizer:
def __init__(self, aug_config):
""":param nrm_config: :type nrm_config: NormalizeConfig"""
ia.seed(1)
if not isinstance(aug_config, AugmentConfig):
raise TypeError(f'{aug_config} is not a AugmentConfig')
else:
self.aug_config = aug_conf... | the_stack_v2_python_sparse | app/datasets/image_augmentizer.py | normalct/Keras_MedicalImgAI | train | 0 | |
64434fbe764f20ed5610b6db11948b5b454c5568 | [
"if not a:\n return True\na.sort()\nn = len(a)\nc = self.init_counter(n, a)\nfor i in range(0, n, 1):\n if c[a[i]] > 0 and a[i] < 0:\n if c[a[i] / 2] > 0:\n c[a[i]] -= 1\n c[a[i] / 2] -= 1\n else:\n return False\n elif c[a[i]] > 0 and a[i] > 0:\n if c[a... | <|body_start_0|>
if not a:
return True
a.sort()
n = len(a)
c = self.init_counter(n, a)
for i in range(0, n, 1):
if c[a[i]] > 0 and a[i] < 0:
if c[a[i] / 2] > 0:
c[a[i]] -= 1
c[a[i] / 2] -= 1
... | Iteration over all array elements. Time complexity: O(n * log n) - Sort input array and iterate over all array elements Space complexity: O(n) - Collect all array elements and their counts using hash map | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Iteration over all array elements. Time complexity: O(n * log n) - Sort input array and iterate over all array elements Space complexity: O(n) - Collect all array elements and their counts using hash map"""
def is_double_pair_arr(self, a):
"""Determines whether input arr... | stack_v2_sparse_classes_36k_train_014794 | 3,403 | permissive | [
{
"docstring": "Determines whether input array can be double-pair sorted. Array elements should follow \"a[2 * i + 1] = 2 * a[2 * i]\". :param list[str] a: input array of integers :return: True if input array can be double-pair sorted :rtype: bool",
"name": "is_double_pair_arr",
"signature": "def is_dou... | 2 | stack_v2_sparse_classes_30k_train_015886 | Implement the Python class `Solution` described below.
Class description:
Iteration over all array elements. Time complexity: O(n * log n) - Sort input array and iterate over all array elements Space complexity: O(n) - Collect all array elements and their counts using hash map
Method signatures and docstrings:
- def ... | Implement the Python class `Solution` described below.
Class description:
Iteration over all array elements. Time complexity: O(n * log n) - Sort input array and iterate over all array elements Space complexity: O(n) - Collect all array elements and their counts using hash map
Method signatures and docstrings:
- def ... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Iteration over all array elements. Time complexity: O(n * log n) - Sort input array and iterate over all array elements Space complexity: O(n) - Collect all array elements and their counts using hash map"""
def is_double_pair_arr(self, a):
"""Determines whether input arr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Iteration over all array elements. Time complexity: O(n * log n) - Sort input array and iterate over all array elements Space complexity: O(n) - Collect all array elements and their counts using hash map"""
def is_double_pair_arr(self, a):
"""Determines whether input array can be dou... | the_stack_v2_python_sparse | 0954_array_doubled_pairs/python_source.py | arthurdysart/LeetCode | train | 0 |
03805683f84f9dec7d1e0c83d7126a897cfc8a07 | [
"data = {'name': 'foo', 'path': 'bar'}\ntree = self._setup_test_case(data)\nassert tree.xml_xpath(\"/project/target[@name='stage1']/parallel/*/arg/@line\")[0] == '-v foo.pkg foo.sis'",
"data = {'input': 'foo.pkg'}\ntree = self._setup_test_case(data)\nassert tree.xml_xpath(\"/project/target[@name='stage1']/paralle... | <|body_start_0|>
data = {'name': 'foo', 'path': 'bar'}
tree = self._setup_test_case(data)
assert tree.xml_xpath("/project/target[@name='stage1']/parallel/*/arg/@line")[0] == '-v foo.pkg foo.sis'
<|end_body_0|>
<|body_start_1|>
data = {'input': 'foo.pkg'}
tree = self._setup_test_... | Tests for sis module. | ArchivePreBuilderTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchivePreBuilderTest:
"""Tests for sis module."""
def test_sis_v1(self):
"""V1 config format."""
<|body_0|>
def test_sis_v2(self):
"""V2 config format."""
<|body_1|>
def test_sis_v2_1(self):
"""V2 config format for sisx."""
<|body_2|... | stack_v2_sparse_classes_36k_train_014795 | 2,583 | no_license | [
{
"docstring": "V1 config format.",
"name": "test_sis_v1",
"signature": "def test_sis_v1(self)"
},
{
"docstring": "V2 config format.",
"name": "test_sis_v2",
"signature": "def test_sis_v2(self)"
},
{
"docstring": "V2 config format for sisx.",
"name": "test_sis_v2_1",
"sig... | 4 | null | Implement the Python class `ArchivePreBuilderTest` described below.
Class description:
Tests for sis module.
Method signatures and docstrings:
- def test_sis_v1(self): V1 config format.
- def test_sis_v2(self): V2 config format.
- def test_sis_v2_1(self): V2 config format for sisx.
- def _setup_test_case(self, additi... | Implement the Python class `ArchivePreBuilderTest` described below.
Class description:
Tests for sis module.
Method signatures and docstrings:
- def test_sis_v1(self): V1 config format.
- def test_sis_v2(self): V2 config format.
- def test_sis_v2_1(self): V2 config format for sisx.
- def _setup_test_case(self, additi... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class ArchivePreBuilderTest:
"""Tests for sis module."""
def test_sis_v1(self):
"""V1 config format."""
<|body_0|>
def test_sis_v2(self):
"""V2 config format."""
<|body_1|>
def test_sis_v2_1(self):
"""V2 config format for sisx."""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArchivePreBuilderTest:
"""Tests for sis module."""
def test_sis_v1(self):
"""V1 config format."""
data = {'name': 'foo', 'path': 'bar'}
tree = self._setup_test_case(data)
assert tree.xml_xpath("/project/target[@name='stage1']/parallel/*/arg/@line")[0] == '-v foo.pkg foo.si... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncorecpythontests/test_sis.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
1bfcc686253642958e01c7b51d27879dd771a2d1 | [
"config = await config_dependency()\nkey = config.session_secret.encode()\nfernet = Fernet(key)\ntry:\n data = json.loads(fernet.decrypt(cookie.encode()).decode())\n token = None\n if 'token' in data:\n token = Token.from_str(data['token'])\nexcept Exception as e:\n if request:\n logger = ... | <|body_start_0|>
config = await config_dependency()
key = config.session_secret.encode()
fernet = Fernet(key)
try:
data = json.loads(fernet.decrypt(cookie.encode()).decode())
token = None
if 'token' in data:
token = Token.from_str(data[... | State information stored in a cookie. | State | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
"""State information stored in a cookie."""
async def from_cookie(cls, cookie: str, request: Optional[Request]) -> State:
"""Reconstruct state from an encrypted cookie. Parameters ---------- cookie : `str` The encrypted cookie value. key : `bytes` The `~cryptography.fernet.Fer... | stack_v2_sparse_classes_36k_train_014796 | 3,432 | permissive | [
{
"docstring": "Reconstruct state from an encrypted cookie. Parameters ---------- cookie : `str` The encrypted cookie value. key : `bytes` The `~cryptography.fernet.Fernet` key used to decrypt it. request : `fastapi.Request` or `None` The request, used for logging. If not provided (primarily for the test suite)... | 2 | stack_v2_sparse_classes_30k_train_014983 | Implement the Python class `State` described below.
Class description:
State information stored in a cookie.
Method signatures and docstrings:
- async def from_cookie(cls, cookie: str, request: Optional[Request]) -> State: Reconstruct state from an encrypted cookie. Parameters ---------- cookie : `str` The encrypted ... | Implement the Python class `State` described below.
Class description:
State information stored in a cookie.
Method signatures and docstrings:
- async def from_cookie(cls, cookie: str, request: Optional[Request]) -> State: Reconstruct state from an encrypted cookie. Parameters ---------- cookie : `str` The encrypted ... | a597ae790ccacdf5bea5402fe0edf38592c4788a | <|skeleton|>
class State:
"""State information stored in a cookie."""
async def from_cookie(cls, cookie: str, request: Optional[Request]) -> State:
"""Reconstruct state from an encrypted cookie. Parameters ---------- cookie : `str` The encrypted cookie value. key : `bytes` The `~cryptography.fernet.Fer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
"""State information stored in a cookie."""
async def from_cookie(cls, cookie: str, request: Optional[Request]) -> State:
"""Reconstruct state from an encrypted cookie. Parameters ---------- cookie : `str` The encrypted cookie value. key : `bytes` The `~cryptography.fernet.Fernet` key used... | the_stack_v2_python_sparse | src/gafaelfawr/models/state.py | brianv0/gafaelfawr | train | 0 |
f81f5d291a64e132e0bc2aa04bc54b5cb3831dfe | [
"payload = {'a': 'b', 'c': 'd', 'e': 'f'}\nkeys = sorted(payload.keys())\npayload['signed_field_names'] = ','.join(keys)\npayload['signature'] = generate_cybersource_sa_signature(payload)\nrequest = MagicMock(data=payload)\nassert IsSignedByCyberSource().has_permission(request, MagicMock()) is True",
"payload = {... | <|body_start_0|>
payload = {'a': 'b', 'c': 'd', 'e': 'f'}
keys = sorted(payload.keys())
payload['signed_field_names'] = ','.join(keys)
payload['signature'] = generate_cybersource_sa_signature(payload)
request = MagicMock(data=payload)
assert IsSignedByCyberSource().has_pe... | Tests for ecommerce permissions | PermissionsTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionsTests:
"""Tests for ecommerce permissions"""
def test_has_signature(self):
"""If the payload has a valid signature, it should pass the permissions test"""
<|body_0|>
def test_has_wrong_signature(self):
"""If the payload has an invalid signature, it sho... | stack_v2_sparse_classes_36k_train_014797 | 1,437 | permissive | [
{
"docstring": "If the payload has a valid signature, it should pass the permissions test",
"name": "test_has_signature",
"signature": "def test_has_signature(self)"
},
{
"docstring": "If the payload has an invalid signature, it should fail the permissions test",
"name": "test_has_wrong_sign... | 2 | null | Implement the Python class `PermissionsTests` described below.
Class description:
Tests for ecommerce permissions
Method signatures and docstrings:
- def test_has_signature(self): If the payload has a valid signature, it should pass the permissions test
- def test_has_wrong_signature(self): If the payload has an inva... | Implement the Python class `PermissionsTests` described below.
Class description:
Tests for ecommerce permissions
Method signatures and docstrings:
- def test_has_signature(self): If the payload has a valid signature, it should pass the permissions test
- def test_has_wrong_signature(self): If the payload has an inva... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class PermissionsTests:
"""Tests for ecommerce permissions"""
def test_has_signature(self):
"""If the payload has a valid signature, it should pass the permissions test"""
<|body_0|>
def test_has_wrong_signature(self):
"""If the payload has an invalid signature, it sho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermissionsTests:
"""Tests for ecommerce permissions"""
def test_has_signature(self):
"""If the payload has a valid signature, it should pass the permissions test"""
payload = {'a': 'b', 'c': 'd', 'e': 'f'}
keys = sorted(payload.keys())
payload['signed_field_names'] = ','.... | the_stack_v2_python_sparse | ecommerce/permissions_test.py | mitodl/micromasters | train | 35 |
69dd5729fbef3f612bfe695aaabb5586cedbfc02 | [
"assert isinstance(attr_key, str)\nassert isinstance(attr_value, list)\nreturn attr_key + ' = []'",
"assert isinstance(attr_value, list)\nif isinstance(attr_value[0], dict):\n return attr_value[0]\nBaseCodeGenerator.get_dict_rep(self, attr_key, attr_value)"
] | <|body_start_0|>
assert isinstance(attr_key, str)
assert isinstance(attr_value, list)
return attr_key + ' = []'
<|end_body_0|>
<|body_start_1|>
assert isinstance(attr_value, list)
if isinstance(attr_value[0], dict):
return attr_value[0]
BaseCodeGenerator.get_... | CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`. | ListCodeGenerator | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"HPND",
"GPL-2.0-onl... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCodeGenerator:
"""CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`."""
def generate_code(self, attr_key, attr_value):
"""See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`"""
<|body_0|>
def get_dict_rep(self, attr_key, attr_value):
... | stack_v2_sparse_classes_36k_train_014798 | 5,117 | permissive | [
{
"docstring": "See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`",
"name": "generate_code",
"signature": "def generate_code(self, attr_key, attr_value)"
},
{
"docstring": "See :meth:`.Data_Handler.BaseCodeGenerator.get_dict_rep`",
"name": "get_dict_rep",
"signature": "def get_di... | 2 | null | Implement the Python class `ListCodeGenerator` described below.
Class description:
CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`.
Method signatures and docstrings:
- def generate_code(self, attr_key, attr_value): See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`
- def get_dict_rep(s... | Implement the Python class `ListCodeGenerator` described below.
Class description:
CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`.
Method signatures and docstrings:
- def generate_code(self, attr_key, attr_value): See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`
- def get_dict_rep(s... | 78c02e5fbb129b1bc4147bd55eec2882267d7e87 | <|skeleton|>
class ListCodeGenerator:
"""CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`."""
def generate_code(self, attr_key, attr_value):
"""See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`"""
<|body_0|>
def get_dict_rep(self, attr_key, attr_value):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListCodeGenerator:
"""CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`."""
def generate_code(self, attr_key, attr_value):
"""See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`"""
assert isinstance(attr_key, str)
assert isinstance(attr_value, list)
... | the_stack_v2_python_sparse | QCA4020_SDK/QCA4020_SDK/target/sectools/qdn/sectools/common/utils/datautils/list_handler.py | r8d8/lastlock | train | 1 |
22f7f03eec6f53917c83f28b2da5d4a8d380dfba | [
"dot = Digraph(format='png')\nDibujante.subDibujar(arbol, dot)\ndot.render('output2.png', view=True)",
"dot.node(str(id(arbol)), str(arbol.valor) + ('\\n(' + str(round(arbol.ganancia, 2)) + ',' + str(round(arbol.gananciaRelativa * 100, 2)) + '%)' if arbol.ganancia != 0 else ''))\nfor l, h in arbol.hijos.iteritems... | <|body_start_0|>
dot = Digraph(format='png')
Dibujante.subDibujar(arbol, dot)
dot.render('output2.png', view=True)
<|end_body_0|>
<|body_start_1|>
dot.node(str(id(arbol)), str(arbol.valor) + ('\n(' + str(round(arbol.ganancia, 2)) + ',' + str(round(arbol.gananciaRelativa * 100, 2)) + '%)... | Clase que permite obtener una representacion grafica de un arbol de decision | Dibujante | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dibujante:
"""Clase que permite obtener una representacion grafica de un arbol de decision"""
def dibujar(arbol):
"""Construye una representacion grafica del arbol en formato .png"""
<|body_0|>
def subDibujar(arbol, dot):
"""Sub-rutina que dibuja un nodo del arbo... | stack_v2_sparse_classes_36k_train_014799 | 978 | no_license | [
{
"docstring": "Construye una representacion grafica del arbol en formato .png",
"name": "dibujar",
"signature": "def dibujar(arbol)"
},
{
"docstring": "Sub-rutina que dibuja un nodo del arbol y se llama recursivamente para dibujar a los hijos",
"name": "subDibujar",
"signature": "def su... | 2 | stack_v2_sparse_classes_30k_train_004286 | Implement the Python class `Dibujante` described below.
Class description:
Clase que permite obtener una representacion grafica de un arbol de decision
Method signatures and docstrings:
- def dibujar(arbol): Construye una representacion grafica del arbol en formato .png
- def subDibujar(arbol, dot): Sub-rutina que di... | Implement the Python class `Dibujante` described below.
Class description:
Clase que permite obtener una representacion grafica de un arbol de decision
Method signatures and docstrings:
- def dibujar(arbol): Construye una representacion grafica del arbol en formato .png
- def subDibujar(arbol, dot): Sub-rutina que di... | ecc727c952f2f9ff1d81c407f14ce39ec3b4f605 | <|skeleton|>
class Dibujante:
"""Clase que permite obtener una representacion grafica de un arbol de decision"""
def dibujar(arbol):
"""Construye una representacion grafica del arbol en formato .png"""
<|body_0|>
def subDibujar(arbol, dot):
"""Sub-rutina que dibuja un nodo del arbo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dibujante:
"""Clase que permite obtener una representacion grafica de un arbol de decision"""
def dibujar(arbol):
"""Construye una representacion grafica del arbol en formato .png"""
dot = Digraph(format='png')
Dibujante.subDibujar(arbol, dot)
dot.render('output2.png', vie... | the_stack_v2_python_sparse | Practico2/Entrega/dibujante.py | gsiriani/MAA | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.